code stringlengths 1 199k |
|---|
from django.utils.datastructures import SortedDict
from bencode import bencode, bdecode
def sort_dict(D):
result = SortedDict()
for key in sorted(D.keys()):
if type(D[key]) is dict:
D[key] = sort_dict(D[key])
result[key] = D[key]
return result |
import klampt.math.autodiff.ad as ad
import torch,numpy as np
class TorchModuleFunction(ad.ADFunctionInterface):
"""Converts a PyTorch function to a Klamp't autodiff function class."""
def __init__(self,module):
self.module=module
self._eval_params=[]
torch.set_default_dtype(torch.float6... |
"""Defines a file-derived class to read/write Fortran unformatted files.
The assumption is that a Fortran unformatted file is being written by
the Fortran runtime as a sequence of records. Each record consists of
an integer (of the default size [usually 32 or 64 bits]) giving the
length of the following data in bytes,... |
import pathlib
from typing import Optional
from cumulusci.core.exceptions import TaskOptionsError
from cumulusci.core.utils import process_bool_arg, process_list_arg
from cumulusci.salesforce_api.metadata import ApiDeploy
from cumulusci.salesforce_api.package_zip import MetadataPackageZipBuilder
from cumulusci.tasks.sa... |
from karmabot.core.facets import Facet
from karmabot.core.commands import CommandSet, thing
import random
predictions = [ "As I see it, yes",
"It is certain",
"It is decidedly so",
"Most likely",
"Outlook good",
"Signs point to yes",
"Without a doubt",
"Yes",
"Yes - definitely",
"You may rely on it",... |
"""
"""
from smartcard.System import readers
from smartcard.pcsc.PCSCPart10 import (SCARD_SHARE_DIRECT,
SCARD_LEAVE_CARD, SCARD_CTL_CODE, getTlvProperties)
for reader in readers():
cardConnection = reader.createConnection()
cardConnection.connect(mode=SCARD_SHARE_DIRECT,
disposition=SCARD_LEAVE_CARD... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0010_auto_20170530_1509'),
]
operations = [
migrations.AddField(
model_name='corpus',
name='date_ended',
fiel... |
import sys
from . import (
utils, env, defs, context, layers, parser, preprocessor, loader, analyzer,
generator)
LAYERS = (
(parser.Parser, "parse"),
(preprocessor.Preprocessor, "transform_ast"),
(loader.Loader, "expand_ast"),
(analyzer.Analyzer, "expand_ast"),
(generator.Generator, "expand_... |
from bda.plone.discount import UUID_PLONE_ROOT
from bda.plone.discount.tests import Discount_INTEGRATION_TESTING
from bda.plone.discount.tests import set_browserlayer
from plone.uuid.interfaces import IUUID
import unittest2 as unittest
class TestDiscount(unittest.TestCase):
layer = Discount_INTEGRATION_TESTING
... |
'''
YARN Cluster Metrics
--------------------
yarn.metrics.appsSubmitted The number of submitted apps
yarn.metrics.appsCompleted The number of completed apps
yarn.metrics.appsPending The number of pending apps
yarn.metrics.appsRunning The number of running apps
yarn.metrics.appsF... |
def extractRoontalesCom(item):
'''
Parser for 'roontales.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'),
('Loiterous', 'Loiterous', ... |
try:
import pymysql
pymysql.install_as_MySQLdb()
except ImportError:
pass |
def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n - 1 to helper
hanoi(n - 1, source, target, helper)
# move disk from source peg to target peg
if source:
target.append(source.pop())
# move tower of size n-1 from helper to target
hanoi(... |
import itertools
import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_allclose
from pvlib import atmosphere
from pvlib import solarposition
latitude, longitude, tz, altitude = 32.2, -111, 'US/Arizona', 700
times = pd.date_range(start='20140626', end='20140626', freq='6h', tz=tz)
ephem_d... |
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.utils.decorators import method_decorator
from ..core.app import SatchlessApp
from . import models
class Or... |
"""Utility functions for handling and fetching repo archives in zip format."""
from __future__ import absolute_import
import os
import tempfile
from zipfile import ZipFile
import requests
try:
# BadZipfile was renamed to BadZipFile in Python 3.2.
from zipfile import BadZipFile
except ImportError:
from zipfi... |
from base import StreetAddressValidation, AddressValidation
UPS_XAV_CONNECTION = 'https://onlinetools.ups.com/ups.app/xml/XAV'
UPS_XAV_CONNECTION_TEST = 'https://wwwcie.ups.com/ups.app/xml/XAV'
UPS_AV_CONNECTION = 'https://onlinetools.ups.com/ups.app/xml/AV'
UPS_AV_CONNECTION_TEST = 'https://wwwcie.ups.com/ups.app/xml/... |
import code
import sys
from awesomestream.jsonrpc import Client
def main():
try:
host = sys.argv[1]
except IndexError:
host = 'http://localhost:9997/'
banner = """>>> from awesomestream.jsonrpc import Client
>>> c = Client('%s')""" % (host,)
c = Client(host)
code.interact(banner, loc... |
import uuid
import socket
import time
__appname__ = "pymessage"
__author__ = "Marco Sirabella, Owen Davies"
__copyright__ = ""
__credits__ = "Marco Sirabella, Owen Davies"
__license__ = "new BSD 3-Clause"
__version__ = "0.0.3"
__maintainers__ = "Marco Sirabella, Owen Davies"
__email__ = "ms... |
from diesel import Loop, fork, Application, sleep
def sleep_and_print(num):
sleep(1)
print num
sleep(1)
a.halt()
def forker():
for x in xrange(5):
fork(sleep_and_print, x)
a = Application()
a.add_loop(Loop(forker))
a.run() |
"""
zine.forms
~~~~~~~~~~
The form classes the zine core uses.
:copyright: (c) 2010 by the Zine Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from copy import copy
from datetime import datetime
from zine.i18n import _, lazy_gettext, list_languages
from zine.app... |
from falcor import *
def render_graph_BSDFViewer():
g = RenderGraph("BSDFViewerGraph")
loadRenderPassLibrary("AccumulatePass.dll")
loadRenderPassLibrary("BSDFViewer.dll")
BSDFViewer = createPass("BSDFViewer")
g.addPass(BSDFViewer, "BSDFViewer")
AccumulatePass = createPass("AccumulatePass")
g... |
from django.conf.urls.defaults import *
from django_de.apps.authors.models import Author
urlpatterns = patterns('django.views.generic.list_detail',
(r'^$', 'object_list',
dict(
queryset = Author.objects.order_by('name', 'slug'),
template_object_name = 'author',
allow_empt... |
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from djangoautoconf.local_key_manager import get_default_admin_username, \
get_default_admin_password
from djangoautoconf.management.commands.web_manage_tools.user_creator import create_admin
def create_default_admin():
... |
"""
Parsing resource files.
See base.py for the ParsedResource base class.
"""
import os.path
from pontoon.sync.formats import (
compare_locales,
ftl,
json_extensions,
lang,
po,
silme,
xliff,
)
SUPPORTED_FORMAT_PARSERS = {
".dtd": silme.parse_dtd,
".ftl": ftl.parse,
".inc": silme... |
import astar
import os
import sys
import csv
import math
from difflib import SequenceMatcher
import unittest
class Station:
def __init__(self, id, name, position):
self.id = id
self.name = name
self.position = position
self.links = []
def build_data():
"""builds the 'map' by read... |
from __future__ import print_function, division, absolute_import
import numpy as np
import astropy
import astropy.units as u
import marvin.tools
from marvin.tools.quantities.spectrum import Spectrum
from marvin.utils.general.general import get_drpall_table
from marvin.utils.plot.scatter import plot as scatplot
from mar... |
from djpcms import sites
if sites.settings.CMS_ORM == 'django':
from djpcms.core.cmsmodels._django import *
elif sites.settings.CMS_ORM == 'stdnet':
from djpcms.core.cmsmodels._stdnet import *
else:
raise NotImplementedError('Objecr Relational Mapper {0} not available for CMS models'.format(sites.settings.C... |
import os
import tempfile
from rest_framework import status
from hs_core.hydroshare import resource
from .base import HSRESTTestCase
class TestPublicResourceFlagsEndpoint(HSRESTTestCase):
def setUp(self):
super(TestPublicResourceFlagsEndpoint, self).setUp()
self.tmp_dir = tempfile.mkdtemp()
... |
import misc
id_supported = False
_type = ["1","10"]
def scrap_manga(link, chapter):
chapter[1] = {}
tmp = link.split("/")[-1]
if tmp.isdigit():
id_ = tmp
link = "http://e621.net/pool/show.json?id=%s"%(id_)
j = misc.download_json(link)
name = j["name"]
total = j["post_... |
import setuptools
try:
import multiprocessing
assert multiprocessing
except ImportError:
pass
setuptools.setup(
name='orwell.agent',
version='0.0.1',
description='Agent connecting to the game server.',
author='',
author_email='',
packages=setuptools.find_packages(exclude="test"),
... |
"""
.. module:: burpui.misc.backend.burp2
:platform: Unix
:synopsis: Burp-UI burp2 backend module.
.. moduleauthor:: Ziirish <hi+burpui@ziirish.me>
"""
import re
import os
import time
import json
from collections import OrderedDict
from .burp1 import Burp as Burp1
from .interface import BUIbackend
from .utils.b... |
from enum import Enum
from typing import List, Any, cast
import yass
from tutorial.base_types_external import Integer
class ExpirationHandler(yass.BaseTypeHandler):
def readBase(self, reader: yass.Reader) -> 'Expiration':
return Expiration(
reader.readZigZagInt()
)
def writeBase(self... |
import re
from nexusmaker.tools import natsort
is_combined_cognate = re.compile(r"""(\d+)([a-z]+)""")
class CognateParser(object):
UNIQUE_IDENTIFIER = "u_"
def __init__(self, strict=True, uniques=True, sort=True):
"""
Parses cognates.
- strict (default=True): remove dubious cognates (?)... |
"""Tests for analyzer
"""
import json
import TestGyp
found = 'Found dependency'
found_all = 'Found dependency (all)'
not_found = 'No dependencies'
def _CreateConfigFile(files, additional_compile_targets, test_targets=[]):
"""Creates the analyzer config file, which is used as the input to analyzer.
See description o... |
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('entries', '0005_resultsmode_json'),
]
operations = [
migrations.AlterField(
model_name='resultsmode',
name='json',
field=models.TextField(default='', blank=T... |
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.utils import durationToSeconds, ipAddressToShow, ircLower, now
from zope.interface import implementer
from... |
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpatterns = [
url(r'^$', T... |
import json
from json_url_rewriter import config
from json_url_rewriter.rewrite import URLRewriter
class HeaderToPathPrefixRewriter(object):
"""
A rewriter to take the value of a header and prefix any path.
"""
def __init__(self, keys, base, header_name):
self.keys = keys
self.base = bas... |
def extractSweetjamtranslationsCom(item):
'''
Parser for 'sweetjamtranslations.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'),
('Loite... |
def extractMiratlsWordpressCom(item):
'''
Parser for 'miratls.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'),
('Loiterous', ... |
from textwrap import dedent
from sympy import (
symbols, Integral, Tuple, Dummy, Basic, default_sort_key, Matrix,
factorial, true)
from sympy.combinatorics import RGS_enum, RGS_unrank, Permutation
from sympy.utilities.iterables import (
_partition, _set_partitions, binary_partitions, bracelets, capture,
... |
from pypom import Region
from selenium.webdriver.common.by import By
from base import Base
class Collections(Base):
"""Collections page."""
_item_locator = (By.CSS_SELECTOR, '.item')
def wait_for_page_to_load(self):
self.wait.until(lambda _: len(self.collections) > 0 and
self... |
from __future__ import unicode_literals
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.wagtailcore.models import Page
from wagtail.wagtailcore import fields
from wagtail.wagtailadmin.edit_handlers import FieldPanel
from wagtail.wagtailadmin.edit_handlers import InlinePanel
from wa... |
import eqpy
import sympy
from eqpy._utils import raises
def test_constants():
assert eqpy.nums.Catalan is sympy.Catalan
assert eqpy.nums.E is sympy.E
assert eqpy.nums.EulerGamma is sympy.EulerGamma
assert eqpy.nums.GoldenRatio is sympy.GoldenRatio
assert eqpy.nums.I is sympy.I
assert eqpy.nums.n... |
from contextlib import contextmanager
from datetime import datetime
from django import forms
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.core import validators
from django.db import models
from django.utils import translation
from django.utils.encoding import sma... |
def extractVodkatranslationsCom(item):
'''
Parser for 'vodkatranslations.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Ordinary I and Extraordinary Them', 'Ordinary I and Extraordinar... |
from __future__ import unicode_literals
from aldryn_client import forms
class Form(forms.BaseForm):
plugin_module = forms.CharField('Plugin module name', initial='Generic')
plugin_name = forms.CharField('Plugin name', initial='Facebook Comments')
plugin_template = forms.CharField('Plugin Template', initial=... |
from django.conf.urls.defaults import *
from models import Entry, Tag
from django.views.generic.dates import ArchiveIndexView, DateDetailView
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^/?$', ArchiveIndexView.as_view(model=Entry, date_field="published_on"), name="news-main"),
... |
import logging
from django.http import HttpResponse
from receiver.submitresponse import SubmitResponse
def duplicate_attachment(way_handled, additional_params):
'''Return a custom http response associated the handling
of the xform. In this case, telling the sender that
they submitted a duplicate
... |
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.test import TestCase
from models import Student, StudyGroup, Task, Lab, Subject, GroupSubject
class PortalTest(TestCase):
def setUp(self):
self.study_group1 = StudyGroup.objects.create(name="10А")
... |
'''Windowing and user-interface events.
This module allows applications to create and display windows with an
OpenGL context. Windows can be created with a variety of border styles
or set fullscreen.
You can register event handlers for keyboard, mouse and window events.
For games and kiosks you can also restrict the i... |
from .working_gif import working_encoded
from .splash import SplashScreen, Spinner, CheckProcessor
from .multilistbox import MultiListbox
from .utils import set_widget_state, set_binding, set_button_action, set_tab_order
from .tooltip import ToolTip |
"""The freesurfer module provides basic functions for interfacing with
freesurfer tools.
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpath(os.path.join(filepath, '../../testing/data'))
>>>... |
from . import domainresource
class TestScript(domainresource.DomainResource):
""" Describes a set of tests.
A structured set of tests against a FHIR server implementation to determine
compliance against the FHIR specification.
"""
resource_type = "TestScript"
def __init__(self, jsondict=None, st... |
import shelve, time, random
def main(connection, info) :
"""This is the old plugin"""
if info["message"].startswith("\x01ACTION") and info["message"].endswith("\x01") :
on_ACTION(connection, info)
return None
seendb = shelve.open("seen.db", writeback=True)
if not seendb.has_key("users") ... |
import math
import random
import onmt
from torch.autograd import Variable
class Dataset(object):
def __init__(self, srcData, tgtData, batchSize, cuda, volatile=False):
self.src = srcData
if tgtData:
self.tgt = tgtData
assert(len(self.src) == len(self.tgt))
else:
... |
from __future__ import unicode_literals
from ..utils import AffineInitializer
def test_AffineInitializer_inputs():
input_map = dict(args=dict(argstr='%s',
),
dimension=dict(argstr='%s',
position=0,
usedefault=True,
),
environ=dict(nohash=True,
usedefault=True,
),
fixed_image=dict... |
name = "neurogenesis" |
from binding import *
from src.namespace import llvm
from src.Value import MDNode
from src.Instruction import Instruction, TerminatorInst
llvm.includes.add('llvm/Transforms/Utils/BasicBlockUtils.h')
SplitBlockAndInsertIfThen = llvm.Function('SplitBlockAndInsertIfThen',
ptr(Term... |
from __future__ import absolute_import
import mock
import os
from django.conf import settings
from sentry_sdk import Hub
TEST_ROOT = os.path.normpath(
os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir, os.pardir, "tests")
)
def pytest_configure(config):
# HACK: Only needed for testing!
... |
import pytest
from django.db import connection, IntegrityError
from .models import MyTree
def flush_constraints():
# the default db setup is to have constraints DEFERRED.
# So IntegrityErrors only happen when the transaction commits.
# Django's testcase thing does eventually flush the constraints but to
... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from markitup import settings
from markitup.markup import filter_func
from markitup.sanitize import sanitize_html
def apply_filter(request):
cleaned_data = sanitize_html(request.POST.get('data', ''), strip=True)
markup = ... |
"""
Doctest runner for 'birdhousebuilder.recipe.adagucserver'.
"""
__docformat__ = 'restructuredtext'
import os
import sys
import unittest
import zc.buildout.tests
import zc.buildout.testing
from zope.testing import doctest, renormalizing
optionflags = (doctest.ELLIPSIS |
doctest.NORMALIZE_WHITESPACE |... |
"""
API Issues to work out:
- MatrixTransform and STTransform both have 'scale' and 'translate'
attributes, but they are used in very different ways. It would be nice
to keep this consistent, but how?
- Need a transform.map_rect function that returns the bounding rectangle of
a rect after transformation... |
from x86asm import codePackageFromFile
from x86cpToMemory import CpToMemory
from pythonConstants import PythonConstants
import cStringIO
import excmem
def pyasm(scope,s):
cp = codePackageFromFile(cStringIO.StringIO(s),PythonConstants)
mem = CpToMemory(cp)
mem.MakeMemory()
mem.BindPythonFunctions(scope) |
"""
Custom Authenticator to use MediaWiki OAuth with JupyterHub
Requires `mwoauth` package.
"""
import json
import os
from asyncio import wrap_future
from concurrent.futures import ThreadPoolExecutor
from jupyterhub.handlers import BaseHandler
from jupyterhub.utils import url_path_join
from mwoauth import ConsumerToken... |
"""This program wraps an arbitrary command since gn currently can only execute
scripts."""
import os
import subprocess
import sys
from shutil import copy2
args = sys.argv[1:]
args[0] = os.path.abspath(args[0])
sys.exit(subprocess.call(args)) |
import os, glob
import stat, time
from ginga.misc import Bunch
from ginga import GingaPlugin
from ginga import AstroImage
from ginga.util import paths
from ginga.util.six.moves import map, zip
class FBrowserBase(GingaPlugin.LocalPlugin):
def __init__(self, fv, fitsimage):
# superclass defines some variables... |
from .cuda_products import gmt_func as gp_device
from .cuda_products import imt_func as ip_device
import numpy as np
import numba.cuda
import numba
import math
import random
from . import *
def sequential_rotor_estimation_chunks(reference_model_array, query_model_array, n_samples, n_objects_per_sample, mutation_probabi... |
__author__ = 'Jorge De La Cruz, Carmen Castano'
__copyright__ = 'Copyright (c) 2017 Jorge De La Cruz, Carmen Castano'
__license__ = 'BSD'
__maintainer__ = 'Jorge De La Cruz'
__email__ = 'delacruz@igm.rwth-aachen.de'
import sys
sys.path.append('/usr/lib/freecad/lib')
import FreeCAD as App
import Import
from datetime imp... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 0, transform = "Fisher", sigma = 0.0, exog_count = 100, ar_order = 0); |
"""
===========================
Upper Air Sounding Tutorial
===========================
Upper air analysis is a staple of many synoptic and mesoscale analysis
problems. In this tutorial we will gather weather balloon data, plot it,
perform a series of thermodynamic calculations, and summarize the results.
To learn more... |
""" Deploy and install a package to a target
"""
import os
import sys
import zipfile
from qisys import ui
import qisys.command
import qisys.parsers
import qipkg.package
def configure_parser(parser):
qisys.parsers.default_parser(parser)
qisys.parsers.deploy_parser(parser)
parser.add_argument("pkg_path")
def ... |
"""
SMQTK Web Applications
"""
import inspect
import logging
import os
import flask
import smqtk.utils
from smqtk.utils import plugin
class SmqtkWebApp (flask.Flask, smqtk.utils.Configurable, plugin.Pluggable):
"""
Base class for SMQTK web applications
"""
@classmethod
def impl_directory(cls):
... |
from __future__ import unicode_literals
from django.db import models
from smartmin.models import SmartModel, ActiveManager
class Post(SmartModel):
title = models.CharField(max_length=128,
help_text="The title of this blog post, keep it relevant")
body = models.TextField(help_text="T... |
from __future__ import absolute_import
import pkgutil
import six
MODEL_MOVES = {
"sentry.models.tagkey.TagKey": "sentry.tagstore.legacy.models.tagkey.TagKey",
"sentry.models.tagvalue.tagvalue": "sentry.tagstore.legacy.models.tagvalue.TagValue",
"sentry.models.grouptagkey.GroupTagKey": "sentry.tagstore.legac... |
from pyelectro import analysis as pye_analysis
from matplotlib import pyplot
file_name = "100pA_1a.csv"
t, v = pye_analysis.load_csv_data(file_name)
analysis_var = {
"peak_delta": 0.1,
"baseline": 0,
"dvdt_threshold": 2,
"peak_threshold": 0,
}
analysis = pye_analysis.IClampAnalysis(
v, t, analysis_v... |
import json
from django.test.utils import override_settings
import pytest
from pyquery import PyQuery
from fjord.base import views
from fjord.base.tests import (
LocalizingClient,
TestCase,
AnalyzerProfileFactory,
reverse
)
from fjord.base.views import IntentionalException
from fjord.search.tests import... |
"""
test_i3wm-formula
----------------------------------
Tests for `i3wm-formula` module.
"""
import unittest
from i3wm-formula import i3wm-formula
class TestI3wm-formula(unittest.TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
if __name__ == ... |
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E08000032'
addresses_name = 'parl.2017-06-08/Version 1/Democracy_Club__08June2017.tsvJune2017.tsv'
stations_name = 'parl.2017-06-08/Version 1/Democracy_Club__08... |
import os
import pytest
from datetime import time
from sport_systems import stats
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def response_1():
path = os.path.join(BASE_DIR, 'response-1.xml')
with open(path, 'rb') as fin:
data = fin.read()
return data
@pytest.fixture
def results_1():
re... |
from django.test import TestCase
from mock import Mock, patch
from paymentexpress.facade import Facade
from paymentexpress.gateway import AUTH, PURCHASE
from paymentexpress.models import OrderTransaction
from tests import (XmlTestingMixin, CARD_VISA, SAMPLE_SUCCESSFUL_RESPONSE,
SAMPLE_DECLINED_RESPON... |
import os.path
import sys
from genshi.builder import tag
from trac.admin import IAdminCommandProvider, IAdminPanelProvider
from trac.config import ListOption
from trac.core import *
from trac.perm import IPermissionRequestor
from trac.util import as_bool, is_path_below
from trac.util.compat import any
from trac.util.te... |
from acoustics.decibel import *
def test_dbsum():
assert(abs(dbsum([10.0, 10.0]) - 13.0103) < 1e-5)
def test_dbmean():
assert(dbmean([10.0, 10.0]) == 10.0)
def test_dbadd():
assert(abs(dbadd(10.0, 10.0) - 13.0103) < 1e-5)
def test_dbsub():
assert(abs(dbsub(13.0103, 10.0) - 10.0) < 1e-5)
def test_dbmul()... |
from djangothis.app import read_yaml, read_yaml_file, watchfile |
import unittest
from rpaas import plan, storage
class MongoDBStorageTestCase(unittest.TestCase):
def setUp(self):
self.storage = storage.MongoDBStorage()
self.storage.db[self.storage.quota_collection].remove()
self.storage.db[self.storage.plans_collection].remove()
self.storage.db[se... |
"""
Collection of query wrappers / abstractions to both facilitate data
retrieval and to reduce dependency on DB-specific API.
"""
from contextlib import contextmanager
from datetime import date, datetime, time
from functools import partial
import re
from typing import Iterator, Optional, Union, overload
import warning... |
from webkitpy.common.checkout.scm.scm_mock import MockSCM
from webkitpy.common.net.buildbot.buildbot_mock import MockBuildBot
from webkitpy.common.net.web_mock import MockWeb
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.layout_tests.port.factory import PortFactory
from webkitpy.layout... |
import numpy as np
from ._layout import Layout
from ._multivector import MultiVector
class ConformalLayout(Layout):
r"""
A layout for a conformal algebra, which adds extra constants and helpers.
Typically these should be constructed via :func:`clifford.conformalize`.
.. versionadded:: 1.2.0
Attribut... |
"""
Menu-driven login system
Contribution - Griatch 2011
This is an alternative login system for Evennia, using the
contrib.menusystem module. As opposed to the default system it doesn't
use emails for authentication and also don't auto-creates a Character
with the same name as the Player (instead assuming some sort of... |
"""Runs Android's lint tool."""
import argparse
import os
import re
import sys
import traceback
from xml.dom import minidom
from util import build_utils
_SRC_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),
'..', '..', '..'))
def _OnStaleMd5(changes, lint_path, con... |
"""
Concurrent downloaders
"""
import os
import sys
import signal
import logging
import itertools
from functools import partial
from concurrent.futures import ProcessPoolExecutor
from pomp.core.base import (
BaseCrawler, BaseDownloader, BaseCrawlException,
)
from pomp.contrib.urllibtools import UrllibDownloadWorker... |
import logging
import os
import time
import traceback
import urlparse
import random
import csv
from chrome_remote_control import page_test
from chrome_remote_control import util
from chrome_remote_control import wpr_modes
class PageState(object):
def __init__(self):
self.did_login = False
class PageRunner(object)... |
"""Migrate review conditions from settings
Revision ID: 933665578547
Revises: 02bf20df06b3
Create Date: 2020-04-02 11:13:58.931020
"""
import json
from collections import defaultdict
from uuid import uuid4
from alembic import context, op
from indico.modules.events.editing.models.editable import EditableType
revision = ... |
"""
PynamoDB exceptions
"""
from typing import Any, Optional
import botocore.exceptions
class PynamoDBException(Exception):
"""
A common exception class
"""
def __init__(self, msg: Optional[str] = None, cause: Optional[Exception] = None) -> None:
self.msg = msg
self.cause = cause
... |
"""
handler base
~~~~~~~~~~~~
Presents a reasonable base class for a ``Handler`` object, which handles
responding to an arbitrary "request" for action. For example, ``Handler``
is useful for responding to HTTP requests *or* noncyclical realtime-style
requests, and acts as a base class for ``Page`` and ``Ser... |
import math
import numpy as np
import relations
def _avg_difference(npiece, side):
if side == relations.LEFT:
difference = npiece[:, 0] - npiece[:, 1]
elif side == relations.RIGHT:
difference = npiece[:, -1] - npiece[:, -2]
elif side == relations.UP:
difference = npiece[0, :] - npiec... |
import RPi.GPIO as GPIO
import os
import time
import datetime
import glob
import MySQLdb
from time import strftime
import serial
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter = 0
... |
"""High level API for learning. See the @{$python/contrib.learn} guide.
@@BaseEstimator
@@Estimator
@@Trainable
@@Evaluable
@@KMeansClustering
@@ModeKeys
@@ModelFnOps
@@MetricSpec
@@PredictionKey
@@DNNClassifier
@@DNNRegressor
@@DNNLinearCombinedRegressor
@@DNNLinearCombinedClassifier
@@LinearClassifier
@@LinearRegress... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.