path
stringlengths
23
146
source_code
stringlengths
0
261k
data/aerosol/django-dilla/setup.py
from setuptools import setup, find_packages from distribute_setup import use_setuptools use_setuptools() setup( name='django-dilla', version='0.2beta', author='Adam Rutkowski', author_email='adam@mtod.org', packages=find_packages(), url='http://aerosol.github.com/django-dilla/', license='B...
data/SheffieldML/GPy/GPy/inference/latent_function_inference/var_gauss.py
import numpy as np from ...util.linalg import pdinv from .posterior import Posterior from . import LatentFunctionInference log_2_pi = np.log(2*np.pi) class VarGauss(LatentFunctionInference): """ The Variational Gaussian Approximation revisited @article{Opper:2009, title = {The Variational Gaussian...
data/SMART-Lab/smartlearner/smartlearner/optimizers/__init__.py
from .sgd import SGD from .adagrad import AdaGrad from .adam import Adam from .rmsprop import RMSProp from .adadelta import Adadelta
data/adeel/timed/setup.py
from distutils.core import setup setup( name='timed', version='0.4.1', description="command-line time tracker", url='http://adeel.github.com/timed', author='Adeel Ahmad Khan', author_email='adeel@adeel.ru', packages=['timed'], scripts=['bin/timed'], install_requires=['termcolor'], license='MIT', ...
data/ImageEngine/gaffer/python/GafferUITest/WidgetTest.py
import unittest import weakref import sys import IECore import Gaffer import GafferTest import GafferUI import GafferUITest QtCore = GafferUI._qtImport( "QtCore" ) QtGui = GafferUI._qtImport( "QtGui" ) class TestWidget( GafferUI.Widget ) : def __init__( self, **kw ) : GafferUI.Widget.__init__( self, QtGui.QLa...
data/ProgVal/Limnoria/plugins/RSS/__init__.py
""" Provides basic functionality for handling RSS/RDF feeds. """ import supybot import supybot.world as world __version__ = "%%VERSION%%" __author__ = supybot.authors.jemfinch __contributors__ = {} from . import config from . import plugin from imp import reload reload(plugin) if world.testing: from . ...
data/StackStorm/st2contrib/packs/puppet/actions/cert_clean.py
from lib.python_actions import PuppetBasePythonAction __all__ = [ 'PuppetCertCleanAction' ] class PuppetCertCleanAction(PuppetBasePythonAction): def run(self, environment, host): success = self.client.cert_clean(environment=environment, host=host) return success
data/SmokinCaterpillar/pypet/pypet/tests/all_multi_core_tests.py
__author__ = 'Robert Meyer' from pypet.tests.testutils.ioutils import run_suite, discover_tests, TEST_IMPORT_ERROR, parse_args tests_include=set(('MultiprocNoPoolLockTest', 'MultiprocPoolSortQueueTest', 'MultiprocFrozenPoolSortQueueTest', '...
data/Lasagne/Lasagne/lasagne/layers/base.py
from collections import OrderedDict import theano.tensor as T from .. import utils __all__ = [ "Layer", "MergeLayer", ] class Layer(object): """ The :class:`Layer` class represents a single layer of a neural network. It should be subclassed when implementing new types of layers. Because...
data/Theano/Theano/doc/hpcs2011_tutorial/scan_pow.py
from __future__ import absolute_import, print_function, division import theano import theano.tensor as T from six.moves import xrange k = T.iscalar("k"); A = T.vector("A") def inner_fct(prior_result, A): return prior_result * A result, updates = theano.scan(fn=inner_fct, outputs_info=T....
data/agconti/cookiecutter-django-rest/{{cookiecutter.github_repository_name}}/{{cookiecutter.app_name}}/authentication/urls.py
from django.conf.urls import include, url from rest_framework.authtoken import views urlpatterns = [ url(r'^api-token-auth/', views.obtain_auth_token), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), ]
data/JohnDoee/autotorrent/autotorrent/at.py
from __future__ import division, unicode_literals import os import hashlib import logging from collections import defaultdict from .bencode import bencode, bdecode from .humanize import humanize_bytes from .utils import is_unsplitable, get_root_of_unsplitable, Pieces logger = logging.getLogger('autotorrent') class...
data/STIXProject/python-stix/examples/indicator-simplehash.py
""" Description: Build a STIX File Hash Observables document. Note that this does NOT create an Indicator and instead will add the File Hash Observable to the top-level Observables collection found in the STIX Package. """ from cybox.common import Hash from cybox.objects.file_object import File from stix.core import...
data/OrbitzWorldwide/droned/droned/lib/droned/responders/support.py
from droned.models.team import Team, SupportAgent from droned.models.issue import Issue from droned.responders import responder @responder(pattern="^teams$", form="teams", help="List known Teams") def teams(conversation): teamlist = '\n'.join("%s (%d members)" % (team.name, len(team.agents)) for team in Team.object...
data/HewlettPackard/python-hpOneView/examples/scripts/get-address-pool.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/Skype4Py/Skype4Py/Skype4Py/skype.py
"""Main Skype interface. """ __docformat__ = 'restructuredtext en' import threading import weakref import logging from api import * from errors import * from enums import * from utils import * from conversion import * from client import * from user import * from call import * from profile import * from settings impo...
data/adaptivdesign/django-sellmo/sellmo/contrib/variation/helpers.py
from sellmo.utils.text import underscore_concat from sellmo.contrib.attribute.helpers import ( ProductAttributeHelper as _ProductAttributeHelper ) from sellmo.contrib.attribute.helpers import AttributeHelper from django.db import models from django.db.models import Q from django.core.exceptions import ValidationEr...
data/StackStorm/st2/st2common/tests/unit/test_keyvalue_lookup.py
from st2tests.base import CleanDbTestCase from st2common.models.db.keyvalue import KeyValuePairDB from st2common.persistence.keyvalue import KeyValuePair from st2common.services.keyvalues import KeyValueLookup class TestKeyValueLookup(CleanDbTestCase): def test_non_hierarchical_lookup(self): k1 = KeyValu...
data/ImageEngine/gaffer/python/GafferUI/CompoundDataPlugValueWidget.py
from __future__ import with_statement import IECore import Gaffer import GafferUI class CompoundDataPlugValueWidget( GafferUI.PlugValueWidget ) : def __init__( self, plug, parenting = None ) : self.__column = GafferUI.ListContainer( spacing = 6 ) GafferUI.PlugValueWidget.__init__( self, self.__column, plu...
data/TheTorProject/ooni-probe/ooni/utils/net.py
import sys import socket from random import randint from zope.interface import implements from twisted.internet import protocol, defer from twisted.web.iweb import IBodyProducer from scapy.config import conf from ooni.errors import IfaceError try: from twisted.internet.endpoints import connectProtocol except Im...
data/RDFLib/rdflib/run_tests.py
""" Testing with Nose ================= This test runner uses Nose for test discovery and running. It uses the argument spec of Nose, but with some options pre-set. To begin with, make sure you have Nose installed, e.g.: $ sudo easy_install nose For daily test runs, use: $ ./run_tests.py If you supply attr...
data/Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/openstack/common/local.py
"""Greenthread local storage of variables using weak references""" import weakref from eventlet import corolocal class WeakLocal(corolocal.local): def __getattribute__(self, attr): rval = corolocal.local.__getattribute__(self, attr) if rval: rva...
data/ImageEngine/gaffer/contrib/doc/GafferUserGuide/images/autoGenerated_source/interface_layouts_figAA.py
import IECore import GafferUI import GafferScene import GafferSceneUI import os scriptNode = script scriptWindow = GafferUI.ScriptWindow.acquire( script ) layout = eval( "GafferUI.CompoundEditor( scriptNode, children = ( GafferUI.SplitContainer.Orientation.Horizontal, 0.495974, ( ( GafferUI.SplitContainer.Orientation.V...
data/SmileyChris/easy-thumbnails/easy_thumbnails/south_migrations/0015_auto__del_unique_thumbnail_name_storage_hash__add_unique_thumbnail_sou.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.delete_unique('easy_thumbnails_thumbnail', ['name', 'storage_hash']) db.create_unique('easy_thumbnails...
data/RisingOak/stashy/stashy/helpers.py
from .errors import maybe_throw def add_json_headers(kw): if 'headers' not in kw: kw['headers'] = {} headers = {'Content-type': 'application/json', 'Accept': 'application/json'} for header, value in headers.items(): kw['headers'][header] = value return kw class ResourceBase(object...
data/KushalP/serfclient-py/tests/test_result.py
from serfclient import result class TestSerfResult(object): def test_initialises_to_none(self): r = result.SerfResult() assert r.head is None assert r.body is None def test_provides_a_pretty_printed_form_for_repl_use(self): r = result.SerfResult(head={"a": 1}, body=('foo', 'ba...
data/WGBH/django-versatileimagefield/tests/test_settings.py
from .settings_base import * INSTALLED_APPS += ["tests"] VERSATILEIMAGEFIELD_SETTINGS = { 'cache_length': 2592000, 'cache_name': 'versatileimagefield_cache', 'jpeg_resize_quality': 70, 'global_placeholder_image': os.path.join( PROJECT_...
data/XiaoMi/minos/owl/business/urls.py
from django.conf.urls import patterns, url import views urlpatterns = patterns( '', url(r'^$', views.index), url(r'(?P<id>1)/(?P<access_type>[^/]+)/(?P<label>[^/]+)', views.show_online), url(r'(?P<id>2)/(?P<access_type>[^/]+)/(?P<label>[^/]+)', views.show_business), )
data/Impactstory/total-impact-webapp/core_celeryconfig.py
import os import sys import urlparse from kombu import Exchange, Queue sys.path.append('.') redis_url = os.environ.get('REDIS_URL', "redis://127.0.0.1:6379/") if not redis_url.endswith("/"): redis_url += "/" BROKER_URL = redis_url + "1" CELERY_RESULT_BACKEND = redis_url + "2" REDIS_CONNECT_RETRY = True BR...
data/OSCAAR/OSCAAR/oscaar/differentialPhotometry.py
""" OSCAAR/Code/differentialPhotometry.py Load in the images and analysis parameters set in the Code/init.par file, loop through each star within each image, for all images, and measure the stellar centroid positions and fluxes. Save these data to the oscaar.dataBank() object, and save that out to a binary "pickle". ...
data/Nextdoor/ndscheduler/ndscheduler/core/datastore/providers/postgresql.py
"""Represents PostgreSQL datastore.""" from ndscheduler import settings from ndscheduler.core.datastore.providers import base class DatastorePostgresql(base.DatastoreBase): @classmethod def get_db_url(cls): """ DATABASE_CONFIG_DICT = { 'user': 'myuser', 'password': 'p...
data/RDFLib/rdflib/test/test_issue576.py
import rdflib html = """<!DOCTYPE html> <html> <head> <title>Boom</title> </head> <body vocab="http://schema.org/" typeof="Book" resource="http://example.com/"> <time property="dateCreated"><em>2016-01-01</em></time> </body> </html> """ def test_time_child_element(): """ Ensure TIME eleme...
data/QuentinJi/viming/.vim/bundle/jedi-vim/jedi/jedi/evaluate/docstrings.py
""" Docstrings are another source of information for functions and classes. :mod:`jedi.evaluate.dynamic` tries to find all executions of functions, while the docstring parsing is much easier. There are two different types of docstrings that |jedi| understands: - `Sphinx <http://sphinx-doc.org/markup/desc.html - `Epydo...
data/Svenito/clive/install_requirements.py
from __future__ import unicode_literals, print_function import sys import os def get_requirements_file_path(): """Returns the absolute path to the correct requirements file.""" directory = os.path.dirname(__file__) requirements_file = 'requirements.txt' return os.path.join(directory, requirements_f...
data/Yelp/git-code-debt/tests/conftest.py
from __future__ import absolute_import from __future__ import unicode_literals import collections import contextlib import io import os.path import sqlite3 import subprocess import pytest import six from git_code_debt.create_tables import create_schema from git_code_debt.create_tables import populate_metric_ids from...
data/Robpol86/Flask-Large-Application-Example/pypi_portal/views/examples/alerts.py
from textwrap import dedent from flask import abort, redirect, render_template, request, url_for from pypi_portal.core import flash from pypi_portal.blueprints import examples_alerts @examples_alerts.route('/') def index(): return render_template('examples_alerts.html') @examples_alerts.route('/modal') def mo...
data/Socialsquare/Franklin/global_change_lab/models.py
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.contrib.auth.models import UserManager from django.contrib.flatpages.models import FlatPage from django.core.urlresolvers import reverse from django.db.models import signals from django.templatetags.static import static from django.ut...
data/adblockplus/gyp/test/mac/gyptest-rebuild.py
""" Verifies that app bundles are rebuilt correctly. """ import TestGyp import sys if sys.platform == 'darwin': print "This test is currently disabled: https://crbug.com/483696." sys.exit(0) test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode']) CHDIR = 'rebuild' test.run_gyp('test.gyp', chdir=CHDIR)...
data/SheffieldML/GPy/GPy/util/pca.py
''' Created on 10 Sep 2012 @author: Max Zwiessele @copyright: Max Zwiessele 2012 ''' import numpy try: import pylab import matplotlib except: pass from numpy.linalg.linalg import LinAlgError from operator import setitem import itertools from functools import reduce class PCA(object): """ PCA modul...
data/NeuroVault/NeuroVault/neurovault/apps/statmaps/middleware.py
from django.http import HttpResponseRedirect from neurovault.apps.statmaps.utils import HttpRedirectException class CollectionRedirectMiddleware: def process_exception(self, request, exception): if isinstance(exception, HttpRedirectException): return HttpResponseRedirect(exception.args[0])
data/ViDA-NYU/reprozip/reprounzip/reprounzip/unpackers/common/__init__.py
"""Utility functions for unpacker plugins. This contains functions related to shell scripts, package managers, and the pack files. """ from __future__ import division, print_function, unicode_literals from reprounzip.utils import join_root from reprounzip.unpackers.common.misc import UsageError, \ COMPAT_OK, COM...
data/adamlwgriffiths/PyGLy/pygly/texture.py
""" texture loading helper shape = (32,32,1) format = 'luminance' type = 'uint8' if gl.is_legacy(): format = GL_LUMINANCE else: format = GL_RGB swizzle = 'rrr' """ from OpenGL import GL from OpenGL.GL.ARB import texture_rg import numpy from pyrr.utils import parameters_as_numpy_arrays import numpy_util...
data/MediaMath/t1-python/terminalone/models/strategyconcept.py
"""Provides strategy concept object.""" from __future__ import absolute_import from ..config import PATHS from ..entity import Entity class StrategyConcept(Entity): """docstring for StrategyConcept.""" collection = 'strategy_concepts' resource = 'strategy_concept' _relations = { 'concept', ...
data/SickRage/SickRage/lib/mako/ext/pygmentplugin.py
from pygments.lexers.web import \ HtmlLexer, XmlLexer, JavascriptLexer, CssLexer from pygments.lexers.agile import PythonLexer, Python3Lexer from pygments.lexer import DelegatingLexer, RegexLexer, bygroups, \ include, using from pygments.token import \ Text, Comment, Operator, Keyword, Name, String, Other f...
data/adlibre/Adlibre-TMS/adlibre_tms/wsgi.py
""" WSGI config for foo project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` sett...
data/StackStorm/st2/st2reactor/st2reactor/container/manager.py
import os import sys import signal import eventlet from st2common import log as logging from st2reactor.container.process_container import ProcessSensorContainer from st2common.services.sensor_watcher import SensorWatcher from st2common.models.system.common import ResourceReference LOG = logging.getLogger(__name__) ...
data/OfferTeam/OfferListing/offers/urls.py
from django.conf.urls import patterns, url, include from haystack.views import search_view_factory, SearchView from offers.feeds import OfferFeed, OfferAtomFeed from offers.forms import OfferSearchForm from . import views as offer_views urlpatterns = patterns('offers.views', url(r'^view/(?P<offer_pk>\d+)/$', 'vie...
data/ImageEngine/gaffer/python/GafferSceneUI/ObjectSourceUI.py
import Gaffer import GafferScene import GafferUI Gaffer.Metadata.registerNode( GafferScene.ObjectSource, "description", """ A node which produces scenes with exactly one object in them. """, plugs = { "name" : [ "description", """ The name of the object in the output scene. """, ], "tran...
data/VisTrails/VisTrails/scripts/dist/windows/Input/startup.py
addPackage('vtk') addPackage('pythonCalc') addPackage('spreadsheet') addPackage('URL') addPackage('pylab') def testHook(): """Prints the Module class hierarchy to stdout.""" def printTree(n, indent = 0): def iprint(str): print '%s%s' % (" " * indent, str) i...
data/RobotLocomotion/director/src/python/director/shallowCopy.py
def deepCopy(dataOb): newData = dataObject.NewInstance() newData.DeepCopy(dataObj) return newData def shallowCopy(dataObj): newData = dataObj.NewInstance() newData.ShallowCopy(dataObj) return newData
data/adblockplus/gyp/buildbot/buildbot_run.py
"""Argument-less script to select what to run on the buildbots.""" import os import shutil import subprocess import sys BUILDBOT_DIR = os.path.dirname(os.path.abspath(__file__)) TRUNK_DIR = os.path.dirname(BUILDBOT_DIR) ROOT_DIR = os.path.dirname(TRUNK_DIR) CMAKE_DIR = os.path.join(ROOT_DIR, 'cmake') CMAKE_BIN_DIR =...
data/NervanaSystems/neon/tests/serialization/alexnet.py
""" alexnet model adapted for serialization testing has subset_pct set so that there are a low number of iterations per epoch and no partial minibatches, dropout is turned off for reproducibility on gpu and the learning rate is scaled to handle the reduced dropout percentage. """ from neon.util.argparser import Neon...
data/HubSpot/sanetime/sanetime/sanetime.py
from .constants import MILLI_MICROS,SECOND_MICROS,MINUTE_MICROS import calendar from datetime import datetime from dateutil import parser from dateutil.tz import tzlocal from .error import TimeConstructionError from .sanedelta import SaneDelta import pytz MICROS_TRANSLATIONS = ( (('m','mins','minutes','epo...
data/PyHDI/veriloggen/tests/extension/fsm_/delayed_eager_val_lazy_cond/fsm_delayed_eager_val_lazy_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.dirname(os.path.abspath(__file__))))))) from veriloggen import * def mkLed(): m = Module('blinkled') clk = m.Input('CLK...
data/RDFLib/rdflib/test/test_serializexml.py
from rdflib.term import URIRef, BNode from rdflib.namespace import RDFS from rdflib.py3compat import b from rdflib.plugins.serializers.rdfxml import XMLSerializer from rdflib.graph import ConjunctiveGraph try: from io import BytesIO except ImportError: from StringIO import StringIO as BytesIO class Seriali...
data/Yelp/Testify/testing_suite/example_test.py
from testify import TestCase, run class ExampleTestCase(TestCase): def test_one(self): pass def test_two(self): pass class SecondTestCase(TestCase): def test_one(self): pass if __name__ == "__main__": run()
data/Shopify/shopify_python_api/test/order_test.py
import shopify from test.test_helper import TestCase from pyactiveresource.activeresource import ActiveResource from pyactiveresource.util import xml_to_dict class OrderTest(TestCase): def test_should_be_loaded_correctly_from_order_xml(self): order_xml = """<?xml version="1.0" encoding="UTF-8"?> ...
data/Keeper-Security/Commander/tests/test_record.py
from keepercommander.record import Record def sample_record(): record = Record() record.folder = 'folder' record.title = 'title' record.login = 'login' record.password = 'password' record.login_url = 'login_url' record.notes = 'line1\nline2\nline3' record.custom_fields = [ {'na...
data/Stiivi/bubbles/bubbles/execution/__init__.py
from .context import * from .engine import * from .graph import * from .pipeline import *
data/NeuralEnsemble/python-neo/neo/io/neurosharectypesio.py
""" NeuroshareIO is a wrap with ctypes of neuroshare DLLs. Neuroshare is a C API for reading neural data. Neuroshare also provides a Matlab and a Python API on top of that. Neuroshare is an open source API but each dll is provided directly by the vendor. The neo user have to download separtatly the dll on neurosharewe...
data/Pylons/substanced/substanced/file/views.py
import pkg_resources import mimetypes import colander import deform.schema from pyramid.httpexceptions import HTTPFound from pyramid.response import Response from pyramid.security import NO_PERMISSION_REQUIRED from ..form import FormView from ..file import ( FilePropertiesSchema, FileUploadTempStore, fil...
data/RichardBronosky/aws-ecs-service-discovery/setup.py
from setuptools import setup setup( name='aws_ecs_service_discovery', version='0.1', py_modules=['services'], install_requires=[ 'boto', ], entry_points=''' [console_scripts] awsesd=services:cli ''', )
data/Nikola-K/django_reddit/users/views.py
from django.contrib import messages from django.contrib.auth import logout, login, authenticate from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import HttpResponseBadRequest, Http404 from django.shortcuts import render, redirect, get_object_or_404 ...
data/Tivix/django-cron/django_cron/models.py
from django.db import models class CronJobLog(models.Model): """ Keeps track of the cron jobs that ran etc. and any error messages if they failed. """ code = models.CharField(max_length=64, db_index=True) start_time = models.DateTimeField(db_index=True) end_time = models.DateTimeField(db_index...
data/Shougo/deoplete.nvim/rplugin/python3/deoplete/sources/file.py
import os import re from os.path import exists, dirname from .base import Base from deoplete.util import \ set_default, get_simple_buffer_config class Source(Base): def __init__(self, vim): Base.__init__(self, vim) self.name = 'file' self.mark = '[F]' self.min_pattern_length ...
data/adblockplus/gyp/test/variables/commands/gyptest-commands-ignore-env.py
""" Test that environment variables are ignored when --ignore-environment is specified. """ import os import TestGyp test = TestGyp.TestGyp(format='gypd') os.environ['GYP_DEFINES'] = 'FOO=BAR' os.environ['GYP_GENERATORS'] = 'foo' os.environ['GYP_GENERATOR_FLAGS'] = 'genflag=foo' os.environ['GYP_GENERATOR_OUTPUT'] =...
data/LxMLS/lxmls-toolkit/lxmls/big_data_em/preprocess.py
import numpy as np import lxmls.readers.pos_corpus as pcc from os import path import pickle corpus = pcc.PostagCorpus() input_data = path.join( path.dirname(__file__), "../../data/train-02-21.conll") train_seq = corpus.read_sequence_list_conll(input_data, max_sent_len=15, max_nr_sent=10...
data/IanLewis/kay/kay/lib/jinja2/tests.py
""" jinja2.tests ~~~~~~~~~~~~ Jinja test functions. Used with the "is" operator. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import re from jinja2.runtime import Undefined __test__ = False number_re = re.compile(r'^-?\d+(\.\d+)?$') regex_type = type...
data/NeuralEnsemble/python-neo/neo/core/recordingchannelgroup.py
''' This module defines :class:`RecordingChannelGroup`, a container for multiple data channels. :class:`RecordingChannelGroup` derives from :class:`Container`, from :module:`neo.core.container`. ''' from __future__ import absolute_import, division, print_function import numpy as np from neo.core.container import C...
data/OSIOT/OBSOLETE-IoT-Toolkit/SmartObjectFramework/ObjectService/SmartObject/Observers.py
''' Created on Sep 15, 2012 Observers class for observation of changes in a resource @author: mjkoster ''' from RESTfulResource import RESTfulResource from urlparse import urlparse class Observers(RESTfulResource): def __init__(self): RESTfulResource.__init__(self) self.__schemes = ['http', ...
data/adlnet/LR-Data/src/tasks/validate.py
from celery.task import task from celery.execute import send_task from celery.log import get_default_logger log = get_default_logger() @task def emptyValidate(envelope,config): send_task(config['insertTask'],[envelope,config])
data/RoseOu/flasky/app/main/forms.py
from flask.ext.wtf import Form from wtforms import StringField, TextAreaField, BooleanField, SelectField,\ SubmitField from wtforms.validators import Required, Length, Email, Regexp from wtforms import ValidationError from flask.ext.pagedown.fields import PageDownField from ..models import Role, User class NameFo...
data/OpenMDAO-Plugins/pyopt_driver/setup.py
from setuptools import setup, find_packages kwargs = {'author': 'Kenneth T. Moore', 'author_email': 'kenneth.t.moore-1@nasa.gov', 'classifiers': ['Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering'], 'description': 'OpenMDAO driver wrapper for the open-source optimization pac...
data/LeightonStreet/LingoBarter/lingobarter/ext/celery_app.py
from celery import Celery def create_celery_app(app): if app.config.get('CELERY_ENABLED'): app.celery = Celery(__name__, broker=app.config['CELERY_BROKER_URL']) app.celery.conf.update(app.config) taskbase = app.celery.Task class ContextTask(taskbase): abstract = True ...
data/ImageEngine/gaffer/python/GafferImageTest/CopyImageMetadataTest.py
import os import IECore import Gaffer import GafferImage import GafferTest import GafferImageTest class CopyImageMetadataTest( GafferImageTest.ImageTestCase ) : checkerFile = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" ) def test( self ) : r = GafferImage.ImageReader() r["fi...
data/ReactiveX/RxPY/tests/test_concurrency/test_newthreadscheduler.py
import unittest from datetime import datetime, timedelta from time import sleep from rx.concurrency import NewThreadScheduler class TestNewThreadScheduler(unittest.TestCase): def test_new_thread_now(self): scheduler = NewThreadScheduler() res = scheduler.now() - datetime.utcnow() assert re...
data/JeremyGrosser/supervisor/src/supervisor/tests/fixtures/fakeos.py
from os import * from os import _exit import os class FakeOS: def __init__(self): self.orig_uid = os.getuid() self.orig_gid = os.getgid() def setgroups(*args): return def getuid(): return 0 def setuid(arg): self.uid = arg self.setuid_called = 1 de...
data/StackStorm/st2contrib/packs/openhab/actions/send_command.py
from lib.action import BaseAction class SendCommandAction(BaseAction): def run(self, item, command): self._post(item, command) return {'status': 'ok'}
data/StackStorm/st2/contrib/linux/actions/checks/check_processes.py
import os import sys import re import json class CheckProcs(object): myPid = 0 state = "" name = "" pid = 0 allProcs = [] interestingProcs = [] procDir = "/proc" debug = False def __init__(self): self.myPid = os.getpid() def setup(self, debug=False, pidlist=False): ...
data/IceCTF/ctf-platform/api/graders/autogentest/generator.py
""" Generator example. """ def generate(random, pid, tools, n): """ Generate an instance of the problem Needs to return a list of files to copy to particular instance. """ f = open("/tmp/key", "w") k = str(random.randint(0, 1000)) f.write(k) f.close() return { "resource_...
data/RoseOu/flasky/venv/lib/python2.7/site-packages/gunicorn/sock.py
import errno import os import socket import stat import sys import time from gunicorn import util from gunicorn.six import string_types SD_LISTEN_FDS_START = 3 class BaseSocket(object): def __init__(self, address, conf, log, fd=None): self.log = log self.conf = conf self.cfg_addr = add...
data/Opentaste/bombolone/bombolone/core/validators.py
""" core.validators.py ~~~~~~ :copyright: (c) 2014 by @zizzamia :license: BSD (See LICENSE for details) """ import re URL_REGEX = re.compile( r'^(?:http|ftp)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' r'localhost|' r'\d{1,3}\.\d{1,3}...
data/RobotLocomotion/director/src/python/director/multisensepanel.py
import PythonQt from PythonQt import QtCore, QtGui, QtUiTools from director import lcmUtils from director import applogic as app from director.utime import getUtime from director.timercallback import TimerCallback import numpy as np import math from time import time from copy import deepcopy def addWidgetsToDict(widg...
data/Net-ng/kansha/kansha/card/__init__.py
from . import view from .comp import Card, NewCard
data/StackStorm/st2/tools/st2-analyze-links.py
""" Visualize the links created by rules. 1. requires graphviz pip install graphviz apt-get install graphviz To run : ./st2-analyze-links.py --action_ref <action-ref> The command must run on a StackStorm box. """ import os import sets from oslo_config import cfg from st2common import config fr...
data/Yelp/fullerite/src/diamond/collectors/cpu/cpu.py
""" The CPUCollector collects CPU utilization metric using /proc/stat. * /proc/stat """ import diamond.collector import os import time from diamond.collector import str_to_bool try: import psutil except ImportError: psutil = None class CPUCollector(diamond.collector.Collector): PROC = '/proc/stat'...
data/Nordeus/pushkin/pushkin/protobuf/PushNotificationMessage_pb2.py
from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import descriptor_pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='PushNotificationMessage.proto', package='', serialized_pb...
data/JoelBender/bacpypes/py25/bacpypes/tcp.py
""" TCP Communications Module """ import asyncore import socket import cPickle as pickle from time import time as _time, sleep as _sleep from StringIO import StringIO from .debugging import ModuleLogger, DebugContents, bacpypes_debugging from .core import deferred from .task import FunctionTask, OneShotFunction from...
data/Theano/Theano/theano/tensor/tests/test_var.py
from __future__ import absolute_import, print_function, division import numpy as np from numpy.testing import assert_equal, assert_string_equal import theano import theano.tensor as tt import theano.tests.unittest_tools as utt from theano.tensor import (Subtensor, AdvancedSubtensor, AdvancedSubtensor1, ...
data/adamhadani/logtools/logtools/parsers.py
""" logtools.parsers Parsers for some common log formats, e.g Common Log Format (CLF). These parsers can be used both programmaticaly as well as by the logtools command-line tools to meaningfully parse log fields from standard formats. """ import os import re import sys import logging from functools import partial fr...
data/PyMySQL/PyMySQL/pymysql/tests/test_load_local.py
from pymysql import OperationalError, Warning from pymysql.tests import base import os import warnings __all__ = ["TestLoadLocal"] class TestLoadLocal(base.PyMySQLTestCase): def test_no_file(self): """Test load local infile when the file does not exist""" conn = self.connections[0] c = c...
data/QuentinJi/viming/.vim/bundle/jedi-vim/jedi/test/test_evaluate/absolute_import/local_module.py
""" This is a module that imports the *standard library* unittest, despite there being a local "unittest" module. It specifies that it wants the stdlib one with the ``absolute_import`` __future__ import. The twisted equivalent of this module is ``twisted.trial._synctest``. """ from __future__ import absolute_import i...
data/Relrin/aiorest-ws/examples/auth_token/settings.py
DATABASES = { 'default': { 'backend': 'aiorest_ws.db.backends.sqlite3', 'name': ':memory:' } }
data/Kitware/minerva/plugin_tests/source_test.py
import os os.environ['GIRDER_PORT'] = os.environ.get('GIRDER_TEST_PORT', '20200') from tests import base def setUpModule(): """ Enable the minerva plugin and start the server. """ base.enabledPlugins.append('jobs') base.enabledPlugins.append('romanesco') base.enabledPlugins.append('gravat...
data/SublimeGit/SublimeGit/sgit/diff.py
import re from functools import partial import sublime from sublime_plugin import WindowCommand, TextCommand, EventListener from .util import find_view_by_settings, get_setting from .cmd import GitCmd from .helpers import GitDiffHelper, GitErrorHelper, GitStatusHelper RE_DIFF_HEAD = re.compile(r'(---|\+\+\+){3} (a|...
data/RoseOu/flasky/venv/lib/python2.7/fnmatch.py
"""Filename matching with shell patterns. fnmatch(FILENAME, PATTERN) matches according to the local convention. fnmatchcase(FILENAME, PATTERN) always takes case in account. The functions operate by translating the pattern into a regular expression. They cache the compiled regular expressions for speed. The function...
data/SeyZ/baboon/baboon/common/pyrsync.py
""" This is a pure Python implementation of the [rsync algorithm] [TM96]. Updated to use SHA256 hashing (instead of the standard implementation which uses outdated MD5 hashes), and packages for disutils distribution by Isis Lovecruft, <isis@patternsinthevoid.net>. The majority of the code is blatantly stolen from Eric...
data/adieu/python-openid/examples/djopenid/views.py
from djopenid import util from django.views.generic.simple import direct_to_template def index(request): consumer_url = util.getViewURL( request, 'djopenid.consumer.views.startOpenID') server_url = util.getViewURL(request, 'djopenid.server.views.server') return direct_to_template( request,...
data/aellerton/demo-allauth-bootstrap/allauthdemo/auth/admin.py
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.admin import UserAdmin try: from django.utils.encoding import force_text except ImportError: from django.utils.encoding import force_unicode as force_text from .models import DemoUser, UserProfi...
data/SpriteLink/NIPAP/nipap/nipap/errors.py
class NipapError(Exception): """ NIPAP base error class. """ error_code = 1000 class NipapInputError(NipapError): """ Erroneous input. A general input error. """ error_code = 1100 class NipapMissingInputError(NipapInputError): """ Missing input. Most input is passed i...