path
stringlengths
23
146
source_code
stringlengths
0
261k
data/VisTrails/VisTrails/vistrails/core/vistrail/plugin_data.py
from __future__ import division from vistrails.db.domain import DBPluginData import unittest import copy import random from vistrails.db.domain import IdScope import vistrails.core class PluginData(DBPluginData): def __init__(self, *args, **kwargs): DBPluginData.__init__(self, *args, **kwargs...
data/Lawouach/WebSocket-for-Python/ws4py/messaging.py
import os import struct from ws4py.framing import Frame, OPCODE_CONTINUATION, OPCODE_TEXT, \ OPCODE_BINARY, OPCODE_CLOSE, OPCODE_PING, OPCODE_PONG from ws4py.compat import unicode, py3k __all__ = ['Message', 'TextMessage', 'BinaryMessage', 'CloseControlMessage', 'PingControlMessage', 'PongControlMessa...
data/Kozea/brigit/setup.py
""" briGit - Very simple git wrapper module """ from setuptools import setup, find_packages VERSION = '1.2' options = dict( name="brigit", version=VERSION, description="Very simple git wrapper module", long_description=__doc__, author="Florian Mounier - Kozea", author_email="florian.mounier@...
data/IanLewis/kay/kay/tests/models.py
""" Models for Kay tests. :Copyright: (c) 2009 Accense Technology, Inc. All rights reserved. :license: BSD, see LICENSE for more details. """ from google.appengine.ext import db from kay.utils.forms import ValidationError from kay.utils.forms.modelform import ModelForm class MaxLengthValidator(object): def __ini...
data/adblockplus/gyp/test/win/gyptest-link-tsaware.py
""" Make sure tsaware setting is extracted properly. """ import TestGyp import sys if sys.platform == 'win32': test = TestGyp.TestGyp(formats=['msvs', 'ninja']) CHDIR = 'linker-flags' test.run_gyp('tsaware.gyp', chdir=CHDIR) test.build('tsaware.gyp', test.ALL, chdir=CHDIR) def GetHeaders(exe): return...
data/SublimeText/SublimeCMD/actions.py
import os import sublime CMD_TARGET_APPLICATION = 0 CMD_TARGET_WINDOW = 1 CMD_TARGET_VIEW = 2 CMD_RUN = 'run_' CMD_KEY = 'key_' CMD_SET = 'set_' def str_to_dict(s): """Converts a string like 'one:two three:4' into a dict with parsed values that's suitable to pass as args to obj.run_command. """ d ...
data/VisTrails/VisTrails/examples/vtk_examples/Modelling/iceCream.py
import vtk from vtk.util.colors import chocolate, mint cone = vtk.vtkCone() cone.SetAngle(20) vertPlane = vtk.vtkPlane() vertPlane.SetOrigin(.1, 0, 0) vertPlane.SetNormal(-1, 0, 0) basePlane = vtk.vtkPlane() basePlane.SetOrigin(1.2, 0, 0) basePlane.SetNormal(1, 0, 0) iceCream = vtk.vtkSphere() iceCream.SetCenter(...
data/RoseOu/flasky/venv/lib/python2.7/site-packages/pygments/console.py
""" pygments.console ~~~~~~~~~~~~~~~~ Format colored console output. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ esc = "\x1b[" codes = {} codes[""] = "" codes["reset"] = esc + "39;49;00m" codes["bold"] = esc + ...
data/Kitware/minerva/server/rest/geojson_dataset.py
from girder.api import access from girder.api.describe import Description from girder.api.rest import loadmodel, RestException from girder.constants import AccessType from girder.plugins.minerva.rest.dataset import Dataset from girder.plugins.minerva.utility.minerva_utility import findDatasetFolder, \ updateMiner...
data/Kuniwak/vint/vint/linting/policy/prohibit_abbreviation_option.py
import re from vint.ast.node_type import NodeType from vint.linting.level import Level from vint.linting.policy.abstract_policy import AbstractPolicy from vint.linting.policy_registry import register_policy from vint.ast.dictionary.abbreviations import ( Abbreviations, AbbreviationsIncludingInvertPrefix, ) Se...
data/agiliq/merchant/example/settings/travis.py
import os from common import * from formencode.variabledecode import variable_decode DEBUG = False def get_merchant_settings(): env_dict = dict(filter(lambda x: x[0].startswith('MERCHANT'), os.environ.items())) return variable_decode(env_dict, dict_char='__')['MERCHANT'] MERCHANT_TEST_MODE = True MERCHANT...
data/IvanMalison/okcupyd/okcupyd/tasks/db.py
import logging from invoke import task import IPython from okcupyd import db from okcupyd import util from okcupyd.db import mailbox, model from okcupyd.user import User log = logging.getLogger(__name__) @task(default=True) def session(): with db.txn() as session: IPython.embed() @task def reset(): ...
data/adaptivdesign/django-sellmo/example/category/links.py
from sellmo.core import chaining from sellmo.core.http.query import QueryString from sellmo.apps.product.routines import (list_products_from_request, product_filters_from_request) from sellmo.contrib.category.views import category from django.shortcuts import render from django.template.response import TemplateRes...
data/MirantisWorkloadMobility/CloudFerry/cloudferry/lib/os/actions/detach_used_volumes_via_compute.py
import copy import logging from oslo_config import cfg from cloudferry.lib.base.action import action from cloudferry.lib.utils import utils CONF = cfg.CONF LOG = logging.getLogger(__name__) class DetachVolumesCompute(action.Action): def run(self, info, **kwargs): info = copy.deepcopy(info) com...
data/abusesa/abusehelper/abusehelper/core/rules/tests/test_rules.py
from __future__ import unicode_literals import re import pickle import unittest from ..atoms import String, RegExp, IP, DomainName from ..rules import And, Or, No, Match, NonMatch, Fuzzy from ...events import Event class TestRules(unittest.TestCase): def test_results_should_get_cached(self): rule = Mat...
data/ProgVal/Limnoria/src/drivers/Socket.py
""" Contains simple socket drivers. Asyncore bugged (haha, pun!) me. """ from __future__ import division import os import time import errno import select import socket from .. import (conf, drivers, log, utils, world) from ..utils import minisix from ..utils.str import decode_raw_line try: import ssl SSLEr...
data/Juniper/py-junos-eznc/lib/jnpr/junos/op/isis.py
""" Pythonifier for ISIS Table/View """ from jnpr.junos.factory import loadyaml from os.path import splitext _YAML_ = splitext(__file__)[0] + '.yml' globals().update(loadyaml(_YAML_))
data/Tanganelli/CoAPthon/coapthon/messages/message.py
from coapthon.utils import parse_blockwise from coapthon import defines from coapthon.messages.option import Option __author__ = 'Giacomo Tanganelli' __version__ = "3.0" class Message(object): def __init__(self): self._type = None self._mid = None self._token = None self._options ...
data/ZEROFAIL/goblin/goblin/properties/__init__.py
from .properties import * from .strategy import *
data/SmokinCaterpillar/pypet/pypet/tests/profiling/speed_analysis/avg_runtima_as_function_of_length.py
__author__ = 'robert' from pypet import Environment, Trajectory from pypet.tests.testutils.ioutils import make_temp_dir, get_log_config import os import matplotlib.pyplot as plt import numpy as np import time def job(traj): traj.f_ares('$set.$', 42, comment='A result') def get_runtime(length): filename =...
data/JeffHeard/sondra/sondra/tests/test_valuehandlers.py
from sondra.document.valuehandlers import DateTime, Geometry, Now from shapely.geometry import Point from datetime import datetime import rethinkdb as r import pytest from sondra.tests.api import * from sondra.auth import Auth s = ConcreteSuite() api = SimpleApp(s) auth = Auth(s) AuthenticatedApp(s) AuthorizedApp(s)...
data/UDST/activitysim/activitysim/activitysim.py
from operator import itemgetter import numpy as np import pandas as pd from zbox import toolz as tz from .skim import Skims, Skims3D from .mnl import utils_to_probs, make_choices, interaction_dataset import os import psutil import gc def usage(when): gc.collect() process = psutil.Process(os.getpid()) b...
data/Impactstory/total-impact-webapp/totalimpactwebapp/tweet.py
from totalimpactwebapp import json_sqlalchemy from util import commit from util import cached_property from util import dict_from_dir from util import as_int_or_float_if_possible from totalimpactwebapp import db from totalimpactwebapp.tweeter import Tweeter from birdy.twitter import AppClient, TwitterApiError, Twitter...
data/SEED-platform/seed/seed/tests/api/seed_readingtools.py
 """ :copyright (c) 2014 - 2016, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from the U.S. Department of Energy) and contributors. All rights reserved. :author """ import logging import pprint import json import os import r...
data/PyHDI/PyCoRAM/pycoram/utils/coram2pycoram.py
from __future__ import absolute_import from __future__ import print_function import re import sys import os def getRamId(oid, sid): if 0 <= sid and sid <= 31: return 0 if 32 <= sid and sid <= 63: return 1 if 64 <= sid and sid <= 95: return 2 if 96 <= sid and sid <= 127: ...
data/Lawouach/WebSocket-for-Python/example/echo_gevent_client.py
from gevent import monkey; monkey.patch_all() import gevent from ws4py.client.geventclient import WebSocketClient if __name__ == '__main__': ws = WebSocketClient('ws://localhost:9000/ws', protocols=['http-only', 'chat']) ws.connect() ws.send("Hello world") print((ws.receive(),)) ws.send("Hello w...
data/MongoEngine/mongoengine/mongoengine/dereference.py
from bson import DBRef, SON from mongoengine.python_support import txt_type from base import ( BaseDict, BaseList, EmbeddedDocumentList, TopLevelDocumentMetaclass, get_document ) from fields import (ReferenceField, ListField, DictField, MapField) from connection import get_db from queryset import QuerySet fro...
data/acil-bwh/SlicerCIP/Scripted/CIP_Common/CIP/logic/StructuresParameters.py
from collections import OrderedDict class StructuresParameters(object): INF = 100000 """Structures""" structureTypes = OrderedDict() structureTypes["UNDEFINED"] = (0, 0, 0, "Undefined structure", 0, 0, 0, -INF, INF , '') slicePlane="Axial" structureTypes['LeftHumerus'+s...
data/USArmyResearchLab/Dshell/decoders/templates/SessionDecoder.py
import dshell import output import util class DshellDecoder(dshell.TCPDecoder): '''generic session-level decoder template''' def __init__(self, **kwargs): '''decoder-specific config''' '''pairs of 'option':{option-config}''' self.optiondict = {} '''bpf filter, for ipV4''' ...
data/PyHDI/veriloggen/tests/verilog/read_verilog_/module_str/test_read_verilog_module_str.py
from __future__ import absolute_import from __future__ import print_function import read_verilog_module_str expected_verilog = """ module top ( parameter WIDTH = 8 ) ( input CLK, input RST, output [WIDTH-1:0] LED ); blinkled ( .WIDTH(WIDTH) ) inst_blinkled ( .CLK(CLK), .RST(R...
data/Yubico/python-pyhsm/pyhsm/cmd.py
""" module for accessing a YubiHSM """ import re import struct __all__ = [ 'reset', 'YHSM_Cmd', ] import pyhsm.exception import pyhsm.defines class YHSM_Cmd(): """ Base class for YubiHSM commands. """ response_status = None executed = False def __init__(self, stic...
data/SMART-Lab/smartdispatch/smartdispatch/tests/test_smartdispatch.py
import os import re import shutil import time as t from os.path import join as pjoin from StringIO import StringIO import tempfile from nose.tools import assert_true, assert_equal from numpy.testing import assert_array_equal import smartdispatch from smartdispatch import utils def test_generate_name_from_command():...
data/Nodd/spyder_line_profiler/p_memoryprofiler.py
"""Memory profiler Plugin""" from spyderlib.qt.QtGui import QVBoxLayout, QGroupBox, QLabel from spyderlib.qt.QtCore import SIGNAL, Qt from spyderlib.baseconfig import get_translation _ = get_translation("p_memoryprofiler", dirname="spyderplugins") from spyderlib.utils.qthelpers import get_icon, create_action from sp...
data/agiliq/merchant/billing/forms/common.py
from django import forms from billing.utils.credit_card import CreditCard, CardNotSupported class CreditCardFormBase(forms.Form): """ Base class for a simple credit card form which provides some utilities like 'get_credit_card' to return a CreditCard instance. If you pass the gateway as a keyword ar...
data/KanColleTool/kcsrv/kcsrv.py
import logging from app import app, logger root = logging.getLogger() root.setLevel(logging.DEBUG) logging.getLogger("sqlalchemy.engine").setLevel(logging.INFO) if __name__ == '__main__': logger.warn("This is a debugging configuration. Run with the gunicorn script to run in production.") app.run(host='0.0....
data/MBoustani/Geothon/Create Spatial File/Vector/create_wkt_multipoint.py
''' Project: Geothon (https://github.com/MBoustani/Geothon) File: Vector/create_wkt_multipoint.py Description: This code creates a wkt multi point from longitue and latitude. Author: Maziyar Boustani (github.com/MBoustani) ''' try: import ogr except ImportError: from osgeo import ogr l...
data/agronholm/apscheduler/examples/schedulers/tornado_.py
""" Demonstrates how to use the Tornado compatible scheduler to schedule a job that executes on 3 second intervals. """ from datetime import datetime import os from tornado.ioloop import IOLoop from apscheduler.schedulers.tornado import TornadoScheduler def tick(): print('Tick! The time is: %s' % datetime.now()...
data/adafruit/Adafruit_Python_SSD1306/setup.py
from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages classifiers = ['Development Status :: 4 - Beta', 'Operating System :: POSIX :: Linux', 'License :: OSI Approved :: MIT License', 'Intended Audience :: Developers', ...
data/adblockplus/gyp/test/actions-none/src/fake_cross.py
import sys fh = open(sys.argv[-1], 'wb') for filename in sys.argv[1:-1]: fh.write(open(filename).read()) fh.close()
data/adambullmer/sublime_docblockr_python/formatters/PEP0257.py
from .base import Base class Pep0257Formatter(Base): name = 'PEP0257' def decorators(self, attributes): return '' def extends(self, attributes): return '' def arguments(self, attributes): section = '\nArguments:\n' template = '\t{name} -- {description}\n' fo...
data/Kotti/Kotti/setup.py
import os import sys from setuptools import setup from setuptools import find_packages here = os.path.abspath(os.path.dirname(__file__)) try: README = open(os.path.join(here, 'README.rst')).read() AUTHORS = open(os.path.join(here, 'AUTHORS.txt')).read() CHANGES = open(os.path.join(here, 'CHANGES.txt')).re...
data/Kloudless/kloudless-python/setup.py
from setuptools import setup, find_packages import re import os from os.path import join as opj curdir = os.path.dirname(os.path.realpath(__file__)) def read(fname): contents = '' with open(fname) as f: contents = f.read() return contents package_name = 'kloudless' def version(): text = read...
data/Stiivi/bubbles/tests/test_graph.py
import unittest from bubbles import * class GraphTestCase(unittest.TestCase): def test_basic(self): g = Graph() g.add(Node("src"), "n1") g.add(Node("distinct"),"n2") g.add(Node("pretty_print"), "n3") self.assertEqual(3, len(g.nodes)) g.connect("n1", "n2") ...
data/PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/Chapter 6/6-6.py
import pygame from pygame.locals import * from sys import exit from gameobjects.vector2 import Vector2 picture_file = 'map.png' pygame.init() screen = pygame.display.set_mode((640, 480), 0, 32) picture = pygame.image.load(picture_file).convert() picture_pos = Vector2(0, 0) scroll_speed = 1000. clock = pygame.time.C...
data/OrbitzWorldwide/droned/droned/lib/droned/management/dmx/__main__.py
__doc__ = """Daemon Maker eXtraordinaire - aka DMX an application wrapper""" __author__ = """Justin Venus <justin.venus@orbitz.com>""" if __name__ != '__main__': raise ImportError('Not importable') import os import sys DIRECTORY = os.path.abspath(os.path.dirname(__file__)) sys.path.insert(0,os.path.abspath(os.pa...
data/RoseOu/flasky/venv/lib/python2.7/site-packages/flask_pagedown/fields.py
from wtforms.fields import TextAreaField from .widgets import PageDown class PageDownField(TextAreaField): widget = PageDown()
data/Microsoft/ivy/ivy/utils/rectagtuple.py
""" Immutable data structures based on Python's tuple (and inspired by namedtuple). Defines: tagtuple -- A tagged variant of tuple rectuple -- A record with named fields (a'la namedtuple) """ import sys as _sys from operator import itemgetter as _itemgetter from keyword import iskeyword as _iskeyword from collectio...
data/Yelp/fullerite/src/diamond/metric.py
import time import re import logging from error import DiamondException class Metric(object): _METRIC_TYPES = ['COUNTER', 'GAUGE', 'CUMCOUNTER'] def __init__(self, path, value, raw_value=None, timestamp=None, precision=0, metric_type='COUNTER', ttl=None, host="ignored", dimensions=None): ...
data/NumentaCorp/agamotto/agamotto/package.py
from agamotto.utils import execute, grepc def installed(package): """Confirm that a package is installed""" try: return grepc(execute("yum list installed %s" % package), package) >0 except Exception, _e: return False def is_installed(package): """Convenience alias to make the tests look nicer""" ...
data/Theano/Theano/theano/tests/test_printing.py
""" Tests of printing functionality """ from __future__ import absolute_import, print_function, division import logging from nose.plugins.skip import SkipTest import numpy from six.moves import StringIO import theano import theano.tensor as tensor from theano.printing import min_informative_str, debugprint def te...
data/adlibre/Adlibre-DMS/adlibre_dms/apps/dms_plugins/pluginpoints.py
from djangoplugins.point import PluginMount class BeforeStoragePluginPoint(object): __metaclass__ = PluginMount settings_field_name = 'before_storage_plugins' class DatabaseStoragePluginPoint(object): __metaclass__ = PluginMount settings_field_name = 'database_storage_plugins' class StoragePluginPo...
data/OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/casehandlers/query_hdf5.py
from weakref import ref import numpy as np from openmdao.main.api import VariableTree from openmdao.lib.casehandlers.query import DictList, ListResult _GLOBAL_DICT = dict(__builtins__=None) class CaseDatasetHDF5(object): """ Reads case data from `filename` and allows queries on it. To get all case da...
data/UDST/urbansim/urbansim/tests/test_accounts.py
import pandas as pd import pytest from pandas.util import testing as pdt from .. import accounts @pytest.fixture(scope='module') def acc_name(): return 'test' @pytest.fixture(scope='module') def acc_bal(): return 1000 @pytest.fixture def acc(acc_name, acc_bal): return accounts.Account(acc_name, acc_b...
data/Yelp/bravado/tests/petstore/user/updateUser_test.py
from __future__ import print_function import pytest def test_200_success(petstore): User = petstore.get_model('User') user = User( id=1, username='bozo', firstName='Bozo', lastName='TheClown', email='bozo@clown.com', password='newpassword', phone='111-22...
data/adafruit/Adafruit_Python_BluefruitLE/Adafruit_BluefruitLE/bluez_dbus/gatt.py
import uuid import dbus from ..interfaces import GattService, GattCharacteristic, GattDescriptor from ..platform import get_provider _SERVICE_INTERFACE = 'org.bluez.GattService1' _CHARACTERISTIC_INTERFACE = 'org.bluez.GattCharacteristic1' _DESCRIPTOR_INTERFACE = 'org.bluez.GattDescriptor1' class BluezG...
data/Parsely/pykafka/tests/__init__.py
__license__ = """ Copyright 2015 Parse.ly, Inc. Licensed 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.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in wri...
data/ImageEngine/gaffer/python/GafferUI/PresetsPlugValueWidget.py
import functools import IECore import Gaffer import GafferUI class PresetsPlugValueWidget( GafferUI.PlugValueWidget ) : def __init__( self, plug, parenting = None ) : self.__menuButton = GafferUI.MenuButton( "", menu = GafferUI.Menu( Gaffer.WeakMethod( self.__menuDefinition ) ) ) GafferUI.PlugValueWidget.__in...
data/Nextdoor/ndscheduler/simple_scheduler/jobs/curl_job.py
"""A job to send a HTTP (GET or DELETE) periodically.""" import logging import requests from ndscheduler import job logger = logging.getLogger(__name__) class CurlJob(job.JobBase): TIMEOUT = 10 @classmethod def meta_info(cls): return { 'job_class_string': '%s.%s' % (cls.__module__,...
data/aboutyou/aboutyou-python-sdk/aboutyou/django/middleware.py
""" :Author: Arne Simon [arne.simon@slice-dice.de] """ import django.core.exceptions try: from django.conf import settings from django.contrib.auth import authenticate, login except django.core.exceptions.ImproperlyConfigured: pass import logging logger = logging.getLogger("aboutyou.middleware") class...
data/WestpointLtd/pytls/tls/ext_servername.py
import struct from handshake import * from utils import * class ServerNameExtension(TLSExtension): HostName = 0 def __init__(self): TLSExtension.__init__(self) @classmethod def create(cls, hostname, hostnames=[], name_type=HostName): if len(hostnames) == 0: hostnames = ...
data/acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/blogger/client.py
"""Contains a client to communicate with the Blogger servers. For documentation on the Blogger API, see: http://code.google.com/apis/blogger/ """ __author__ = 'j.s@google.com (Jeff Scudder)' import gdata.client import gdata.gauth import gdata.blogger.data import atom.data import atom.http_core BLOGS_URL = 'http...
data/T0ha/ezodf/setup.py
import os from distutils.core import setup from version import VERSION AUTHOR_NAME = 'Manfred Moitzi' AUTHOR_EMAIL = 'mozman@gmx.at' MAINTAINER_NAME = 'Anton Shvein' MAINTAINER_EMAIL = 't0hashvein@gmail.com' def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname)).read() ex...
data/agoragames/chai/tests/comparator_test.py
import unittest import sys from chai.comparators import * if sys.version_info.major==2: from comparator_py2 import * class ComparatorsTest(unittest.TestCase): def test_build_comparators_builds_equals(self): comp = build_comparators("str")[0] self.assertTrue(isinstance(comp, Equals)) comp = build_c...
data/Lukasa/hyper/hyper/compat.py
""" hyper/compat ~~~~~~~~~~~~ Normalizes the Python 2/3 API for internal use. """ from contextlib import contextmanager import sys import zlib try: from . import ssl_compat except ImportError: ssl_compat = None _ver = sys.version_info is_py2 = _ver[0] == 2 is_py2_7_9_or_later = _ver[0] >= 2 and _ver[1] ...
data/MostAwesomeDude/construct/construct/formats/filesystem/__init__.py
""" file systems on-disk formats (ext2, fat32, ntfs, ...) and related disk formats (mbr, ...) """
data/MirantisWorkloadMobility/CloudFerry/tests/lib/os/actions/test_converter_volume_to_image.py
import mock from cloudferry.lib.os.actions import convert_volume_to_image from cloudferry.lib.utils import utils from tests import test class ConverterVolumeToImageTest(test.TestCase): def setUp(self): super(ConverterVolumeToImageTest, self).setUp() self.fake_src_cloud = mock.Mock() self....
data/acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/alt/app_engine.py
"""Provides functions to persist serialized auth tokens in the datastore. The get_token and set_token functions should be used in conjunction with gdata.gauth's token_from_blob and token_to_blob to allow auth token objects to be reused across requests. It is up to your own code to ensure that the token key's are uniqu...
data/StackStorm/st2/st2tests/st2tests/actions.py
from unittest2 import TestCase from st2actions.runners.utils import get_action_class_instance from st2tests.mocks.action import MockActionWrapper from st2tests.mocks.action import MockActionService __all__ = [ 'BaseActionTestCase' ] class BaseActionTestCase(TestCase): """ Base class for Python runner a...
data/Theano/Theano/theano/tensor/nnet/Conv3D.py
from __future__ import absolute_import, print_function, division import numpy as N from six.moves import xrange import theano from theano.tensor import basic as T from theano.tensor.blas_headers import blas_header_text, blas_header_version from theano.tensor.blas import ldflags from theano.misc import strutil from t...
data/OctavianLee/Pywechat/pywechat/services/basic.py
import json import time import requests from pywechat.excepts import WechatError class Basic(object): """The basic class of all services. Attributes: app_id: the app id of a wechat account. app_secret: the app secret of a wechat account. access_token: the access token requests from ...
data/KKBOX/mass/setup.py
import os from setuptools import setup, find_packages with open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as f: required = f.read().splitlines() setup( name='mass', version='0.1.0', description='Computer Farm Management', author='', author_email='', packages=find_packag...
data/Hyphen-ated/RebirthItemTracker/src/item_tracker.py
""" This module handles everything related to the tracker behaviour. """ import json import time import urllib2 import logging from view_controls.view import DrawingTool, Event from game_objects.item import Item from game_objects.state import TrackerState, TrackerStateEncoder from log_parser import LogPars...
data/StackStorm/st2/st2reactor/tests/unit/test_hash_partitioner.py
import math from random_words import RandomWords from st2reactor.container.hash_partitioner import HashPartitioner, Range from st2tests import config from st2tests import DbTestCase from st2tests.fixturesloader import FixturesLoader PACK = 'generic' FIXTURES_1 = { 'sensors': ['sensor1.yaml', 'sensor2.yaml', 'sens...
data/OrbitzWorldwide/droned/droned/services/janitizer.py
from kitt.interfaces import moduleProvides, IDroneDService moduleProvides(IDroneDService) from kitt.util import dictwrapper import config SERVICENAME = 'janitizer' SERVICECONFIG = dictwrapper({ 'JANITIZE': { config.LOG_DIR: [ ('.*.log.\d+.*', int(7*len(config.AUTOSTART_SERVICES))), ]...
data/Sage-Bionetworks/synapsePythonClient/tests/unit/unit_test_Evaluation.py
from nose.tools import assert_raises from synapseclient.evaluation import Evaluation, Submission def test_Evaluation(): """Test the construction and accessors of Evaluation objects.""" assert_raises(ValueError, Evaluation, name='foo', description='bar', status='BAH') assert_raises(ValueError, Evalua...
data/Yelp/yelp-python/yelp/obj/span.py
from yelp.obj.response_object import ResponseObject class Span(ResponseObject): _fields = [ 'latitude_delta', 'longitude_delta' ]
data/Kami/python-yubico-client/yubico_client/yubico.py
import re import os import sys import time import hmac import base64 import hashlib import threading import logging import requests from yubico_client.otp import OTP from yubico_client.yubico_exceptions import (StatusCodeError, InvalidClientIdError, ...
data/Robpol86/colorclass/colorclass/parse.py
"""Parse color markup tags into ANSI escape sequences.""" import re from colorclass.codes import ANSICodeMapping, BASE_CODES CODE_GROUPS = ( tuple(set(str(i) for i in BASE_CODES.values() if i and (40 <= i <= 49 or 100 <= i <= 109))), tuple(set(str(i) for i in BASE_CODES.values() if i and (30 <= i <= 39 or ...
data/IanLewis/kay/kay/lib/werkzeug/datastructures.py
""" werkzeug.datastructures ~~~~~~~~~~~~~~~~~~~~~~~ This module provides mixins and classes with an immutable interface. :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import re import codecs import mimetypes from werkzeug...
data/Zeeker/sublime-SessionManager/json/decoder.py
import json import sublime from ..modules import session def _objectify(s): if isinstance(s, str): return json.loads(s) return s class SessionDecoder(json.JSONDecoder): def decode(self, s): o = _objectify(s) try: name = o["name"] windows = [ ...
data/ManiacalLabs/BiblioPixel/bibliopixel/drivers/network.py
from driver_base import DriverBase import socket import sys import time import os os.sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import log class CMDTYPE: SETUP_DATA = 1 PIXEL_DATA = 2 BRIGHTNESS = 3 class RETURN_CODES: SUCCESS = 255 ERROR = 0 ERROR...
data/JRBANCEL/Chromagnon/chromagnon/csvOutput.py
""" CSV Output Module """ import csv import sys def csvOutput(queryResult, separator=',', quote='"'): """ Display the data according to csv format """ csvWriter = csv.writer(sys.stdout, delimiter=separator, quotechar=quote, quoting=csv.QUOTE_MINIMAL) for line in queryRes...
data/Koed00/django-q/django_q/management/commands/qcluster.py
from optparse import make_option from django.core.management.base import BaseCommand from django.utils.translation import ugettext as _ from django_q.cluster import Cluster class Command(BaseCommand): help = _("Starts a Django Q Cluster.") option_list = BaseCommand.option_list + ( make_option(...
data/PyHDI/veriloggen/tests/extension/pipeline_/draw_graph/test_pipeline_draw_graph.py
from __future__ import absolute_import from __future__ import print_function import pipeline_draw_graph expected_verilog = """ module test ( ); reg CLK; reg RST; reg [32-1:0] x; reg vx; wire rx; reg [32-1:0] y; reg vy; wire ry; wire [32-1:0] z; wire vz; reg rz; blinkled uut ( .CLK(CLK...
data/Mimino666/langdetect/langdetect/detector_factory.py
import os from os import path import sys try: import simplejson as json except ImportError: import json from .detector import Detector from .lang_detect_exception import ErrorCode, LangDetectException from .utils.lang_profile import LangProfile class DetectorFactory(object): ''' Language Detector Fa...
data/DamnWidget/anaconda/anaconda_lib/jedi/utils.py
""" Utilities for end-users. """ from __future__ import absolute_import import __main__ from collections import namedtuple import re import os import sys from jedi import Interpreter from jedi.api.helpers import completion_parts from jedi.parser.user_context import UserContext def setup_readline(namespace_module=__...
data/adieu/djangoappengine/tests/transactions.py
from .testmodels import EmailModel from django.db.models import F from django.test import TestCase class TransactionTest(TestCase): emails = ['app-engine@scholardocs.com', 'sharingan@uchias.com', 'rinnengan@sage.de', 'rasengan@naruto.com'] def setUp(self): EmailModel(email=self.emails[0], numb...
data/PublicMapping/DistrictBuilder/django/publicmapping/redistricting/views.py
""" Django views used by the redistricting application. The methods in redistricting.views define the views used to interact with the models in the redistricting application. Each method relates to one type of output url. There are views that return GeoJSON, JSON, and HTML. This file is part of The Public Mapping Pr...
data/Starou/SimpleIDML/setup.py
import os from distutils.core import setup README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name="SimpleIDML", version="0.92.4", license='BSD Licence', author='Stanislas Guerra', auth...
data/RoseOu/flasky/venv/lib/python2.7/site-packages/forgery_py/forgery/name.py
"""Generate random names and name-related strings.""" import random from ..dictionaries_loader import get_dictionary __all__ = [ 'first_name', 'last_name', 'full_name', 'male_first_name', 'female_first_name', 'company_name', 'job_title', 'job_title_suffix', 'title', 'suffix', 'location', 'industry' ] d...
data/Jakemichaeldrew/Ctrl-S/build/bdist.win32/winexe/temp/bz2.py
def __load(): import imp, os, sys try: dirname = os.path.dirname(__loader__.archive) except NameError: dirname = sys.prefix path = os.path.join(dirname, 'bz2.pyd') mod = imp.load_dynamic(__name__, path) __load() del __load
data/SimonSapin/cairocffi/cairocffi/xcb.py
""" cairocffi.xcb ~~~~~~~~~~~~~ Bindings for XCB surface objects using xcffib. :copyright: Copyright 2014 by Simon Sapin :license: BSD, see LICENSE for details. """ from xcffib import visualtype_to_c_struct from . import cairo, constants from .surfaces import Surface, SURFACE_TYPE_TO_CLASS clas...
data/Pylons/pylons/tests/test_units/test_decorator_jsonify.py
import warnings from paste.fixture import TestApp from paste.registry import RegistryManager from __init__ import TestWSGIController def make_cache_controller_app(): from pylons.testutil import ControllerWrap, SetupCacheGlobal from pylons.decorators import jsonify from pylons.controllers import WSGIContr...
data/NervanaSystems/neon/examples/fast-rcnn/voc_eval.py
""" The mAP evaluation script and various util functions are from: https://github.com/rbgirshick/py-faster-rcnn/commit/45e0da9a246fab5fd86e8c96dc351be7f145499f """ import xml.etree.ElementTree as ET import os import cPickle import numpy as np def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree ...
data/HenryHu/pybbs/Config.py
from ConfigParser import * from StringIO import * from Log import Log import datetime class Config: @staticmethod def LoadConfig(): Config.parser = ConfigParser() try: sconff = open(CONFIG_FILE, "r") except: Log.warn("cannot open config file") return ...
data/SmartTeleMax/iktomi/iktomi/forms/shortcuts.py
from . import convs, widgets, fields from iktomi.utils.i18n import N_ class PasswordConv(convs.Char): error_mismatch = N_('password and confirm mismatch') error_required = N_('password required') def from_python(self, value): return dict([(field.name, None) for field in self.field.fields]) ...
data/VisualComputingInstitute/Beacon8/beacon8/init/Normal.py
import numpy as _np def normal(std): def init(shape, fan): return std*_np.random.randn(*shape) return init
data/LxMLS/lxmls-toolkit/lxmls/sequences/id_feature.py
from lxmls.sequences.label_dictionary import * import pdb class IDFeatures: ''' Base class to extract features from a particular dataset. feature_dic --> Dictionary of all existing features maps feature_name (string) --> feature_id (int) feture_names --> List of feature names. Each po...
data/adewes/blitzdb/blitzdb/tests/sql/test_many_to_many.py
import pytest import pprint from ..helpers.movie_data import Movie,Actor,Director from .fixtures import backend from blitzdb.backends.sql.relations import ManyToManyProxy def test_basics(backend): backend.init_schema() backend.create_schema() francis_coppola = Director({'name' : 'Francis Coppola'}) ...
data/HewlettPackard/python-hpOneView/examples/scripts/get-managed-sans.py
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import range from future import standard_library standard_library.install_aliases() import sys import re PYTHON_VERSION = sys.version_info[:3] PY2 = (PYTHON...