code stringlengths 1 199k |
|---|
from collections import defaultdict
from nose.tools import eq_, ok_
from rest_framework.serializers import ValidationError
import amo
import amo.tests
import mkt
import mkt.feed.constants as feed
from mkt.feed import serializers
from mkt.feed.constants import COLLECTION_LISTING, COLLECTION_PROMO
from mkt.feed.models im... |
from blueice.test_helpers import *
from blueice.model import Model
def test_mcsource():
conf = test_conf(mc=True)
m = Model(conf)
s = m.sources[0]
bins = conf['analysis_space'][0][1]
assert s.events_per_day == 1000
assert s.fraction_in_range > 0.9999 # Ten sigma events happen sometimes..
... |
import datetime
from decimal import Decimal
from django_factory import TestCase
from financial_transactions.models import (
Transaction,
)
class TransactionTestCase(TestCase):
def test_unicode(self):
trans = self.factory.make_one(
Transaction, memo=u'Sublime purchase',
date=datet... |
import GafferScene
from _GafferSceneTest import *
from SceneTestCase import SceneTestCase
from ScenePlugTest import ScenePlugTest
from GroupTest import GroupTest
from SceneTimeWarpTest import SceneTimeWarpTest
from SceneProceduralTest import SceneProceduralTest
from CubeTest import CubeTest
from PlaneTest import PlaneT... |
import pytest ; pytest
import re
import mock
from bokeh._version import get_versions
import bokeh.util.version as buv # isort:skip
VERSION_PAT = re.compile(r"^(\d+\.\d+\.\d+)$")
class Test___version__(object):
def test_basic(self) -> None:
assert isinstance(buv.__version__, str)
assert buv.__version... |
import os
import sys
def main():
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sflindy.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main() |
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.openid import OpenID
from config import basedir
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
lm = Logi... |
import os
import sys
try:
from setuptools import setup, Command
except ImportError:
from distutils.core import setup, Command
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
datadir = os.path.dirname(__file__)
with open(os.path.join(datadir, 'README.rst')) as f:
re... |
def extractDellstoriesWordpressCom(item):
'''
Parser for 'dellstories.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loit... |
'''This file generates shell code for the setup.SHELL scripts to set environment variables'''
from __future__ import print_function
import argparse
import copy
import errno
import os
import platform
import sys
CATKIN_MARKER_FILE = '.catkin'
system = platform.system()
IS_DARWIN = (system == 'Darwin')
IS_WINDOWS = (syste... |
import math
import torch
from .Module import Module
class TemporalConvolution(Module):
def __init__(self, inputFrameSize, outputFrameSize, kW, dW=1):
super(TemporalConvolution, self).__init__()
self.inputFrameSize = inputFrameSize
self.outputFrameSize = outputFrameSize
self.kW = kW
... |
from unipath import Path
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
PROJECT_DIR = Path(__file__).ancestor(3)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
... |
"""
test_flaskpypi
----------------------------------
Tests for `flaskpypi` module.
"""
import pytest
from flaskpypi import flaskpypi
from xml.etree import ElementTree
from urllib.request import urlopen
def get_distributions(simple_index='https://pypi.python.org/simple/'):
with urlopen(simple_index) as f:
t... |
import unittest
from autothreadharness.harness_case import HarnessCase
class REED_5_2_5(HarnessCase):
role = HarnessCase.ROLE_REED
case = '5 2 5'
golden_devices_required = 17
def on_dialog(self, dialog, title):
pass
if __name__ == '__main__':
unittest.main() |
from ipctest import IpcTest
class TestLeaves(IpcTest):
def test_workspace_leaves(self, i3):
ws_name = self.fresh_workspace()
con1 = self.open_window()
i3.command('[id=%s] floating enable' % con1)
self.open_window()
self.open_window()
ws = [w for w in i3.get_tree().wor... |
from __future__ import division, unicode_literals, print_function
from hawaii.apps.weixin.models import App
from hawaii.apps.weixin.response import MessageResponse, EventResponse
from hawaii.apps.weixin.weixin.interface import StateInterface
class NoCacheState(StateInterface):
def __init__(self, *args, **kwargs):
... |
import string
from Widget import Widget
HEADER = [
'<link type="text/css" href="/CTK/css/CTK.css" rel="stylesheet" />',
'<script type="text/javascript" src="/CTK/js/jquery-ui-1.7.2.custom.min.js"></script>',
'<script type="text/javascript" src="/CTK/js/jquery.cookie.js"></script>'
]
HTML = """
<div id="tab_... |
import sys, os
sys.path.append(os.path.abspath('_themes'))
sys.path.append(os.path.abspath('.'))
needs_sphinx = '1.1'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo',
'sphinx.ext.coverage', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suf... |
__VERSION__ = "0.7.1" |
"""scvi-tools."""
import logging
from logging import NullHandler
from ._constants import _CONSTANTS
from ._settings import settings
from . import data, model
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
import importlib_metadata
package_name = "scvi-tools"
__version__ = impor... |
"""
human_curl.debug
~~~~~~~~~~~~~~~~~~~~~~~~~~
Debuggging tests for human_curl
:copyright: (c) 2011 by Alexandr Lispython (alex@obout.ru).
:license: BSD, see LICENSE for more details.
"""
import logging
from .tests import *
logger = logging.getLogger("human_curl")
logger.setLevel(logging.DEBUG)
handler = logging.Strea... |
import numpy as np
import pandas as pd
from bokeh.plotting import *
AAPL = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000",
parse_dates=['Date'])
GOOG = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=GOOG&a=0&b=1&c=2000",
parse_dates=['Date'])
MSFT = pd.read_csv(
"http://ic... |
import chainer
def main():
return chainer.datasets.get_mnist(withlabel=False)[0] |
"""
__init__
A translator using the micrsoft translation engine documented here:
http://msdn.microsoft.com/en-us/library/ff512419.aspx
:copyright: © 2011 by Openlabs Technologies & Consulting (P) Limited
:license: BSD, see LICENSE for more details.
"""
__all__ = ['Translator', 'TranslateApiException... |
import re
class CommandError(Exception):
pass
class BaseCommand():
"""
Base command, this will accept and handle some generic features of all commands.
Like error handling, argument retrieving / checking
"""
def __init__(self, args):
"""
Initialize the class
"""
s... |
from fiona import crs
def test_proj_keys():
assert len(crs.all_proj_keys) == 85
assert 'proj' in crs.all_proj_keys
assert 'no_mayo' in crs.all_proj_keys
def test_from_string():
# A PROJ.4 string with extra whitespace.
val = crs.from_string(
" +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs... |
import os
import xlrd
import configparser
import logging
from ..entities import product
def process_cell(cell):
"""Converts the given cell to the appropriate value."""
if cell.value == 'NA':
return ''
ttype = cell.ctype # get the cell's 'type'
if ttype == xlrd.XL_CELL_EMPTY or ttype == xlrd.XL_C... |
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.config import ConfigValidationError
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.modules.xlinebase import XLineBase
from txircd.utils import durationToSeconds, ircLower, now
from zope.int... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Quantization'] , ['MovingMedian'] , ['Seasonal_DayOfWeek'] , ['LSTM'] ); |
import unittest
import json
import logintc
class TestLoginTCClient(unittest.TestCase):
def set_response(self, method, url, headers, body):
full_url = ''.join(['https://cloud.logintc.com/api', url])
self.responses[(method, full_url)] = (headers, body)
def verify_request(self, method, url, body=No... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('courses', '0002_auto_20150403_2321'),
]
operations = [
migrations.AddField(
model_name='course',
name='departments',
... |
from horizon_contrib.utils.dotdict import dotdict, list_to_dotdict, to_dotdict |
"""
Client module for connecting to and interacting with SmartyStreets API
"""
import json
import numbers
import requests
from .data import Address, AddressCollection
from .exceptions import SmartyStreetsError, ERROR_CODES
def validate_args(f):
"""
Ensures that *args consist of a consistent type
:param f: a... |
import datetime
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase, skipIfDBFeature
from django.utils import tzinfo
from models import Donut, RumBaba
class DataTypesTestCase(TestCase):
def test_boolean_type(self):
d = Donut(name='Apple Fritter')
... |
__all__ = ['threshold_adaptive',
'threshold_otsu',
'threshold_yen',
'threshold_isodata',
'threshold_li', ]
import numpy as np
from scipy import ndimage as ndi
from ..exposure import histogram
from .._shared.utils import assert_nD
import warnings
def threshold_adaptive(image, ... |
from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.base import StatsMixin
from sentry.api.bases.group import GroupEndpoint
from sentry.api.exceptions import ResourceDoesNotExist
from sentry.api.serializers import serialize
from sentry.api.serializers.models.environment i... |
import numpy as np
import os
import time
from ..utils import *
def _costMAD(block1, block2):
block1 = block1.astype(np.float)
block2 = block2.astype(np.float)
return np.mean(np.abs(block1 - block2))
def _minCost(costs):
h, w = costs.shape
if costs[h/2, w/2] == 0:
return np.int((h-1)/2), np.i... |
import json
import requests
import types
import pandas as pd
from datetime import datetime, date
import gzip
import io
from ..utils.simplenamespace import *
from ..utils.query_helper import query
from ..utils.pi_helper import *
import collections
class PiRest(object):
"""create Pi object that can interact with REST... |
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
for app in settings.INSTALLED_APPS:
if '.' not in app:
continue
mod = import_module(app)
try:
import_module('%s.internal_urls' % app)
except:
... |
import sys, os
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'{{ cookiecutter.project_name }}'
version = '{{ cookiecutter.version }}'
release = '{{ cookiecutter.version }}'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static... |
import pygame
from pygame.locals import *
from math import sin
import states
class EndEvent(object):
text = [
"Ah, hello there. Welcome to the center of the moon!",
"Oh, me? I'm just the man in the moon. I live here.",
"Don't act so shocked! It's rude you know.",
"I don't get ... |
from fsm import parse_automaton, accept
import re
__author__ = 'Roland'
import sys
keywords = ['float', 'char', 'print', 'input', 'break', 'continue', 'return', 'def', 'if', 'elif',
'else', 'while', 'or', 'and', 'not']
operators = ['=', '<', '>', '==', '>=', '<=', '!=', '+', '-', '*', '/', '%']
separators =... |
from pandas.core.arrays.sparse.accessor import SparseAccessor, SparseFrameAccessor
from pandas.core.arrays.sparse.array import (
BlockIndex,
IntIndex,
SparseArray,
_make_index,
)
from pandas.core.arrays.sparse.dtype import SparseDtype |
from __future__ import print_function
from builtins import str
import os
import re
import tempfile
import shutil
from sibispy import sibislogger as slog
from sibispy import utils as sutils
import_bindir = os.path.join( os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) ), 'import', 'laptops' )
bindir = os.pa... |
"""
Tests for mrcmemmap.py
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import os
import unittest
import numpy as np
from .test_mrcfile import MrcFileTest
from mrcfile.mrcmemmap import MrcMemmap
class MrcMemmapTest(MrcFileTest):
"""Unit tests for M... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 5, transform = "RelativeDifference", sigma = 0.0, exog_count = 0, ar_order = 0); |
from __future__ import absolute_import
from __future__ import with_statement
import sys
import time
from kombu.tests.utils import redirect_stdouts
from mock import Mock, patch
import celery.utils.timer2 as timer2
from celery.tests.utils import Case, skip_if_quick
class test_Entry(Case):
def test_call(self):
... |
from .fields import CharArrayField, TextArrayField, IntegerArrayField |
from bisect import bisect
from uhashring.ring_ketama import KetamaRing
from uhashring.ring_meta import MetaRing
class HashRing:
"""Implement a consistent hashing ring."""
def __init__(self, nodes=[], **kwargs):
"""Create a new HashRing given the implementation.
:param nodes: nodes used to create... |
from __future__ import with_statement
import sys
import logging
import warnings
import django
from django.conf import settings
try:
from django.conf.urls import patterns, url
except ImportError: # Django < 1.4
from django.conf.urls.defaults import patterns, url
from django.core.exceptions import ObjectDoesNotEx... |
from __future__ import absolute_import
from enable.base_tool import * |
"""
Models for code snippets and related data.
Most of these models also have custom managers defined which add
convenient shortcuts for repetitive or common bits of logic; see
``managers.py`` in this directory.
"""
import datetime, re
from django.db import connection, models
from django.template.defaultfilters import ... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('travelogue', '0004_auto_20150418_1655'),
]
operations = [
migrations.AddField(
model_name='tripnote',
name='date_taken',
... |
class SiteActivationNotification(object):
def __init__(self):
self.type = None
self.status = None
self.primarySite = None
self.modifiedSite = None
self.runMode = None
self.serverName = None
self.pluginName = None
def getType(self):
return self.type... |
"""
Created on Fri Jul 27 10:08:25 2018
@author: cdeline
Using pytest to create unit tests for gencumulativesky.
Note that this can't be included in the repo until TravisCI has a Linux version of gencumsky
set up in .travis.yml
to run unit tests, run pytest from the command line in the bifacial_radiance directory
to ru... |
import sys
import os
import inspect
__location__ = os.path.join(os.getcwd(), os.path.dirname(
inspect.getfile(inspect.currentframe())))
import subprocess
output_dir = os.path.join(__location__, "../docs/_rst")
module_dir = os.path.join(__location__, "../mymeal")
cmd_line_template = "sphinx-apidoc -f -o {outputdir} ... |
import rospy
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxyPublisher
from smach import CBState
class StartCheck(EventState):
'''
Example for a state to demonstrate which functionality is available for state implementation.
This example lets the behavior wait until the given target_tim... |
"""code generator for GL/GLES extension wrangler."""
import os
import collections
import re
import sys
GL_FUNCTIONS = [
{ 'return_type': 'void',
'names': ['glActiveTexture'],
'arguments': 'GLenum texture', },
{ 'return_type': 'void',
'names': ['glAttachShader'],
'arguments': 'GLuint program, GLuint shader', },
... |
from yoyo.connections import parse_uri, unparse_uri
def _test_parse_uri(connection_string, expected_uri_tuple):
uri_tuple = parse_uri(connection_string)
assert isinstance(uri_tuple, tuple)
assert (uri_tuple == expected_uri_tuple)
def _test_unparse_uri(uri_tuple, expected_connection_string):
connection_s... |
import rapidsms
import datetime
from rapidsms.apps.base import AppBase
from .models import Poll
from django.db.models import Q
from rapidsms_httprouter.models import Message,MessageBatch
class App(AppBase):
def respond_to_message(self,message,response_msg,poll):
if response_msg == poll.default_response:
... |
""" Friendly Dates and Times """
import calendar
import datetime
import locale
import os
import pytz
import random
_FORCE_UTC = False
class _FormatsMetaClass(type):
"""Allows the formats class to be treated as an iterable.
It is important to understand has this class works.
``hasattr(formats, 'DATE')`` is t... |
"""
Patrols the edges of the map going clockwise. Just drives around in circles,
taking pains not to hit a wall.
When we see a wall, turn right a little.
"""
from courier import RoboLink
robot = RoboLink.connect(name="Patroller", scanner=2, engine=5)
if not robot:
print "Error connecting"
exit(1)
while True:
... |
import theano.sandbox.cuda.basic_ops as sbcuda
import numpy as np
import load_data
import realtime_augmentation as ra
import time
import sys
import os
import json
from custom_for_keras import input_generator
from datetime import datetime, timedelta
from custom_keras_model_x_cat import kaggle_x_cat
from keras.optimizers... |
import logging
import uuid
from datetime import timedelta
from typing import List, Optional
import stripe
from django.apps import apps
from django.db import IntegrityError, models, transaction
from django.utils import dateformat, timezone
from django.utils.encoding import smart_str
from stripe.api_resources.abstract.ap... |
from django.contrib import admin
from models import *
import datetime
admin.site.register(PingHost)
admin.site.register(PingResult) |
import factory
from test_utils import TestCase as BaseTestCase
from mozillians.announcements import models
class TestCase(BaseTestCase):
pass
class AnnouncementFactory(factory.DjangoModelFactory):
FACTORY_FOR = models.Announcement
title = factory.Sequence(lambda n: 'Test Announcement {0}'.format(n))
tex... |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.contrib import admin
from django.contrib.admin.sites import AdminSite
from django.contrib.contenttypes.generic import (
generic_inlineformset_factory, GenericTabularInline)
from django.forms.models import ModelForm... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'ObjAttribute.db_value'
db.delete_column('objects_objattribute', 'db_value')
db.rename_column('objects_objattr... |
from ginga.misc import Bunch, Future
from ginga.gtkw import FitsImageCanvasTypesGtk as CanvasTypes
from ginga.gtkw import ColorBar
from ginga import GingaPlugin
from ginga import cmap, imap
from ginga import wcs
import gobject
import gtk
import pango
from ginga.gtkw import GtkHelp
class Catalogs(GingaPlugin.LocalPlugin... |
import dataStructures
import logging, os
log = logging.getLogger("tray_item")
log.setLevel(logging.WARN)
class TrayItem:
"""
Parent Class for all items in a tray.
"""
def __init__(self):
self.selected = False
self.changed = False
dataStructures.changingItems.append(self)
... |
from __future__ import absolute_import
from django import forms
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.views.generic import View
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.safestring import mark_safe... |
from core import send_request
from people import get_me
from projects import get_all_active_projects, get_project
from todo_lists import get_todo_list, get_todo, get_all_active_todo_lists
from stars import get_starred_projects
try:
from MY_BC import BC
except ImportError:
from core import MY_BC_NUMBER as BC
cla... |
"""Abstract base class for Port classes.
The Port classes encapsulate Port-specific (platform-specific) behavior
in the web test infrastructure.
"""
import time
import collections
import json
import logging
import optparse
import os
import re
import sys
import tempfile
from collections import defaultdict
import six
fro... |
from __future__ import annotations
import random
import pytest
import scitbx.matrix
from cctbx import sgtbx
from cctbx.sgtbx import bravais_types
from dials.algorithms.indexing.max_cell import find_max_cell
from dials.array_family import flex
@pytest.fixture(params=bravais_types.acentric)
def setup(request):
space_... |
from settings.secure import OAUTH_TOKEN, CANVAS_URL
from canvas_sdk.methods import courses
from canvas_sdk.utils import get_all_list_data
from canvas_sdk import RequestContext
import sys
course_id = None
if len(sys.argv) == 2:
course_id = sys.argv[1]
else:
sys.exit("Error: missing course_id")
request_context = ... |
import numpy
import random
import math
from exit_weight import *
from privexUtils import resolution
def Noise(sigma, fingerprint, sum_of_sq, p_exit):
sigma_i = p_exit*sigma/math.sqrt(sum_of_sq)
random_sample = random.gauss(0,sigma_i)
return random_sample |
"""
Plotting (requires matplotlib)
"""
from colorsys import hsv_to_rgb, hls_to_rgb
from libmp import NoConvergence
class VisualizationMethods(object):
plot_ignore = (ValueError, ArithmeticError, ZeroDivisionError, NoConvergence)
def plot(ctx, f, xlim=[-5,5], ylim=None, points=200, file=None, dpi=None,
singulari... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['None'] , ['Lag1Trend'] , ['Seasonal_DayOfWeek'] , ['AR'] ); |
import click
import os
import os.path
import ntpath
import serial
import sys
import prosflasher.ports
import prosflasher.upload
import prosconfig
from proscli.utils import default_cfg, AliasGroup
from proscli.utils import get_version
@click.group(cls=AliasGroup)
def flasher_cli():
pass
@flasher_cli.command(short_he... |
"""
Created on Tue Aug 18 09:29:56 2015
@author: monteiro
"""
from thermopy.iapws import Water
from thermopy.units import Pressure, Temperature
def test_iapws():
"""
Tests are given inside the IAPWS document. See references for more details.
"""
#test Tsat given P
assert round(Water(
1e5, 37... |
import mysql.connector
def findUser(userToken, cnx):
userQuery = 'SELECT user_id FROM user_token WHERE user_token = %s'
try:
userCursor = cnx.cursor()
userCursor.execute(userQuery, (userToken, ))
return userCursor.fetchone()
#return 0 for db error
except mysql.connector.Error as ... |
import argparse, os, sys
from time import clock
import nibabel as nib
import numpy as np
from scipy.linalg import logm
from scipy.linalg.matfuncs import sqrtm
from numpy.linalg import det
from numpy.linalg import eigvals
from numpy.linalg import eigvalsh
def mylogm (v):
return np.reshape(logm(v.reshape(N,N)), [1,N*N... |
from airflow.models import DAG
from airflow.operators.dummy_operator import DummyOperator
from datetime import datetime, timedelta
from airflow.operators import PythonOperator
from airflow.hooks import RedisHook
from airflow.models import Variable
from airflow.hooks import MemcacheHook
from etl_tasks_functions import... |
from django import VERSION
from django.core.management import call_command
from ._compat import patch
CELERYD_COMMAND = 'djcelery.management.commands.celeryd.Command.handle'
def test_celeryd_command():
if VERSION >= (1, 10):
traceback = False
else:
traceback = None
with patch(CELERYD_COMMAND... |
from sqlalchemy.orm import sessionmaker as sqla_sessionmaker
from sqlalchemy import engine_from_config
import zope.sqlalchemy
import transaction
from .meta import Base
from .user import (
User,
UserTickets,
)
from .domain import Domain
from .record import Record
from .types import (
... |
"""
None of the functions/objects in this module need be passed `db`.
Naming convention: a `pub` is either a pubkey or a pubkeyhash
"""
import hashlib
import bitcoin as bitcoinlib
import binascii
from bitcoin.core.key import CPubKey
from counterpartylib.lib import util
from counterpartylib.lib import config
from counte... |
from bank_CI import BankCI
from bank_controller import BankController
from settings import DB_NAME, CREATE_TABLES, DROP_DATABASE
from sql_manager import BankDatabaseManager
def main():
manager = BankDatabaseManager.create_from_db_and_sql(DB_NAME, CREATE_TABLES, DROP_DATABASE, create_if_exists=False)
controller ... |
from rpython.flowspace.model import Variable
from rpython.rtyper.lltypesystem import lltype
from rpython.translator.simplify import get_graph
from rpython.tool.uid import uid
class CreationPoint(object):
def __init__(self, creation_method, TYPE, op=None):
self.escapes = False
self.returns = False
... |
import sys
import os
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand, CommandError
from workshops.models import Award, Badge, Person
SKIP_DIRS = ['class']
class Command(BaseCommand):
args = '/path/to/site'
help = 'Report inconsistencies in badges.'
d... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
""" |
def is_integer(nr):
try:
int(nr)
return True
except ValueError:
return False |
import os
import sys
import argparse
import traceback
sys.path.insert(1, os.path.join(os.path.dirname(__file__), os.pardir))
from toollib.group import Group,UnsortedInputGrouper
import scipy.stats as ss
class KSGroup(Group):
def __init__(self, tup):
super(KSGroup, self).__init__(tup)
self.samples = ... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Score.created_at'
db.add_column(u'core_score', 'created_at',
s... |
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
return str(int(num1) * int(num2)) |
from transmute_core import *
from .route import route
from .swagger import add_swagger |
from voluptuous import Invalid
import re
def Url(msg=None):
def f(v):
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'... |
"""Support for vacuum cleaner robots (botvacs)."""
from dataclasses import dataclass
from datetime import timedelta
from functools import partial
import logging
from typing import final
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ( # noqa: F401 # STATE_... |
from pyxer.base import *
@controller
def index():
return "/index" |
import sys
import requests
from urllib.parse import urlparse
docs_repos = [
"frappe_docs",
"erpnext_documentation",
"erpnext_com",
"frappe_io",
]
def uri_validator(x):
result = urlparse(x)
return all([result.scheme, result.netloc, result.path])
def docs_link_exists(body):
for line in body.splitlines():
for wor... |
from django.template import Library
register = Library()
def filer_actions(context):
"""
Track the number of times the action field has been rendered on the page,
so we know which value to use.
"""
context['action_index'] = context.get('action_index', -1) + 1
return context
filer_actions = regis... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.