code stringlengths 1 199k |
|---|
"""
Fixture to configure XQueue response.
"""
import json
import requests
from common.test.acceptance.fixtures import XQUEUE_STUB_URL
class XQueueResponseFixtureError(Exception):
"""
Error occurred while configuring the stub XQueue.
"""
pass
class XQueueResponseFixture(object):
"""
Configure the... |
import copy
import json
import logging
import os
import sys
from lxml import etree
from lxml.etree import Element, ElementTree, XMLParser
from xblock.core import XML_NAMESPACES
from xblock.fields import Dict, Scope, ScopeIds
from xblock.runtime import KvsFieldData
import dogstats_wrapper as dog_stats_api
from xmodule.m... |
import glob
import os
import re
import llnl.util.tty as tty
from spack import *
from spack.pkg.builtin.openfoam import (
OpenfoamArch,
add_extra_files,
mplib_content,
rewrite_environ_files,
write_environ,
)
from spack.util.environment import EnvironmentModifications
class OpenfoamOrg(Package):
"... |
import sys
sys.path.insert(0,'../../../build/swig/python')
import os
import yui
log = yui.YUILog.instance()
log.setLogFileName("/tmp/debug.log")
log.enableDebugLogging( True )
appl = yui.YUI.application()
appl.setApplicationTitle("Show dialogs example")
class Info(object):
def __init__(self,title,richtext,text):
... |
"""Serves static content for "static_dir" and "static_files" handlers."""
import base64
import errno
import httplib
import mimetypes
import os
import os.path
import re
import zlib
from google.appengine.api import appinfo
from google.appengine.tools import augment_mimetypes
from google.appengine.tools.devappserver2 impo... |
from util import *
"""
Tsu bot responds to all queries with a Sun Tsu sayings
Quoted from Sun Tsu's The Art of War
Translated by LIONEL GILES, M.A. 1910
Hosted by the Gutenberg Project
http://www.gutenberg.org/
"""
pairs = (
(r'quit',
( "Good-bye.",
"Plan well",
"May victory be your future")),
(r'[^\?]*\?... |
import tempfile
import uuid
from keystone import config
from keystone import exception
from keystone.openstack.common import jsonutils
from keystone.policy.backends import rules
from keystone import tests
from keystone.tests import test_v3
CONF = config.CONF
DEFAULT_DOMAIN_ID = CONF.identity.default_domain_id
class Ide... |
""" metrichandler.py """
import traceback
import tornado.gen
import tornado.web
from heron.common.src.python.utils.log import Log
from heron.proto import common_pb2
from heron.proto import tmaster_pb2
from heron.tools.tracker.src.python import constants
from heron.tools.tracker.src.python.handlers import BaseHandler
cl... |
"""Support for Firmata switch output."""
import logging
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant
from .const import (
CONF_INITIAL_STATE,
CONF_NEGATE_STATE,... |
import acos_client.errors as acos_errors
import acos_client.v30.base as base
class HealthMonitor(base.BaseV30):
# Valid method objects
ICMP = 'icmp'
TCP = 'tcp'
HTTP = 'http'
HTTPS = 'https'
url_prefix = "/health/monitor/"
_method_objects = {
ICMP: {
"icmp": 1
},
... |
"""All sorts of properties for every field.
Generated by ./generate-onetime-js-widget-data.py
AMD-style module definition.
Note: No leading, internal path before the [], since we'd have to hardwire it
to data/whatever-fns.js which is inflexible.
"""
META_INFO = r"""
{
"end_snippet.bbs_server_info.base_url:value": {
... |
""" _importer.py
Merge _yang_ns for subpackage to a single _yang_ns at runtime.
"""
import importlib
import pkgutil
from ydk import models
class YangNs(object):
def __init__(self, d):
self.__dict__ = d
_yang_ns_dict = {}
exempt_keys = set(['__builtins__', '__doc__', '__file__',
'__nam... |
"""Update a task in maniphest.
you can use the 'task id' output from the 'arcyon task-create' command as input
to this command.
usage examples:
update task '99' with a new title, only show id:
$ arcyon task-update 99 -t 'title' --format-id
99
"""
from __future__ import absolute_import
from __future__ import... |
import logging
import terminal
INFO = logging.INFO
VERBOSE = (logging.INFO + logging.DEBUG) / 2
DEBUG = logging.DEBUG
log = logging.getLogger('rdopkg')
log.setLevel(logging.INFO)
if len(log.handlers) < 1:
formatter = logging.Formatter(fmt='%(message)s')
handler = logging.StreamHandler()
handler.setFormatter... |
from fake_switches.command_processing.base_command_processor import BaseCommandProcessor
class ConfigVlanCommandProcessor(BaseCommandProcessor):
def init(self, switch_configuration, terminal_controller, logger, piping_processor, *args):
super(ConfigVlanCommandProcessor, self).init(switch_configuration, term... |
"""
``fitsinfo`` is a command-line script based on astropy.io.fits for
printing a summary of the HDUs in one or more FITS files(s) to the
standard output.
Example usage of ``fitsinfo``:
1. Print a summary of the HDUs in a FITS file::
$ fitsinfo filename.fits
Filename: filename.fits
No. Name Type ... |
"""
Tests of neo.io.igorproio
"""
import unittest
try:
import igor
HAVE_IGOR = True
except ImportError:
HAVE_IGOR = False
from neo.io.igorproio import IgorIO
from neo.test.iotest.common_io_test import BaseTestIO
@unittest.skipUnless(HAVE_IGOR, "requires igor")
class TestIgorIO(BaseTestIO, unittest.TestCase)... |
import numpy as np
from numpy.random import randn
from numpy.testing import assert_almost_equal, dec
from dipy.reconst.vec_val_sum import vec_val_vect
def make_vecs_vals(shape):
return randn(*(shape)), randn(*(shape[:-2] + shape[-1:]))
try:
np.einsum
except AttributeError:
with_einsum = dec.skipif(True, "Ne... |
"""
Sphinx plugin to run example scripts and create a gallery page.
Lightly modified from the mpld3 project.
"""
from __future__ import division
import os
import os.path as op
import re
import glob
import token
import tokenize
import shutil
from seaborn.external import six
import matplotlib
matplotlib.use('Agg')
import... |
from functools import update_wrapper
from django.http import Http404, HttpResponseRedirect
from django.contrib.admin import ModelAdmin, actions
from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth import logout as auth_logout, REDIRECT_FIELD_NAME
from django.contrib.contenttypes impor... |
import unittest
from webkitpy.common.net.buildbot import Builder
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.thirdparty.mock import Mock
from webkitpy.tool.bot.sheriff import Sheriff
from webkitpy.tool.mocktool import MockTool
class MockSheriffBot(object):
name = "mock-sheriff-bot"
... |
import unittest
from webkitpy.common import lru_cache
class LRUCacheTest(unittest.TestCase):
def setUp(self):
self.lru = lru_cache.LRUCache(3)
self.lru['key_1'] = 'item_1'
self.lru['key_2'] = 'item_2'
self.lru['key_3'] = 'item_3'
self.lru2 = lru_cache.LRUCache(1)
self... |
import re
import sublime
import sublime_plugin
class IndentListItemCommand(sublime_plugin.TextCommand):
bullet_pattern = r'([-+*]|([(]?(\d+|#|[a-y]|[A-Y]|[MDCLXVImdclxvi]+))([).]))'
bullet_pattern_re = re.compile(bullet_pattern)
line_pattern_re = re.compile(r'^\s*' + bullet_pattern)
spaces_re = re.compi... |
"""Tools for working with virtualenv environments"""
import os
import sys
import subprocess
from pip.exceptions import BadCommand
from pip.log import logger
def restart_in_venv(venv, base, site_packages, args):
"""
Restart this script using the interpreter in the given virtual environment
"""
if base an... |
from uuid import uuid4
from gluon import current
def rlpcm_person_anonymize():
""" Rules to anonymize a case file """
auth = current.auth
s3db = current.s3db
ANONYMOUS = "-"
# Standard anonymizers
from s3db.pr import pr_address_anonymise as anonymous_address, \
pr_person_... |
"""
Strictly internal utilities.
"""
from __future__ import absolute_import, division, print_function
from twisted.web.client import HTTPConnectionPool
def default_reactor(reactor):
"""
Return the specified reactor or the default.
"""
if reactor is None:
from twisted.internet import reactor
... |
from __future__ import absolute_import
from django.core.exceptions import PermissionDenied
from django.db import models
from django.contrib.auth import authenticate
from django.contrib.sites.models import Site
from django.utils.encoding import python_2_unicode_compatible
from django.utils.crypto import get_random_strin... |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test Qt creation from a copied empty environment.
"""
import TestSCons
test = TestSCons.TestSCons()
test.Qt_dummy_installation('qt')
test.write('SConstruct', """\
orig = Environment()
env = orig.Clone(QTDIR = r'%s',
QT_LIB = r'%s',
... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from .. import Rule
class HasNoLatOrLon(Rule):
"""Rule that checks if Latitude or Longitude are not given"""
labels = []
name = _('Places with no latitude or longitude given')
description = _("Matches places with empty latitu... |
import unittest
from pyexiv2.utils import Rational
class TestRational(unittest.TestCase):
def test_constructor(self):
r = Rational(2, 1)
self.assertEqual(r.numerator, 2)
self.assertEqual(r.denominator, 1)
self.assertRaises(ZeroDivisionError, Rational, 1, 0)
def test_read_only(sel... |
"""
Find all the available input interfaces and try to initialize them.
"""
import os
import glob
import logging
from ..inputreaderinterface import InputReaderInterface
__author__ = 'Bitcraze AB'
__all__ = ['InputInterface']
logger = logging.getLogger(__name__)
found_interfaces = [os.path.splitext(os.path.basename(f))[... |
MCUREGS = {
'ADCSRB': '&123',
'ADCSRB_ACME': '$40',
'ACSR': '&80',
'ACSR_ACD': '$80',
'ACSR_ACBG': '$40',
'ACSR_ACO': '$20',
'ACSR_ACI': '$10',
'ACSR_ACIE': '$08',
'ACSR_ACIC': '$04',
'ACSR_ACIS': '$03',
'DIDR1': '&127',
'DIDR1_AIN1D': '$02',
'DIDR1_AIN0D': '$01',
'UDR0': '&198',
'UCS... |
"""
/***************************************************************************
Name : DB Manager
Description : Database manager plugin for QGIS
Date : May 23, 2011
copyright : (C) 2011 by Giuseppe Sucameli
email : brush.tyler@gmail.com
The content of ... |
from django.contrib.auth import get_user_model
User = get_user_model()
from rest_framework import serializers
from nodeshot.core.base.serializers import ModelValidationSerializer
from nodeshot.community.profiles.serializers import ProfileRelationSerializer
from .models import Comment, Vote, Rating, NodeRatingCount
__al... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible import constants as C
from ansible import context
from ansible.cli import CLI
from ansible.cli.arguments import optparse_helpers as opt_help
from ansible.errors import AnsibleError, AnsibleOptionsError
from ansible.exec... |
import test_access_control
import test_users
import test_groups |
"""
Common utility functions useful throughout the contentstore
"""
import logging
from datetime import datetime
from django.conf import settings
from django.urls import reverse
from django.utils.translation import ugettext as _
from opaque_keys.edx.keys import CourseKey, UsageKey
from pytz import UTC
from six import t... |
from spack import *
class PyAsn1crypto(PythonPackage):
"""Python ASN.1 library with a focus on performance and a pythonic API """
homepage = "https://github.com/wbond/asn1crypto"
url = "https://pypi.io/packages/source/a/asn1crypto/asn1crypto-0.22.0.tar.gz"
version('0.22.0', '74a8b9402625b38ef19cf3f... |
"""Debounce helper."""
from __future__ import annotations
import asyncio
from collections.abc import Awaitable, Callable
from logging import Logger
from typing import Any
from homeassistant.core import HassJob, HomeAssistant, callback
class Debouncer:
"""Class to rate limit calls to a specific command."""
def _... |
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.http import HttpRequest, HttpResponse
from six import text_type
from zerver.models import get_client, UserProfile, Client
from zerver.decorator import asynchronous, \
authenticated_json_post_view, internal_notify_v... |
import logging
import os
from oslo_concurrency import processutils as putils
from oslo_config import cfg
from taskflow.patterns import linear_flow as lf
from taskflow import task
from glance import i18n
_ = i18n._
_LI = i18n._LI
_LE = i18n._LE
_LW = i18n._LW
LOG = logging.getLogger(__name__)
convert_task_opts = [
c... |
"""Gluster storage class.
This class is very similar to FileStorage, given that Gluster when mounted
behaves essentially like a regular file system. Unlike RBD, there are no
special provisions for block device abstractions (yet).
"""
import logging
import os
import socket
from ganeti import utils
from ganeti import err... |
from trac.core import *
from trac.config import ConfigSection
from trac.perm import IPermissionRequestor
class ExtraPermissionsProvider(Component):
"""Extra permission provider."""
implements(IPermissionRequestor)
extra_permissions_section = ConfigSection('extra-permissions',
doc="""This section pro... |
"""
=============================================
Effect of varying threshold for self-training
=============================================
This example illustrates the effect of a varying threshold on self-training.
The `breast_cancer` dataset is loaded, and labels are deleted such that only 50
out of 569 samples ha... |
from __future__ import absolute_import
import imp
import os
import platform
import re
import subprocess
import sys
from . import option_list
from digits import device_query
from digits.utils import parse_version
def load_from_envvar(envvar):
"""
Load information from an installation indicated by an environment ... |
import threading
import time
from . import _impl
from .common import *
from .connection import *
from .networktablenode import NetworkTableNode
from .type import NetworkTableEntryTypeManager
import logging
logger = logging.getLogger('nt')
__all__ = ["NetworkTableServer"]
class ServerConnectionState:
"""Represents t... |
from __future__ import division, unicode_literals, print_function
import logging
from collections import OrderedDict
import numpy as np
from monty.json import jsanitize
from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine
from pymatgen.util.plotting import pretty_plot
from pymatgen.electronic_structure... |
full_tests = False
def test(fmt, *args):
print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<')
test("}}{{")
test("{}-{}", 1, [4, 5])
test("{0}-{1}", 1, [4, 5])
test("{1}-{0}", 1, [4, 5])
test("{:x}", 1)
test("{!r}", 2)
test("{:x}", 0x10)
test("{!r}", "foo")
test("{!s}", "foo")
test("{0!r:>10s} {0!s:>10s}", "f... |
"""
WSGI config for src project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODUL... |
import xml.sax.saxutils as xml
class LiveService(object):
CONTACTS = ("contacts.msn.com", "MBI")
MESSENGER = ("messenger.msn.com", "?id=507")
MESSENGER_CLEAR = ("messengerclear.live.com", "MBI_KEY_OLD")
MESSENGER_SECURE = ("messengersecure.live.com", "MBI_SSL")
SPACES = ("spaces.live.com", "MBI")
... |
"""QGIS Unit tests for QgsComposerEffects.
.. note:: 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, or
(at your option) any later version.
"""
__author__ = '(C) 2012 ... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from .._changedsincebase import ChangedSinceBase
class ChangedSince(ChangedSinceBase):
"""Rule that checks for persons changed since a specific time."""
labels = [ _('Changed after:'), _('but before:') ]
name = _('Persons ch... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: group
version_added: "0.0.2"
short_description: Add or remove groups
requirements:
- groupadd
- groupdel
- groupmod
description:
- Manage presence of groups on a host.
- For Windows targets, use... |
from twisted.trial import unittest
from deluge.transfer import DelugeTransferProtocol
import base64
import deluge.rencode as rencode
class TransferTestClass(DelugeTransferProtocol):
def __init__(self):
DelugeTransferProtocol.__init__(self)
self.transport = self
self.messages_out = []
... |
from openerp.osv import osv, fields
class attributes(osv.Model):
_name = "product.attribute"
def _get_float_max(self, cr, uid, ids, field_name, arg, context=None):
result = dict.fromkeys(ids, 0)
if ids:
cr.execute("""
SELECT attribute_id, MAX(value)
FR... |
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh."""
from import_shims.warn import warn_deprecated_import
warn_deprecated_import('xblock_django.tests.test_user_service', 'common.djangoapps.xblock_django.tests.test_user_service')
from common.djangoapps.xblock_django.tests.test_user_service ... |
'''Test cases for QImage'''
import unittest
import py3kcompat as py3k
from PySide.QtGui import *
from helper import UsesQApplication, adjust_filename
xpm = [
"27 22 206 2",
" c None",
". c #FEFEFE",
"+ c #FFFFFF",
"@ c #F9F9F9",
"# c #ECECEC",
"$ c #D5D5D5",
"% c #A0A0A0",
"&... |
from lib.actions import BaseAction
class ApprovalAction(BaseAction):
def run(self, number):
s = self.client
s.table = 'change_request'
res = s.get({'number': number})
sys_id = res[0]['sys_id']
response = s.update({'approval': 'approved'}, sys_id)
return response |
from cinder import test
class ExampleSkipTestCase(test.TestCase):
test_counter = 0
@test.skip_test("Example usage of @test.skip_test()")
def test_skip_test_example(self):
self.fail("skip_test failed to work properly.")
@test.skip_if(True, "Example usage of @test.skip_if()")
def test_skip_if_... |
from org.o3project.odenos.core.component.network.flow.basic.flow_action import (
FlowAction
)
class OFPFlowActionPopMpls(FlowAction):
MPLS_UNICAST = 0x8847
MPLS_MULTICAST = 0x8848
# property key
ETH_TYPE = "eth_type"
def __init__(self, type_, eth_type):
super(OFPFlowActionPopMpls, self).... |
from cloudify import ctx
from cloudify.exceptions import NonRecoverableError
from cloudify.state import ctx_parameters as inputs
import subprocess
import os
import re
import sys
import time
import threading
import platform
from StringIO import StringIO
from cloudify_rest_client import CloudifyClient
from cloudify impor... |
import errno
import os
import re
import tempfile
from hashlib import md5
class _FileCacheError(Exception):
"""Base exception class for FileCache related errors"""
class _FileCache(object):
DEPTH = 3
def __init__(self, root_directory=None):
self._InitializeRootDirectory(root_directory)
def Get(se... |
from pyasn1.type import constraint
from pyasn1.type import namedtype
from pyasn1.type import univ
class UsmSecurityParameters(univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('msgAuthoritativeEngineID', univ.OctetString()),
namedtype.NamedType('msgAuthoritativeEngineBoots',
... |
import unittest
import shutil
import tempfile
import sys
import stat
import os
import os.path
from os.path import splitdrive
from distutils.spawn import find_executable, spawn
from shutil import (_make_tarball, _make_zipfile, make_archive,
register_archive_format, unregister_archive_format,
... |
"""scons.Node.Alias
Alias nodes.
This creates a hash of global Aliases (dummy targets).
"""
__revision__ = "src/engine/SCons/Node/Alias.py 2014/07/05 09:42:21 garyo"
import collections
import SCons.Errors
import SCons.Node
import SCons.Util
class AliasNameSpace(collections.UserDict):
def Alias(self, name, **kw):
... |
from __future__ import absolute_import
from __future__ import print_function
import calendar
import datetime
import jwt
import mock
from twisted.cred import strcred
from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
from twisted.internet import defer
from twisted.trial import unittest
from twiste... |
import unittest
from django.core.urlresolvers import resolve, reverse, NoReverseMatch
from pulp.server.webservices.urls import handler404
def assert_url_match(expected_url, url_name, *args, **kwargs):
"""
Generate a url given args and kwargs and pass it through Django's reverse and
resolve funct... |
from datetime import date, datetime
import six
from wtforms import DateField
from wtforms.validators import optional
from ..field_base import WebDepositField
__all__ = ['Date']
class Date(WebDepositField, DateField):
def __init__(self, **kwargs):
defaults = dict(
icon='calendar',
val... |
"""Utility functions, node construction macros, etc."""
from .pgen2 import token
from .pytree import Leaf, Node
from .pygram import python_symbols as syms
from . import patcomp
def KeywordArg(keyword, value):
return Node(syms.argument,
[keyword, Leaf(token.EQUAL, u'='), value])
def LParen():
ret... |
import requests
from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter,
OAuth2LoginView,
OAuth2CallbackView)
from .provider import BasecampProvider
class BasecampOAuth2Adapter(OAuth2Adapt... |
"""
discovery-wrapper A small tool which wraps around discovery and tries to
guide the discovery process with a more modern approach with a
Queue and workers.
Based on the original version of poller-wrapper.py by Job Snijders
Author: Neil Lathwood <neil@librenms.org>
Date: ... |
import boto
import boto.jsonresponse
from boto.compat import json
from boto.regioninfo import RegionInfo
from boto.connection import AWSQueryConnection
class Layer1(AWSQueryConnection):
APIVersion = '2010-12-01'
DefaultRegionName = 'us-east-1'
DefaultRegionEndpoint = 'elasticbeanstalk.us-east-1.amazonaws.co... |
"""Libraries to build Recurrent Neural Networks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function |
from cinder.compute import nova
from cinder import context
from cinder import test
class FakeNovaClient(object):
class Volumes(object):
def __getattr__(self, item):
return None
def __init__(self):
self.volumes = self.Volumes()
def create_volume_snapshot(self, *args, **kwargs):
... |
"""Fake data generator.
To use:
1. Install fake-factory.
pip install fake-factory
2. Create your OSF user account
3. Run the script, passing in your username (email).
::
python3 -m scripts.create_fakes --user fred@cos.io
This will create 3 fake public projects, each with 3 fake contributors (with
you as the... |
import jinja2
from django_jinja import library
from kitsune.sumo import parser
from kitsune.wiki.diff import BetterHtmlDiff
@library.global_function
def diff_table(content_from, content_to):
"""Creates an HTML diff of the passed in content_from and content_to."""
html_diff = BetterHtmlDiff()
diff = html_dif... |
from __future__ import division, absolute_import, print_function
import re
import os
import sys
import warnings
import platform
import tempfile
from subprocess import Popen, PIPE, STDOUT
from numpy.distutils.fcompiler import FCompiler
from numpy.distutils.exec_command import exec_command
from numpy.distutils.misc_util ... |
"""
Create movie from MEG inverse solution
=======================================
Data were computed using mne-python (http://martinos.org/mne)
"""
import os
import numpy as np
from surfer import Brain
from surfer.io import read_stc
print(__doc__)
"""
create Brain object for visualization
"""
brain = Brain('fsaverage... |
"""Mixins that are useful for classes using vtk_kit.
@author: Charl P. Botha <http://cpbotha.net/>
"""
from external.vtkPipeline.ConfigVtkObj import ConfigVtkObj
from external.vtkPipeline.vtkMethodParser import VtkMethodParser
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin # temporar... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: elasticache
short_description: Manage cache clusters in Amazon Elasticache.
description:
- Manage cache clusters in Amazon Elasticache.
- Returns... |
{
"name": "Stock Move Backdating",
"version": "1.0",
'author': ['Marco Dieckhoff, BREMSKERL', 'Agile Business Group'],
"category": "Stock Logistics",
'website': 'www.bremskerl.com',
"depends": ["stock"],
"summary": "Allows back-dating of stock moves",
"description": """This module allows... |
import os
import unittest
import zipfile
import config
import store
import common
from db import db_session, Source
import crypto_util
os.environ['SECUREDROP_ENV'] = 'test'
class TestStore(unittest.TestCase):
"""The set of tests for store.py."""
def setUp(self):
common.shared_setup()
def tearDown(se... |
"""Model managers for Reversion."""
try:
set
except NameError:
from sets import Set as set # Python 2.3 fallback.
from django.contrib.contenttypes.models import ContentType
from django.db import models
class VersionManager(models.Manager):
"""Manager for Version models."""
def get_for_object(self, obje... |
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.or... |
import os
import pytest
from pyleus.cli.storm_cluster import _get_storm_cmd_env
from pyleus.cli.storm_cluster import STORM_JAR_JVM_OPTS
from pyleus.cli.storm_cluster import StormCluster
from pyleus.cli.storm_cluster import TOPOLOGY_BUILDER_CLASS
from pyleus.testing import mock
class TestGetStormCmdEnd(object):
@pyt... |
from math import exp
from collections import defaultdict
@outputSchema("scaled: double")
def logistic_scale(val, logistic_param):
return -1.0 + 2.0 / (1.0 + exp(-logistic_param * val))
@outputSchema("t: (item_A, item_B, dist: double, raw_weight: double)")
def best_path(paths):
return sorted(paths, key=lambda t:... |
from .models import ( # NOQA
DIRECT_FORM_FIELD_OVERRIDES, FORM_FIELD_OVERRIDES, WagtailAdminModelForm,
WagtailAdminModelFormMetaclass, formfield_for_dbfield)
from .pages import WagtailAdminPageForm # NOQA |
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
import wagtail.search.index
class Migration(migrations.Migration):
initial = True
dependencies = [
('taggit', '0002_auto_20150616_2121'),
]
operations = [
migrations.CreateModel(
... |
from nose.tools import *
from networkx import *
from networkx.generators.random_graphs import *
class TestGeneratorsRandom():
def smoke_test_random_graph(self):
seed = 42
G=gnp_random_graph(100,0.25,seed)
G=binomial_graph(100,0.25,seed)
G=erdos_renyi_graph(100,0.25,seed)
G=fa... |
from __future__ import unicode_literals
from .. import Provider as PhoneNumberProvider
class Provider(PhoneNumberProvider):
formats = (
# Mobile
# Government website: http://www.uke.gov.pl/numeracja-843
'50# ### ###',
'51# ### ###',
'53# ### ###',
'57# ### ###',
... |
"""
***************************************************************************
lasoverlapPro.py
---------------------
Date : October 2014
Copyright : (C) 2014 by Martin Isenburg
Email : martin near rapidlasso point com
**************************************... |
"""
Declaration of toolchains.linalg namespace.
@author: Stijn De Weirdt (Ghent University)
@author: Kenneth Hoste (Ghent University)
"""
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) #@ReservedAssignment |
import hashlib
import itertools
import numpy
from nupic.bindings.math import Random
from nupic.encoders.base import Encoder
class CoordinateEncoder(Encoder):
"""
Given a coordinate in an N-dimensional space, and a radius around
that coordinate, the Coordinate Encoder returns an SDR representation
of that positi... |
"""
Metric class used in monitor mixin framework.
"""
import numpy
class Metric(object):
"""
A metric computed over a set of data (usually from a `CountsTrace`).
"""
def __init__(self, monitor, title, data):
"""
@param monitor (MonitorMixinBase) Monitor Mixin instance that generated
... |
import matplotlib.pyplot as plt
import glob
import collections
import pandas
import numpy as np
class ConvergencePlot(object):
"""
A tool for making convergence plots.
Args:
x[np.array]: The x data of the graph (e.g., dofs)
y[np.array]: The y data of the graph (e.g., L2_error)
Key, value... |
"""Test the Advantage Air Sensor Platform."""
from datetime import timedelta
from json import loads
from homeassistant.components.advantage_air.const import DOMAIN as ADVANTAGE_AIR_DOMAIN
from homeassistant.components.advantage_air.sensor import (
ADVANTAGE_AIR_SERVICE_SET_TIME_TO,
ADVANTAGE_AIR_SET_COUNTDOWN_V... |
""" This provides some useful code used by other modules. This is not to be
used by the end user which is why it is hidden. """
import string, sys
class LinkError(Exception):
pass
def refine_import_err(mod_name, extension_name, exc):
""" Checks to see if the ImportError was because the library
itself was n... |
"""
A sub-package for efficiently dealing with polynomials.
Within the documentation for this sub-package, a "finite power series,"
i.e., a polynomial (also referred to simply as a "series") is represented
by a 1-D numpy array of the polynomial's coefficients, ordered from lowest
order term to highest. For example, ar... |
import os
import re
import sys
def ReadFileAsLines(filename):
"""Reads a file, removing blank lines and lines that start with #"""
file = open(filename, "r")
raw_lines = file.readlines()
file.close()
lines = []
for line in raw_lines:
line = line.strip()
if len(line) > 0 and not l... |
"""
This package contains various command line wrappers to programs used in
pymatgen that do not have Python equivalents.
""" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.