path stringlengths 23 146 | source_code stringlengths 0 261k |
|---|---|
data/Zimbra-Community/python-zimbra/pythonzimbra/response_xml.py | """ XML-Response format. """
from xml.dom import minidom
from pythonzimbra.tools.xmlserializer import dom_to_dict
from .response import Response
class ResponseXml(Response):
response_doc = None
""" The response document we're working on """
response_type = "xml"
def clean(self):
super(Res... |
data/VisTrails/VisTrails/vistrails/db/services/vistrail.py | from __future__ import division
from vistrails.db.domain import DBWorkflow, DBAdd, DBDelete, DBAction, DBAbstraction, \
DBModule, DBConnection, DBPort, DBFunction, DBParameter, DBGroup
from vistrails.db.services.action_chain import getActionChain, getCurrentOperationDict, \
getCurrentOperations, simplify_ops
f... |
data/Kuniwak/vint/test/unit/vint/linting/config/test_config_file_source.py | import unittest
from test.asserting.config_source import ConfigSourceAssertion
from test.asserting.config_source import get_fixture_path
from vint.linting.config.config_file_source import ConfigFileSource
from vint.linting.level import Level
FIXTURE_CONFIG_FILE = get_fixture_path('fixture_config_file')
class TestCo... |
data/Moguri/bgui/bgui/video.py | from .gl_utils import *
from .texture import VideoTexture
from .widget import Widget, BGUI_DEFAULT, WeakMethod
from .image import Image
class Video(Image):
"""Widget for displaying video"""
def __init__(self, parent, vid, name=None, play_audio=False, repeat=0, aspect=None, size=[1, 1], pos=[0, 0],
sub_theme='... |
data/Yelp/bravado/tests/functional/request_func_test.py | """
Request related functional tests
"""
import httpretty
from six.moves import cStringIO
from six.moves.urllib import parse as urlparse
from bravado.client import SwaggerClient
from tests.functional.conftest import register_spec, API_DOCS_URL, register_get
def test_form_params_in_request(httprettified, swagger_dict... |
data/StackStorm/st2contrib/packs/libcloud/actions/lib/libcloud_parsers.py | import libcloud.compute.base as compute_base
import libcloud.dns.base as dns_base
import libcloud.loadbalancer.base as lb_base
import libcloud.container.base as container_base
__all__ = [
'FieldLists',
'ResultSets'
]
class FieldLists(object):
"""
The lists of fields we want to return for each class
... |
data/VisTrails/VisTrails/vistrails/core/system/unix.py | """Routines common to Linux and OSX."""
from __future__ import division
import os
import subprocess
__all__ = ['executable_is_in_path', 'list2cmdline', 'execute_cmdline',
'get_executable_path', 'execute_piped_cmdlines', 'execute_cmdline2']
def executable_is_in_path(filename):
""" executable_is_in_p... |
data/Pylons/pylons/pylons/decorators/util.py | """Decorator internal utilities"""
import pylons
from pylons.controllers import WSGIController
def get_pylons(decorator_args):
"""Return the `pylons` object: either the :mod`~pylons` module or
the :attr:`~WSGIController._py_object` equivalent, searching a
decorator's *args for the latter
:attr:`~WSGI... |
data/OpenMDAO/OpenMDAO/openmdao/components/constraint.py | """ ConstraintComp is now deprecated."""
import warnings
from openmdao.components.exec_comp import ExecComp
class ConstraintComp(ExecComp):
"""
ConstraintComp is deprecated. Please see the basic tutorial for more information.
A Component that represents an equality or inequality constraint.
Args
... |
data/Unidata/siphon/siphon/__init__.py | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
__all__ = ['catalog', 'testing', 'http_util']
|
data/OpenKMIP/PyKMIP/kmip/services/server/config.py | import logging
import os
import six
from six.moves import configparser
from kmip.core import exceptions
class KmipServerConfig(object):
"""
A configuration management tool for the KmipServer.
"""
def __init__(self):
"""
Create a KmipServerConfig object.
"""
self._log... |
data/PacificBiosciences/cDNA_primer/pbtranscript-tofu/pbtranscript/pbtools/pbtranscript/icedalign/IceDalignReader.py | __author__ = 'etseng@pacificbiosciences.com'
import pdb
import os, sys, subprocess
import numpy
from pbtools.pbtranscript.io.BLASRRecord import BLASRRecord
from pbtools.pbtranscript.ice.IceUtils import HitItem, eval_blasr_alignment, alignment_has_large_nonmatch
from pbtools.pbtranscript.ice.c_IceAlign import get_ece_a... |
data/ImageEngine/gaffer/python/GafferTest/pythonScripts/name.py | assert( __name__ == "__main__" )
|
data/abarto/tracker_project/tracker_project/tracker_project/views.py | from __future__ import absolute_import, unicode_literals
from braces.views import LoginRequiredMixin
from django.views.generic import TemplateView
class HomeView(LoginRequiredMixin, TemplateView):
template_name = 'tracker_project/home.html'
home = HomeView.as_view() |
data/Yelp/mrjob/tests/mr_sort_values.py | """Job to test if runners respect SORT_VALUES."""
from mrjob.job import MRJob
class MRSortValues(MRJob):
SORT_VALUES = True
def mapper_init(self):
pass
if __name__ == '__main__':
MRSortValues.run()
|
data/OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/optproblems/api.py | from sellar import SellarProblem, SellarProblemWithDeriv
from branin import BraninProblem
from scalable import UnitScalableProblem
from polyscale import PolyScalableProblem |
data/Theano/Theano/theano/sparse/sandbox/sp2.py | from __future__ import absolute_import, print_function, division
import numpy
from six.moves import xrange
import theano
import scipy.sparse
from theano import gof, tensor
from theano.tensor.opt import register_specialize
from theano.sparse.basic import (
as_sparse_variable, SparseType, add_s_s, neg,
mul_s_s, ... |
data/OpenMDAO/OpenMDAO-Framework/docs/python-scripts/rebuild.py | import glob
import os.path
from dirwalk import includingWalk
from os import system
from subprocess import Popen,PIPE,STDOUT
from compmodtimes import compmodtimes
from PIL import Image
def resize_image(fname, max_width=620):
im = Image.open(fname)
width, height = tuple(im.getbbox()[2:])
print 'height =',he... |
data/ImageEngine/gaffer/python/GafferAppleseedTest/AppleseedRenderTest.py | import os
import unittest
import subprocess32 as subprocess
import IECore
import Gaffer
import GafferTest
import GafferScene
import GafferAppleseed
import GafferAppleseedTest
class AppleseedRenderTest( GafferTest.TestCase ) :
def setUp( self ) :
GafferTest.TestCase.setUp( self )
self.__scriptFileName = self.... |
data/Kuniwak/vint/test/integration/vint/linting/policy/test_prohibit_command_with_unintented_side_effect.py | import unittest
from test.asserting.policy import PolicyAssertion, get_fixture_path
from vint.linting.level import Level
from vint.linting.policy.prohibit_command_with_unintended_side_effect import ProhibitCommandWithUnintendedSideEffect
PATH_VALID_VIM_SCRIPT = get_fixture_path('prohibit_command_with_unintended_side_... |
data/acil-bwh/SlicerCIP/Scripted/CIP_PAARatio/CIP_PAARatio.py | import os, sys
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
try:
from CIP.logic.SlicerUtil import SlicerUtil
except Exception as ex:
currentpath = os.path.dirname(os.path.realpath(__file__))
path = os.path.normpath(currentpath +... |
data/adblockplus/gyp/test/dependencies/gyptest-all-dependent-settings-order.py | """
Tests that all_dependent_settings are processed in topological order.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('all_dependent_settings_order.gyp', chdir='adso')
test.build('all_dependent_settings_order.gyp', chdir='adso')
test.built_file_must_match('out.txt', 'd.cc a.cc b.cc c.cc',
... |
data/KristianOellegaard/django-health-check/health_check/urls.py | from django.conf.urls import patterns, include, url
import health_check
health_check.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'health_check.views.home', name='health_check_home'),
)
|
data/Microsoft/ApplicationInsights-Python/applicationinsights/channel/contracts/ExceptionDetails.py | import collections
import copy
from .Utils import _write_complex_object
class ExceptionDetails(object):
"""Data contract class for type ExceptionDetails.
"""
_defaults = collections.OrderedDict([
('id', None),
('outerId', None),
('typeName', None),
('message', None),
... |
data/MediaMath/t1-python/tests/test_permissions.py | from __future__ import print_function
from __future__ import absolute_import
import unittest
import responses
import requests
from .requests_patch import patched_extract_cookies_to_jar
from terminalone import T1
mock_credentials = {
'username': 'user;',
'password': 'password',
'api_key': 'api_key',
}
AP... |
data/STIXProject/python-stix/stix/test/ttp_test.py | import unittest
from stix.test import EntityTestCase, assert_warnings
from stix.test import data_marking_test
from stix.test.common import related_test, identity_test, kill_chains_test
from stix.core import STIXPackage
import stix.ttp as ttp
from stix.ttp import (
resource, infrastructure, exploit_targets, malwar... |
data/HewlettPackard/python-hpOneView/examples/scripts/get-storage-volume-template-policy.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
PYTHON_VERSION = sys.version_info[:3]
PY2 = (PYTHON_VERSION[0... |
data/ImageEngine/gaffer/python/GafferSceneUI/CubeUI.py | import Gaffer
import GafferScene
Gaffer.Metadata.registerNode(
GafferScene.Cube,
"description",
"""
Produces scenes containing a cube.
""",
plugs = {
"dimensions" : [
"description",
"""
The size of the cube.
""",
],
}
)
|
data/KavenC/Linot/tests/interfaces/test_line_interface.py | from nose.tools import ok_, raises
from linot import config
from linot.interfaces.line_interface import LineClientP, LineInterface
class TestLineClientP:
def setUp(self):
self.line_cfg = config['interface']['line']
self.lineclient = LineClientP(self.line_cfg['account'],
... |
data/SALib/SALib/SALib/sample/morris.py | from __future__ import division
import numpy as np
import random as rd
from . import common_args
from ..util import scale_samples, read_param_file, compute_groups_matrix
from . optimal_trajectories import return_max_combo
from . morris_util import *
from operator import or_
try:
from gurobipy import *
except Im... |
data/NordicSemiconductor/pc-nrfutil/nordicsemi/dfu/tests/test_package.py | import json
import os
import tempfile
import unittest
from zipfile import ZipFile
import shutil
from nordicsemi.dfu.package import Package
class TestPackage(unittest.TestCase):
def setUp(self):
self.work_directory = tempfile.mkdtemp(prefix="nrf_dfu_tests_")
def tearDown(self):
shutil.rmtree(... |
data/adieu/allbuttonspressed/pygments/styles/fruity.py | """
pygments.styles.fruity
~~~~~~~~~~~~~~~~~~~~~~
pygments version of my "fruity" vim theme.
:copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Token, Comment, Name, Keyword, \
... |
data/VisTrails/VisTrails/contrib/edu_utah_sci_cscheid_teem/__init__.py | """Teem package for VisTrails.
"""
import core.modules
import core.modules.module_registry
import core.modules.basic_modules as basic
from core.modules.vistrails_module import Module, ModuleError, \
new_module, IncompleteImplementation
import os
import subprocess
_teemPath = None
_teemLimnTestPath = None
_... |
data/OpenMDAO/OpenMDAO-Framework/contrib/cobyla/setup.py | import os.path
import setuptools
import sys
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
include_dirs = []
library_dirs = []
if sys.platform == 'win32':
import types
def _lib_dir_option(self, dir):
return '/LIBPATH:"%s"' % dir
from distutils... |
data/NeuralEnsemble/python-neo/neo/test/coretest/test_segment.py | """
Tests of the neo.core.segment.Segment class
"""
from __future__ import absolute_import, division, print_function
from datetime import datetime
try:
import unittest2 as unittest
except ImportError:
import unittest
import numpy as np
import quantities as pq
try:
from IPython.lib.pretty import pretty... |
data/OpenBazaar/OpenBazaar-Server/log.py | """
Copyright (c) 2014 Brian Muller
"""
import sys
from twisted.python import log
DEBUG = 5
WARNING = 4
INFO = 3
ERROR = 2
CRITICAL = 1
levels = {"debug": 5, "warning": 4, "info": 3, "error": 2, "critical": 1}
class FileLogObserver(log.FileLogObserver):
def __init__(self, f=None, level="info", default=DEBUG):
... |
data/Mindwerks/worldengine/worldengine/basic_map_operations.py | import math
def distance(pa, pb):
ax, ay = pa
bx, by = pb
return math.sqrt((ax - bx) ** 2 + (ay - by) ** 2)
def index_of_nearest(p, hot_points, distance_f=distance):
"""Given a point and a set of hot points it found the hot point
nearest to the given point. An arbitrary distance function can
... |
data/SublimeHaskell/SublimeHaskell/hsdev.py | import os
import os.path
import sys
import socket
import sublime
import sublime_plugin
import subprocess
import threading
import json
import time
import re
from functools import reduce
if int(sublime.version()) < 3000:
import symbols
from sublime_haskell_common import *
else:
import SublimeHaskell.symbols ... |
data/SEED-platform/seed/seed/features/steps.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 salad.steps.everything import ImportRecord, world, djan... |
data/boto/boto/tests/integration/route53/domains/__init__.py | |
data/ahmetalpbalkan/personal-dashboard/tasks/jawboneup.py | from . import requires, today_utc
import requests
from datetime import timedelta
DAYS_BACK = 4
@requires('jawboneup.access_token')
def sleeps(gauge_factory, config, logger):
gauge = gauge_factory('jawbone.sleeps')
access_token = config['jawboneup.access_token']
headers = {'Authorization' : 'Bearer {0}'.... |
data/VisTrails/VisTrails/vistrails/db/versions/v1_0_1/__init__.py | from __future__ import division
version = '1.0.1'
|
data/PyHDI/PyCoRAM/examples/contest/stencil-9p-light/cthread_st.py | DSIZE = 4
SIZE = 512
a_offset = 1 * 1024 * 1024
b_offset = 2 * 1024 * 1024
iochannel = CoramIoChannel(idx=0, datawidth=32)
mem0 = CoramMemory(idx=0, datawidth=8*DSIZE, size=SIZE)
mem1 = CoramMemory(idx=1, datawidth=8*DSIZE, size=SIZE)
mem2 = CoramMemory(idx=2, datawidth=8*DSIZE, size=SIZE)
mem_d0 = CoramM... |
data/Nikola-K/django_reddit/django_reddit/settings/local.py | '''
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
'''
from .common import *
DEBUG = env.bool('DJANGO_DEBUG', default=True)
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
SECRET_KEY = env("DJANGO_SECRET_KEY", default='CHANGEME!!!')
... |
data/Pylons/pyramid_jinja2/setup.py | import os
import sys
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
if sys.version_info[0] > 2:
README = open(os.path.join(here, 'README.rst'), encoding="utf-8").read()
CHANGES = open(os.path.join(here, 'CHANGES.txt'), encoding="utf-8").read()
else:
README = ... |
data/aarongarrett/inspyred/recipes/network_migrator.py | import sys
import socket
import pickle
import threading
import collections
import SocketServer
class NetworkMigrator(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
"""Defines a migration function across a network.
This callable class acts as a migration function that
allows candidate solutions... |
data/VisTrails/VisTrails/doc/usersguide/conf.py | import sys
import os
sys.path.insert(0, os.path.abspath('../..'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.pngmath',
'sphinx.ext.ifconfig',
'sphinx.ext.extlinks',
'sphinxarg... |
data/aacanakin/glim/glim/prototype/app/routes.py | """
This module provides url definitions for glim framework.
Example - basic routing
-----------------------
In glim, the route definitions are restful by default.
The available http methods are the following;
- POST
- PUT
- OPTIONS
- GET
- DELETE
- TRACE
- COPY
You can define by giving ht... |
data/PressLabs/silver/silver/migrations/0003_auto_20150417_0634.py | from __future__ import unicode_literals
from django.db import migrations
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('silver', '0002_auto_20150416_1009'),
]
operations = [
migrations.AddField(
model_name='customer',
name='meta... |
data/RobotLocomotion/director/src/python/director/thirdparty/min_bounding_rect.py | from __future__ import division
from numpy import *
import sys
def minBoundingRect(hull_points_2d):
edges = zeros( (len(hull_points_2d)-1,2) )
for i in range( len(edges) ):
edge_x = hull_points_2d[i+1,0] - hull_points_2d[i,0]
edge_y = hull_points_2d[i+1,1] - hull_points_2d[i,... |
data/TurboGears/gearbox/gearbox/commands/scaffold.py | from __future__ import print_function
import os
from argparse import RawDescriptionHelpFormatter
from gearbox.command import Command
from gearbox.template import GearBoxTemplate
from gearbox.utils.plugins import find_egg_info_dir
class ScaffoldCommand(Command):
def get_description(self):
return '''Create... |
data/OP2/PyOP2/test/unit/test_coloring.py | import pytest
import numpy
from random import randrange
from pyop2 import plan as _plan
from pyop2 import op2
backends = ['opencl', 'openmp']
valuetype = numpy.float64
NUM_ELE = 12
NUM_NODES = 36
NUM_ENTRIES = 4
class TestColoring:
"""
Coloring tests
"""
@pytest.fixture
def nodes(cls):
... |
data/MapQuest/mapquest-osm-server/src/python/apiserver/const.py | _ID = '_id'
API = 'api'
API_CALL_TIMEOUT = 'api-call-timeout'
API_VERSION = 'api-version'
API_VERSION_MAXIMUM = 'api-version-maximum'
API_VERSION_MINIMUM = 'api-version-minimum'
AREA = 'area'
AREA_MAX = 'area-max'
BBOX = 'bbox'
BOUNDS = 'bounds'
CFGSLAB = 'cfgslab'
CFGVERSION = 1
CHANGESET = 'changeset'... |
data/DamnWidget/anaconda/anaconda_lib/jedi/evaluate/cache.py | """
- the popular ``memoize_default`` works like a typical memoize and returns the
default otherwise.
- ``CachedMetaClass`` uses ``memoize_default`` to do the same with classes.
"""
import inspect
NO_DEFAULT = object()
def memoize_default(default=NO_DEFAULT, evaluator_is_first_arg=False, second_arg_is_evaluator=F... |
data/ImageEngine/gaffer/python/GafferDispatchTest/TextWriter.py | import os
import IECore
import Gaffer
import GafferDispatch
class TextWriter( GafferDispatch.ExecutableNode ) :
def __init__( self, name="TextWriter", requiresSequenceExecution = False ) :
GafferDispatch.ExecutableNode.__init__( self, name )
self.__requiresSequenceExecution = requiresSequenceExecution
sel... |
data/StackStorm/st2contrib/packs/vault/actions/is_initialized.py | from lib import action
class VaultIsInitializedAction(action.VaultBaseAction):
def run(self):
return self.vault.is_initialized()
|
data/RDFLib/rdfextras/test/test_sparql/test_sparql_load_contexts.py | from urllib2 import URLError
try:
from Ft.Lib import UriException
except:
from urllib2 import URLError as UriException
import unittest
from rdflib import ConjunctiveGraph, URIRef
class SPARQLloadContextsTest(unittest.TestCase):
def test_dSet_parsed_as_URL_raises_Exception(self):
querystr = """SELE... |
data/HewlettPackard/python-ilorest-library/src/ilorest/ris/validation.py | """RIS Schema classes"""
import os
import re
import sys
import json
import locale
import zipfile
import logging
import textwrap
import validictory
from .sharedtypes import JSONEncoder
from ilorest.rest.v1_helper import (RisObject)
LOGGER = logging.getLogger(__name__)
class ValidationError(Exception):
... |
data/Yelp/fullerite/src/diamond/collectors/jolokia/test/testkafka_jolokia.py | from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from kafka_jolokia import KafkaJolokiaCollector
def find_metric(metric_list, metric_name):
return filter(lambda metric:metric["na... |
data/SheffieldML/GPy/GPy/testing/pickle_tests.py | '''
Created on 13 Mar 2014
@author: maxz
'''
import unittest, itertools
import pickle
import numpy as np
import tempfile
from GPy.examples.dimensionality_reduction import mrd_simulation
from GPy.core.parameterization.variational import NormalPosterior
from GPy.models.gp_regression import GPRegression
import GPy
from ... |
data/StackStorm/st2/st2client/tests/fixtures/loader.py | try:
import simplejson as json
except ImportError:
import json
import os
import six
import yaml
ALLOWED_EXTS = ['.json', '.yaml', '.yml', '.txt']
PARSER_FUNCS = {'.json': json.load, '.yml': yaml.safe_load, '.yaml': yaml.safe_load}
def get_fixtures_base_path():
return os.path.dirname(__file__)
def loa... |
data/PMEAL/OpenPNM/test/unit/Phases/GenericPhaseTest.py | import pytest
import OpenPNM
class GenericPhaseTest:
def setup_class(self):
self.net = OpenPNM.Network.Cubic(shape=[5, 5, 5])
def test_init_w_no_network(self):
OpenPNM.Phases.GenericPhase()
def test_init_w_components(self):
comp1 = OpenPNM.Phases.GenericPhase(network=self.net)
... |
data/LargePanda/LearnPy/examples/nb_example.py | __author__ = 'Jiarui Xu'
from learnpy.Problem import Problem
pro = Problem("BinaryClassification", "./data/iris_training.csv")
pro.set_label('Name')
pro.set_model("NaiveBayes")
pro.model.fit(None)
pro.set_testing("./data/iris_testing.csv")
pro.predict()
pro2 = Problem("BinaryClassification", "./data/lin_tra... |
data/RobotWebTools/rosbridge_suite/rosbridge_library/setup.py | from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['rosbridge_library', 'rosbridge_library.internal', 'rosbridge_library.capabilities', 'rosbridge_library.util'],
package_dir={'' : 'src'},
)
setup(**d)
|
data/LabPy/lantz/lantz/drivers/legacy/cobolt/__init__.py | """
lantz.drivers.legacy.cobolt
~~~~~~~~~~~~~~~~~~~~~~~~~~~
:company: Cobolt.
:description: DPSS lasers, diode laser modules, fiber pigtailed lasers.
:website: http://www.cobolt.se/
----
:copyright: 2015 by Lantz Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for mo... |
data/StackStorm/st2/st2common/st2common/util/crypto.py | import binascii
def symmetric_encrypt(encrypt_key, message):
"""
Encrypt the given message using the encrypt_key. Returns a UTF-8 str
ready to be stored in database. Note that we convert the hex notation
to a ASCII notation to produce a UTF-8 friendly string.
Also, this method will not return the... |
data/RoseOu/flasky/venv/lib/python2.7/site-packages/markdown/extensions/sane_lists.py | """
Sane List Extension for Python-Markdown
=======================================
Modify the behavior of Lists in Python-Markdown t act in a sane manor.
In standard Markdown sytex, the following would constitute a single
ordered list. However, with this extension, the output would include
two lists, the first an ... |
data/Rochester-NRT/RocAlphaGo/tests/test_gtp_wrapper.py | from interface.gtp_wrapper import run_gtp
from multiprocessing import Process
from AlphaGo import go
import unittest
class PassPlayer(object):
def get_move(self, state):
return go.PASS_MOVE
class TestGTPProcess(unittest.TestCase):
def test_run_commands(self):
def stdin_simulator():
return "\n".join([
... |
data/agermanidis/SnapchatBot/snapchat_bots/bot.py | import logging, time, uuid, requests, base64
from pysnap import Snapchat
from pysnap.utils import make_request_token, timestamp
from snap import Snap
from constants import DEFAULT_TIMEOUT, STATIC_TOKEN, BASE_URL
FORMAT = '[%(asctime)-15s] %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger()
log... |
data/StackStorm/st2contrib/packs/reamaze/actions/create_message.py | from lib.actions import BaseAction
class CreateMessage(BaseAction):
VISIBILITY = {
'internal': 1,
'regular': 0,
}
def run(self, slug, message, visibility='internal',
suppress_notification=False):
payload = {
'message': {
'body': message,
... |
data/KunihikoKido/sublime-elasticsearch-client/commands/show_output_panel.py | import sublime_plugin
class ShowOutputPanelCommand(sublime_plugin.WindowCommand):
default_syntax = "Packages/Text/Plain text.tmLanguage"
def run(self, text, syntax=None):
if syntax is None:
syntax = self.default_syntax
panel = self.window.create_output_panel("elasticsearch")
... |
data/ImageEngine/gaffer/python/GafferImageTest/ObjectToImageTest.py | import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTes... |
data/HenryHu/pybbs/xmppserver.py | import time
import UserManager
import UserInfo
from Session import Session
from Log import Log
import UCache
import Config
import MsgBox
import xmpp
import modes
import Util
import traceback
import os
from xmpp.features import NoRoute
__disco_info_ns__ = 'http://jabber.org/protocol/disco
__disco_items_ns__ = 'http://... |
data/RobotWebTools/rosbridge_suite/rosbridge_server/src/tornado/curl_httpclient.py | """Non-blocking HTTP client implementation using pycurl."""
from __future__ import absolute_import, division, print_function, with_statement
import collections
import logging
import pycurl
import threading
import time
from tornado import httputil
from tornado import ioloop
from tornado.log import gen_log
from tornad... |
data/NicoSantangelo/sublime-text-trello/tests/test_operations.py | import unittest
from .mock import MagicMock, Mock
from .util import TrelloElementMock, CommandMock, OperationMock
from operations import *
class BaseOperationTests(unittest.TestCase):
def setUp(self):
self.base_operation, self.trello_element = OperationMock.create(BaseOperation)
self.class_mock, s... |
data/OpenSlides/OpenSlides/tests/unit/users/test_serializers.py | from unittest import TestCase
from unittest.mock import MagicMock, patch
from openslides.users.serializers import UserFullSerializer
from openslides.utils.rest_api import ValidationError
class UserCreateUpdateSerializerTest(TestCase):
def test_validate_no_data(self):
"""
Tests, that the validator... |
data/MBoustani/Geothon/Conversion Tools/shp_line_to_point.py | '''
Project: Geothon (https://github.com/MBoustani/Geothon)
File: Conversion_Tools/shp_line_to_point.py
Description: This code converts polygon shapfile to point shapefile.
Author: Maziyar Boustani (github.com/MBoustani)
'''
import os
try:
import ogr
except ImportError:
from osgeo impor... |
data/ImageEngine/gaffer/python/GafferTest/FileSystemPathTest.py | from __future__ import with_statement
import unittest
import time
import datetime
import pwd
import grp
import os
import IECore
import Gaffer
import GafferTest
class FileSystemPathTest( GafferTest.TestCase ) :
def test( self ) :
p = Gaffer.FileSystemPath( __file__ )
self.assert_( p.isValid() )
self.assert... |
data/OpenSlides/OpenSlides/openslides/assignments/__init__.py | default_app_config = 'openslides.assignments.apps.AssignmentsAppConfig'
|
data/NeuralEnsemble/python-neo/neo/test/iotest/test_neuroscopeio.py | """
Tests of neo.io.neuroscopeio
"""
from __future__ import absolute_import, division
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import NeuroScopeIO
from neo.test.iotest.common_io_test import BaseTestIO
class TestNeuroScopeIO(BaseTestIO, unittest.TestCase, ):
ioc... |
data/aerospike/aerospike-admin/test/e2e/test_util.py | import re
def parse_output(actual_out = "", horizontal = False, mearge_header = True):
"""
commmon parser for all show commands will return touple of following
@param heading : first line of output
@param header: Second line of output
@param params: list of parameters
"""
... |
data/adamcharnock/dokku-client/dokku_client/commands/__init__.py | import re
from sarge import capture_stdout, run
from dokku_client.command_tools import global_opts_doc
class BaseCommand(object):
check_config = True
sort_order = 10
def __init__(self, name):
self._name = name
self.args = {}
@property
def doc(self):
"""Get the d... |
data/Workiva/furious/furious/tests/test_config.py | import unittest
import os
from mock import patch
class TestConfigurationLoading(unittest.TestCase):
def setUp(self):
super(TestConfigurationLoading, self).setUp()
self._reset_config()
def tearDown(self):
super(TestConfigurationLoading, self).tearDown()
self._reset_config()
... |
data/Theano/Theano/theano/tensor/tests/test_complex.py | from __future__ import absolute_import, print_function, division
import unittest
from six.moves import xrange
import theano
from theano.tensor import *
from theano.tests import unittest_tools as utt
from numpy.testing import dec
class TestRealImag(unittest.TestCase):
def test0(self):
x = zvector()
... |
data/RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/dialects/postgresql/ranges.py | from .base import ischema_names
from ... import types as sqltypes
__all__ = ('INT4RANGE', 'INT8RANGE', 'NUMRANGE')
class RangeOperators(object):
"""
This mixin provides functionality for the Range Operators
listed in Table 9-44 of the `postgres documentation`__ for Range
Functions and Operators. It i... |
data/TheTorProject/ooni-probe/ooni/templates/httpt.py | import re
import random
from twisted.internet import defer
from txtorcon.interface import StreamListenerMixin
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
from ooni.utils.trueheaders import TrueHeadersAgent, TrueHeadersSOCKS5Agent
from ooni.nettest import NetTestCas... |
data/MirantisWorkloadMobility/CloudFerry/tests/lib/utils/test_cache.py | from cloudferry.lib.utils.cache import Memoized, Cached
from tests import test
class MemoizationTestCase(test.TestCase):
def test_treats_self_as_separate_objects(self):
class C(object):
def __init__(self, i):
self.i = i
@Memoized
def get_i(self):
... |
data/Unidata/netcdf4-python/test/tst_filepath.py | import os
import unittest
import netCDF4
class test_filepath(unittest.TestCase):
def setUp(self):
self.netcdf_file = os.path.join(os.getcwd(), "netcdf_dummy_file.nc")
self.nc = netCDF4.Dataset(self.netcdf_file)
def test_filepath(self):
assert self.nc.filepath() == str(self.netcdf_file... |
data/kuri65536/python-for-android/python3-alpha/python-libs/gdata/tlslite/utils/RSAKey.py | """Abstract class for RSA."""
from .cryptomath import *
class RSAKey:
"""This is an abstract base class for RSA keys.
Particular implementations of RSA keys, such as
L{OpenSSL_RSAKey.OpenSSL_RSAKey},
L{Python_RSAKey.Python_RSAKey}, and
L{PyCrypto_RSAKey.PyCrypto_RSAKey},
inherit from this.
... |
data/agiliq/merchant/billing/integrations/braintree_payments_integration.py | from billing import Integration, IntegrationNotConfigured
from django.conf import settings
from django.views.decorators.http import require_GET
from billing.signals import transaction_was_successful, transaction_was_unsuccessful
from django.conf.urls import patterns, url
import braintree
import urllib
from django.core.... |
data/Xion/SublimeScold/scold/system.py | """
Utilities for opening files or URLs in the registered default application
and for sending e-mail using the user's preferred composer.
Taken from the following recipe:
http://code.activestate.com/recipes/511443-cross-platform-startfile-and-mailto-functions/
"""
__version__ = '1.1'
__all__ = ['open', 'mailto']
imp... |
data/HydraChain/hydrachain/hydrachain/examples/native/fungible/test_iou_contract.py | from ethereum import tester
import hydrachain.native_contracts as nc
from fungible_contract import IOU
import ethereum.slogging as slogging
log = slogging.get_logger('test.iou')
def test_iou_template():
"""
Tests;
IOU initialization as Issuer,
Testing issue funds, get_issued_amount
"""
... |
data/QingdaoU/OnlineJudge/problem/migrations/0007_remove_problem_last_update_time.py | from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('problem', '0006_merge'),
]
operations = [
migrations.RemoveField(
model_name='problem',
name='last_update_time',
),
... |
data/NervanaSystems/neon/neon/layers/__init__.py | from neon.layers.layer import (Linear, Bias, Affine, Conv, Convolution, GeneralizedCost, Dropout,
Pooling, Activation, DataTransform, BatchNorm, BatchNormAutodiff,
Deconv, Deconvolution, GeneralizedCostMask, LookupTable,
Branch... |
data/QianmiOpen/dubbo-client-py/setup.py | """
Python Dubbo Library Client Server - Setup
Created
2015-4-10 by Joe - https://github.com/JoeCao
"""
import os
from setuptools import setup, find_packages
THISDIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(THISDIR)
VERSION = open("version.txt").readline().strip()
HOMEPAGE = "https://github.com/o... |
data/Yelp/fullerite/src/diamond/collectors/portstat/portstat.py | """
The PortStatCollector collects metrics about ports listed in config file.
* psutil
"""
from collections import defaultdict
import diamond.collector
try:
import psutil
except ImportError:
psutil = None
def get_port_stats(port):
"""
Iterate over connections and count states for specified port
... |
data/Robot-Will/Stino/stino/main.py | """
Documents
"""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import shutil
import sublime
import re
import zipfile
import time
from . import pyarduino
from . import st_base
from . import st_menu
from .... |
data/Edraak/edx-platform/common/lib/xmodule/xmodule/open_ended_grading_classes/__init__.py | __author__ = 'vik'
|
data/agiliq/django-socialnews/socialnews/news/admin.py | from django.contrib import admin
from django.db.models import get_models, get_app
models = get_models(get_app('news'))
for model in models:
admin.site.register(model) |
data/Leo-G/Flask-Scaffold/app/users/test_users.py | import unittest
import os
import sys
import json
sys.path.append(os.path.dirname(os.path.realpath(__file__).rsplit('/', 2)[0]))
from app import create_app
app = create_app('config')
add_data = """{
"data": {
"attributes":
{"active": "true", "role": "test string", "password": "test string", "creation_tim... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.