path stringlengths 23 146 | source_code stringlengths 0 261k |
|---|---|
data/OneDrive/onedrive-sdk-python/src/onedrivesdk/model/file.py | '''
'''
from __future__ import unicode_literals
from ..model.hashes import Hashes
from ..one_drive_object_base import OneDriveObjectBase
class File(OneDriveObjectBase):
def __init__(self, prop_dict={}):
self._prop_dict = prop_dict
@property
def hashes(self):
"""
... |
data/MongoEngine/django-mongoengine/setup.py | """
Django-MongoEngine
------------------
Django support for MongoDB using MongoEngine.
Links
`````
* `development version
<https://github.com/MongoEngine/django-mongoengine/raw/master
"""
from setuptools import setup, find_packages
import sys, os
__version__ = '0.2.1'
__description__ = 'Django support for Mong... |
data/IDSIA/brainstorm/brainstorm/scorers.py | from __future__ import division, print_function, unicode_literals
from collections import OrderedDict
import numpy as np
from brainstorm.describable import Describable
class Scorer(Describable):
def __init__(self, out_name='', targets_name='targets', mask_name='',
name=None):
self.ou... |
data/Lothiraldan/ZeroServices/examples/fosdem_2015/api.py | import asyncio
from zeroservices import ZeroMQMedium, ResourceService
from zeroservices.services import get_http_interface
from zeroservices.discovery import UdpDiscoveryMedium
if __name__ == '__main__':
loop = asyncio.get_event_loop()
medium = ZeroMQMedium(loop, UdpDiscoveryMedium)
service = ResourceSe... |
data/RJT1990/pyflux/pyflux/inference/__init__.py | """
The module Inference holds estimation procedures.
"""
from priors import Normal, InverseGamma, Uniform
from metropolis_hastings import metropolis_hastings
from norm_post_sim import norm_post_sim
from bbvi import BBVI
|
data/NYTimes/nytcampfin/test.py | import os
import unittest
import requests
import requests_cache
from nytcampfin import NytCampfin, NytCampfinError, NytNotFoundError
CURRENT_CYCLE = 2012
try:
API_KEY = os.environ['NYT_CAMPFIN_API_KEY']
except:
print "Please set your API Key as an environment variable"
class APITest(unittest.TestCase):
... |
data/XiaoMi/minos/supervisor/supervisor/supervisorctl.py | """supervisorctl -- control applications run by supervisord from the cmd line.
Usage: %s [options] [action [arguments]]
Options:
-c/--configuration -- configuration file path (default /etc/supervisor.conf)
-h/--help -- print usage message and exit
-i/--interactive -- start an interactive shell after executing command... |
data/PythonJS/PythonJS/pythonjs/inline_function.py | import ast, copy
from ast_utils import *
class Inliner:
def setup_inliner(self, writer):
self.writer = writer
self._with_inline = False
self._inline = []
self._inline_ids = 0
self._inline_breakout = False
def inline_helper_remap_names(self, remap):
return "JS('var %s')" %','.join(remap.values())
def i... |
data/VisTrails/VisTrails/scripts/watch_vistrail_servers.py | import xmlrpclib
import os
from subprocess import Popen, PIPE
from time import sleep
import smtplib
from email.mime.text import MIMEText
import logging
import logging.handlers
class VistrailWatcher(object):
"""
A class for watching the status of VisTrail Servers running on a machine
Servers are pinged and ... |
data/SheffieldML/GPy/GPy/core/parameterization/param.py | from paramz import Param
from .priorizable import Priorizable
from paramz.transformations import __fixed__
import logging, numpy as np
class Param(Param, Priorizable):
pass
|
data/SmokinCaterpillar/pypet/examples/example_21_scoop_multiprocessing.py | """ Example how to use SCOOP (http://scoop.readthedocs.org/en/0.7/) with pypet.
Start the script via ``python -m scoop example_21_scoop_multiprocessing.py``.
"""
__author__ = 'Robert Meyer'
import os
from pypet import Environment, cartesian_product
from pypet import pypetconstants
def multiply(traj):
"""So... |
data/StackStorm/st2/st2actions/st2actions/runners/windows_runner.py | import abc
from distutils.spawn import find_executable
import six
from st2actions.runners import ActionRunner
__all__ = [
'BaseWindowsRunner',
'WINEXE_EXISTS',
'SMBCLIENT_EXISTS'
]
WINEXE_EXISTS = find_executable('winexe') is not None
SMBCLIENT_EXISTS = find_executable('smbclient') is not None
ERROR_... |
data/VisTrails/VisTrails/vistrails/db/versions/v0_9_3/domain/workflow.py | from __future__ import division
from auto_gen import DBWorkflow as _DBWorkflow
from auto_gen import DBAbstractionRef, DBModule, DBGroup
from id_scope import IdScope
import copy
class DBWorkflow(_DBWorkflow):
def __init__(self, *args, **kwargs):
_DBWorkflow.__init__(self, *args, **kwargs)
self.ob... |
data/ReactiveX/RxPY/tests/test_observable/test_interval.py | import unittest
from datetime import datetime, timedelta
from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable
from rx.subjects import Subject
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_complete... |
data/PyHDI/veriloggen/veriloggen/dataflow/mul.py | from __future__ import absolute_import
from __future__ import print_function
import veriloggen.core.vtypes as vtypes
import veriloggen.core.module as module
def mkMultiplierCore(index, lwidth=32, rwidth=32, lsigned=True, rsigned=True, depth=6):
retwidth = lwidth + rwidth
m = module.Module('multiplier_cor... |
data/PyHDI/veriloggen/tests/extension/dataflow_/fixed_mul_shift/dataflow_fixed_mul_shift.py | from __future__ import absolute_import
from __future__ import print_function
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
from veriloggen import *
import veriloggen.dataflow as dataflow
def mkMain():
... |
data/NVIDIA/DIGITS/digits/model/tasks/__init__.py | from __future__ import absolute_import
from .caffe_train import CaffeTrainTask
from .torch_train import TorchTrainTask
from .train import TrainTask
|
data/MobProgramming/MobTimer.Python/Infrastructure/CountdownManager.py | import datetime
import time
class CountdownManager(object):
def __init__(self, root_tk_app):
self.start_time = time.time()
self.minutes = 0
self.seconds = 0
self.time_change_callbacks = []
self.count_down_total = datetime.timedelta(days=-1, minutes=0, seconds=0)
se... |
data/StartTheShift/thunderdome/thunderdome/connection.py | from collections import namedtuple
import httplib
import json
import logging
import Queue
import random
import re
import socket
import textwrap
from thunderdome.exceptions import ThunderdomeException
from thunderdome.spec import Spec
logger = logging.getLogger(__name__)
class ThunderdomeConnectionError(Thunderdome... |
data/XiaoMi/minos/owl/monitor/templatetags/extended_filter.py | from django import template
import utils.quota_util
register = template.Library()
@register.filter(name='param_group')
def param_group(graph_config) :
return '|'.join([group for group, key in graph_config])
@register.filter(name='param_key')
def param_key(graph_config):
return '|'.join(['-'.join((group,key)) f... |
data/StackStorm/st2/st2api/tests/unit/controllers/v1/test_actions_rbac.py | import httplib
import mock
import six
import st2common.validators.api.action as action_validator
from st2common.rbac.types import PermissionType
from st2common.rbac.types import ResourceType
from st2common.persistence.auth import User
from st2common.persistence.rbac import Role
from st2common.persistence.rbac import ... |
data/SUSE/azurectl/test/unit/commands_storage_container_test.py | import dateutil.parser
import sys
import mock
from mock import patch
from test_helper import *
import datetime
import azurectl
from azurectl.azurectl_exceptions import *
from azurectl.commands.storage_container import StorageContainerTask
class TestStorageContainerTask:
def setup(self):
sys.argv = [
... |
data/adamgreig/agg-kicad/scripts/check_lib.py | """
check_lib.py
Copyright 2015 Adam Greig
Licensed under the MIT licence, see LICENSE file for details.
Check all library files in a directory against a set of consistency rules.
"""
from __future__ import print_function, division
import sys
import os
import fnmatch
import re
EXCLUSIONS = ("agg-kicad.lib", "conn.... |
data/QuantSoftware/QuantSoftwareToolkit/Legacy/csvconverter/yahoo_csv_to_pkl.py | '''
Created on Feb 25, 2011
@note: This assumes that all the CSV files will have exactly 7 columns. It ignores the first row in the csv files because it it the heading.
All the data is converted from csv to pkl
@author: Shreyas Joshi
@contact: shreyasj@gatech.edu
@summary: This is used to convert CSV files fro... |
data/JeremyOT/Toto/templates/toto/chat/chat/receive_message.py | import toto
from toto.invocation import *
from tornado.ioloop import IOLoop
@asynchronous
def invoke(handler, params):
def receive_message(message):
handler.respond(result={'message': message})
handler.register_event_handler('message', receive_message, deregister_on_finish=True)
|
data/ProgVal/Limnoria/src/utils/python.py | import sys
import types
import fnmatch
import threading
def universalImport(*names):
"""Attempt to import the given modules, in order, returning the first
successfully imported module. ImportError will be raised, as usual, if
no imports succeed. To emulate ``from ModuleA import ModuleB'', pass the
st... |
data/OpenBazaar/OpenBazaar-Server/seed/peers.py | import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.pr... |
data/JeremyOT/Toto/tests/test_tasks.py | import unittest
from uuid import uuid4
from time import time, sleep
from toto.tasks import TaskQueue, AwaitableInstance, InstancePool
from tornado.ioloop import IOLoop
from tornado.gen import coroutine
class _Instance(object):
def __init__(self):
self.counter = 0
def increment(self):
self.counter += 1
... |
data/Yelp/paasta/paasta_itests/steps/chronos_steps.py | from behave import then
from behave import when
from paasta_tools import chronos_tools
@when(u'we create a trivial chronos job called "{job_name}"')
def create_trivial_chronos_job(context, job_name):
job_config = {
'async': False,
'command': 'echo 1',
'epsilon': 'PT15M',
'name': '... |
data/adamewing/bamsurgeon/scripts/match_fasta_to_bam.py | import os
import pysam
import argparse
import logging
import subprocess
from collections import OrderedDict as od
logger = logging.getLogger(__name__)
FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(format=FORMAT)
logger.setLevel(logging.INFO)
def main(args):
assert os.path.exists(args.fasta + '.fai'), '... |
data/Yelp/mrjob/tests/fs/__init__.py | from io import BytesIO
from tests.py2 import mock_stdout_or_stderr
from tests.sandbox import SandboxedTestCase
class MockSubprocessTestCase(SandboxedTestCase):
def mock_popen(self, module, main_func, env):
"""Main func should take the arguments
(stdin, stdout, stderr, argv, environ_dict).
... |
data/PyTables/PyTables/tables/tests/test_do_undo.py | from __future__ import print_function
from __future__ import absolute_import
import warnings
import tables
from tables import IsDescription, StringCol, BoolCol, IntCol, FloatCol
from tables.node import NotLoggedMixin
from tables.path import join_path
from tables.tests import common
from tables.tests.common import uni... |
data/StackStorm/st2contrib/packs/servicenow/actions/lib/actions.py | from st2actions.runners.pythonrunner import Action
import servicenow_rest.api as sn
class BaseAction(Action):
def __init__(self, config):
super(BaseAction, self).__init__(config)
self.client = self._get_client()
def _get_client(self):
instance_name = self.config['instance_name']
... |
data/IanLewis/django-lifestream/lifestream/rss.py | from django.contrib.syndication.views import Feed as SyndicationFeed
from django.core.urlresolvers import reverse
from django.conf import settings
from lifestream.models import Lifestream, Item
class RecentItemsFeed(SyndicationFeed):
title = "Recent Items"
description = "Recent Lifestream Items"
def link... |
data/StackStorm/st2contrib/packs/aws/actions/lib/ec2parsers.py | import boto
import six
class FieldLists():
ADDRESS = [
'allocation_id',
'association_id',
'domain',
'instance_id',
'network_interface_id',
'network_interface_owner_id',
'private_ip_address',
'public_ip'
]
BLOCK_DEVICE_TYPE = [
'attac... |
data/PacificBiosciences/cDNA_primer/pbtranscript-tofu/pbtranscript/tests/unit/test_initICE.py | """Test initICE."""
import unittest
class TestInitICE(unittest.TestCase):
"""Class for testing initICE."""
def setUp(self):
"""Set up testDir, dataDir, outDir, stdoutDir."""
self.rootDir = op.dirname(op.dirname(op.abspath(__file__)))
self.testDir = op.join(self.rootDir, "")
|
data/MostAwesomeDude/construct/construct/protocols/layer3/icmpv4.py | """
Internet Control Message Protocol for IPv4 (TCP/IP protocol stack)
"""
from construct import *
from ipv4 import IpAddress
echo_payload = Struct("echo_payload",
UBInt16("identifier"),
UBInt16("sequence"),
Bytes("data", 32),
)
dest_unreachable_payload = Struct("dest_unreachable... |
data/HumanDynamics/openPDS/openpds/core/templatetags/verbatim.py | """
From ericflo (https://gist.github.com/629508)
jQuery templates use constructs like:
{{if condition}} print something{{/if}}
This, of course, completely screws up Django templates,
because Django thinks {{ and }} mean something.
Wrap {% verbatim %} and {% endverbatim %} around those
blocks of jQuery template... |
data/IDSIA/brainstorm/brainstorm/tests/test_schedules.py | from __future__ import division, print_function, unicode_literals
import pytest
import six
from brainstorm.training.schedules import Exponential, Linear, MultiStep
def test_linear():
sch = Linear(initial_value=1.0, final_value=0.5, num_changes=5)
epochs = [0] * 2 + [1] * 2 + [2] * 2 + [3] * 2 + [4] * 2
... |
data/OpenMDAO/OpenMDAO/openmdao/core/problem.py | """ OpenMDAO Problem class defintion."""
from __future__ import print_function
import os
import sys
import json
import warnings
import traceback
from collections import OrderedDict
from itertools import chain
from six import iteritems, itervalues
from six.moves import cStringIO
import networkx as nx
import numpy as ... |
data/StackStorm/st2contrib/packs/dimensiondata/actions/create_balancer.py | from libcloud.loadbalancer.base import Algorithm
from lib.actions import BaseAction
__all__ = [
'CreateBalancerAction'
]
class CreateBalancerAction(BaseAction):
def run(self, region, network_domain_id, name, port, protocol,
algorithm=Algorithm.ROUND_ROBIN):
driver = self._get_lb_driver(... |
data/PMEAL/OpenPNM/test/unit/Geometry/models/PoreCentroidTest.py | class PoreCentroidTest:
def test_voronoi(self):
pass
|
data/VinF/deer/deer/agent_ale.py | """This module contains classes used to define an agent suited for playing with the ALE environment.
See environments.ALE_env, run_ALE.
Authors: Vincent Francois-Lavet, David Taralla
"""
from .agent import NeuralAgent
class ALEAgent(NeuralAgent):
def _chooseAction(self):
if self._mode != -1:
... |
data/UFAL-DSG/cloud-asr/cloudasr/worker/run.py | import os
from lib import create_worker
worker = create_worker(os.environ['MODEL'], os.environ['HOST'], os.environ['PORT0'], os.environ['MASTER_ADDR'], os.environ['RECORDINGS_SAVER_ADDR'])
worker.run()
|
data/RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py | """
Provides the hierarchy of DDL-defining schema items as well as routines
to invoke them for a create/drop call.
"""
from .. import util
from .elements import ClauseElement
from .visitors import traverse
from .base import Executable, _generative, SchemaVisitor, _bind_or_error
from ..util import topological
from .. ... |
data/OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/types/newbytes.py | """
Pure-Python implementation of a Python 3-like bytes object for Python 2.
Why do this? Without it, the Python 2 bytes object is a very, very
different beast to the Python 3 bytes object.
"""
from collections import Iterable
from numbers import Integral
import string
from future.utils import istext, isbytes, PY3, ... |
data/HunanTV/redis-ctl/models/proxy.py | from werkzeug.utils import cached_property
from base import db, Base
from cluster import Cluster
class Proxy(Base):
__tablename__ = 'proxy'
host = db.Column(db.String(255), nullable=False)
port = db.Column(db.Integer, nullable=False)
eru_container_id = db.Column(db.String(64), index=True)
cluste... |
data/KunihikoKido/sublime-elasticsearch-client/panel/__init__.py | from .alias_list_panel import AliasListPanel
from .analyzer_list_panel import AnalyzerListPanel
from .doc_type_list_panel import DocTypeListPanel
from .field_list_panel import FieldListPanel
from .index_list_panel import IndexListPanel
from .index_template_list_panel import IndexTemplateListPanel
from .repository_list_... |
data/HumanDynamics/openPDS/openpds/authorization.py | from tastypie.authorization import Authorization
from openpds.authentication import OAuth2Authentication
from openpds.core.models import Profile, AuditEntry
import settings
import pdb
import traceback
class PDSAuthorization(Authorization):
audit_enabled = True
scope = ""
requester_uuid = ""
def r... |
data/adamb70/CSGO-Market-Float-Finder/CSGOproto/csgo_base.py | class GCConnectionStatus:
GCConnectionStatus_HAVE_SESSION = 999
GCConnectionStatus_GC_GOING_DOWN = 1
GCConnectionStatus_NO_SESSION = 2
GCConnectionStatus_NO_SESSION_IN_LOGON_QUEUE = 3
GCConnectionStatus_NO_STEAM = 4
class EGCSystemMsg:
k_EGCMsgInvalid = 0
k_EGCMsgMulti = 1
k_EGCMsgGene... |
data/ODM2/ODMToolsPython/odmtools/gui/pageMethod.py | import wx
import wx.grid
import wx.richtext
from odmtools.odmdata import Method
[wxID_PNLMETHOD, wxID_PNLMETHODSLISTCTRL1, wxID_PNLMETHODSRBCREATENEW,
wxID_PNLMETHODSRBGENERATE, wxID_PNLMETHODSRBSELECT,
wxID_PNLMETHODSRICHTEXTCTRL1,
] = [wx.NewId() for _init_ctrls in range(6)]
from odmtools.common.logger import Log... |
data/adlnet/ADL_LRS/lrs/tests/test_AgentProfile.py | import hashlib
import urllib
import base64
import json
import ast
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from adl_lrs.views import register
class AgentProfileTests(TestCase):
testagent = '{"mbox":"mailto:test@example.com"}'
otheragent = ... |
data/RDFLib/rdfextras/test/test_sparql/test_advanced_sparql_constructs.py | import unittest
from rdflib import plugin
from rdflib.namespace import Namespace,RDF,RDFS
from rdflib.term import URIRef
from rdflib.store import Store
from cStringIO import StringIO
from rdflib import Graph
import rdflib
try:
set
except NameError:
from sets import Set as set
testGraph1N3="""
@prefix rdf: ... |
data/OpenBazaar/OpenBazaar-Server/db/migrations/migration1.py | import sqlite3
def migrate(database_path):
print "migrating to db version 1"
conn = sqlite3.connect(database_path)
conn.text_factory = str
cursor = conn.cursor()
cursor.execute('''SELECT * FROM notifications''')
notifications = cursor.fetchall()
cursor.execute('''DROP TABLE not... |
data/Impactstory/total-impact-core/test/unit_tests/providers/test_pmc.py | import os, collections, simplejson
from totalimpact import db, app
from totalimpact.providers import pmc
from test.unit_tests.providers import common
from test.unit_tests.providers.common import ProviderTestCase
from totalimpact.providers.provider import Provider, ProviderContentMalformedError, ProviderFactory
from to... |
data/Impactstory/total-impact-core/totalimpact/providers/plosalm.py | from totalimpact.providers import provider
from totalimpact.providers.provider import Provider, ProviderContentMalformedError
import simplejson, os, re, urllib
import logging
logger = logging.getLogger('ti.providers.plosalm')
class Plosalm(Provider):
example_id = ("doi", "10.1371/journal.pcbi.1000361")
u... |
data/ReactiveX/RxPY/rx/linq/observable/skipuntilwithtime.py | from datetime import datetime
from rx.observable import Observable
from rx.anonymousobservable import AnonymousObservable
from rx.disposables import CompositeDisposable
from rx.internal import extensionmethod
@extensionmethod(Observable)
def skip_until_with_time(self, start_time, scheduler):
"""Skips elements fr... |
data/Yelp/dumb-init/tests/tty_test.py | EOF = b'\x04'
def ttyflags(fd):
"""normalize tty i/o for testing"""
import termios as T
attrs = T.tcgetattr(fd)
attrs[1] &= ~T.OPOST
attrs[3] &= ~T.ECHO
T.tcsetattr(fd, T.TCSANOW, attrs)
def readall(fd):
"""read until EOF"""
from os import read
result = b''
whil... |
data/agschwender/pilbox/pilbox/test/runtests.py | from __future__ import absolute_import, division, with_statement
import logging
import sys
import textwrap
from tornado.test.util import unittest
TEST_MODULES = [
'pilbox.test.app_test',
'pilbox.test.errors_test',
'pilbox.test.image_test',
'pilbox.test.signature_test',
]
def all():
return unitt... |
data/SEED-platform/seed/seed/lib/mcm/mappings/espm.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
"""
"""
This module describes how data is mapped from our ontology... |
data/adampresley/sublime-view-in-browser/ViewInBrowserCommand.py | import os
import sys
import re
import json
import urllib
import sublime
import tempfile
import subprocess
import sublime_plugin
import webbrowser
PLUGIN_VERSION = "2.0.0"
class ViewInBrowserCommand(sublime_plugin.TextCommand):
_pythonVersion = sys.version_info[0]
def expandWindowsUserShellFolder(self, comm... |
data/adieu/django-mediagenerator/mediagenerator/management/commands/importsassframeworks.py | from ...filters import sass
from ...utils import get_media_dirs
from django.conf import settings
from django.core.management.base import NoArgsCommand
from subprocess import Popen, PIPE
import os
import shutil
import sys
import __main__
_frameworks_dir = 'imported-sass-frameworks'
if hasattr(__main__, '__file__'):
... |
data/Netflix/security_monkey/security_monkey/auditors/rds_security_group.py | """
.. module: security_monkey.auditors.rds_security_group
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Patrick Kelley <pkelley@netflix.com> @monkeysecurity
"""
from security_monkey.auditor import Auditor
from security_monkey.watchers.rds_security_group import RDSSecurityGroup
from security_monkey.d... |
data/SEED-platform/seed/config/settings/dev.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
"""
from __future__ import absolute_import
from config.settings.c... |
data/PythonCharmers/python-future/discover_tests.py | """
Simple auto test discovery.
From http://stackoverflow.com/a/17004409
"""
import os
import sys
import unittest
if not hasattr(unittest.defaultTestLoader, 'discover'):
try:
import unittest2 as unittest
except ImportError:
raise ImportError('The unittest2 module is required to run tests on Py... |
data/Yubico/python-yubico/test/soft/__init__.py | """
Unit tests testing logic of the library.
These do not require a physical YubiKey to run.
"""
|
data/SmokinCaterpillar/pypet/pypet/tests/unittests/pypetlogging_test.py | __author__ = 'Robert Meyer'
import sys
if (sys.version_info < (2, 7, 0)):
import unittest2 as unittest
else:
import unittest
try:
import cPickle as pickle
except ImportError:
import pickle
from pypet.pypetlogging import LoggingManager
from pypet.tests.testutils.ioutils import get_log_config, run_suit... |
data/PythonJS/PythonJS/pythonjs/pythonjs_to_dart.py | import sys
import ast
import pythonjs
class TransformSuperCalls( ast.NodeVisitor ):
def __init__(self, node, class_names):
self._class_names = class_names
self.visit(node)
def visit_Call(self, node):
if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id in s... |
data/StackStorm/st2/st2client/st2client/config.py | __all__ = [
'get_config',
'set_config'
]
CONFIG = {}
def get_config():
"""
Retrieve parsed config object.
:rtype: ``dict``
"""
global CONFIG
return CONFIG
def set_config(config):
"""
Store parsing config object.
:type config: ``dict``
:rtype: ``dict``
"""
... |
data/UniversalDevicesInc/Polyglot/setup.py | """ Controls how Polyglot should be built by Python """
from distutils.core import setup
from Cython.Build import cythonize
PACKAGES = ['polyglot', 'polyglot.element_manager',
'polyglot.element_manager.http', 'polyglot.element_manager.isy']
setup(
name="Polyglot",
version="0.0.1",
author="Un... |
data/Theano/Theano/theano/gof/tests/test_types.py | from __future__ import absolute_import, print_function, division
import numpy
import theano
from theano import Op, Apply
from theano.tensor import TensorType
from theano.gof.type import CDataType
from nose.plugins.skip import SkipTest
class ProdOp(Op):
__props__ = ()
def make_node(self, i):
retur... |
data/IDSIA/sacred/tests/test_config/test_config_dict.py | from __future__ import division, print_function, unicode_literals
import pytest
import sacred.optional as opt
from sacred.config import ConfigDict
from sacred.config.custom_containers import DogmaticDict, DogmaticList
@pytest.fixture
def conf_dict():
cfg = ConfigDict({
"a": 1,
"b": 2.0,
"... |
data/MongoEngine/mongoengine/tests/fields/geo.py | import sys
sys.path[0:0] = [""]
import unittest
from mongoengine import *
from mongoengine.connection import get_db
__all__ = ("GeoFieldTest", )
class GeoFieldTest(unittest.TestCase):
def setUp(self):
connect(db='mongoenginetest')
self.db = get_db()
def _test_for_expected_error(self, Cls,... |
data/NeuroVault/NeuroVault/neurovault/apps/statmaps/migrations/0047_merge.py | from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('statmaps', '0046_auto_20150428_0616'),
('statmaps', '0040_auto_20150602_0312')
]
operations = [
]
|
data/QingdaoU/OnlineJudge/account/migrations/0019_user_is_forbidden.py | from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0018_auto_20160217_0920'),
]
operations = [
migrations.AddField(
model_name='user',
name='is_forbidden',
... |
data/Narcolapser/python-o365/O365/message.py | from O365.attachment import Attachment
from O365.contact import Contact
from O365.group import Group
import logging
import json
import requests
logging.basicConfig(filename='o365.log',level=logging.DEBUG)
log = logging.getLogger(__name__)
class Message( object ):
'''
Management of the process of sending, recieving... |
data/Wtower/django-ninecms/ninecms/utils/sanitize.py | """ Sanitize text input """
__author__ = 'George Karakostas'
__copyright__ = 'Copyright 2015, George Karakostas'
__licence__ = 'BSD-3'
__email__ = 'gkarak@9-dev.com'
from django.utils.html import strip_tags
from django import forms
import bleach
def sanitize(t, allow_html=True, full_html=False):
""" Bleach clean... |
data/MongoEngine/flask-mongoengine/flask_mongoengine/wtf/base.py | from mongoengine.base import BaseField
__all__ = ('WtfBaseField')
class WtfBaseField(BaseField):
"""
Extension wrapper class for mongoengine BaseField.
This enables flask-mongoengine wtf to extend the
number of field parameters, and settings on behalf
of document model form generator for WTForm.... |
data/Yipit/pyeqs/pyeqs/dsl/type.py | from __future__ import unicode_literals, absolute_import
class Type(dict):
def __init__(self, type_name):
super(Type, self).__init__()
self.type_name = type_name
self["type"] = self._build_dict()
def _build_dict(self):
return {
"value": self.type_name
}
|
data/MirantisWorkloadMobility/CloudFerry/cloudferry/lib/base/action/is_option.py | from cloudferry.lib.base.action import action
DEFAULT = 0
PATH_ONE = 1
PATH_TWO = 2
class IsOption(action.Action):
def __init__(self, init, option_name):
self.option_name = option_name
super(IsOption, self).__init__(init)
def run(self, **kwargs):
self.set_next_path(DEFAULT)
... |
data/StackStorm/st2contrib/packs/vsphere/actions/vm_hw_power.py | import eventlet
from pyVmomi import vim
from vmwarelib import inventory
from vmwarelib import checkinputs
from vmwarelib.actions import BaseAction
class VMApplyPowerState(BaseAction):
def run(self, vm_id, vm_name, power_onoff):
checkinputs.one_of_two_strings(vm_id, vm_name, "ID or Name")
... |
data/StackStorm/st2/st2api/st2api/controllers/v1/actions.py | import os
import os.path
import six
from pecan import abort
from mongoengine import ValidationError
from st2api.controllers import resource
from st2api.controllers.v1.actionviews import ActionViewsController
from st2common import log as logging
from st2common.constants.triggers import ACTION_FILE_WRITTEN_TRIGGER
... |
data/aaugustin/django-pymssql/setup.py | import os
import setuptools
os.putenv('COPYFILE_DISABLE', 'true')
README = os.path.join(os.path.dirname(__file__), 'README')
if not os.path.exists(README):
os.symlink(README + '.rst', README)
description = ('Django database backend for Microsoft SQL Server '
'that works on non-Windows systems.'... |
data/NeuroVault/NeuroVault/scripts/delete_old_collection_folders.py | """
deletes collection folders for collections that were deleted. after this update, folders should be deleted
automatically when the collection is deleted so this is simply to delete folders created before this update
"""
from neurovault.settings import PRIVATE_MEDIA_ROOT
import os
import os.path
from neurovault.apps... |
data/IDSIA/brainstorm/brainstorm/layers/batch_normalization_layer.py | from __future__ import division, print_function, unicode_literals
from collections import OrderedDict
from brainstorm.layers.base_layer import Layer
from brainstorm.structure.buffer_structure import (BufferStructure,
StructureTemplate)
from brainstorm.structure.const... |
data/MediaMath/qasino/lib/constants.py | SQL_PORT = 15000
ZMQ_RPC_PORT = 15598
HTTP_PORT = 15597
HTTPS_PORT = 443
ZMQ_PUBSUB_PORT = 15596
|
data/JamesHarrison/openob/openob/logger.py | import logging
class LoggerFactory(object):
_isSetup = False
def __init__(self, level=logging.DEBUG):
if LoggerFactory._isSetup is False:
logger = logging.getLogger("openob")
logger.setLevel(level)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(l... |
data/StackStorm/st2/st2common/st2common/exceptions/api.py | from st2common.exceptions import StackStormBaseException
__all__ = [
]
class InternalServerErrorException(StackStormBaseException):
pass
|
data/Kotti/Kotti/kotti/security.py | from __future__ import with_statement
from contextlib import contextmanager
from datetime import datetime
from UserDict import DictMixin
import bcrypt
from pyramid.location import lineage
from pyramid.security import view_execution_permitted
from six import string_types
from sqlalchemy import Boolean, bindparam
from s... |
data/QuantSoftware/QuantSoftwareToolkit/Legacy/Legacy/alphaDataModel/AlphaDataModel.py | '''
Created on Jun 1, 2010
@author: Shreyas Joshi
@summary: The purpose of this module is to make it easy to create hdf5 files with "alpha" values in them
'''
import tables as pt
fileName="defaultAlphaFileName.h5"
h5f=[]
group=[]
table=[]
opened=False
ctr=float (0.0)
class AlphaDataModelClass(pt.IsDescription... |
data/LxMLS/lxmls-toolkit/lxmls/parsing/dependency_parser.py | import sys
import numpy as np
from lxmls.parsing.dependency_reader import *
from lxmls.parsing.dependency_writer import *
from lxmls.parsing.dependency_features import *
from lxmls.parsing.dependency_decoder import *
from lxmls.util.my_math_utils import *
class DependencyParser():
'''
Dependency parser class
... |
data/StackStorm/st2contrib/packs/hue/actions/color_temp_kelvin.py | from lib import action
class ColorTempKelvinAction(action.BaseAction):
def run(self, light_id, temperature, transition_time):
light = self.hue.lights.get(light_id)
light.ct(temperature, transition_time)
|
data/adaptivdesign/django-sellmo/sellmo/apps/checkout/links.py | from sellmo.core import chaining
from sellmo.apps.customer.routines import customer_from_request
from sellmo.apps.customer.models import Contactable, Customer
from .routines import completed_order_from_request
@chaining.link(customer_from_request, takes_result=True)
def _customer_from_request(customer, request, **k... |
data/KeepSafe/aiohttp/tests/test_stream_writer.py | import pytest
import socket
from aiohttp.parsers import StreamWriter, CORK
from unittest import mock
def test_nodelay_default(loop):
transport = mock.Mock()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
transport.get_extra_info.return_value = s
proto = mock.Mock()
reader = mock.Mock()
... |
data/Rediker-Software/doac/doac/utils.py | def prune_old_authorization_codes():
"""
Removes all unused and expired authorization codes from the database.
"""
from .compat import now
from .models import AuthorizationCode
AuthorizationCode.objects.with_expiration_before(now()).delete()
def get_handler(handler_name):
"""
Imp... |
data/abunsen/Paython/paython/gateways/__init__.py | from authorize_net import AuthorizeNet
from innovative_gw import InnovativeGW
from firstdata_legacy import FirstDataLegacy
from plugnpay import PlugnPay
from stripe_com import Stripe
from samurai_ff import Samurai
from firstdata import FirstData
|
data/ImageEngine/gaffer/python/GafferUI/UIEditor.py | import weakref
import functools
import types
import re
import collections
import IECore
import Gaffer
import GafferUI
class UIEditor( GafferUI.NodeSetEditor ) :
def __init__( self, scriptNode, parenting = None ) :
self.__frame = GafferUI.Frame( borderWidth = 4, borderStyle = GafferUI.Frame.BorderStyle.None )
... |
data/RDFLib/rdfextras/test/JSON.py | from rdflib import ConjunctiveGraph, plugin
from rdflib.store import Store
from StringIO import StringIO
import unittest
"""Tests for JSON Serialization of SPARQL Results"""
test_data = """
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
<http://ex... |
data/ZEROFAIL/goblin/goblin/tests/properties_tests/properties_tests/integer_tests.py | from __future__ import unicode_literals
from nose.plugins.attrib import attr
from tornado.testing import gen_test
from .base_tests import GraphPropertyBaseClassTestCase, create_key
from goblin import connection
from goblin.properties.properties import Integer, Short, PositiveInteger, Long, PositiveLong
from goblin.mo... |
data/RDFLib/rdflib/examples/resource.py | """
RDFLib has a :class:`~rdflib.resource.Resource` class, for a resource-centric API.
A resource acts like a URIRef with an associated graph, and allows
quickly adding or querying for triples where this resource is the
subject.
"""
from rdflib import Graph, RDF, RDFS, Literal
from rdflib.namespace import FOAF
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.