path stringlengths 23 146 | source_code stringlengths 0 261k |
|---|---|
data/aerospike/aerospike-client-python/test/new_tests/test_list_get_range.py | import pytest
import sys
import random
from .test_base_class import TestBaseClass
from aerospike import exception as e
aerospike = pytest.importorskip("aerospike")
try:
import aerospike
except:
print("Please install aerospike python client.")
sys.exit(1)
class TestListGetRange(object):
@pytest.fixtu... |
data/adblockplus/gyp/pylib/gyp/generator/xcode.py | import filecmp
import gyp.common
import gyp.xcodeproj_file
import gyp.xcode_ninja
import errno
import os
import sys
import posixpath
import re
import shutil
import subprocess
import tempfile
_intermediate_var = 'INTERMEDIATE_DIR'
_shared_intermediate_var = 'SHARED_INTERMEDIATE_DIR'
_library_search_paths_... |
data/Yipit/pyeqs/tests/unit/test_filter.py | from __future__ import unicode_literals
from pyeqs import Filter
from pyeqs.dsl import Term
from tests.helpers import homogeneous
def test_create_filter():
"""
Create Default Filter
"""
t = Filter()
results = {
"and": []
}
homogeneous(t, results)
def test_add_filter(... |
data/adaptivdesign/django-sellmo/example/variation/admin.py | from django.contrib import admin
from sellmo.contrib.variation.models import Variation
class VariationAdmin(admin.ModelAdmin):
search_fields = ['description']
list_display = ['description', 'stock']
list_editable = ['stock']
def has_add_permission(self, request):
return False
admin.site.re... |
data/Juniper/py-junos-eznc/tests/unit/utils/test_util.py | __author__ = "Nitin Kumar, Rick Sherman"
__credits__ = "Jeremy Schulman"
import unittest
from nose.plugins.attrib import attr
from jnpr.junos import Device
from jnpr.junos.utils.util import Util
from mock import patch
@attr('unit')
class TestUtil(unittest.TestCase):
@patch('ncclient.manager.connect')
def ... |
data/SergioChan/SCTornadoTCP/Server/urls.py | __author__ = 'Yuheng Chen'
Handler_mapping = {}
def handler(cmdid):
'''
decorator for custom Handler
used to add mapping between cmdId and Handler
'''
def _module_dec(cls):
Handler_mapping[cmdid] = cls
return cls
return _module_dec |
data/YelpArchive/pushmanager/pushmanager/tests/test_ui_methods.py | import testify as T
from pushmanager.ui_methods import authorized_to_manage_request
from pushmanager.ui_methods import sort_pickmes
class UIMethodTest(T.TestCase):
def test_authorized_to_manage_request_random_user(self):
request = {'user': 'testuser', 'watchers': None}
T.assert_equal(False, autho... |
data/NVIDIA/DIGITS/digits/dataset/images/__init__.py | from __future__ import absolute_import
from .classification import *
from .generic import *
from .job import ImageDatasetJob
|
data/Koed00/django-q/runtests.py | sources = """
eNrcvWuTG0eSIKjbe2Nvds/sztbsvmWDxwFAopIPqbd7sCrNUCTVzRuJpJFUN9tKNWAWkKjKLiAT
zExUFVqrsftwP/i+nN3X81dEekRGAihKvTN2sm5WIjPC4+Xh4e7hj//z3/z08bPh+//w2Wefrbfx
dFbM03iaVFVa1lmR5+n1x//q/YeHn33W7/d732T5PMryOi1X6TxL6jRKr5Llpk6waFSm1WZZV1Ag
4vpRBV/SVZrDy/qiLDbnF9HZJlvWUOLJ23dx791FVkXVRbFZzqH2epnM0qhpu1jO4/UWmgAAm2S... |
data/WatchPeopleCode/WatchPeopleCode/migrations/versions/14bb1343f5dc_.py | """empty message
Revision ID: 14bb1343f5dc
Revises: 15119ab3dc68
Create Date: 2015-04-06 01:26:26.626951
"""
revision = '14bb1343f5dc'
down_revision = '15119ab3dc68'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table('chat_message',
sa.Column('id', sa.Integer(), nullable=F... |
data/SmokinCaterpillar/pypet/examples/example_01_first_steps.py | __author__ = 'Robert Meyer'
import os
from pypet import Environment
from pypet.utils.explore import cartesian_product
def multiply(traj):
"""Example of a sophisticated simulation that involves multiplying two values.
:param traj:
Trajectory containing
the parameters in a particular combina... |
data/adobe/brackets-shell/gyp/pylib/gyp/__init__.py | import copy
import gyp.input
import optparse
import os.path
import re
import shlex
import sys
import traceback
from gyp.common import GypError
debug = {}
DEBUG_GENERAL = 'general'
DEBUG_VARIABLES = 'variables'
DEBUG_INCLUDES = 'includes'
def DebugOutput(mode, message):
if 'all' in gyp.debug.keys() or mode in gy... |
data/SUSE/azurectl/azurectl/management/request_result.py | import time
from ..azurectl_exceptions import (
AzureRequestStatusError,
AzureRequestTimeout,
AzureRequestError
)
class RequestResult(object):
"""
operate on azure request ID and provide methods
to get status information as well as define operations
based on the request statu... |
data/agoragames/torus/test/functional/web_test.py | '''
Copyright (c) 2013, Agora Games, LLC All rights reserved.
https://github.com/agoragames/torus/blob/master/LICENSE.txt
'''
import time
import ujson
from chai import Chai
from torus.web import Web
from torus.configuration import Configuration
SCHEMAS = {
'redis-minutely' : {
'type' : 'histogram',
'hos... |
data/Netflix/security_monkey/security_monkey/watchers/redshift.py | """
.. module: security_monkey.watchers.redshift
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Ivan Leichtling <ivanlei@yelp.com> @c0wl
"""
from security_monkey.watcher import Watcher
from security_monkey.watcher import ChangeItem
from security_monkey.constants import TROUBLE_REGIONS
from security_m... |
data/RoseOu/flasky/venv/lib/python2.7/site-packages/httpie/compat.py | """
Python 2/3 compatibility.
"""
from requests.compat import (
is_windows,
bytes,
str,
is_py3,
is_py26,
)
try:
from urllib.parse import urlsplit
except ImportError:
from urlparse import urlsplit
|
data/PythonJS/PythonJS/regtests/bench/webworker_single.py | '''
webworker single
'''
from time import time
from time import sleep
import threading
def main():
if PYTHON=='PYTHONJS':
pythonjs.configure( direct_operator='+' )
pass
starttime = time()
n = 3000
seq = []
cache = []
w1 = threading.start_webworker( worker, (0, n, seq, cache) )
sleep(1.0)
testtime = t... |
data/Net-ng/kansha/kansha/card_addons/gallery/view.py | from nagare.i18n import _
from nagare import presentation, ajax, security, component
from .comp import Gallery, Asset, AssetCropper
def render_image(self, h, comp, size, randomize=False, **kw):
metadata = self.assets_manager.get_metadata(self.filename)
src = self.assets_manager.get_image_url(self.filename, s... |
data/ImageEngine/gaffer/python/GafferSceneTest/SceneTimeWarpTest.py | import unittest
import IECore
import Gaffer
import GafferTest
import GafferScene
import GafferSceneTest
class SceneTimeWarpTest( GafferSceneTest.SceneTestCase ) :
def testConstruct( self ) :
s = Gaffer.ScriptNode()
s["n"] = GafferScene.SceneTimeWarp()
self.assertEqual( s["n"]["speed"].getValue(), 1 )
sel... |
data/ImageEngine/gaffer/python/GafferTest/SequencePathTest.py | import unittest
import IECore
import Gaffer
import GafferTest
class SequencePathTest( GafferTest.TestCase ) :
def __dictPath( self ) :
dict = {}
dict["dir"] = {}
for f in IECore.FileSequence( "a.
dict["dir"][f] = 1
for f in IECore.FileSequence( "b.
dict["dir"][f] = 1
return Gaffer.DictPath( dict,... |
data/Yelp/mrjob/mrjob/examples/mr_next_word_stats.py | """For any word that appears in a document, compute stats about which
words come next (including percentage).
This is meant as a simple demonstration of why SORT_VALUES is useful.
"""
from mrjob.job import MRJob
from mrjob.step import MRStep
import re
WORD_RE = re.compile(r"[\w']+")
class MRNextWordStats(MRJob):
... |
data/PyHDI/veriloggen/examples/dataflow_example/test_dataflow_example.py | from __future__ import absolute_import
from __future__ import print_function
import dataflow_example
expected_verilog = """
module test;
reg CLK;
reg RST;
reg [32-1:0] xdata;
reg xvalid;
wire xready;
reg [32-1:0] ydata;
reg yvalid;
wire yready;
wire [32-1:0] zdata;
wire zvalid;
reg zready;
ma... |
data/IvanMalison/okcupyd/okcupyd/db/adapters.py | import logging
from okcupyd.db import model, txn, with_txn
log = logging.getLogger(__name__)
class UserAdapter(object):
def __init__(self, profile):
self.profile = profile
def build(self, session):
found = model.User.query_no_txn(session, model.User.handle ==
... |
data/Shopify/shopify_python_api/shopify/resources/shipping_zone.py | from ..base import ShopifyResource
class ShippingZone(ShopifyResource):
pass
|
data/VisTrails/VisTrails/contrib/titan/__init__.py | """The Titan Informatics Toolkit is a collaborative effort between
Sandia National Laboratories and Kitware Inc. It represents a
significant expansion of the Visualization ToolKit (VTK) to support
the ingestion, processing, and display of informatics data. By
leveraging the VTK engine, Titan provides a flexible, co... |
data/Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/openstack/common/rpc/zmq_receiver.py | import eventlet
eventlet.monkey_patch()
import contextlib
import sys
from oslo.config import cfg
from openstack_dashboard.openstack.common import log as logging
from openstack_dashboard.openstack.common import rpc
from openstack_dashboard.openstack.common.rpc import impl_zmq
CONF = cfg.CONF
CONF.register_opts(rpc.r... |
data/Tivix/django-rest-auth/rest_auth/tests/test_api.py | from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.core import mail
from django.conf import settings
from django.test.utils import override_settings
from django.utils.encoding import force_text
from rest_framework import status
from... |
data/HenryHu/pybbs/digest.py | import re
import os
import stat
import json
import struct
import time
import Config
import Board
import Post
import BoardManager
from Util import Util
from Log import Log
from errors import *
DEFAULT_DIGEST_LIST_COUNT = 20
class DigestItem:
def __init__(self, basepath):
self.basepath = basepath
se... |
data/adamchainz/django-mysql/tests/testapp/test_monkey_patches.py | from django.db import connections
from django.test import TestCase
class IsMariaDBTests(TestCase):
def test_connections(self):
for alias in connections:
connection = connections[alias]
if not hasattr(connection, 'mysql_version'):
continue
with connectio... |
data/Simont3/hcpsdk/src/setup.py | from setuptools import setup, find_packages
from codecs import open
from os import path
from hcpsdk.version import _Version
here = path.abspath(path.dirname(__file__))
with open(path.normpath(path.join(here, 'DESCRIPTION.rst')),encoding='utf-8') as f:
long_description = f.read()
setup(
name='hcpsdk',... |
data/ImageEngine/gaffer/python/GafferImageUI/DisplayUI.py | import threading
import IECore
import Gaffer
import GafferUI
import GafferImage
__all__ = []
Gaffer.Metadata.registerNode(
GafferImage.Display,
"description",
"""
Interactively displays images as they are rendered.
This node runs a server on a background thread,
allowing it to receive images from both loc... |
data/RoseOu/flasky/venv/lib/python2.7/site-packages/pip/_vendor/html5lib/treewalkers/_base.py | from __future__ import absolute_import, division, unicode_literals
from pip._vendor.six import text_type
import gettext
_ = gettext.gettext
from ..constants import voidElements, spaceCharacters
spaceCharacters = "".join(spaceCharacters)
class TreeWalker(object):
def __init__(self, tree):
self.tree = tre... |
data/ODM2/ODMToolsPython/tests/test_odmdata/test_session_factory.py | from odmtools.odmdata import SessionFactory
class TestSessionFactory:
def setup(self):
self.connection_string = "sqlite:///:memory:"
self.session_factory = SessionFactory(self.connection_string, echo=True)
def test_create_session_factory(self):
assert repr(self.session_factory) == "<S... |
data/JeremyGrosser/supervisor/src/supervisor/medusa/demo/publish.py | from supervisor.medusa import asyncore_25 as asyncore
from supervisor.medusa import default_handler
from supervisor.medusa import http_server
from supervisor.medusa import put_handler
from supervisor.medusa import auth_handler
from supervisor.medusa import filesys
users = { 'mozart' : 'jupiter', 'beethoven' : 'pa... |
data/Yelp/paasta/tests/monitoring/test_replication_utils.py | import os
import mock
import requests
from paasta_tools.monitoring.replication_utils import backend_is_up
from paasta_tools.monitoring.replication_utils import get_registered_marathon_tasks
from paasta_tools.monitoring.replication_utils import get_replication_for_services
from paasta_tools.monitoring.replication_util... |
data/adaptivdesign/django-sellmo/sellmo/contrib/checkout/mailing/internal/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from sellmo.core.loading import load
import sellmo.contrib.checkout.mailing as _checkout_mailing
@load(action='finalize_checkout_OrderMailMessage')
def finalize_model():
class OrderMailMessage(_checkout_mailing.models.OrderMail... |
data/ImageEngine/gaffer/python/GafferArnoldUITest/DocumentationTest.py | import GafferUITest
import GafferScene
import GafferSceneUI
import GafferArnold
import GafferArnoldUI
class DocumentationTest( GafferUITest.TestCase ) :
def test( self ) :
self.maxDiff = None
self.assertNodesAreDocumented(
GafferArnold,
additionalTerminalPlugTypes = ( GafferScene.ScenePlug, )
)
if __na... |
data/aerospike/aerospike-client-python/examples/client/append.py | from __future__ import print_function
import aerospike
import sys
from optparse import OptionParser
usage = "usage: %prog [options] key"
optparser = OptionParser(usage=usage, add_help_option=False)
optparser.add_option(
"--help", dest="help", action="store_true",
help="Displays this message.")
optparse... |
data/Keeper-Security/Commander/keepercommander/plugins/adpasswd/adpasswd.py | from ldap3 import Server, Connection, ALL
"""Commander Plugin for Active Directory
Dependencies:
pip3 install ldap3
"""
def rotate(record, newpassword):
result = False
host = record.get('cmdr:host')
user_dn = record.get('cmdr:userdn')
try:
server = Server(
host=host,
... |
data/JustinSGray/Hyperloop/src/hyperloop/test/test_tube_temp.py | import unittest
from openmdao.main.api import set_as_top, Assembly
from openmdao.util.testutil import assert_rel_error
from openmdao.lib.drivers.api import BroydenSolver
from hyperloop.tube_wall_temp import TubeWallTemp
class TubeHeatBalance(Assembly):
def configure(self):
tm = self.add('tm', TubeWallT... |
data/SawdustSoftware/disredis/disredis/disredis_client/client.py | """
Distributed Redis Client
The DisredisClient class can be used in place of a StrictRedis client. Instead
of passing the host and port in, pass in a list of Sentinel addresses in
the form of "host:port". It will connect to the first responding Sentinel
and query it for masters that it knows about. These masters will... |
data/adblockplus/gyp/test/win/gyptest-link-force-symbol-reference.py | """
Make sure ForceSymbolReference is translated properly.
"""
import TestGyp
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['msvs', 'ninja'])
CHDIR = 'linker-flags'
test.run_gyp('force-symbol-reference.gyp', chdir=CHDIR)
test.build('force-symbol-reference.gyp', test.ALL, chdir=CHDIR... |
data/Unidata/netcdf4-python/examples/bench.py | from numpy.random.mtrand import uniform
import netCDF4
from timeit import Timer
import os, sys
n1dim = 30
n2dim = 15
n3dim = 73
n4dim = 144
ntrials = 10
sys.stdout.write('reading and writing a %s by %s by %s by %s random array ..\n'%(n1dim,n2dim,n3dim,n4dim))
array = uniform(size=(n1dim,n2dim,n3dim,n4dim))
def write... |
data/adblockplus/gyp/test/ninja/use-console/gyptest-use-console.py | """
Make sure 'ninja_use_console' is supported in actions and rules.
"""
import TestGyp
test = TestGyp.TestGyp(formats=['ninja'])
test.run_gyp('use-console.gyp')
no_pool = open(test.built_file_path('obj/no_pool.ninja')).read()
if 'pool =' in no_pool:
test.fail_test()
action_pool = open(test.built_file_path('obj/... |
data/SheffieldML/GPy/GPy/mappings/piecewise_linear.py | from GPy.core.mapping import Mapping
from GPy.core import Param
import numpy as np
class PiecewiseLinear(Mapping):
"""
A piecewise-linear mapping.
The parameters of this mapping are the positions and values of the function where it is broken (self.breaks, self.values).
Outside the range of the breaks... |
data/JelteF/PyLaTeX/examples/numpy_ex.py | """
This example shows numpy functionality.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
import numpy as np
from pylatex import Document, Section, Subsection, Math, Matrix, VectorName
if __name__ == '__main__':
a = np.array([[100, 10, 20]]).T
doc = Docume... |
data/Toblerity/Shapely/tests/test_wkt.py | from math import pi
import pytest
from shapely.geometry import LineString, Point
from shapely.wkt import dumps
@pytest.fixture(scope="module")
def pipi():
return Point((pi, -pi))
@pytest.fixture(scope="module")
def pipi4():
return Point((pi*4, -pi*4))
def test_wkt(pipi):
""".wkt and wkt.dumps() both... |
data/SafeSlingerProject/SafeSlinger-AppEngine/safeslinger-demo/python/cleanup.py | import datetime
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import util
import member
class CleanUp(webapp.RequestHandler):
def get(self):
if self.request.headers.get('X-AppEngine-Cron') == 'true':
now = datetime.datetime.now()
... |
data/PythonJS/PythonJS/regtests/loop/range.py | '''
range builtin
'''
def main():
a = range(10)
TestError( a[0]==0 )
TestError( a[1]==1 )
TestError( len(a)==10 )
b = range(1,10)
TestError( b[0]==1 )
TestError( b[1]==2 )
TestError( len(b)==9 )
c = 0
for i in range(10):
c += 1
TestError( c == 10 )
d = 0
for i in range(1, 10):
d += 1
TestError( d ... |
data/IDSIA/brainstorm/docs/conf.py | import os
import sys
try:
from unittest.mock import MagicMock
except ImportError:
from mock import Mock as MagicMock
class Mock(MagicMock):
@classmethod
def __getattr__(cls, name):
return Mock()
MOCK_MODULES = ['h5py', 'brainstorm.handlers._cpuop']
sys.modules.update((mod_name, Mock()) for m... |
data/ReactiveX/RxPY/rx/linq/observable/multicast.py | from rx import Observable, AnonymousObservable
from rx.linq.connectableobservable import ConnectableObservable
from rx.disposables import CompositeDisposable
from rx.internal import extensionmethod
@extensionmethod(Observable)
def multicast(self, subject=None, subject_selector=None, selector=None):
"""Multicasts ... |
data/Miserlou/django-easy-api/easy_api/shortcuts.py | """
This is based off of Django's own shorcuts.py which provides render_to_response.
The key function here is easy_api_render_to_response()
"""
from django.template import loader, RequestContext
from django.http import HttpResponse, Http404
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
... |
data/aerospike/aerospike-client-python/test/old_tests/test_admin_set_password.py | import pytest
import sys
from .test_base_class import TestBaseClass
from aerospike import exception as e
aerospike = pytest.importorskip("aerospike")
try:
import aerospike
except:
print("Please install aerospike python client.")
sys.exit(1)
class TestSetPassword(TestBaseClass):
pytestmark = pytest.m... |
data/SimonSapin/Flask-FlatPages/flask_flatpages/compat.py | """
======================
flask_flatpages.compat
======================
Compatibility module for supporting both Python 2 and Python 3.
"""
import sys
IS_PY3 = sys.version_info[0] == 3
string_types = (str, ) if IS_PY3 else (basestring, )
text_type = str if IS_PY3 else unicode
def itervalues(obj, **kwargs):
... |
data/MontmereLimited/django-lean/django_lean/utils.py | from contextlib import contextmanager
from django.contrib.sites.models import Site
from django.core import mail
from django.db import transaction
from django.utils.functional import LazyObject
def get_current_site():
if Site._meta.installed:
return Site.objects.get_current()
return None
def in_trans... |
data/StackStorm/st2/st2common/st2common/models/api/auth.py | import six
from oslo_config import cfg
from st2common.util import isotime
from st2common.models.api.base import BaseAPI
from st2common.models.db.auth import UserDB, TokenDB, ApiKeyDB
from st2common import log as logging
LOG = logging.getLogger(__name__)
def get_system_username():
return cfg.CONF.system_user.us... |
data/LLNL/boxfish/boxfish/gl/glutils.py | """
Support for nicely indented GL sections in python using Python's with
statement.
Author:
Todd Gamblin, tgamblin@llnl.gov
"""
from contextlib import contextmanager
from OpenGL.GL import *
@contextmanager
def glSection(type):
glBegin(type)
yield
glEnd()
@contextmanager
def glMatrix():
glPushMa... |
data/ProgVal/Limnoria/plugins/MoobotFactoids/__init__.py | """
Moobot factoid compatibility module. Moobot's factoids were originally
designed to emulate Blootbot's factoids, so in either case, you should find
this plugin comfortable.
"""
import supybot
import supybot.world as world
__version__ = "0.1"
__author__ = supybot.authors.strike
__contributors__ = {}
from . ... |
data/agoragames/haigha/tests/unit/transports/gevent_transport_test.py | '''
Copyright (c) 2011-2015, Agora Games, LLC All rights reserved.
https://github.com/agoragames/haigha/blob/master/LICENSE.txt
'''
from chai import Chai
import errno
import unittest
try:
import gevent
from gevent.coros import Semaphore
from gevent import socket
from gevent.pool import Pool
from... |
data/SUSE/azurectl/azurectl/azurectl_exceptions.py | class AzureError(Exception):
"""
Base class to handle all known exceptions. Specific exceptions
are sub classes of this base class
"""
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self.message)
class AzureAccountConfigurationError(... |
data/Stiivi/brewery/brewery/tests/test_sql_streams.py | import unittest
import threading
import time
from brewery import ds
import brewery.metadata
from sqlalchemy import Table, Column, Integer, String, Text
from sqlalchemy import create_engine, MetaData
class SQLStreamsTestCase(unittest.TestCase):
def setUp(self):
self.engine = create_engine("sqlite://")
... |
data/PyHDI/veriloggen/tests/core/cond/cond.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.abspath(__file__))))))
from veriloggen import *
def mkLed():
m = Module('blinkled')
width = m.Parameter('WIDTH', 8)
... |
data/OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/email/__init__.py | """
Backport of the Python 3.3 email package for Python-Future.
A package for parsing, handling, and generating email messages.
"""
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future.utils import surrogateescape
surrogateescape.register_surroga... |
data/Pylons/venusian/venusian/tests/fixtures/category.py | from venusian.tests.fixtures import categorydecorator
from venusian.tests.fixtures import categorydecorator2
@categorydecorator(function=True)
def function(request):
return request
@categorydecorator2(function=True)
def function2(request):
return request
|
data/Kozea/WeasyPrint/weasyprint/layout/float.py | """
weasyprint.float
----------------
:copyright: Copyright 2011-2014 Simon Sapin and contributors, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import division, unicode_literals
from .markers import list_marker_layout
from .min_max import handle_min_max_width
from .perce... |
data/Toblerity/Shapely/tests/__init__.py | import sys
from shapely.geos import geos_version_string, lgeos, WKTWriter
from shapely import speedups
test_int_types = [int]
try:
import numpy
numpy_version = numpy.version.version
test_int_types.extend([int, numpy.int16, numpy.int32, numpy.int64])
except ImportError:
numpy = False
numpy_versio... |
data/MontmereLimited/django-lean/django_lean/experiments/migrations/0001_initial.py | from south.db import db
from django.db import models
from django_lean.experiments.models import *
class Migration:
def forwards(self, orm):
db.create_table('experiments_experiment', (
('id', orm['experiments.Experiment:id']),
('name', orm['experiments.Experiment:name']),
... |
data/adamcharnock/django-su/django_su/tests/test_backends.py | from django.test import TestCase
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
class TestSuBackend(TestCase):
def setUp(self):
super(TestSuBackend, self).setUp()
from django_su.backends imp... |
data/OpenBazaar/OpenBazaar-Installer/windows/PyNaCl-0.3.0-py2.7-win-amd64.egg/nacl/_lib/__init__.py | from __future__ import absolute_import, division, print_function
import glob
import os.path
from cffi import FFI
from cffi.verifier import Verifier
__all__ = ["ffi"]
HEADERS = glob.glob(
os.path.join(os.path.abspath(os.path.dirname(__file__)), "*.h")
)
ffi = FFI()
for header in sorted(HEADERS):
wi... |
data/PyTables/PyTables/c-blosc/bench/plot-speeds.py | """Script for plotting the results of the 'suite' benchmark.
Invoke without parameters for usage hints.
:Author: Francesc Alted
:Date: 2010-06-01
"""
import matplotlib as mpl
from pylab import *
KB_ = 1024
MB_ = 1024*KB_
GB_ = 1024*MB_
NCHUNKS = 128
linewidth=2
markers= [ 's', 'o', 'v', '^', '+', 'x', '>', '<... |
data/StackHut/stackhut/stackhut_toolkit/common/barrister/runtime.py | """
Barrister runtime for Python. Includes all classes used when writing a client or server.
Hacked up for StackHut by StackHut :) Thx
:copyright: 2012 by James Cooper.
:license: MIT, see LICENSE for more details.
"""
import urllib.request
import urllib.error
import urllib.parse
import uuid
import iter... |
data/Miserlou/OpenWatch/openwatch/map/views.py | from django.http import HttpResponse, HttpResponseRedirect, HttpResponseNotFound
from django.template import Context, loader
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response
from django.core.exceptions import Objec... |
data/RDFLib/rdflib/rdflib/plugins/parsers/nquads.py | """
This is a rdflib plugin for parsing NQuad files into Conjunctive
graphs that can be used and queried. The store that backs the graph
*must* be able to handle contexts.
>>> from rdflib import ConjunctiveGraph, URIRef, Namespace
>>> g = ConjunctiveGraph()
>>> data = open("test/nquads.rdflib/example.nquads", "rb")
>>... |
data/VisualComputingInstitute/Beacon8/examples/Kaggle-Otto/test.py | import numpy as np
import theano as th
from kaggle_utils import multiclass_log_loss
from examples.utils import make_progressbar
def validate(dataset_x, dataset_y, model, epoch, batch_size):
progress = make_progressbar('Testing epoch
progress.start()
logloss = 0.
for j in range((dataset_x.shape[0] + ... |
data/Skype4Py/Skype4Py/unittests/smstest.py | import unittest
import skype4pytest
from Skype4Py.sms import *
class SmsMessageTest(skype4pytest.TestCase):
def setUpObject(self):
self.obj = SmsMessage(self.skype, '1234')
def testDelete(self):
self.api.enqueue('DELETE SMS 1234')
self.obj.Delete()
self.failUnless(... |
data/PythonJS/PythonJS/regtests/dict/if_empty.py | """if empty dict then false"""
def main():
d = {}
if d:
err1 = 1
else:
err1 = 0
if {}:
err2 = 1
else:
err2 = 0
d['x'] = 'xxx'
if d:
err3 = 0
else:
err3 = 1
TestError( err1 == 0 )
TestError( err2 == 0 )
TestError( err3 == 0 )
|
data/OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/drivers/slsqpdriver.py | """
slsqpdriver.py - Contains a driver that wraps the SLSQP
optimizer as used in pyOpt:
Minimize a function using Sequential Least SQuares Programming.
SLSQP is a gradient optimizer that can handle both equality and
inequality constraints.
"""
from math import isnan
from numpy import zeros, array
from slsqp.slsqp ... |
data/StackStorm/st2/st2common/st2common/persistence/marker.py | from st2common.models.db import MongoDBAccess
from st2common.models.db.marker import MarkerDB
from st2common.models.db.marker import DumperMarkerDB
from st2common.persistence.base import Access
__all__ = [
'Marker'
]
class Marker(Access):
impl = MongoDBAccess(MarkerDB)
publisher = None
@classmethod
... |
data/StackStorm/st2/st2debug/st2debug/cmd/submit_debug_info.py | """
This script submits information which helps StackStorm employees debug different
user problems and issues to StackStorm.
By default the following information is included:
- Logs from /var/log/st2
- StackStorm and mistral config file (/etc/st2/st2.conf, /etc/mistral/mistral.conf)
- All the content (integration pac... |
data/StackStorm/st2/st2actions/st2actions/notifier/config.py | from oslo_config import cfg
import st2common.config as common_config
from st2common.constants.system import VERSION_STRING
common_config.register_opts()
CONF = cfg.CONF
def parse_args(args=None):
CONF(args=args, version=VERSION_STRING)
def register_opts():
_register_common_opts()
_register_notifier_op... |
data/OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/datatypes/vtree.py | """
Variable meant to contain a VariableTree of a particular type.
"""
__all__ = ["VarTree"]
from traits.api import Instance
from openmdao.main.variable import Variable, gui_excludes
class VarTree(Variable):
""" A Variable for a :class:`VariableTree` of a particular type. """
def __init__(self, default_v... |
data/PacificBiosciences/cDNA_primer/pbtranscript-tofu/pbtranscript/pbtools/pbtranscript/fusion_finder.py | import pdb
import os, sys
import itertools
from cPickle import *
from collections import defaultdict, namedtuple
from pbtools.pbtranscript.Utils import check_ids_unique
import pbtools.pbtranscript.tofu_wrap as tofu_wrap
import pbtools.pbtranscript.BioReaders as BioReaders
import pbtools.pbtranscript.branch.branch_simpl... |
data/RDFLib/rdfextras/rdfextras/sparql/graph.py | from types import FunctionType
from rdflib.graph import ConjunctiveGraph
from rdflib.graph import Graph
from rdflib.term import BNode
from rdflib.term import Literal
from rdflib.term import URIRef
from rdflib.term import Variable
from rdflib.namespace import NamespaceManager
from rdfextras.sparql import _questChar
from... |
data/SublimeLinter/SublimeLinter-phpcs/linter.py | """This module exports the Phpcs plugin class."""
from SublimeLinter.lint import Linter
class Phpcs(Linter):
"""Provides an interface to phpcs."""
syntax = ('php', 'html', 'html 5')
regex = (
r'.*line="(?P<line>\d+)" '
r'column="(?P<col>\d+)" '
r'severity="(?:(?P<error>error)|(?P... |
data/ReactiveX/RxPY/rx/linq/observable/find.py | from rx.observable import Observable
from rx.anonymousobservable import AnonymousObservable
from rx.internal import extensionmethod
def find_value(source, predicate, yield_index):
def subscribe(observer):
i = [0]
def on_next(x):
should_run = False
try:
shou... |
data/RoseOu/flasky/venv/lib/python2.7/site-packages/selenium/webdriver/support/expected_conditions.py | from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchFrameException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import NoAlertPresentException
"""
*... |
data/YelpArchive/python-gearman/tests/client_tests.py | import collections
import random
import unittest
from gearman.client import GearmanClient
from gearman.client_handler import GearmanClientCommandHandler
from gearman.constants import PRIORITY_NONE, PRIORITY_HIGH, PRIORITY_LOW, JOB_UNKNOWN, JOB_PENDING, JOB_CREATED, JOB_FAILED, JOB_COMPLETE
from gearman.errors import ... |
data/VikParuchuri/percept/percept/workflows/datastores.py | """
Used to save and load workflows
"""
from percept.utils.input import import_from_string
from percept.conf.base import settings
import pickle
import logging
log = logging.getLogger(__name__)
class BaseStore(object):
"""
Basic datastore
"""
def __init__(self):
self.data_path = settings.DATA_... |
data/KeepSafe/ks-email-parser/email_parser/cmd.py | """
Handles command line and calls the email parser with corrent options.
"""
import argparse
import logging
from collections import namedtuple
from . import placeholder
logger = logging.getLogger()
ShortenerSettings = namedtuple('ShortenerSettings', [
'name',
'properties'
])
Settings = namedtuple('Setting... |
data/MirantisWorkloadMobility/CloudFerry/cloudferry/lib/os/compute/libvirt.py | import json
import os
from xml.etree import ElementTree
from cloudferry.lib.utils import log
LOG = log.getLogger(__name__)
nova_instances_path = "/var/lib/nova/instances/"
def instance_path(instance_id):
return os.path.join(nova_instances_path, instance_id)
def instance_image_path(instance_id):
return o... |
data/adaptivdesign/django-sellmo/skeleton/color/admin.py | from sellmo import modules
from django.contrib import admin
class ColorAdmin(admin.ModelAdmin):
list_display = ['name', 'value']
admin.site.register(modules.color.Color, ColorAdmin)
|
data/PyHDI/veriloggen/examples/seq_example/seq_example.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.abspath(__file__)))))
from veriloggen import *
def mkLed():
m = Module('blinkled')
interval = m.Parameter('INTERVAL', 16)
clk = m.I... |
data/StackStorm/st2/st2common/st2common/config.py | import os
import sys
from oslo_config import cfg
from st2common.constants.system import VERSION_STRING
def do_register_opts(opts, group=None, ignore_errors=False):
try:
cfg.CONF.register_opts(opts, group=group)
except:
if not ignore_errors:
raise
def do_register_cli_opts(opt, i... |
data/agronholm/apscheduler/apscheduler/jobstores/sqlalchemy.py | from __future__ import absolute_import
from apscheduler.jobstores.base import BaseJobStore, JobLookupError, ConflictingIdError
from apscheduler.util import maybe_ref, datetime_to_utc_timestamp, utc_timestamp_to_datetime
from apscheduler.job import Job
try:
import cPickle as pickle
except ImportError:
import... |
data/IanLewis/kay/kay/management/__init__.py | """
kay.management
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
All rights reserved.
:license: BSD, see LICENSE for more details.
Taken from django.
"""
import sys
import os
from werkzeug.utils import import_string
from kay.management... |
data/Robpol86/terminaltables/tests/test_base_table_padded_table_data.py | """Test padding cells."""
import pytest
from terminaltables.tables import AsciiTable, UnixTable
@pytest.mark.parametrize('cls', [AsciiTable, UnixTable])
def test_empty(cls):
"""Test on empty tables."""
table = cls([])
assert table.padded_table_data == []
table = cls([[]])
assert table.padded_ta... |
data/JoelBender/bacpypes/tests/test_pdu/__init__.py | """
Test BACpypes PDU Module
"""
from . import test_address
|
data/PyHDI/veriloggen/tests/extension/seq_/countup/seq_countup.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 *
def mkLed():
m = Module('blinkled')
interval = m.Param... |
data/Pathoschild/stewbot/CHANGELOG.py | """
2012-12-03 r23
- added support for IPv6 addresses in commands (Issue
2011-04-01 r22
- new configuration: toggle handling of !commit command;
- use new API modules for getGlobalRights;
- use new API modules for getGlobalDetails (merged from getGlobalAccounts and getGlobalEdits);
- simplified package design.
... |
data/Tivix/django-common/django_common/http.py | from __future__ import print_function, unicode_literals, with_statement, division
from django.http import HttpResponse
try:
import json
except ImportError:
from django.utils import simplejson as json
class JsonResponse(HttpResponse):
def __init__(self, data=None, errors=None, success=True):
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.