content string |
|---|
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'destiny.views.home', name='home'),
# url(r'^destiny/', include('destiny.foo.urls')),
# Unc... |
#STANDARD LIB
from datetime import datetime
from decimal import Decimal
from itertools import chain
import warnings
#LIBRARIES
import django
from django.conf import settings
from django.db import models
from django.db.backends.util import format_number
from django.db import IntegrityError
from django.utils import tim... |
import os
import sys
from django.conf import settings
from django.core.management.base import BaseCommand
from django.test.simple import DjangoTestSuiteRunner
import nose.core
from plugin import ResultPlugin
from django.db.backends import creation
from django.db import connection, DatabaseError
try:
any
e... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from unidecode import unidecode
from jsonfield import JSONField
from uuid import uuid4
from django.db import models
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.template.defaultfilter... |
# coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#---------------------------------------------------------------------... |
from mongrel2 import handler
import base64
import hashlib
import json
def wsChallenge(v):
try:
x=hashlib.sha1(v+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
return base64.b64encode(x.digest())
except:
return ""
sender_id = "59619F68-8E14-4743-81B2-038E7294541D"
conn = handler.Connection(se... |
import os
import pytest
from django.core.urlresolvers import reverse
from shuup.testing.factories import create_product, get_default_shop
from shuup.testing.utils import initialize_admin_browser_test
pytestmark = pytest.mark.skipif(os.environ.get("SHUUP_BROWSER_TESTS", "0") != "1", reason="No browser tests run.")
... |
empty = '.'
red = 'r'
black = 'b'
colums = 7
rows = 6
def start_new_board_game()
'''
Creates a new game board. Initially, a game board has the size
BOARD_COLUMNS x BOARD_ROWS and is comprised only of strings with the
value empty
'''
board = []
for col in range(columns):
board.ap... |
"""
Tests for miscellaneous functionality in the `funcs` module
"""
import pytest
import numpy as np
from numpy import testing as npt
from ... import units as u
from ...time import Time
def test_sun():
"""
Test that `get_sun` works and it behaves roughly as it should (in GCRS)
"""
from ..funcs imp... |
__author__ = 'sstober'
import logging
log = logging.getLogger(__name__)
from deepthought.util.fs_util import load
from deepthought.datasets.selection import DatasetMetaDB
from pylearn2.utils.timing import log_timing
import os
class Datasource(object):
def __init__(self, data, metadata, targets=None):
s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Test files gathered from json.org and yaml.org
import json
import os
import shutil
from pathlib import Path
from test.common import test_root, tmp_dir
import pytest
import ruamel.yaml as yaml
import toml
from box import Box, BoxError, BoxList
class TestBoxList:
@... |
# -*- coding: utf-8 -*-
# tiki2po unit tests
from translate.convert import test_convert, tiki2po
from translate.misc import wStringIO
class TestTiki2Po(object):
ConverterClass = tiki2po.tiki2po
def _convert(self, input_string, template_string=None,
include_unused=False, success_expected=T... |
# -*- coding: utf-8 -*-
#!/usr/bin/python
"""
Reading Electric Consumption with OCR
Copyright (C) 2017 Jiri Dohnalek
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, ... |
"""MeCab based Segmenter.
Word segmenter module powered by `MeCab <https://github.com/taku910/mecab>`_.
You need to install MeCab to use this segmenter.
The easiest way to install MeCab is to run :code:`make install-mecab`. The
script will download source codes from GitHub and build the tool. It also setup
`IPAdic <ht... |
"""Test 1-1 tubes support."""
import dbus
from servicetest import call_async, EventPattern, sync_dbus, assertEquals
from gabbletest import acknowledge_iq, sync_stream
import constants as cs
import ns
import tubetestutil as t
from twisted.words.xish import domish, xpath
last_tube_id = 69
def contact_offer_dbus_tube... |
import json
from tests.integration.util import IntegrationTestCase
class InventoryIntegrationTestCase(IntegrationTestCase):
def test_inventory_empty(self):
client = self.get_client()
self.register_and_login(client, "test_inventory_empty")
client.send("inventory\r\n")
response = jso... |
from json.decoder import JSONDecodeError
import mock
from paasta_tools.secret_tools import get_hmac_for_secret
from paasta_tools.secret_tools import get_secret_hashes
from paasta_tools.secret_tools import get_secret_name_from_ref
from paasta_tools.secret_tools import get_secret_provider
from paasta_tools.secret_tools... |
import math
import os
from pdfrw import PdfReader, PdfWriter, PageMerge
import re
import sys
from typing import Dict, List, Iterator, Optional, Any, Tuple
paperformats: Dict[str, List[int]] = {
"a0": [2384, 3371],
"a1": [1685, 2384],
"a2": [1190, 1684],
"a3": [842, 1190],
"a4": [595, 842],
"a5... |
import numpy as np
def softmax(x):
xs = np.exp(x - np.max(x)) # center values to avoid overflow
return xs/np.sum(xs)
def save_model_parameters_theano(outfile, model):
U, V, W = model.U, model.V, model.W
np.savez(outfile, U=U, V=V, W=W)
print("Saved model parameters to %s." % outfile)
def load_mod... |
#!/usr/bin/python3
#
# Id:
#
# We test a bit of the atrshmlog here.
#
# This is for the first starter, so only the basic things.
import sys
import atrshmlog
target = int(sys.argv[1])
result = atrshmlog.attach()
atrshmlog.sleep_nanos(1000000000)
akcount = 0
slave = atrshmlog.get_next_slave_local(0)
while slave !=... |
import sys
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import (
InvalidElementStateException,
NoAlertPresentException,
UnexpectedAlertPre... |
# coding:utf-8
import os
import time
import threading
import six
from cactus.utils.filesystem import fileList
from cactus.utils.network import retry
class PollingListener(object):
def __init__(self, path, f, delay=.5, ignore=None):
self.path = path
self.f = f
self.delay = delay
s... |
import pandas as pd
from numba import njit
@njit
def df_rolling_skew():
df = pd.DataFrame({'A': [4, 3, 5, 2, 6], 'B': [-4, -3, -5, -2, -6]})
out_df = df.rolling(3).skew()
# Expect DataFrame of
# {'A': [NaN, NaN, 0.000000, 0.935220, -1.293343],
# 'B': [NaN, NaN, 0.000000, -0.935220, 1.293343]}
... |
from __future__ import with_statement
import os.path
import re
import mmap
class DictBase(object):
ENCODING = 'EUC-JIS-2004'
def split_candidates(self, line):
'''Parse a single candidate line into a list of candidates.'''
def seperate_annotation(candidate):
index = candidate.find(u... |
import os
from subprocess import Popen, PIPE
import dxf
from util import fmessage, VERSION
from geometry.font import *
def read_image_file(settings):
font = Font()
file_full = settings.get('IMAGE_FILE')
if not os.path.isfile(file_full):
return
fileName, fileExtension = os.path.splitext(fil... |
#!/usr/bin/env python2.6
from __future__ import unicode_literals
import setuptools
setuptools.setup(
name = "supermann",
version = '3.2.0',
author = "Sam Clements",
author_email = "<EMAIL>",
url = "https://github.com/borntyping/supermann",
description = "A Supervisor event listener for Riem... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from examples.babi.run import run_babi
from examples.babi.train_online import run_babi_online
from examples.concerts.run import run_concerts
from examples.concerts.train_... |
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class SummaryRanges(object):
def __init__(self):
"""
Initialize your data structure here.
"""
# inspired by @ qianzhige
self._interval... |
"""LinearQubitOperator is a linear operator from QubitOperator."""
import functools
import logging
import multiprocessing
import numpy
import numpy.linalg
import scipy
import scipy.sparse
import scipy.sparse.linalg
from openfermion.utils import count_qubits
class LinearQubitOperatorOptions(object):
"""Options ... |
config_template = """\
###############################
## S3Site Configuration File ##
###############################
[global]
# enable experimental features for this release
#ENABLE_EXPERIMENTAL=True
# specify a web browser to launch when viewing spot history plots
#WEB_BROWSER=chromium
# split the config into multip... |
import unittest
from typing import List
import utils
def _kth(a, b, k):
m = len(a)
n = len(b)
if m > n:
a, b, m, n = b, a, n, m
kfloor = int(k)
kceil = kfloor + 1
lo = max(0, kceil - n)
hi = min(m, kceil)
while True:
i = lo + ((hi - lo) >> 1)
j = kceil - i
... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class AuthCallsCredentialListMa... |
"""Base class for anomaly detectors' REST calls
https://bigml.com/developers/anomalies
"""
try:
import simplejson as json
except ImportError:
import json
from bigml.resourcehandler import ResourceHandler
from bigml.resourcehandler import (check_resource_type, resource_is_ready,
... |
try:
from unittest2 import TestCase
except ImportError:
from unittest import TestCase
from time import sleep
import types
from specter.spec import (TimedObject, CaseWrapper, Spec, Describe,
DataSpec, copy_function, get_function_kwargs,
convert_to_hashable)
... |
import bs4
import requests
import sqlalchemy.ext.declarative
from kijiji_api import get_token
from posting_category import *
from sqlalchemy.orm import sessionmaker
engine = sqlalchemy.create_engine('sqlite:///kijiji_api.db')
Base = sqlalchemy.ext.declarative.declarative_base()
def get_category_map(session, branchCat... |
import itertools
import numpy as np
from neon import NervanaObject
from neon.backends.autodiff import Autodiff
from neon.backends.tests.utils import call_func, gen_backend_tensors
from neon.backends.tests.utils import tensors_allclose
def get_audiff_gradient(f, be, tensors):
"""
get autodiff gradient w.r.t t... |
__author__ = 'Dario'
import os
import io
import psutil
import time
import random
import string
import FrameMYR
import win32gui
import win32con
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
#PATH_TO_EXE = os.getcwd() + "\\" + FrameMYR.FrameMYRClass.RESOURCE_PATH + "wallets\\myriadcoin-qt.exe"
PA... |
import os
import random
import string
import sys
def path_validator(p):
if os.path.isdir(p):
# return the normalized path including safe case sensitivity
return os.path.normpath(os.path.normcase(p))
else:
raise argparse.ArgumentTypeError('Path location incorrect')
def name_size_validator(s):
""" Thi... |
import os
from PyQt4 import QtGui
from PyQt4.QtCore import *
from opengeo.gui.explorertree import ExplorerTreeWidget
from opengeo.gui.gsexploreritems import GsCatalogsItem
from opengeo.gui.pgexploreritems import PgConnectionsItem
from opengeo.gui.qgsexploreritems import QgsProjectItem
from opengeo.gui.treepanels import... |
"""
Flask-Celery
------------
Celery integration for Flask
"""
import codecs
from setuptools import setup
setup(
name='Flask-Celery',
version='2.4.3',
url='http://github.com/ask/flask-celery/',
license='BSD',
author='Ask Solem',
author_email='<EMAIL>',
description='Celery integration for ... |
import keras
from keras import backend as K
from keras.layers import Input, Dropout, Conv2D, MaxPooling2D, UpSampling2D, concatenate
from keras.optimizers import Adam
from keras.models import Model
# change the loss function
def dice_coef(y_true, y_pred):
smooth = 1.
y_true_f = K.flatten(y_true)
y_pred_f... |
"""Operations for embeddings."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.pyth... |
import os
import shutil
from cerbero.commands import gensdkshell
from cerbero.errors import FatalError
from cerbero.utils import _, N_, shell
from cerbero.utils import messages as m
from cerbero.packages import PackagerBase
LAUNCH_BUNDLE_COMMAND = """# Try to discover plugins only once
LOCKFILE="/tmp/%(appname)s-bun... |
from .. util import *
class ReportTestSettings:
def __init__(self, imageDifferenceTolerance = 0.0):
self.imageDifferenceTolerance = imageDifferenceTolerance
class ReportTest:
def __init__(self, key, testfun, message):
self.key = key
self.testfun = testfun
self.message = message
def test(self, report):
r... |
"""
WSGI Handler
=============
NOTE: This is experimental software.
This is the WSGI handler for ServerCore. It will wait on the
HTTPParser to transmit the body in full before proceeding. Thus, it is probably
not a good idea to use any WSGI apps requiring a lot of large file uploads (although
it could theoreticall... |
import ipaddress
def get_user_from_ip(cfg, addr):
""" Search in the config database the user with the provided ip.
NOTE : This function depends on config database structure.
"""
target = ipaddress.IPv4Address(unicode(addr))
for user in cfg.users.users_list:
if ipaddress.IPv4Address(unicode(user.ip_ad... |
from collections import OrderedDict
from operator import add
from numpy import arange
import matplotlib.pyplot as plt
def freq_gather(freq_filename):
"""Parses the Genepop output file with allele frequencies and returns a
dict like this: {locus:{pop:[allelesFreq, allelesFreq]}"""
snp_dict = {}
with op... |
import math
import random
import functools
from collections import Counter
import logging
from datetime import datetime, date, timedelta as td
import csv
import io
class Rota:
_days = [1,2,3,4,5]
_start = 0
_end = 0
_bank_holidays = [datetime.strptime("2016/12/26","%Y/%m/%d"),
d... |
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy import select, func
import uuid
# create a new SQLAlchemy object
db = SQLAlchemy()
# Base model that for other models to inherit from
class Base(db.Model):
__abstract__ = True
id = db.Column(db.Integer,... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v7.enums",
marshal="google.ads.googleads.v7",
manifest={"FeedItemTargetDeviceEnum",},
)
class FeedItemTargetDeviceEnum(proto.Message):
r"""Container for enum describing possible data types for a feed
item tar... |
#!/usr/bin/env python
"""
Helper code for file writing with optional compression.
@contact: Debian FTPMaster <<EMAIL>>
@copyright: 2011 Torsten Werner <<EMAIL>>
@license: GNU General Public License version 2 or later
"""
################################################################################
# This program ... |
import random
from six.moves.urllib import parse
from tempest.api.volume import base
from tempest import test
class VolumesV2ListTestJSON(base.BaseVolumeTest):
"""volumes v2 specific tests.
This test creates a number of 1G volumes. To run successfully,
ensure that the backing file for the volume group t... |
"""Script to run a receiving SSM."""
from __future__ import print_function
import ssm.agents
from ssm import __version__, LOG_BREAK
import logging
import os
import sys
from optparse import OptionParser
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
def main():
"""Set ... |
from time import gmtime, strftime
import timeit
import threading
from SA_Scrape import getSaURL
from newspaper import Article
from vaderSentiment import vaderSentiment
import RSS_URL
#setting lock variable for threading
global lock
lock = threading.Lock()
def SaSentimentRSS (symbol):
url = "http://seekingalpha.... |
'''
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
'''
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rt... |
"""
EasyBuild support for installing Intel compilers, implemented as an easyblock
@author: Kenneth Hoste (Ghent University)
"""
import os
from distutils.version import LooseVersion
from easybuild.easyblocks.generic.intelbase import IntelBase
from easybuild.tools.build_log import EasyBuildError, print_msg
class EB_i... |
from django.contrib import admin
from phpbb import models as pm
class PhpbbForumAdmin(admin.ModelAdmin):
list_display = (
'forum_name',
'forum_id',
'forum_desc',
)
admin.site.register(pm.PhpbbForum, PhpbbForumAdmin)
class PhpbbTopicAdmin(admin.ModelAdmin):
list_d... |
import sys
import os
import urllib2
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Updater (QDialog):
def __init__ (self, parent, rev):
super (Updater, self).__init__(parent)
self.rev = rev
self.update_rev = ''
vbox = QVBoxLayout()
self.status = QLabel('')
vbox.addWidget (self.status)
butt... |
"""ReMixMatch training, changes from MixMatch are:
- Add distribution matching.
"""
import os
from absl import app
from absl import flags
from cta.cta_remixmatch import CTAReMixMatch
from libml import utils, data
FLAGS = flags.FLAGS
class ABCTAReMixMatch(CTAReMixMatch):
pass
def main(argv):
utils.setup_... |
import type_conv
from core_types import StructT, ImmutableT, IncompatibleTypes
class SliceT(StructT, ImmutableT):
def __init__(self, start_type, stop_type, step_type):
self.start_type = start_type
self.stop_type = stop_type
self.step_type = step_type
self._fields_ = [('start',start_type), ('stop', s... |
"""
The :mod:`db` module provides the database and schema that is the backend for
the Alerts plugin
"""
from sqlalchemy import Column, Table, types
from sqlalchemy.orm import mapper
from openlp.core.lib.db import BaseModel, init_db
class AlertItem(BaseModel):
"""
AlertItem model
"""
pass
def init_sc... |
import base64
from functools import wraps
from django.contrib.auth.models import AnonymousUser as DjangoAnonymousUser, User as DjangoUser
from django.http import HttpResponse
from apps.canvas_auth.backends import authenticate
from apps.canvas_auth.http import HttpUnauthorizedException
from apps.canvas_auth.models imp... |
"""Tuner for Scikit-learn Models."""
import collections
import os
import pickle
import warnings
import numpy as np
import pandas as pd
import tensorflow as tf
try:
import sklearn # pytype: disable=import-error
except ImportError:
sklearn = None
from ..engine import base_tuner
def split_data(data, indices)... |
'''
Copyright (C) 2015 Dato, Inc.
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
'''
import os
import time
import logging
import platform
import sys as _sys
class GraphLabConfig:
__slots__ = ['graphlab_server', 'server_addr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Dummy echo server based on binary protocol with asyncio
'''
import asyncio
import struct
async def handle_echo(reader, writer):
while True:
is_close = False
length, = struct.unpack('<i', await reader.read(4))
print('Preparing {} bytes l... |
# -*- coding: utf-8 -*-
"""
adam.domain.documents.py
~~~~~~~~~~~~~~~~~~~~~~~~
'documents' resource and schema settings.
:copyright: (c) 2015 by Nicola Iarocci and CIR2000.
:license: BSD, see LICENSE for more details.
"""
from collections import namedtuple
from common import base_def, base_schema, ... |
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from rubberstamp.tests.base import RubberStampTestCase
from rubberstamp.models import AppPermission
from rubberstamp.tests.testapp.models import TestModel
from rubberstamp.exceptions import PermissionLookupError
from... |
import functools
from sqlalchemy.exc import IntegrityError
from tornado.web import HTTPError
from elixir import session
from windpotion.errors import DatabaseException
from windpotion.settings import Options
__author__ = 'Rubens Pinheiro'
__date__ = "03/07/13 22:26"
def REST(Service):
"""
REST Handler annotat... |
from distutils.version import LooseVersion as Version
from tests.tools import *
import hashlib
import azurelinuxagent.common.utils.textutil as textutil
from azurelinuxagent.common.future import ustr
class TestTextUtil(AgentTestCase):
def test_get_password_hash(self):
with open(os.path.join(os.path.dirn... |
# -*- coding: utf-8 -*-
import logging
from os import path
import wx
from wx.lib.newevent import NewCommandEvent
from ...local_container import ContainerStatus
from ...common.i18n import N_
from ..common.pictos import get_bitmap
from ..event_promise import ensure_gui_thread
from ..base_view import BaseView
from ..tr... |
"""
.. module: security_monkey.watchers.rds_security_group
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Patrick Kelley <<EMAIL>> @monkeysecurity
"""
from security_monkey.watcher import Watcher
from security_monkey.watcher import ChangeItem
from security_monkey.constants import TROUBLE_REGIONS
from ... |
from gi.repository import Gtk
import os
import canonical.validation as validation
import config
import show_message as show
from gtkbasebox import GtkBaseBox
class UserInfo(GtkBaseBox):
""" Asks for user information """
def __init__(self, params, prev_page=None, next_page="slides"):
super().__init__(... |
import http.client
import json
import sqlite3
import os
import os.path
import time
import logging
import re
import sys
import io
from contextlib import closing
class RegExps:
reddit_r_name = re.compile(r'^/r/[A-Za-z0-9_-]+$')
imgur_image_uri_path = re.compile(r'^/[A-Za-z0-9]+\.(jpg|gif|png)$')
imgur_page_... |
import logging
from cubetl.core import Node
from incf.countryutils import transformations
import GeoIP
# Get an instance of a logger
logger = logging.getLogger(__name__)
class GeoIPFromAddress(Node):
"""
This CubETL node performs a GeoIP library search for a given IP address,
adding country and contine... |
"""Pure python implementation of the binary Tokyo Tyrant 1.1.17 protocol
Tokyo Cabinet <http://tokyocabinet.sourceforge.net/> is a "super hyper ultra
database manager" written and maintained by Mikio Hirabayashi and released
under the LGPL.
Tokyo Tyrant is the de facto database server for Tokyo Cabinet written and
ma... |
import logging
import random
# Utilities
from RiotApiDevServer import models
from RiotApiDevServer.helpers import fake
class Spectator( object ):
def __init__( self ):
"""
Creates a randomly generated CurrentGameInfo
"""
# Game Constants
platforms = [ 'BR1', 'EUN1', 'EUW1... |
'''
Entry point module to start the interactive console.
'''
from _pydev_imps._pydev_saved_modules import thread
start_new_thread = thread.start_new_thread
try:
from code import InteractiveConsole
except ImportError:
from _pydevd_bundle.pydevconsole_code_for_ironpython import InteractiveConsole
from code impo... |
from __future__ import print_function
import argparse
import vulkanmitts as vk
import numpy as np
from cube_data import *
from vkcontextmanager import vkreleasing, VkContextManager
from transforms import *
def render_textured_cube(vkc, cube_coords):
vkc.init_presentable_image()
rp_begin = vkc.make_render_pass_... |
"""Test dispatcher.
The dispatcher can choose which template to use according
to the parameters of workload"""
from collections import namedtuple
from tvm import autotvm
from tvm.autotvm.task import dispatcher, DispatchContext
SimpleConfig = namedtuple('SimpleConfig', ('template_key', 'is_fallback'))
def test_dispat... |
import test_support
class OldStyleFunctionRuleTest(test_support.TestBase):
def setUp(self):
self.set_default_rules_selection(['OldStyleFunctionRule'])
self.set_default_error_id('old style function')
self.set_default_error_severity('warning')
def test_declaration_and_point_of_use_in_nex... |
#!/usr/bin/python
import requests
from bs4 import BeautifulSoup
import xmltodict
import click
from ConfigParser import SafeConfigParser
def get_config(key):
""" Fetch config from config file """
parser = SafeConfigParser()
parser.read('../.config')
return parser.get(key)
class Match(object):
""" Represen... |
#! /usr/bin/python
'''
Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
'''
class Solution:
# @param num, a list of integer
# @return an integer
# You may assume no duplicate exists in the array.
def fi... |
import sys
from colorama import init
from colorama import Fore
init()
sys.tracebacklimit = None
class GeneralError(ValueError):
"""Handles general errors. Subclasses the ValueError class."""
def __init__(self, message, *args):
self.message = message
super(GeneralError, self).__init__(mess... |
#!/usr/bin/python
import os.path, sys
sys.path.append(os.path.join(os.path.split(__file__)[0], '..'))
from elftools.elf.elffile import ELFFile
from elftools.elf.dynamic import DynamicSegment
from elftools.common.exceptions import ELFError
from sys import argv, stdin, stderr
from struct import unpack
from re import ma... |
# -*- coding: utf-8 -*-
from openerp import fields, api, models
class infrastructure_rename_db_name(models.TransientModel):
_name = "infrastructure.rename_database.name"
_description = "Infrastructure Rename Database Name Wizard"
name = fields.Char(
'New Database Name',
size=64,
r... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
CSRF_ENABLED = True
SECRET_KEY = "\2\1thisismyscretkey\1\2\e\y\y\h"
OPENID_PROVIDERS = [
{"name": "Google", "url": "https://www.google.com/accounts/o8/id"},
{"name": "Yahoo", "url": "https://me.yahoo.com"},
{"name": "AOL", "url": "http://open... |
"""
*******************************************************
*
* checkOptions - CHECK USER PROVIDED ARGS FOR OPTIONS
*
* License: Apache 2.0
* Written by: Michael Slugocki
* Created on: April 14, 2018
* Last updated: September 13, 2018
*
*******************************************************
"""
######... |
from trytond.model import fields, ModelView, Workflow
from trytond.pyson import Eval
from trytond.pool import Pool, PoolMeta
from trytond.transaction import Transaction
from trytond.tools import grouped_slice
__all__ = ['PurchaseRequest', 'PurchaseConfig', 'Purchase', 'PurchaseLine',
'ProductSupplier', 'CreatePur... |
from settings import *
import unittest
from tethne.persistence.hdf5.corpus import HDF5Corpus, HDF5Paper
from tethne import Corpus, Paper
from tethne.persistence.hdf5.corpus import from_hdf5, to_hdf5
from nltk.corpus import stopwords
from tethne.readers import wos, dfr
import os
D = dfr.read_corpus(datapath + '/dfr'... |
"""
The command line interface for htsget.
"""
from __future__ import division
from __future__ import print_function
import argparse
import logging
import os
import signal
import sys
import htsget
import htsget.exceptions as exceptions
def error_message(message):
"""
Writes an error message to stderr.
"... |
from bson import ObjectId
from mock import patch
from flask import url_for
from udata.core.dataset.factories import DatasetFactory
from udata.features.transfer.factories import TransferFactory
from udata.core.user.factories import UserFactory
from udata.utils import faker
from . import APITestCase
class TransferAP... |
"""
The snippets dockwindow.
"""
import weakref
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QAction
import actioncollection
import actioncollectionmanager
import app
import panel
class SnippetTool(panel.Panel):
"""A dockwidget for selecting, applying and editin... |
import functools
import json
import os
import warnings
from modularodm import fields, Q
from modularodm.exceptions import NoResultsFound
from framework.mongo import (
ObjectId,
StoredObject,
utils as mongo_utils
)
from website import settings
def _serialize(fields, instance):
return {
field... |
#!/usr/bin/env python
import sys
# Simple python version test
major,minor = sys.version_info[:2]
py_version = sys.version.split()[0]
if major != 2 or minor < 7:
# SystemExit defaults to returning 1 when printing a string to stderr
raise SystemExit("You are using python %s, but version 2.7 or greater is required" ... |
# coding: utf-8
from collections import namedtuple
from decimal import Decimal
import logging
import os
from pprint import pformat
import re
import unicodedata
import urlparse
from bs4 import BeautifulSoup
from flask import session, url_for
import xlrd
from cla_public.apps.checker.means_test import MeansTest
from cla... |
import pytest, os, stat, commands
from src.generators import MP3FileGenerator
def setup_module(module):
module.generator = MP3FileGenerator.MP3FileGenerator()
module.getFileResult = generator.getFile()
def teardown_module(module):
os.remove(module.getFileResult)
def test_fileExists():
if (not os.path.exists(getF... |
import webob
from cinder import context
from cinder import db
from cinder import exception
from cinder import test
from cinder.openstack.common import jsonutils
from cinder.tests.api.openstack import fakes
def app():
# no auth, just let environ['cinder.context'] pass through
api = fakes.volume.APIRouter()
... |
"""
Queue adapter for Dask
"""
import traceback
from typing import Any, Dict, Hashable, Tuple
from qcelemental.models import FailedOperation
from .base_adapter import BaseAdapter
def _get_future(future):
try:
return future.result()
except Exception as e:
msg = "Caught Executor Error:\n" + t... |
# Importing packages
from matplotlib import pyplot as plt
import numpy as np
from matplotlib import cm
from scipy.spatial import Delaunay
# Setting up the database
execfile('settings.py')
# creating some shortcuts
d = db_manager # database manager
c = db_manager.cls # useful to call Simulation attributs
# Load... |
"""
Argument checking decorator and support
"""
import inspect
from kiwi.datatypes import number as number_type
import collections
_NoValue = object()
class CustomType(type):
@classmethod
def value_check(mcs, name, value):
pass
class number(CustomType):
"""
Custom type that verifies that ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.