path stringlengths 23 146 | source_code stringlengths 0 261k |
|---|---|
data/Theano/Theano/theano/gof/cutils.py | from __future__ import absolute_import, print_function, division
import errno
import os
import sys
from theano.compat import PY3
from theano.gof.compilelock import get_lock, release_lock
from theano import config
from . import cmodule
if os.path.exists(os.path.join(config.compiledir, 'cutils_ext.so')):
os.remov... |
data/IndicoDataSolutions/Passage/examples/load.py | import os
import numpy as np
def load_gender_data(ntrain=10000, ntest=10000):
import pandas as pd
file_loc = os.path.dirname(os.path.realpath(__file__))
relative_path = "blogger_data_2.csv"
fullpath = os.path.join(file_loc, relative_path)
data = pd.read_csv(fullpath, nrows=ntrain+ntest)
X = da... |
data/Theano/Theano/theano/sandbox/rng_mrg.py | """
Implementation of MRG31k3p random number generator for Theano.
Generator code in SSJ package (L'Ecuyer & Simard).
http://www.iro.umontreal.ca/~simardr/ssj/indexe.html
"""
from __future__ import absolute_import, print_function, division
import warnings
import numpy
from six import integer_types
from six.moves imp... |
data/PyHDI/PyCoRAM/examples/app/stencil-9p/stencil-9p-separate/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)
mem3 = CoramMem... |
data/OpenMDAO/OpenMDAO/openmdao/surrogate_models/multifi_cokriging.py | """
This module integrates the Multi-Fidelity Co-Kriging method described in
[LeGratiet2013].
(Author: Remi Vauclin <vauclin.remi@gmail.com>)
This code was implemented using the package scikit-learn as basis.
(Author: Vincent Dubourg <vincent.dubourg@gmail.com>)
OpenMDAO adaptation. Regression and correlation functio... |
data/SparkPost/python-sparkpost/sparkpost/tornado/transmissions.py | from .utils import wrap_future
from ..transmissions import Transmissions as SyncTransmissions
class Transmissions(SyncTransmissions):
def get(self, transmission_id):
results = self._fetch_get(transmission_id)
return wrap_future(results, lambda f: f["transmission"])
|
data/PyHDI/Pyverilog/examples/example_dataflow_analyzer.py | from __future__ import absolute_import
from __future__ import print_function
import sys
import os
from optparse import OptionParser
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pyverilog.utils.version
from pyverilog.dataflow.dataflow_analyzer import VerilogDataflowAnalyzer
... |
data/adaptivdesign/django-sellmo/sellmo/contrib/payment/inject.py | from sellmo.core.loading import load
NO_MUTATION = object()
import sellmo.apps.checkout as _checkout
@load(before='finalize_checkout_Order')
def load_model():
class Order(_checkout.models.Order):
_mutated_payment = NO_MUTATION
def invalidate(self):
super(Order, self).invalidate()
... |
data/adaptivdesign/django-sellmo/sellmo/core/registry/base.py | import sys
import traceback
from types import ModuleType
from importlib import import_module
from django.apps import apps
from django.conf import settings
from django.utils import six
from django.utils.functional import cached_property
from .exceptions import RegistryError
allowed = None
def should_fix_type(typ):
... |
data/Sandia-Labs/PVLIB_Python/pvlib/pvl_getaoi.py | import pandas as pd
import numpy as np
import pvl_tools
def pvl_getaoi(SurfTilt,SurfAz,SunZen,SunAz):
'''
Determine angle of incidence from surface tilt/azimuth and apparent sun zenith/azimuth
The surface is defined by its tilt angle from horizontal and its azimuth pointing angle.
The sun position is defined... |
data/JT5D/Alfred-Popclip-Sublime/Sublime Text 2/JsFormat/libs/jsbeautifier/unpackers/packer.py | """Unpacker for Dean Edward's p.a.c.k.e.r"""
import re
import string
from jsbeautifier.unpackers import UnpackingError
PRIORITY = 1
def detect(source):
"""Detects whether `source` is P.A.C.K.E.R. coded."""
return source.replace(' ', '').startswith('eval(function(p,a,c,k,e,r')
def unpack(source):
"""Unpa... |
data/OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/container.py | """
The Container class.
"""
import datetime
import copy
import pprint
import socket
import sys
import weakref
copy._copy_dispatch[weakref.ref] = copy._copy_immutable
copy._deepcopy_dispatch[weakref.ref] = copy._deepcopy_atomic
copy._deepcopy_dispatch[weakref.KeyedRef] = copy._deepcopy_atomic
from zope.inter... |
data/Mouse-Imaging-Centre/pydpiper/pydpiper_testing/conftest.py | def pytest_funcarg__setupopts(request):
return OptsSetup(request)
def pytest_addoption(parser):
parser.addoption("--uri-file", dest="urifile",
type=str, default=None,
help="Location for uri file if NameServer is not used. If not specified, default is current working di... |
data/Knio/pynmea2/pynmea2/nmea_file.py | try:
basestring = basestring
except NameError:
basestring = str
from .nmea import NMEASentence
class NMEAFile(object):
"""
Reads NMEA sentences from a file similar to a standard python file object.
"""
def __init__(self, f, *args, **kwargs):
super(NMEAFile, self).__init__()
... |
data/YelpArchive/pushmanager/pushmanager/servlets/livepush.py | import time
import sqlalchemy as SA
import pushmanager.core.db as db
import pushmanager.core.util
from pushmanager.core.mail import MailQueue
from pushmanager.core.rb import RBQueue
from pushmanager.core.requesthandler import RequestHandler
class LivePushServlet(RequestHandler):
def _arg(self, key):
re... |
data/QuantSoftware/QuantSoftwareToolkit/QSTK/qstktest/testDataAccess.py | '''
Created on Jun 1, 2010
@author: Shreyas Joshi
@summary: Just a quick way to test the DataAccess class... nothing more "I dare do all that may become a DataAccessTester. Who dares do more is none"
'''
import QSTK.qstkutil.DataAccess as da
import tables as pt
import numpy as np
from itertools import izip
imp... |
data/Suor/django-easymoney/tests/admin.py | from __future__ import absolute_import
from django.contrib import admin
from .models import Product, Option
admin.site.register(Product)
admin.site.register(Option)
|
data/JamesPHoughton/pysd/pysd/functions/__init__.py | from .functions import *
|
data/PythonJS/PythonJS/regtests/lang/if_not.py | """if not"""
def main():
a = False
b = False
if not a:
b = True
TestError( b == True )
a = 0
b = False
if not a:
b = True
TestError( b == True )
a = 0.0
b = False
if not a:
b = True
TestError( b == True )
a = None
b = False
if not a:
b = True
TestError( b == True )
|
data/VisTrails/VisTrails/vistrails/db/versions/v0_9_0/persistence/__init__.py | from __future__ import division
from xml.auto_gen import XMLDAOListBase
from sql.auto_gen import SQLDAOListBase
from vistrails.core.system import get_elementtree_library
from vistrails.db import VistrailsDBException
from vistrails.db.versions.v0_9_0 import version as my_version
ElementTree = get_elementtree_library(... |
data/PyTables/PyTables/examples/undo-redo.py | """Yet another couple of examples on do/undo feauture."""
import tables
def setUp(filename):
fileh = tables.open_file(filename, mode="w", title="Undo/Redo demo")
fileh.create_group("/", "agroup", "Group 1")
fileh.create_group("/agroup", "agroup2", "Group 2")
fileh.create_array("/", "anarray... |
data/JetBrains/youtrack-rest-python-library/python/pyactiveresource/fake_connection.py | """A fake HTTP connection for testing"""
__author__ = 'Mark Roach (mrroach@google.com)'
import urllib
from pyactiveresource import connection
from pyactiveresource import formats
class Error(Exception):
"""The base exception class for this module."""
class FakeConnection(object):
"""A fake HTTP connection ... |
data/ProgVal/Limnoria/plugins/Alias/config.py | import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('Alias')
def configure(advanced):
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('... |
data/OpenMDAO/OpenMDAO-Framework/openmdao.devtools/src/openmdao/devtools/locdistbld.py | """
This module builds a binary distribution from the specified source directory.
"""
import sys
import os
import shutil
import urllib2
import subprocess
import codecs
from optparse import OptionParser
def has_setuptools():
try:
import setuptools
except ImportError:
return False
return Tr... |
data/ImageEngine/gaffer/python/GafferUITest/NumericSliderTest.py | import unittest
import GafferTest
import GafferUI
class NumericSliderTest( unittest.TestCase ) :
def testConstruction( self ) :
s = GafferUI.NumericSlider( value = 0, min = 0, max = 1 )
self.assertEqual( s.getPosition(), 0 )
self.assertEqual( s.getValue(), 0 )
self.assertEqual( s.getRange(), ( 0, 1, 0, 1 ... |
data/SEED-platform/seed/seed/celery.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
import os
import cele... |
data/Theano/Theano/theano/sandbox/cuda/fftconv.py | from __future__ import absolute_import, print_function, division
import string
import numpy as np
import theano
import theano.tensor as T
from theano.sandbox.cuda import cuda_available, GpuOp
from theano.ifelse import ifelse
from theano.misc.pycuda_init import pycuda_available
if cuda_available:
from theano.sand... |
data/Stiivi/brewery/brewery/ds/elasticsearch_streams.py | import base
from brewery import dq
import time
from brewery.metadata import expand_record
try:
from pyes.es import ES
except ImportError:
from brewery.utils import MissingPackage
pyes = MissingPackage("pyes", "ElasticSearch streams", "http://www.elasticsearch.org/")
class ESDataSource(base.DataSource):
... |
data/StorjOld/upstream/tests/test_streamer.py | import os
import unittest
import mock
from upstream.shard import Shard
from upstream.streamer import Streamer
from upstream.exc import ConnectError, FileError, ShardError, ResponseError
class TestStreamer(unittest.TestCase):
def setUp(self):
self.stream = Streamer("http://node1.metadisk.org")
se... |
data/Teradata/PyTd/teradata/pulljson.py | """A pull parser for parsing JSON streams"""
import sys
import decimal
import re
import json
import logging
from . import util
if sys.version_info[0] == 2:
from StringIO import StringIO
else:
from io import StringIO
logger = logging.getLogger(__name__)
OBJECT = "OBJECT"
ARRAY = "... |
data/Theano/Theano/theano/tensor/nnet/tests/test_neighbours.py | from __future__ import absolute_import, print_function, division
from nose.plugins.skip import SkipTest
import numpy
import unittest
import theano
from theano import shared, function
import theano.tensor as T
from theano.tensor.nnet.neighbours import images2neibs, neibs2images, Images2Neibs
from theano.tests import u... |
data/Lukasa/hyper/test/server.py | """
test/server
~~~~~~~~~~~
This module defines some testing infrastructure that is very useful for
integration-type testing of hyper. It works by spinning up background threads
that run test-defined logic while listening to a background thread.
This very-clever idea and most of its implementation are ripped off from... |
data/adaptivdesign/django-sellmo/sellmo/contrib/reporting/generators/weasyprint/generator.py | from weasyprint import HTML
from sellmo.contrib.reporting.generators import AbstractReportGenerator
import logging
logger = logging.getLogger('weasyprint')
logger.handlers = []
class WeasyPrintReportGenerator(AbstractReportGenerator):
@property
def input_formats(self):
return ['html']
@proper... |
data/SickRage/SickRage/lib/sqlalchemy/testing/pickleable.py | """Classes used in pickling tests, need to be at the module level for
unpickling.
"""
from . import fixtures
class User(fixtures.ComparableEntity):
pass
class Order(fixtures.ComparableEntity):
pass
class Dingaling(fixtures.ComparableEntity):
pass
class EmailUser(User):
pass
class Address(fixt... |
data/YelpArchive/pushmanager/pushmanager/tests/test_core_requesthandler.py | import mock
import testify as T
import tornado.httpserver
from pushmanager.core.requesthandler import RequestHandler
from pushmanager.core.requesthandler import get_base_url
from pushmanager.core.settings import Settings
from pushmanager.testing.mocksettings import MockedSettings
class RequestHandlerTest(T.TestCase... |
data/ImageEngine/gaffer/python/GafferSceneUI/SceneViewToolbar.py | import functools
import IECore
import Gaffer
import GafferUI
import GafferScene
import GafferSceneUI
Gaffer.Metadata.registerNode(
GafferSceneUI.SceneView,
plugs = {
"shadingMode" : [
"toolbarLayout:index", 2,
"toolbarLayout:divider", True,
"plugValueWidget:type", "GafferSceneUI.SceneViewToolbar._Sh... |
data/PythonCharmers/python-future/src/libpasteurize/fixes/fix_future_builtins.py | """
Adds this import line:
from builtins import XYZ
for each of the functions XYZ that is used in the module.
"""
from __future__ import unicode_literals
from lib2to3 import fixer_base
from lib2to3.pygram import python_symbols as syms
from lib2to3.fixer_util import Name, Call, in_special_context
from libfuturi... |
data/adamchainz/django-mysql/django_mysql/models/fields/__init__.py | from django_mysql.models.fields.bit import (
Bit1BooleanField, NullBit1BooleanField
)
from django_mysql.models.fields.dynamic import DynamicField
from django_mysql.models.fields.enum import EnumField
from django_mysql.models.fields.json import JSONField
from django_mysql.models.fields.lists import (
L... |
data/NVIDIA/DIGITS/digits/inference/__init__.py | from __future__ import absolute_import
from .images import *
from .job import InferenceJob
|
data/Piratenfraktion-Berlin/OwnTube/videoportal/migrations/0015_auto__add_field_collection_channel.py | import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
db.add_column('videoportal_collection', 'channel',
self.gf('django.db.models.fields.related.ForeignKey')(to=o... |
data/Toblerity/Shapely/shapely/examples/geoms.py | from numpy import asarray
import pylab
from shapely.geometry import Point, LineString, Polygon
polygon = Polygon(((-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0), (1.0, -1.0)))
point_r = Point(-1.5, 1.2)
point_g = Point(-1.0, 1.0)
point_b = Point(-0.5, 0.5)
line_r = LineString(((-0.5, 0.5), (0.5, 0.5)))
line_g = LineString(((... |
data/a-tal/pyweet/pyweet/settings.py | """Pyweet runtime settings."""
import os
class Settings(object):
"""Basic settings object for pyweet."""
API = "rgIYSFIeGBxVXOPy22QzA"
API_SECRET = "VX7ohOHpJm1mXlGX6XS08JcT4Vp8j83QhRNo1SVRevb"
AUTH_FILE = os.path.expanduser("~/.pyweet")
|
data/OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/moves/sys.py | from __future__ import absolute_import
from future.utils import PY2
from sys import *
if PY2:
from __builtin__ import intern
|
data/Smartling/api-sdk-python/setup.py | ''' Copyright 2012 Smartling, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by appli... |
data/SpriteLink/NIPAP/nipap-www/nipapwww/config/middleware.py | """Pylons middleware initialization"""
from beaker.middleware import SessionMiddleware
from paste.cascade import Cascade
from paste.registry import RegistryManager
from paste.urlparser import StaticURLParser
from paste.deploy.converters import asbool
from pylons.middleware import ErrorHandler, StatusCodeRedirect
from p... |
data/SEED-platform/seed/seed/tests/test_utils.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 django.test import TestCase
from seed.utils.generic impor... |
data/adieu/allbuttonspressed/pygments/lexers/_luabuiltins.py | """
pygments.lexers._luabuiltins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This file contains the names and modules of lua functions
It is able to re-generate itself, but for adding new functions you
probably have to add some callbacks (see function module_callbacks).
Do not edit the MODULES dict by hand.
... |
data/MirantisWorkloadMobility/CloudFerry/cloudferry_devlab/cloudferry_devlab/tests/testcases/rollback_verification.py | """
This is module to verify if rollback procedure was executed correctly.
Basically two dictionaries are being compared:
- pre_data: data collected from SRC and DST clusters, is being stored in
file with name which is described in config file.
- data_after: data collected from SRC and DST clust... |
data/Netflix/aminator/aminator/plugins/finalizer/tagging_ebs.py | """
aminator.plugins.finalizer.tagging_ebs
======================================
ebs tagging image finalizer
"""
import logging
from os import environ
from aminator.config import conf_action
from aminator.plugins.finalizer.tagging_base import TaggingBaseFinalizerPlugin
from aminator.util.linux import sanitize_metadat... |
data/adaptivdesign/django-sellmo/sellmo/contrib/discount/constants.py | from django.utils.translation import ugettext_lazy as _
from .price import DiscountPriceComponent
DISCOUNT = DiscountPriceComponent()
APPLIES_TO_PRODUCT_PRICE = 'product'
APPLIES_TO_SHIPPING_COSTS = 'shipping'
APPLIES_TO_TOTAL = 'total'
APPLIES_TO_CHOICES = (
(APPLIES_TO_PRODUCT_PRICE, _("product price")),
(... |
data/Shopify/shopify_django_app/settings.py | import os
from shopify_settings import *
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
try:
from djangoappengine.settings_base import *
USING_APP_ENGINE = True
except ImportError:
USING_APP_ENGINE = False
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
... |
data/SALib/SALib/versioneer.py | """
The Versioneer
==============
* like a rocketeer, but for versions!
* https://github.com/warner/python-versioneer
* Brian Warner
* License: Public Domain
* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, and pypy
[](https://travis-ci... |
data/NeuroVault/NeuroVault/neurovault/apps/statmaps/tests/test_counter.py | import os.path
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase, Client
from neurovault.apps.statmaps.forms import NIDMResultsForm
from neurovault.apps.statmaps.models import Collection, StatisticMap, Comparison
from neurovault.... |
data/RobotLocomotion/director/src/python/tests/testLoadUrdf.py | from director.consoleapp import ConsoleApp
from director import visualization as vis
from director import roboturdf
from director import jointcontrol
import argparse
def getArgs():
parser = argparse.ArgumentParser()
parser.add_argument('--urdf', type=str, default=None, help='urdf filename to load')
args, ... |
data/Lasagne/Lasagne/lasagne/tests/layers/test_merge.py | from mock import Mock
import numpy
import pytest
import theano
class TestAutocrop:
def test_autocrop_array_shapes(self):
from lasagne.layers.merge import autocrop_array_shapes
crop0 = None
crop1 = [None, 'lower', 'center', 'upper']
crop2 = ['lower', 'upper']
... |
data/ReactiveX/RxPY/rx/linq/observable/toasync.py | from rx.observable import Observable
from rx.concurrency import timeout_scheduler
from rx.subjects import AsyncSubject
from rx.internal import extensionclassmethod
@extensionclassmethod(Observable)
def to_async(cls, func, scheduler=None):
"""Converts the function into an asynchronous function. Each invocation
... |
data/StackStorm/st2contrib/packs/docker/actions/pull_image.py | from lib.base import DockerBasePythonAction
__all__ = [
'DockerPullImageAction'
]
class DockerPullImageAction(DockerBasePythonAction):
def run(self, repo, tag=None, insecure_registry=False,
auth_username_override=None, auth_password_override=None):
auth_override = (auth_username_override... |
data/aerospike/aerospike-client-python/test/old_tests/test_udf_put.py | import pytest
import sys
import time
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 TestUdfPut(TestBaseClass):
def setup_clas... |
data/MirantisWorkloadMobility/CloudFerry/cloudferry/lib/os/actions/check_config_quota_neutron.py | from cloudferry.lib.base.action import action
from cloudferry.lib.utils import log
from cloudferry.lib.utils import utils as utl
LOG = log.getLogger(__name__)
class CheckConfigQuotaNeutron(action.Action):
"""
Checking config quotas between src and dst clouds.
If all tenants have customs quotas then dif... |
data/OpenMDAO/OpenMDAO/examples/intersect_parabola_line.py | from __future__ import print_function
from openmdao.api import Component, Group, Problem, Newton, ScipyGMRES
class Line(Component):
"""Evaluates y = -2x + 4."""
def __init__(self):
super(Line, self).__init__()
self.add_param('x', 1.0)
self.add_output('y', 0.0)
self... |
data/IvanMalison/okcupyd/tests/photo_test.py | from . import util
from okcupyd import User, photo
@util.use_cassette(path='photo_upload',
match_on=util.match_on_no_body)
def test_photo_upload():
uploader = photo.PhotoUploader()
upload_response_dict = uploader.upload_and_confirm('fixtures/image.jpg')
assert int(upload_response_dict['... |
data/Schwanksta/python-arcgis-rest-query/setup.py | import sys
from setuptools import setup
install_requires = [
"argparse>=1.2.1",
"requests>=2.4.3"
]
setup(
name='arcgis-rest-query',
version='0.14',
description='A tool to download a layer from an ArcGIS web service as GeoJSON',
author='Ken Schwencke',
author_email='schwank@gmail.com',
... |
data/StackStorm/st2/st2common/tests/unit/test_aliasesregistrar.py | import os
from st2common.bootstrap import aliasesregistrar
from st2tests import DbTestCase, fixturesloader
ALIASES_FIXTURE_PACK_PATH = os.path.join(fixturesloader.get_fixtures_base_path(), 'dummy_pack_1')
ALIASES_FIXTURE_PATH = os.path.join(ALIASES_FIXTURE_PACK_PATH, 'aliases')
class TestAliasRegistrar(DbTestCase)... |
data/RoseOu/flasky/venv/lib/python2.7/site-packages/pygments/lexers/_stan_builtins.py | """
pygments.lexers._stan_builtins
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This file contains the names of functions for Stan used by
``pygments.lexers.math.StanLexer.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
CONSTANTS=[ 'e',
... |
data/ZoomerAnalytics/xlwings/xlwings/conversion/numpy_conv.py | try:
import numpy as np
except ImportError:
np = None
if np:
try:
import pandas as pd
except ImportError:
pd = None
from . import Converter, Options
class NumpyArrayConverter(Converter):
writes_types = np.ndarray
@classmethod
def base_reader(cls, op... |
data/StackStorm/st2contrib/packs/nest/actions/get_mode.py | from lib import actions
class GetModeAction(actions.BaseAction):
def run(self, structure=None, device=None):
if structure and device:
nest = self._get_device(structure, device)
else:
nest = self._get_default_device()
return nest.mode
|
data/Netflix/security_monkey/env-config/config-deploy.py | LOG_LEVEL = "DEBUG"
LOG_FILE = "/var/log/security_monkey/security_monkey-deploy.log"
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:securitymonkeypassword@localhost:5432/secmonkey'
SQLALCHEMY_POOL_SIZE = 50
SQLALCHEMY_MAX_OVERFLOW = 15
ENVIRONMENT = 'ec2'
USE_ROUTE53 = False
FQDN = 'ec2-XX-XXX-XXX-XXX.compute-1.ama... |
data/ReactiveX/RxPY/tests/test_observable/test_takeuntil.py | import unittest
from rx import Observable
from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable
from rx.disposables import Disposable, SerialDisposable
on_next = ReactiveTest.on_next
on_completed = ReactiveTest.on_completed
on_error = ReactiveTest.on_error
subscribe = ReactiveTest.subscribe
sub... |
data/PyTables/PyTables/bench/indexed_search.py | from __future__ import print_function
from time import time
import subprocess
import random
import numpy
STEP = 1000 * 100
SCALE = 0.1
NI_NTIMES = 1
MROW = 1000 * 1000.
COLDCACHE = 5
WARMCACHE = 5
READ_TIMES = 10
rdm_cod = ['lin', 'rnd']
prec = 6
def ge... |
data/KunihikoKido/sublime-elasticsearch-client/lib/dateutil/easter.py | """
This module offers a generic easter computing method for any given year, using
Western, Orthodox or Julian algorithms.
"""
import datetime
__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"]
EASTER_JULIAN = 1
EASTER_ORTHODOX = 2
EASTER_WESTERN = 3
def easter(year, method=EASTER_WESTERN):... |
data/Impactstory/total-impact-core/totalimpact/cache.py | import os
import sys
import hashlib
import logging
import json
from cPickle import PicklingError
import redis
from totalimpact import REDIS_CACHE_DATABASE_NUMBER
logger = logging.getLogger("ti.cache")
cache_client = redis.from_url(os.getenv("REDIS_URL"), REDIS_CACHE_DATABASE_NUMBER)
MAX_PAYLOAD_SIZE_BYTES = 1000*1... |
data/TheTorProject/ooni-probe/ooni/nettests/experimental/script.py | from ooni import nettest
from ooni.utils import log
from twisted.internet import defer, protocol, reactor
from twisted.python import usage
import os
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
... |
data/adblockplus/gyp/test/lib/TestCmd.py | """
TestCmd.py: a testing framework for commands and scripts.
The TestCmd module provides a framework for portable automated testing
of executable commands and scripts (in any language, not just Python),
especially commands and scripts that require file system interaction.
In addition to running tests and evaluating... |
data/adlnet/ADL_LRS/oauth_provider/managers.py | from django.db import models
class TokenManager(models.Manager):
def create_token(self, consumer, token_type, timestamp, scope,
is_approved=False, user=None, callback=None, callback_confirmed=False):
"""Shortcut to create a token with random key/secret."""
token, created = self.get_or... |
data/MLWave/kepler-mapper/km.py | from __future__ import division
import numpy as np
from collections import defaultdict
import json
import itertools
from sklearn import cluster, preprocessing, manifold
from datetime import datetime
import sys
class KeplerMapper(object):
def __init__(self, verbose=2... |
data/Toblerity/Shapely/tests/test_multi.py | from . import unittest, test_int_types
class MultiGeometryTestCase(unittest.TestCase):
def subgeom_access_test(self, cls, geoms):
geom = cls(geoms)
for t in test_int_types:
for i, g in enumerate(geoms):
self.assertEqual(geom[t(i)], geoms[i])
|
data/ReactiveX/RxPY/rx/subjects/innersubscription.py | from rx import Lock
class InnerSubscription(object):
def __init__(self, subject, observer):
self.subject = subject
self.observer = observer
self.lock = Lock()
def dispose(self):
with self.lock:
if not self.subject.is_disposed and self.observer:
if ... |
data/Toblerity/Shapely/docs/code/parallel_offset_mitre.py | from matplotlib import pyplot
from shapely.geometry import LineString
from descartes import PolygonPatch
from figures import SIZE, BLUE, GRAY
def plot_coords(ax, x, y, color='
ax.plot(x, y, 'o', color=color, zorder=zorder)
def plot_line(ax, ob, color=GRAY):
parts = hasattr(ob, 'geoms') and ob or [ob]
for... |
data/aerospike/aerospike-client-python/test/old_tests/_test_list_insert.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 TestListInsert(object):
def setup_class... |
data/Newmu/Theano-Tutorials/4_modern_net.py | import theano
from theano import tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import numpy as np
from load import mnist
srng = RandomStreams()
def floatX(X):
return np.asarray(X, dtype=theano.config.floatX)
def init_weights(shape):
return theano.shared(floatX(np.random.ra... |
data/PyHDI/Pyverilog/pyverilog/dataflow/replace.py | from __future__ import absolute_import
from __future__ import print_function
import sys
import os
from pyverilog.dataflow.dataflow import *
def replaceUndefined(tree, termname):
if tree is None: return DFTerminal(termname)
if isinstance(tree, DFUndefined): return DFTerminal(termname)
if isinstance(tr... |
data/JohnMaguire/Cardinal/cardinal/test_exceptions.py | import pytest
import exceptions
def test_exceptions():
with pytest.raises(Exception):
raise exceptions.CardinalException
with pytest.raises(exceptions.CardinalException):
raise exceptions.InternalError
with pytest.raises(exceptions.CardinalException):
raise exceptions.Plugi... |
data/OpenMDAO/OpenMDAO-Framework/examples/openmdao.examples.metamodel_tutorial/openmdao/examples/metamodel_tutorial/cokriging_forrester_example.py | """
Cokriging example from [Forrester 2007] to show
MultiFiMetaModel and MultiFiCoKrigingSurrogate usage
"""
import numpy as np
from openmdao.main.api import Assembly, Component
from openmdao.lib.datatypes.api import Float
from openmdao.lib.drivers.api import CaseIteratorDriver
from openmdao.lib.components.api impor... |
data/agiliq/django-datagrid/books/urls.py | from django.conf.urls import *
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^books/', include('mylibrary.urls')),
(r'^admin/', include(admin.site.urls)),
)
|
data/adblockplus/gyp/test/win/win-tool/gyptest-win-tool-handles-readonly-files.py | """
Make sure overwriting read-only files works as expected (via win-tool).
"""
import TestGyp
import filecmp
import os
import stat
import sys
if sys.platform == 'win32':
test = TestGyp.TestGyp(formats=['ninja'])
os.makedirs('subdir')
read_only_files = ['read-only-file', 'subdir/A', 'subdir/B', 'subdir/C']... |
data/Mendeley/mrec/doc/conf.py | import sys, os
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
needs_sphinx = '1.0'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.pngmath', 'sphinx.ext.autosummary', 'numpydoc']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project... |
data/adaptivdesign/django-sellmo/sellmo/contrib/product/apps.py | from sellmo.core.apps import SellmoAppConfig
class DefaultConfig(SellmoAppConfig):
name = 'sellmo.contrib.product'
dependencies = ['sellmo.apps.product']
|
data/ImageEngine/gaffer/python/GafferSceneTest/OpenGLRenderTest.py | import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferScene
import GafferSceneTest
@unittest.skipIf( "TRAVIS" in os.environ, "OpenGL not set up on Travis" )
class OpenGLRenderTest( GafferSceneTest.SceneTestCase ) :
def test( self ) :
self.assertFalse( os.path.exists( self.tempora... |
data/abhik/pebl/src/pebl/test/test_network.py | import os
import numpy as N
from pebl import network, data, config
class TestEdgeSet:
def setUp(self):
self.edges = network.EdgeSet(num_nodes=6)
self.tuplelist = [(0,2), (0,5), (1,2)]
for edge in self.tuplelist:
self.edges.add(edge)
def test_add(self):
self.e... |
data/Theano/Theano/theano/compile/tests/test_debugmode.py | from __future__ import absolute_import, print_function, division
from nose.plugins.skip import SkipTest
import unittest
import numpy
from theano import config
from theano import gof
import theano
import theano.tensor
from theano.compat import exc_message
from theano.compile import debugmode
import theano.compile
from... |
data/Yelp/paasta/tests/cli/fsm/autosuggest_test.py | from contextlib import nested
import mock
from pytest import raises
from paasta_tools.cli.fsm import autosuggest
class TestGetSmartstackProxyPortFromFile:
def test_multiple_stanzas_per_file(self):
with nested(
mock.patch("__builtin__.open", autospec=True),
mock.patch("paasta_tool... |
data/SparkPost/python-sparkpost/examples/suppression_list/update_suppression_enty.py | from sparkpost import SparkPost
sp = SparkPost()
result = sp.suppression_list.update({
'email': 'test@test.com',
'transactional': False,
'non_transactional': True,
'description': 'Test description'
})
print(result)
|
data/UDST/activitysim/activitysim/defaults/tables/__init__.py | import households
import persons
import landuse
import skims
import accessibility
import tours
import size_terms
|
data/Pylons/pylons/tests/test_webapps/filestotest/helpers_sample.py | """Helper functions
Consists of functions to typically be used within templates, but also
available to Controllers. This module is available to both as 'h'.
"""
|
data/Netflix/security_monkey/security_monkey/tests/test_elasticsearch_service.py | """
.. module: security_monkey.tests.test_elasticsearch_service
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Mike Grima <mgrima@netflix.com>
"""
import json
from security_monkey.datastore import NetworkWhitelistEntry, Account
from security_monkey.tests import SecurityMonkeyTestCase
from security_m... |
data/adafruit/Adafruit_Python_CharLCD/examples/char_lcd.py | import time
import Adafruit_CharLCD as LCD
lcd_rs = 27
lcd_en = 22
lcd_d4 = 25
lcd_d5 = 24
lcd_d6 = 23
lcd_d7 = 18
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7,
... |
data/aarongarrett/inspyred/examples/standard/sa_example.py | from random import Random
from time import time
import inspyred
def main(prng=None, display=False):
if prng is None:
prng = Random()
prng.seed(time())
problem = inspyred.benchmarks.Sphere(2)
ea = inspyred.ec.SA(prng)
ea.terminator = inspyred.ec.terminators.evaluation_termi... |
data/JelteF/PyLaTeX/tests/test_quantities.py | import quantities as pq
from pylatex.quantities import _dimensionality_to_siunitx, Quantity
def test_quantity():
v = 1 * pq.m/pq.s
q1 = Quantity(v)
assert q1.dumps() == r'\SI{1.0}{\meter\per\second}'
q2 = Quantity(v, format_cb=lambda x: str(int(x)))
assert q2.dumps() == r'\SI{1}{\meter\per\seco... |
data/KimiNewt/pyshark/tests/conftest.py | import os
import logbook
import pytest
import pyshark
@pytest.fixture
def caps_directory():
return os.path.join(os.path.dirname(__file__), 'caps')
@pytest.fixture
def lazy_simple_capture(request, caps_directory):
"""
Does not fill the cap with packets.
"""
cap_path = os.path.join(caps_directory, ... |
data/adaptivdesign/django-sellmo/sellmo/contrib/shipping/methods/tiered_shipping/configure.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
from sellmo.contrib.settings import settings_manager
from .constants import MAX_TIER_ATTRIBUTES
group = _("Tiered Shipping")
for i in range(MAX_TIER_ATTRIBUTES):
settings_manager.add_setting(
'shipping_tier_attribute{0}... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.