code stringlengths 1 199k |
|---|
cases = [
('pmt.py -s 1 -n 20 populations, first without state filter',
'pmt.py -s 1 -n 20 populations'),
('pmt.py -s 2 -n 20 populations filter3, state filter limits population to 3',
'pmt.py -s 2 -n 20 populations filter3')
] |
from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.Filter import Filter
from PLC.SliceTags import SliceTag, SliceTags
from PLC.Persons import Person, Persons
from PLC.Sites import Site, Sites
from PLC.Nodes import Nodes
from PLC.Slices import Slice, Slices
from PL... |
""" Specify the NetworkNode with its action, context-menus """
import os
from traits.api import Instance, Str, Any
from traitsui.api import TreeNode
from traitsui.menu import Menu, Action, Separator
from cviewer.plugins.cff2.cnetwork import CNetwork
import logging
logger = logging.getLogger('root.'+__name__)
class CNet... |
"""
Build extension modules, package and install Fatiando.
"""
import sys
import os
from setuptools import setup, Extension, find_packages
import numpy
import versioneer
versioneer.VCS = 'git'
versioneer.versionfile_source = 'fatiando/_version.py'
versioneer.versionfile_build = 'fatiando/_version.py'
versioneer.tag_pre... |
from django.utils import baseconv
from django.template.defaultfilters import slugify
import time
def slugify_uniquely(value, model, slugfield="slug"):
"""
Returns a slug on a name which is unique within a model's table
"""
suffix = 0
potential = base = slugify(value)
if len(potential) == 0:
... |
BYTE_BITS = 8
MATCH_BITS = 6
MATCH_MIN = 3
MATCH_MAX = (1 << MATCH_BITS) + (MATCH_MIN - 1)
MATCH_RANGE = range(MATCH_MIN, MATCH_MAX + 1) # Length 64, fine on 2.x.
OFFSET_MASK = (1 << (16 - MATCH_BITS)) - 1
LEMPEL_SIZE = 1024
def size_encode(size, dst=None):
"""
Encodes the given size in little-endian variab... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('heatcontrol', '0015_heatcontrol_profile_add_holes'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='end',
... |
from __future__ import absolute_import
import hashlib
import jwt
from six.moves.urllib.parse import quote
from sentry.shared_integrations.exceptions import ApiError
def percent_encode(val):
# see https://en.wikipedia.org/wiki/Percent-encoding
return quote(val.encode("utf8", errors="replace")).replace("%7E", "~"... |
"""
Clickjacking Protection Middleware.
This module provides a middleware that implements protection against a
malicious site loading resources from your site in a hidden frame.
"""
from django.conf import settings
class XFrameOptionsMiddleware(object):
"""
Middleware that sets the X-Frame-Options HTTP header i... |
from django.conf.urls.defaults import url, patterns
urlpatterns = patterns('tutorial.views',
url(r'^$', 'tutorial', name='tutorial'),
) |
from __future__ import absolute_import
from __future__ import unicode_literals
from base64 import b64encode
from django_digest.test.methods import WWWAuthenticateError, BaseAuth
class BasicAuth(BaseAuth):
def authorization(self, request, response):
if response is not None:
challenges = self._aut... |
"""
Runs polishing binary in parallel and concatentes output
"""
from __future__ import absolute_import
from __future__ import division
import logging
import subprocess
import os
from collections import defaultdict
from flye.polishing.alignment import (make_alignment, get_contigs_info,
... |
import os
from traits.api import HasTraits
from traitsui.api import View, Item
from enable.savage.trait_defs.ui.svg_button import SVGButton
pause_icon = os.path.join(os.path.dirname(__file__), 'player_pause.svg')
resume_icon = os.path.join(os.path.dirname(__file__), 'player_play.svg')
class SVGDemo(HasTraits):
paus... |
"""
BNF reference: http://theory.lcs.mit.edu/~rivest/sexp.txt
<sexp> :: <string> | <list>
<string> :: <display>? <simple-string> ;
<simple-string> :: <raw> | <token> | <base-64> | <hexadecimal> |
<quoted-string> ;
<display> :: "[" <simple-string> "]" ;
<raw> :: <decimal> ":" <bytes> ;
<decim... |
import asyncio
from unittest.mock import MagicMock
def SimpleCoroutineMock(f=lambda *args, **kwargs: None):
builder = CoroutineMockBuilder()
return builder.addDelegate(f).build().mock()
class CoroutineMock(object):
# Handy for debugging failing tests in the debugger.
__blocking_dict = {}
def __init_... |
from collections import OrderedDict
import unittest
import numpy
from ConfigSpace.configuration_space import ConfigurationSpace
from ConfigSpace.hyperparameters import CategoricalHyperparameter
from autosklearn.pipeline.components.classification.liblinear_svc import LibLinear_SVC
from autosklearn.pipeline.components.cl... |
from __future__ import unicode_literals
from tests.utils import ConverterTestCase
class EnumTestCase(ConverterTestCase):
def test_empty(self):
self.assertGeneratedOutput(
"""
enum Bar {
};
""",
"""
from enum import Enum
clas... |
"""
ios.py
Handle arguments, configuration file
@author: K.Edeline
"""
import sys
import argparse
import configparser
import logging
import shutil
class IOManager(object):
"""
extend me
"""
#DEFAULT_CONFIG_LOC="/tmp/deploypl.ini"
PKG_FILE = "packages.txt"
def __init__(self, child=None, **kwargs):
... |
from django.views.generic import TemplateView
from django.shortcuts import render_to_response
from django.template import RequestContext
from braces.views import LoginRequiredMixin
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard.html'
def get(self, *args, **kwargs):
ret... |
from btmux_template_io.item_table import ITEM_TABLE
from btmux_template_io.parsers.ssw.crit_mapping import PHYSICAL_WEAPON_MAP, \
EQUIPMENT_MAP
from . ammo import add_ammo
from . common import add_crits_from_locations
from . weapons import add_weapon
def populate_equipment(xml_root, unit_obj):
"""
Equipment... |
"""The image module provides basic functions for working with images in nipy.
Functions are provided to load, save and create image objects, along with
iterators to easily slice through volumes.
load : load an image from a file
save : save an image to a file
fromarray : create an image from a numpy array
Ex... |
from __future__ import unicode_literals
default_app_config = 'yepes.contrib.slugs.apps.SlugsConfig' |
"""Management command for uploading master json data for OCW courses"""
from django.core.management import BaseCommand
from course_catalog.etl.deduplication import generate_duplicates_yaml
class Command(BaseCommand):
"""Print course duplicates yaml"""
help = "Print course duplicates yaml"
def handle(self, *... |
import re
from django.conf import settings
from django.utils.html import strip_tags
import amo
from amo.helpers import absolutify
from amo.urlresolvers import reverse
from amo.utils import urlparams, epoch
from tags.models import Tag
from versions.compare import version_int
m_dot_n_re = re.compile(r'^\d+\.\d+$')
def ad... |
import zeit.newsletter.testing
class MetadataTest(zeit.newsletter.testing.SeleniumTestCase):
def test_form_should_save_entered_data_on_blur(self):
s = self.selenium
self.open('/repository/newsletter/@@checkout')
s.waitForElementPresent('id=metadata.subject')
s.assertValue('id=metadat... |
from .Base_Action import *
class ProfileAction(Base_Action):
def __init__(self, action_xml, root_action=None):
super(self.__class__, self).__init__(action_xml, root_action)
self.shouldUseLaunchSchemeArgsEnv = self.contents.get('shouldUseLaunchSchemeArgsEnv');
self.savedToolIdentifier = self.... |
class Error ( Exception ):
"""Exception class for Address exceptions"""
def __init__( self, message ) :
Exception.__init__(self,message) |
__version__ = '0.1.0'
from .reports import Report |
from __future__ import absolute_import
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "service.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
from django import forms
from dragnet.dll.models import File, Comment
class FileForm(forms.ModelForm):
"""Using a model form to expedite the creation of DLL records"""
class Meta:
model = File
exclude = ('date_created', 'date_modified', 'created_by',
'modified_by', )
class Com... |
"""
To start UNO for both Calc and Writer:
(Note that if you use the current_document command, it will open the Calc's current document since it's the first switch passed)
libreoffice "--accept=socket,host=localhost,port=18100;urp;StarOffice.ServiceManager" --norestore --nofirststartwizard --nologo --calc --writer
To s... |
__version__ = '0.9a4.dev1' # pragma: nocover |
import copy
import pandas as pd
from threeML.plugins.SpectrumLike import SpectrumLike
from threeML.utils.OGIP.response import InstrumentResponse
from threeML.utils.spectrum.binned_spectrum import (
BinnedSpectrumWithDispersion,
ChannelSet,
)
__instrument_name = "General binned spectral data with energy dispersi... |
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations
import django.db.models.deletion
import sentry.db.models.fields.foreignkey
class Migration(migrations.Migration):
# This flag is used to mark that a migration shouldn't be automatically run in
# production.... |
from django.conf.urls.defaults import *
from corehq import AccountingAdminInterfaceDispatcher
from corehq.apps.accounting.views import *
urlpatterns = patterns('corehq.apps.accounting.views',
url(r'^$', 'accounting_default', name='accounting_default'),
url(r'^accounts/(\d+)/$', ManageBillingAccountView.as_view(... |
from django.conf import settings
def MAX_USERNAME_LENGTH():
return getattr(settings, "MAX_USERNAME_LENGTH", 255)
def MAX_EMAIL_LENGTH():
return getattr(settings, "MAX_EMAIL_LENGTH", 255)
def REQUIRE_UNIQUE_EMAIL():
return getattr(settings, "REQUIRE_UNIQUE_EMAIL", True) |
"""Auto-generated file, do not edit by hand. PE metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_PE = PhoneMetadata(id='PE', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='1\\d{2}', possible_number_pattern='\\d{3... |
def extractDhragonisslytherinWordpressCom(item):
'''
Parser for 'dhragonisslytherin.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', 'translat... |
"""Auto-generated file, do not edit by hand. NF metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_NF = PhoneMetadata(id='NF', country_code=672, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='[13]\\d{5}', possible_number_pattern='\\d... |
"""Fichier contenant la classe SujetAide, détaillée plus bas."""
from abstraits.obase import BaseObj
from primaires.format.description import Description
from primaires.format.fonctions import supprimer_accents, couper_phrase
class SujetAide(BaseObj):
"""Classe représentant un sujet d'aide.
Un sujet d'aide est ... |
import copy
import types
from django.core.urlresolvers import reverse
from django.db.models.query import QuerySet
registry = []
def register(*args):
"""
Register urls, views, model instances and QuerySets to be potential
pages for menu items.
Example::
import simplemenu
simplemenu.regist... |
from setuptools import setup
setup(name='tagdog',
version='0.2',
description='Tag media files',
author='Albert Pham',
author_email='the.sk89q@gmail.com',
url='https://github.com/sk89q/TagDog',
install_requires=[
'titlecase',
'mutagen',
'pyechonest'
... |
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 = 7, transform = "Anscombe", sigma = 0.0, exog_count = 0, ar_order = 12); |
"""Module to find the closest match of a string in a list"""
from __future__ import unicode_literals
import re
import difflib
import six
find_best_control_match_cutoff = .6
class MatchError(IndexError):
"""A suitable match could not be found"""
def __init__(self, items = None, tofind = ''):
"""Init the ... |
__version__ = '1.3.7'
default_app_config = 'aldryn_redirects.apps.AldrynRedirects' |
import json
import shutil
import sys
import warnings
from itertools import zip_longest
import s3fs
from smart_open import open
from tqdm import tqdm
def session_type():
if 'IPython' not in sys.modules:
# IPython hasn't been imported, definitely not
return "python"
from IPython import get_ipython... |
import numpy as nm
try:
import matplotlib.pyplot as plt
import matplotlib as mpl
except (ImportError, RuntimeError):
plt = mpl = None
#print 'matplotlib import failed!'
from sfepy.base.base import output, pause
def spy(mtx, eps=None, color='b', **kwargs):
"""
Show sparsity structure of a `scipy.... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20161116_1209'),
]
operations = [
migrations.AddField(
model_name='workertype',
name='is_active',
f... |
from neurotune.controllers import SineWaveController
import sys
from neurotune import evaluators
from neurotune import optimizers
from neurotune import utils
if __name__ == "__main__":
showPlots = not ("-nogui" in sys.argv)
verbose = not ("-silent" in sys.argv)
sim_vars = {"amp": 65, "period": 250, "offset"... |
import json
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
from .base import Binding
from ..generic.websockets import WebsocketDemultiplexer
from ..sessions import enforce_ordering
class WebsocketBinding(Binding):
"""
Websocket-specific outgoing binding subclass t... |
"""
pakbase module
This module contains the base package class from which
all of the other packages inherit from.
"""
from __future__ import print_function
import os
import webbrowser as wb
import numpy as np
from numpy.lib.recfunctions import stack_arrays
from .modflow.mfparbc import ModflowParBc as mfparbc
from .... |
"""
A script for automated nagging emails based on passed in queries
These can be collated into several 'queries' through the use of multiple query files with
a 'query_name' param set eg: 'Bugs tracked for Firefox Beta (13)'
Once the bugs have been collected from Bugzilla they are sorted into buckets cc: assignee manag... |
import unittest
import operator
import six
from six.moves import range,reduce
import arybo.lib.mba_exprs as EX
from arybo.lib import MBA
from pytanque import expand_esf_inplace, simplify_inplace
class MBAExprsTest:
def setUp(self):
self.mba1 = MBA(1)
self.mba4 = MBA(4)
self.mba4.use_esf = Fa... |
"""
This is a tool to verify checksum hashes produced by LOCKSS against hashes
provided by a BagIt manifest document.
Invoke with -h for usage help.
Written by Stephen Eisenhauer
At University of North Texas Libraries
On 2013-04-17
Notes:
* The LOCKSS hash list will have more entries than we actually care about
(... |
import json
import os
import six
import tensorflow as tf
from PIL import Image
from luminoth.tools.dataset.readers import InvalidDataDirectory
from luminoth.tools.dataset.readers.object_detection import (
ObjectDetectionReader
)
from luminoth.utils.dataset import read_xml, read_image
WNIDS_FILE = 'data/imagenet_wni... |
from abc import ABCMeta, abstractmethod
import six
from django.db.models import Q
from dimagi.utils.chunked import chunked
class DomainFilter(six.with_metaclass(ABCMeta)):
@abstractmethod
def get_filters(self, domain_name):
"""Return a list of filters. Each filter will be applied to a queryset independe... |
"""Defines fixtures available to all tests."""
import pytest
from webtest import TestApp
from p101stat.app import create_app
from p101stat.database import db as _db
from p101stat.settings import TestConfig
from .factories import IdolFactory
@pytest.yield_fixture(scope='function')
def app():
"""An application for th... |
"""
Turn entities to and fro various representations.
This is the base Class and interface Class used to
transform strings of various forms to model objects
and model objects to strings of various forms.
"""
from tiddlyweb.serializer import NoSerializationError
from tiddlyweb.model.tiddler import string_to_tags_list
cl... |
import io
import json
import os
import unittest
from . import riskassessment
from .fhirdate import FHIRDate
class RiskAssessmentTests(unittest.TestCase):
def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', e... |
from django.conf import settings
from django.http import Http404
import os
import shutil
import time
import re
import urlparse
import urllib
from subprocess import call
from exceptions import ImageMagickException, ImageMagickConversionError, ImageMagickOSFileError
from cache_util import file_hash
from django.db.models ... |
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class ContactFormConfig(AppConfig):
"""The default AppConfig for admin which does autodiscovery."""
name = 'django_contact'
verbose_name = _("Contact") |
"""
A *lock* defines access to a particular subsystem or property of
Evennia. For example, the "owner" property can be impmemented as a
lock. Or the disability to lift an object or to ban users.
A lock consists of three parts:
- access_type - this defines what kind of access this lock regulates. This
just a string.... |
"""Kraken Framework."""
import logging
import os
__all__ = ['core', 'helpers', 'plugins', 'ui']
krakenPath = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..'))
if os.environ.get('KRAKEN_PATH', None) is None:
os.environ['KRAKEN_PATH'] = krakenPath
krakenExtsPath = os.path.join(kra... |
"""
Simple Scatter Plot with Labels
===============================
This example shows a basic scatter plot with labels created with Altair.
"""
import altair as alt
import pandas as pd
data = pd.DataFrame({
'x': [1, 3, 5, 7, 9],
'y': [1, 3, 5, 7, 9],
'label': ['A', 'B', 'C', 'D', 'E']
})
bars = alt.Chart(d... |
from datetime import datetime, timedelta
from rdr_service.dao.ghost_check_dao import GhostCheckDao
from tests.helpers.unittest_base import BaseTestCase
class GhostCheckDaoTest(BaseTestCase):
def test_loads_only_vibrent(self):
"""We might accidentally start flagging CE participants as ghosts if they're retur... |
"""
General Character commands usually availabe to all characters
"""
from django.conf import settings
from evennia.utils import utils, prettytable
from evennia.commands.default.muxcommand import MuxCommand
__all__ = ("CmdHome", "CmdLook", "CmdNick",
"CmdInventory", "CmdGet", "CmdDrop", "CmdGive",
... |
from corehq.dbaccessors.couchapps.all_docs import \
get_all_doc_ids_for_domain_grouped_by_db, get_doc_count_by_type, \
delete_all_docs_by_doc_type, get_doc_count_by_domain_type
from dimagi.utils.couch.database import get_db
from django.test import TestCase
class AllDocsTest(TestCase):
maxDiff = None
@cl... |
"""
tests.marshmallow.test_extension
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests for the :class:`MarshmallowAwareApp` to ensure that it will properly
register the extension and can be used, as well as testing the top level
schema.
"""
import pytest
from flask_marshmallow import fields
from fleaker import Schema
from fleaker.ma... |
"""
DataLab survey class. Gets data from any survey
available through the NOAO datalab-client.
"""
import pdb
import numpy as np
import warnings
from astropy.table import Table
from astropy import units
import warnings
import sys, os
try:
from dl import queryClient as qc, authClient as ac
from dl.helpers.utils ... |
from __future__ import absolute_import, division, print_function
from itertools import chain
from dynd import nd
import datashape
from datashape.internal_utils import IndexCallable
from datashape import discover
from functools import partial
from ..dispatch import dispatch
from blaze.expr import Projection, Field
from ... |
from __future__ import absolute_import
from sentry.testutils import AcceptanceTestCase
class AuthTest(AcceptanceTestCase):
def enter_auth(self, username, password):
# disable captcha as it makes these tests flakey (and requires waiting
# on external resources)
with self.settings(RECAPTCHA_PU... |
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'songaday_searcher.settings')
app = Celery('songaday_searcher')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) |
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 = "Lag1Trend", cycle_length = 0, transform = "Anscombe", sigma = 0.0, exog_count = 20, ar_order = 12); |
import numpy as np
from scipy import integrate
from .kern import Kern
from ...core.parameterization import Param
from ...util.linalg import tdot
from ... import util
from ...util.config import config # for assesing whether to use cython
from paramz.caching import Cache_this
from paramz.transformations import Logexp
try... |
import Gaffer
import GafferUI
import GafferScene
Gaffer.Metadata.registerNode(
GafferScene.SceneSwitch,
"description",
"""
Chooses between multiple input scene, passing through the
chosen input to the output.
""",
plugs = {
"index" : [
"description",
"""
The index of the input which is passed through.... |
from . import *
class TestTemplateUse(TestCase):
def test_resized_img_src(self):
@self.app.route('/resized_img_src')
def use():
return render_template_string('''
<img src="{{ resized_img_src('cc.png') }}" />
'''.strip())
res = self.client.get('/resized... |
from cStringIO import StringIO
from datetime import datetime
import errno
import hashlib
import os.path
import posixpath
import re
import shutil
import sys
import unicodedata
from genshi.builder import tag
from trac.admin import AdminCommandError, IAdminCommandProvider, PrefixList, \
console_date... |
import time
from prometheus_client import Counter, Histogram
from prometheus_client import start_http_server
from flask import request
FLASK_REQUEST_LATENCY = Histogram('flask_request_latency_seconds', 'Flask Request Latency',
['method', 'endpoint'])
FLASK_REQUEST_COUNT = Counter('flask_request_count', 'Flask Reque... |
from datetime import datetime
import functools
import os
import uuid
from time import time
from django.conf import settings
from django_statsd.clients import statsd
from mock import Mock
from requests import post
from suds import client as sudsclient
from suds.transport import Reply
from suds.transport.http import Http... |
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
import mozdns
from mozdns.domain.models import Domain
from mozdns.view.models import View
from mozdns.mixins import ObjectUrlMixin, DisplayMixin
from mozdns.validation import validate_first_label, validate_name
from mozd... |
from pandac.PandaModules import *
from direct.directnotify.DirectNotifyGlobal import directNotify
from direct.task import Task
from .DistributedNodeAI import DistributedNodeAI
from .CartesianGridBase import CartesianGridBase
class DistributedCartesianGridAI(DistributedNodeAI, CartesianGridBase):
notify = directNoti... |
from .AlFeatureTemplate import AlFeatureTemplate
from .sensorCountRoutine import AlFeatureSensorCountRoutine
import numpy as np
class AlFeatureSensorCount(AlFeatureTemplate):
def __init__(self, normalize=False):
"""
Initialization of Template Class
:return:
"""
AlFeatureTempl... |
from collections import OrderedDict
import pytest
import numpy as np
import pandas as pd
from pandas import Index, Series, DataFrame, date_range
from pandas.core.indexes.datetimes import Timestamp
from pandas.compat import range
from pandas import compat
import pandas.io.formats.printing as printing
from pandas.util.te... |
from sfepy import data_dir
filename_mesh = data_dir + '/meshes/2d/special/circle_in_square.mesh'
dim = 2
field_1 = {
'name' : 'scalar_field',
'dtype' : 'real',
'shape' : 'scalar',
'region' : 'Omega',
'approx_order' : 1,
}
field_2 = {
'name' : 'vector_field',
'dtype' : 'real',
'shape' : '... |
from builtins import str
from builtins import range
from builtins import object
import json
import os
import solnlib.utils as utils
from splunktaucclib.global_config import GlobalConfig, GlobalConfigSchema
'''
Usage Examples:
setup_util = Setup_Util(uri, session_key)
setup_util.get_log_level()
setup_util.get_proxy_sett... |
import abc
import math
import six
import sqlalchemy as sa
from marshmallow_sqlalchemy.convert import ModelConverter
from marshmallow_pagination import pages
converter = ModelConverter()
def convert_value(row, attr):
field = converter._get_field_class_for_property(attr.property)
value = getattr(row, attr.key)
... |
import sys
import uos
try:
uos.VfsFat
except AttributeError:
print("SKIP")
sys.exit()
class RAMFS:
SEC_SIZE = 512
def __init__(self, blocks):
self.data = bytearray(blocks * self.SEC_SIZE)
def readblocks(self, n, buf):
#print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
... |
import StringIO
import xlsxwriter
"""
Web app module.
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status__ = 'Development'
def generate_cwr_report_excel(cwr):
output = StringIO.StringIO()
workbook = xlsxwriter.Workbook(output, {'in_memory': True})
_generate_cwr_report_excel_general(wo... |
'''
Created on 2015年8月24日
@author: hustcc
'''
import datetime
import time
def now_datetime_string():
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def now_datetime():
return datetime.datetime.now()
def now_date_string():
return datetime.datetime.now().strftime("%Y-%m-%d")
def now_timestamp():... |
import numpy as np
import pycuda.driver as drv
from neon.backends.nervanagpu import NervanaGPU
from openai_gemm import matmul
ng = NervanaGPU()
print drv.Context.get_current().get_device().name()
config = (
# m, n, k, AT, BT (row order)
( 16, 1760, 1760, False, False),
( 32, 1760, 1760, Fal... |
import localpackage
import os
import stat
import shutil
class XRootD(localpackage.LocalPackage):
""" Base XRootD installer."""
def __init__(self, name, system, version):
""" Initialise the XRootD package."""
super(XRootD, self).__init__(name, system)
self._version = version
def get_t... |
'''
Hello Flask
Latest version can be found at https://github.com/dakside/pydemo
References:
Python documentation:
https://docs.python.org/
Flask documentation:
http://flask.pocoo.org/
PEP 0008 - Style Guide for Python Code
https://www.python.org/dev/peps/pep-0008/
PEP 0257 - Pyt... |
"""
Functional test
Anonymous Epic
Storyboard is defined within the comments of the program itself
"""
import unittest
from flask import url_for
from biblib.views.http_errors import NO_PERMISSION_ERROR
from biblib.tests.stubdata.stub_data import UserShop, LibraryShop
from biblib.tests.base import TestCaseDatabase, Mock... |
"""
neighs information
------------------
Auxiliar class in order to manage the information of the neighbourhood
returned by the retrievers.
Due to the complexity of the structure it is convenient to put altogether
in a single class and manage in a centralized way all the different
interactions with neighs_info in the ... |
from cadnano.gui.views.styles import *
from PyQt5.QtGui import QColor, QFont, QFontMetricsF
VIRTUALHELIXHANDLEITEM_RADIUS = 30
VIRTUALHELIXHANDLEITEM_STROKE_WIDTH = 2
PATH_BASE_WIDTH = 20 # used to size bases (grid squares, handles, etc)
PATH_HELIX_HEIGHT = 2 * PATH_BASE_WIDTH # staple + scaffold
PATH_HELIX_PADDING =... |
import pytest
from plumbum.colorlib.styles import ANSIStyle, Color, AttributeNotFound, ColorNotFound
from plumbum.colorlib.names import color_html, FindNearest
class TestNearestColor:
def test_exact(self):
assert FindNearest(0,0,0).all_fast() == 0
for n,color in enumerate(color_html):
# ... |
from sfa.util.sfalogging import logger
from sfa.trust.credential import Credential
from sfa.trust.abac_credential import ABACCredential
import json
import re
class CredentialFactory:
UNKNOWN_CREDENTIAL_TYPE = 'geni_unknown'
# Static Credential class method to determine the type of a credential
# string depe... |
from __future__ import absolute_import, division
from klein.app import Klein, run, route, resource
from klein._plating import Plating
from ._version import __version__ as _incremental_version
__version__ = _incremental_version.base()
__author__ = "The Klein contributors (see AUTHORS)"
__license__ = "MIT"
__copyright__... |
from dask.callbacks import Callback
from os import getcwd, remove
from os.path import join, exists
from dask.diagnostics import ProgressBar
from dask.multiprocessing import get as get_proc
import toolz
import json
class NekCallback(Callback):
def __init__(self, case):
self.case = case
self.cwd = ge... |
from .base import *
from .controller import * |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.