path
stringlengths
23
146
source_code
stringlengths
0
261k
data/agiliq/merchant/billing/tests/test_eway.py
from django.conf import settings from django.test import TestCase from django.utils.unittest import skipIf from billing import get_gateway, CreditCard from billing.signals import * from billing.models import EwayResponse from billing.gateway import CardNotSupported from billing.utils.credit_card import Visa fake_opti...
data/ReactiveX/RxPY/tests/test_observable/test_count.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/TriOptima/tri.table/examples/examples/wsgi.py
""" WSGI config for examples project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "examples.settings") from django.core...
data/FichteFoll/CSScheme/tinycsscheme/tinycss/tests/__init__.py
""" Test suite for tinycss ---------------------- :copyright: (c) 2012 by Simon Sapin. :license: BSD, see LICENSE for more details. """ from __future__ import unicode_literals def assert_errors(errors, expected_errors): """Test not complete error messages but only substrings.""" assert len(...
data/adieu/django-mediagenerator/mediagenerator/contrib/jinja2ext.py
from jinja2 import nodes, TemplateAssertionError, Markup as mark_safe from jinja2.ext import Extension from mediagenerator.generators.bundles.utils import _render_include_media class MediaExtension(Extension): tags = set(['include_media']) def __init__(self, environment): self.environment = environmen...
data/RobotLocomotion/director/src/python/scripts/atlasRecoveryPanel.py
from director import atlasdriver from director import consoleapp from PythonQt import QtCore, QtGui from collections import namedtuple atlasDriver = atlasdriver.init() w = QtGui.QWidget() l = QtGui.QVBoxLayout(w) Button = namedtuple('Button', ['name', 'callback', 'color']); buttons = [ Button('Reactive R...
data/Sandia-Labs/PVLIB_Python/pvlib/sphinx/Docs/source/exts/notebookcell_sphinxext.py
import os, shutil, string, glob, io from sphinx.util.compat import Directive from docutils.parsers.rst import directives from IPython.nbconvert import html, python from IPython.nbformat import current from runipy.notebook_runner import NotebookRunner from jinja2 import FileSystemLoader from notebook_sphinxext import \ ...
data/OpenMDAO/OpenMDAO/openmdao/util/file_wrap.py
""" A collection of utilities for file wrapping. Note: This is a work in progress. """ from __future__ import print_function import re from six.moves import range from pyparsing import CaselessLiteral, Combine, OneOrMore, Optional, \ TokenConverter, Word, nums, oneOf, printables, \ ...
data/T-002/pycast/pycast/tests/regressiontest.py
import unittest from mock import patch from pycast.common.timeseries import TimeSeries from pycast.common.matrix import Matrix from pycast.methods.regression import Regression, LinearRegression class RegressionTest(unittest.TestCase): """Test class for the Regression method.""" def calculate_parameters_tw...
data/QuantumFractal/Data-Structure-Zoo/4-Collections and Iterators/test.py
import unittest import collections_and_iterators """ Collections - TESTS Testing Collections programming examples from collections.py Gabby Ortman """ class TestObjectMethods(unittest.TestCase): def setUp(self): self.singleLinkList = collections_and_iterators.SinglyLinkedList() ...
data/MirantisWorkloadMobility/CloudFerry/cloudferry/lib/os/storage/plugins/copy_mechanisms.py
import abc from cloudferry.lib.utils import files from cloudferry.lib.utils import remote_runner from cloudferry.lib.copy_engines import base class CopyFailed(RuntimeError): pass class CopyMechanism(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def copy(self, context, source_object, des...
data/JetBrains/youtrack-rest-python-library/python/tracLib/client.py
from trac.env import Environment from trac.attachment import Attachment from tracLib import * from ConfigParser import ConfigParser import tracLib import tracLib.timetracking class Client(object): def __init__(self, env_path): self.env_path = env_path self.env = Environment(env_path) self....
data/adaptivdesign/django-sellmo/skeleton/account/apps.py
from django.utils.translation import ugettext_lazy as _ from sellmo.core.apps import SellmoAppConfig class DefaultConfig(SellmoAppConfig): name = 'account' verbose_name = _("Customer accounts")
data/ProgVal/Limnoria/plugins/Unix/__init__.py
""" Provides commands available only on Unix. """ import supybot import supybot.world as world __version__ = "%%VERSION%%" __author__ = supybot.authors.jemfinch __contributors__ = {} __url__ = '' from . import config from . import plugin from imp import reload reload(plugin) if world.testing: from ....
data/NeuroVault/NeuroVault/neurovault/apps/statmaps/migrations/0026_populate_cogatlas.py
from __future__ import unicode_literals from django.db import models, migrations import json, os dir = os.path.abspath(os.path.dirname(__file__)) def populate_cogatlas(apps, schema_editor): CognitiveAtlasTask = apps.get_model("statmaps", "CognitiveAtlasTask") CognitiveAtlasContrast = apps.get_model("statmaps"...
data/Legrandin/PyAuthenNTLM2/pyntlm.py
import sys import base64 import time import urllib from struct import unpack from threading import Lock from binascii import hexlify from urlparse import urlparse from mod_python import apache from PyAuthenNTLM2.ntlm_dc_proxy import NTLM_DC_Proxy from PyAuthenNTLM2.ntlm_ad_proxy import NTLM_AD_Proxy use_basic_auth = ...
data/STIXProject/python-stix/stix/bindings/extensions/vulnerability/cvrf_1_1.py
import sys from mixbox.binding_utils import * from stix.bindings import register_extension import stix.bindings.exploit_target as exploit_target_binding XML_NS = "http://stix.mitre.org/extensions/Vulnerability @register_extension class CVRF1_1InstanceType(exploit_target_binding.VulnerabilityType): """The CV...
data/Yelp/git-code-debt/tests/server/servlets/status_test.py
from __future__ import absolute_import from __future__ import unicode_literals import flask def test_healthcheck(server): server.client.get(flask.url_for('status.healthcheck'))
data/ProgVal/Limnoria/plugins/Conditional/config.py
import supybot.conf as conf import supybot.registry as registry try: from supybot.i18n import PluginInternationalization from supybot.i18n import internationalizeDocstring _ = PluginInternationalization('Conditional') except: _ = lambda x:x internationalizeDocstring = lambda x:x def conf...
data/Chitrank-Dixit/InMyMind/src/lib/requests/packages/charade/escsm.py
from .constants import eStart, eError, eItsMe HZ_cls = ( 1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0...
data/Kuniwak/vint/vint/ast/plugin/scope_plugin/reference_reachability_tester.py
from vint.ast.plugin.scope_plugin.scope_detector import ( detect_scope_visibility, normalize_variable_name, is_builtin_variable, ) from vint.ast.plugin.scope_plugin.scope_linker import ScopeLinker from vint.ast.plugin.scope_plugin.identifier_classifier import ( IdentifierClassifier, is_function_iden...
data/Pylons/substanced/substanced/audit/tests/test_subscribers.py
import json import unittest from pyramid import testing import mock class Test_acl_modified(unittest.TestCase): def setUp(self): self.request = testing.DummyRequest() self.config = testing.setUp(request=self.request) def tearDown(self): testing.tearDown() def _callFUT(self...
data/Yelp/paasta/paasta_tools/contrib/delete_old_marathon_deployments.py
import argparse import datetime import logging import dateutil.parser from dateutil import tz from pytimeparse import timeparse from paasta_tools import marathon_tools log = logging.getLogger('__main__') logging.basicConfig() def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('-a', '...
data/Masood-M/yalih/mechanize/_redirection.py
import os,sys parentdir = os.path.dirname(__file__) sys.path.insert(0,parentdir) import executemechanize class redirection: def createarray(self): setattr(self, "redirection_list", []) def appendurl(self, url): url = str(url) if not url.endswith(".js") or url.endswith(".json"): self.redirection_list.appen...
data/PressLabs/gitfs/tests/utils/test_strptime.py
import pytest import datetime as dt from mock import MagicMock from gitfs.utils.strptime import TimeParser from gitfs.utils import strptime class TestDateTimeUtils(object): def test_strptime(self): date = dt.date(2014, 8, 21) datetime = dt.datetime(2014, 8, 21, 1, 2, 3) assert strptime(...
data/SpriteLink/NIPAP/whoisd/nipap_whoisd.py
import os __version__ = "0.28.4" __author__ = "Kristian Larsson, Lukas Garberg" __author_email__ = "kll@tele2.net, lukas@spritelink.net" __copyright__ = "Copyright 2011-2014, Kristian Larsson, Lukas Garberg" __license__ = "MIT" __status__ = "Development" __url__ = "http://SpriteLink.github.com/NIPAP" UMASK =...
data/PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/Chapter 4/4-4.py
def saturate_color(color): red, green, blue = color red = min(red, 255) green = min(green, 255) blue = min(blue, 255) return red, green, blue
data/Kotti/Kotti/kotti/tests/test_upload.py
import json from mechanize._mechanize import LinkNotFoundError from pytest import raises from kotti.testing import BASE_URL from kotti.testing import user from kotti.views.edit.upload import UploadView def test_upload_anonymous(root, dummy_request, browser): view = UploadView(root, dummy_request) assert v...
data/adieu/django-nonrel/django/test/utils.py
import sys import time import os import warnings from django.conf import settings from django.core import mail from django.core.mail.backends import locmem from django.test import signals from django.template import Template from django.utils.translation import deactivate __all__ = ('Approximate', 'ContextList', 'setu...
data/ImageEngine/gaffer/startup/gui/nodeEditor.py
import GafferUI import GafferSceneUI def __toolMenu( nodeEditor, node, menuDefinition ) : GafferUI.UIEditor.appendNodeEditorToolMenuDefinitions( nodeEditor, node, menuDefinition ) GafferUI.BoxUI.appendNodeEditorToolMenuDefinitions( nodeEditor, node, menuDefinition ) GafferSceneUI.FilteredSceneProcessorUI.appendNod...
data/MostAwesomeDude/construct/construct/text/ast.py
from construct.core import Container from construct.adapters import Adapter class AstNode(Container): def __init__(self, nodetype, **kw): Container.__init__(self) self.nodetype = nodetype for k, v in sorted(kw.iteritems()): setattr(self, k, v) def accept(self, visitor): ...
data/IanLewis/kay/kay/registration/urls.py
""" Kay registration urls. :Copyright: (c) 2009 Takashi Matsuo <tmatsuo@candit.jp> All rights reserved. :license: BSD, see LICENSE for more details. """ from kay.routing import ( ViewGroup, Rule ) view_groups = [ ViewGroup( Rule('/activate/<activation_key>', endpoint='activate', view=('kay.registrat...
data/PyHDI/veriloggen/tests/core/multiple_definition_/instance_variable/multiple_definition_instance_variable.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 mkSub(): m = Module('blinkled') clk = m.Input('CLK...
data/acba/elm/elm/elmk.py
""" This file contains ELMKernel classes and all developed methods. """ from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from __future__ import print_function from .mltools import * import numpy as np import optunity import ast import sys if sys.ver...
data/RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/event/registry.py
"""Provides managed registration services on behalf of :func:`.listen` arguments. By "managed registration", we mean that event listening functions and other objects can be added to various collections in such a way that their membership in all those collections can be revoked at once, based on an equivalent :class:`....
data/OfflineIMAP/imapfw/imapfw/__init__.py
__productname__ = 'Imapfw' __version__ = "0.025" __copyright__ = "Copyright 2015-2016 Nicolas Sebrecht & contributors" __author__ = "Nicolas Sebrecht" __author_email__= "nicolas.s-dev@laposte.net" __description__ = "Framework for working with IMAP and emails" __license__ = "The MIT License (MIT)" __homepage...
data/StackStorm/st2contrib/packs/fireeye/actions/view_ax_config.py
from lib.actions import BaseAction class ViewAXConfig(BaseAction): def run(self): response = self._api_get('config') return response
data/USArmyResearchLab/Dshell/decoders/filter/country.py
''' @author: tparker ''' import dshell import util import netflowout class DshellDecoder(dshell.TCPDecoder): '''activity tracker ''' def __init__(self, **kwargs): ''' Constructor ''' self.sessions = {} self.alerts = False self.file = None dshell.TCPDe...
data/OneDrive/onedrive-sdk-python/src/python2/request/shared_collection.py
''' ''' from __future__ import unicode_literals from ..collection_base import CollectionRequestBase, CollectionResponseBase, CollectionPageBase from ..request_builder_base import RequestBuilderBase from ..model.item import Item import json class SharedCollectionRequest(CollectionRequestBase): ...
data/TargetHolding/pyspark-cassandra/python/pyspark_cassandra/tests.py
from _functools import partial from datetime import datetime, timedelta from decimal import Decimal import string import sys import time import unittest import uuid from cassandra import ConsistencyLevel from cassandra.cluster import Cluster from cassandra.util import uuid_from_time from pyspark import SparkConf from...
data/adlibre/Adlibre-DMS/adlibre_dms/libraries/adlibre/re_gen/re_validate.py
import re from re_constants import DISALLOWED_PATTERNS, DISALLOWED_CHARS, VALID_SEQUENCE_NUMBER_PATTERNS def re_regex_is_valid(regex_str=False): """ Validator main. validates regex string against applied rules """ if not regex_str: return False print '1' if re_has_disallowed_pattern...
data/adewes/blitzdb/blitzdb/fields/date.py
from .base import BaseField class DateField(BaseField): pass
data/KunihikoKido/sublime-elasticsearch-client/commands/indices_stats.py
from .base import BaseCommand class IndicesStatsCommand(BaseCommand): command_name = "elasticsearch:indices-stats" def is_enabled(self): return True def run_request(self, index=None): if index is None: self.show_index_list_panel(self.run) return options =...
data/aht/suas/suas/test/test_session.py
import re from time import time, gmtime from calendar import timegm from webtest import TestApp from google.appengine.ext import webapp from google.appengine.ext.webapp import util import sys, os sys.path.append( os.path.abspath( os.path.join( os.path.dirname(__file__), '..') ) ) from signedcookie import SignedCook...
data/JeffHeard/ga_ows/views/wfs.py
""" An implementation of OGC WFS 2.0.0 over the top of Django. This module requires that OGR be installed and that you use either the PostGIS or Spatialite backends to GeoDjango for the layers you are retrieving. The module provides a generic view, :py:class:WFS that provides standard WFS requests and responses and :p...
data/OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_bndry_var_full_and_sub.py
import unittest from openmdao.main.api import Assembly, Component from openmdao.main.datatypes.api import Float, Array from openmdao.lib.drivers.api import CONMINdriver, BroydenSolver, \ SensitivityDriver, FixedPointIterator from openmdao.lib.optproblems import sellar class Dis...
data/QuantSoftware/QuantSoftwareToolkit/Legacy/quicksim/strategies/OneStock.py
''' (c) 2011, 2012 Georgia Tech Research Corporation This source code is released under the New BSD license. Please see http://wiki.quantsoftware.org/index.php?title=QSTK_License for license details. Created on Jan 1, 2011 @author:Drew Bratcher @contact: dbratcher@gatech.edu @summary: Contains tutorial for backteste...
data/LabPy/lantz/setup.py
try: from setuptools import setup except ImportError: print('Please install or upgrade setuptools or pip to continue') sys.exit(1) import os import sys import codecs def read(filename): return codecs.open(filename, encoding='utf-8').read() long_description = '\n\n'.join([read('README'), ...
data/OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/components/sleep_comp.py
""" sleep_comp.py - component that does one thing and does it well. Sleep. Useful for slowing down a simulation to see what is happening """ from openmdao.main.api import Component from openmdao.main.datatypes.api import Float import time class Sl...
data/VisTrails/VisTrails/vistrails/tests/resources/import_targets/__init__.py
"""This is a target for importing a non-package module. It is used in the PackageManager's tests to check that the dependency-tracking name-fixing import override works correctly. """
data/LibraryOfCongress/chronam/core/middleware.py
import os from django.conf import settings from django.http import HttpResponse class HttpResponseServiceUnavailable(HttpResponse): status_code = 503 class TooBusyMiddleware(object): def process_request(self, request): one, five, fifteen = os.getloadavg() if one > settings.TOO_BUSY_LOAD_AV...
data/adaptivdesign/django-sellmo/sellmo/contrib/attribute/forms.py
from sellmo.utils.forms import FormFactory from django import forms from django.utils.translation import ugettext_lazy as _ from .models import Attribute class ProductAttributeFormMixin(object): def __init__(self, *args, **kwargs): initial = {} if 'initial' in kwargs: initial = kwarg...
data/NVIDIA/DIGITS/digits/webapp.py
from __future__ import absolute_import import flask from flask.ext.socketio import SocketIO from gevent import monkey; monkey.patch_all() from .config import config_value from digits import utils import digits.scheduler app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['WTF_CSRF_ENABLED'] = False ...
data/ProgVal/Limnoria/plugins/Status/__init__.py
""" A simple module to handle various informational commands querying the bot's current status and statistics. """ import supybot import supybot.world as world __version__ = "%%VERSION%%" __author__ = supybot.authors.jemfinch __contributors__ = {} from . import config from . import plugin from imp import reloa...
data/NORDUnet/opennsa/opennsa/backends/ncsvpn.py
""" Backend for NCS VPN module. Author: Henrik Thostrup Jensen <htj at nordu.net> Copyright: NORDUnet(2011-2013) """ import base64 import random from twisted.python import log from twisted.web.error import Error as WebError from opennsa import constants as cnt, config from opennsa.backends.common import genericback...
data/WatchPeopleCode/WatchPeopleCode/migrations/versions/440bcc45ff09_.py
"""empty message Revision ID: 440bcc45ff09 Revises: a147591613 Create Date: 2015-04-20 18:54:51.829730 """ revision = '440bcc45ff09' down_revision = 'a147591613' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('streamer', sa.Column('as_subscriber_id', sa.Integer(), nullable=T...
data/OfferTeam/OfferListing/fabfile/deploy.py
import json from fabric.api import * from .deployer.configuration import Configuration from .deployer.helpers import mkdir, rmdir from .deployer.standard_packages import package_list import os from StringIO import StringIO site_settings = { "settings_module": 'OfferListings.settings', "settings_local": 'Offer...
data/MontmereLimited/django-lean/django_lean/experiments/testsettings.py
class SimpleEngagementCalculator(object): def calculate_user_engagement_score(self, user, start_date, end_date): return 0 ROOT_URLCONF=None DATABASE_ENGINE='sqlite3' DATABASE_NAME=':memory:' DATABASE_SUPPORTS_TRANSACTIONS=False INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes',...
data/adblockplus/gyp/test/same-rule-output-file-name/gyptest-all.py
""" Tests the use of rules with the same output file name. """ import TestGyp test = TestGyp.TestGyp() test.run_gyp('subdirs.gyp', chdir='src') test.relocate('src', 'relocate/src') test.build('subdirs.gyp', test.ALL, chdir='relocate/src') test.must_exist('relocate/src/subdir1/rule.txt') test.must_exist('relocate/s...
data/SalesforceEng/Providence/repos/github.py
''' Copyright (c) 2015, Salesforce.com, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the foll...
data/Raeon/pygar/session.py
__author__ = 'RAEON' import websocket import threading import struct class Session(object): def __init__(self): self.running = False self.thread = None self.ws = None self.host = '' self.port = 443 self.inbound = [] def connect(self, host, port): if...
data/Impactstory/total-impact-webapp/totalimpactwebapp/aliases.py
import datetime import copy import unicode_helpers import json import logging from util import cached_property from util import dict_from_dir from totalimpactwebapp import db logger = logging.getLogger("ti.aliases") def clean_id(nid): try: nid = nid.strip(' "').strip() nid = unicode_helpers.remo...
data/Miserlou/django-easy-split/easy_split/testsettings.py
class SimpleEngagementCalculator(object): def calculate_user_engagement_score(self, user, start_date, end_date): return 0 ROOT_URLCONF=None DATABASE_ENGINE='sqlite3' DATABASE_NAME=':memory:' DATABASE_SUPPORTS_TRANSACTIONS=False INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.contenttypes', 'd...
data/Ttl/evolutionary-circuits/evolutionary/getch.py
class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init_...
data/PMEAL/OpenPNM/OpenPNM/Phases/models/molar_density.py
r""" =============================================================================== Submodule -- molar_density =============================================================================== """ import scipy as sp def standard(phase, pore_MW='pore.molecular_weight', pore_density='pore.dens...
data/MegaMark16/django-live-support/live_support/__init__.py
VERSION = (0,1,9) __version__ = "0.1.9"
data/RoseOu/flasky/venv/lib/python2.7/site-packages/alembic/operations.py
from contextlib import contextmanager from sqlalchemy.types import NULLTYPE, Integer from sqlalchemy import schema as sa_schema from . import util from .compat import string_types from .ddl import impl __all__ = ('Operations',) class Operations(object): """Define high level migration operations. Each opera...
data/PyCQA/pycodestyle/testsuite/noqa.py
url = 'https://api.github.com/repos/sigmavirus24/Todo.txt-python/branches/master?client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxx&?client_secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' from functools import (partial, reduce, wraps, cmp_to_key) from functools import (partial, reduce, wraps, cmp_to_key) a = 1 if...
data/abusesa/abusehelper/abusehelper/bots/stressbot/stressbot.py
""" Bot for testing XMPP server robustness. Sends rapidly as many events to a channel as possible. Maintainer: Codenomicon <clarified@codenomicon.com> """ import idiokit from abusehelper.core import bot, events class StressBot(bot.FeedBot): data = bot.Param("event data") @idiokit.stream def feed(self):...
data/NervanaSystems/neon/neon/backends/winograd4.py
import numpy as np from ipdb import set_trace from struct import pack, unpack def ceil_div(x, y): return -(-x // y) def out_dim(S, X, padding, strides): return ceil_div(X - S + 1 + 2*padding, strides) def strip_mantissa(val): i = unpack('I', pack('f', val))[0] & 0x7f800000 f = unpack('f', pack('I', i...
data/HewlettPackard/python-hpOneView/hpOneView/servers.py
""" servers.py ~~~~~~~~~~~~ This module implements servers HP OneView REST API """ from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from pprint impo...
data/QuentinJi/viming/.vim/bundle/jedi-vim/jedi/test/test_parser/test_token.py
from jedi import parser from jedi._compatibility import u try: import unittest2 as unittest except ImportError: import unittest class TokenTest(unittest.TestCase): def test_end_pos_one_line(self): parsed = parser.Parser(u(''' def testit(): a = "huhu" ''')) tok = parsed.module.subsco...
data/KunihikoKido/sublime-elasticsearch-client/lib/elasticsearch/exceptions.py
__all__ = [ 'ImproperlyConfigured', 'ElasticsearchException', 'SerializationError', 'TransportError', 'NotFoundError', 'ConflictError', 'RequestError', 'ConnectionError', 'SSLError', 'ConnectionTimeout' ] class ImproperlyConfigured(Exception): """ Exception raised when the config passed to the clie...
data/PaulMcMillan/tasa/tasa/cli.py
""" This should probably be rewritten at some point. It's not taking good advantage of argparse. """ import argparse import sys import time import inspect import logging import signal import sys from multiprocessing import Process import tasa from tasa.worker import BaseWorker logger = logging.getLogger(__name__) l...
data/Mendeley/mrec/mrec/parallel/item_similarity.py
import math import glob import re import os import subprocess from shutil import rmtree import logging from mrec import load_sparse_matrix, save_recommender class ItemSimilarityRunner(object): def run(self,view,model,input_format,trainfile,num_engines,simsdir,overwrite,max_sims,simsfile,modelfile): logg...
data/MartinPaulEve/PlotSummary/interactive.py
from __future__ import print_function __author__ = "Martin Paul Eve" __email__ = "martin@martineve.com" """ A class to handle an interactive prompt. Portions of this file are Copyright 2014, Adrian Sampson. """ from debug import Debuggable import sys from difflib import SequenceMatcher import locale cla...
data/Scarygami/mirror-api/demos/instaglass.py
"""Methods for Instaglass service""" __author__ = 'scarygami@gmail.com (Gerwin Sturm)' from service import upload from utils import base_url import logging import Image import ImageOps import cStringIO __all__ = ["handle_item", "CONTACTS", "WELCOMES"] """Contacts that need to registered when the user connects to t...
data/StackStorm/st2contrib/packs/mmonit/actions/action_host.py
from lib.mmonit import MmonitBaseAction class MmonitActionHost(MmonitBaseAction): def run(self, host_id, action, service): self.login() data = {"service": service, "id": host_id, "action": action} self.session.post("{}/admin/hosts/action".format(self.url), data=data) self.logout() ...
data/JoelBender/bacpypes/pcap_tools/WhoIsRouterToNetworkSummaryFilter.py
""" Summarize Who-Is-Router-To-Network Notifications """ import sys from collections import defaultdict from bacpypes.debugging import Logging, function_debugging, ModuleLogger from bacpypes.consolelogging import ConsoleLogHandler from bacpypes.pdu import Address from bacpypes.analysis import trace, strftimestamp, T...
data/RallyTools/RallyRestToolkitForPython/examples/typedef.py
USAGE = """ Usage: typedef.py <entity_name> """ import sys import re from pyral import Rally, rallyWorkset errout = sys.stderr.write ATTRIBUTE_FIELDS = \ """ ObjectID _ref _type _refObjectName _objectVersion _CreatedAt CreationDate Subscription Workspace Ele...
data/HumanDynamics/openPDS/openpds/visualization/views.py
from django.shortcuts import render_to_response from django.template import RequestContext import pdb
data/StackStorm/st2/st2common/st2common/services/rbac.py
from st2common.rbac.types import PermissionType from st2common.rbac.types import ResourceType from st2common.rbac.types import SystemRole from st2common.persistence.rbac import Role from st2common.persistence.rbac import UserRoleAssignment from st2common.persistence.rbac import PermissionGrant from st2common.models.db....
data/ReactiveX/RxPY/tests/test_observable_time.py
import logging from datetime import datetime, timedelta from rx import Observable from rx.testing import TestScheduler, ReactiveTest, is_prime, MockDisposable from rx.disposables import Disposable, SerialDisposable FORMAT = '%(asctime)-15s %(threadName)s %(message)s' logging.basicConfig(filename='rx.log', format=FORM...
data/KunihikoKido/sublime-elasticsearch-client/commands/indices_delete_alias.py
import sublime from .base import DeleteBaseCommand class IndicesDeleteAliasCommand(DeleteBaseCommand): command_name = "elasticsearch:indices-delete-alias" def is_enabled(self): return True def run_request(self, index=None, name=None): if not index or not name: self.show_alias...
data/MarSoft/PebbleNotes/gae/auth.py
import webapp2 from urllib import urlencode import json, urllib2 from secret import client_id, client_secret import config class AuthRedirector(webapp2.RequestHandler): def get(self): args = self.request.GET args["client_id"] = client_id args["redirect_uri"] = config.auth_redir_uri ...
data/OpenMDAO/OpenMDAO-Framework/contrib/example_plugins/mycomp/docs/conf.py
import sys, os extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.doctest', 'sphinx.ext.todo','openmdao.util.doctools', 'sphinx.ext.viewcode' ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'mycomp' copy...
data/OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/builtins/newnext.py
''' This module provides a newnext() function in Python 2 that mimics the behaviour of ``next()`` in Python 3, falling back to Python 2's behaviour for compatibility if this fails. ``newnext(iterator)`` calls the iterator's ``__next__()`` method if it exists. If this doesn't exist, it falls back to calling a ``next()`...
data/MicrosoftResearch/Azimuth/azimuth/load_data.py
import pandas import util import matplotlib.pyplot as plt import scipy as sp import scipy.stats import numpy as np import os cur_dir = os.path.dirname(os.path.abspath(__file__)) def from_custom_file(data_file, learn_options): print "Loading inputs to predict from %s" % data_file data = pandas.read_csv(da...
data/adaptivdesign/django-sellmo/sellmo/core/indexing/adapters/celery/adapter.py
from sellmo.core.indexing.adapters import AbstractIndexAdapter from .tasks import sync_index, build_index class CeleryIndexAdapterWrapper(AbstractIndexAdapter): def sync_index(self, index, documents, full=False): """ (Re)indexes each document from the given iterable. A document can be eit...
data/SEED-platform/seed/seed/migrations/0004_noncanonicalprojectbuildings.py
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('seed', '0003_auto_20151105_1539'), ] operations = [ migrations.CreateModel( name='NonCanonicalProjectBuildings', fields=[ ...
data/ReactiveX/RxPY/tests/test_observable/test_replay.py
import unittest from rx.observable import Observable from rx.testing import TestScheduler, ReactiveTest from rx.disposables import Disposable, SerialDisposable on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = React...
data/OpenSlides/OpenSlides/openslides/mediafiles/access_permissions.py
from ..utils.access_permissions import BaseAccessPermissions class MediafileAccessPermissions(BaseAccessPermissions): """ Access permissions container for Mediafile and MediafileViewSet. """ def can_retrieve(self, user): """ Returns True if the user has read access model instances. ...
data/acrisci/i3ipc-python/examples/workspace-new.py
import i3ipc import re from argparse import ArgumentParser def main(): parser = ArgumentParser(description=''' Simple script to go to a new workspace. It will switch to a workspace with the lowest available number. ''') parser.parse_args() i3 = i3ipc.Connection() workspaces = i3.get_workspace...
data/ReactiveX/RxPY/rx/concurrency/catchscheduler.py
from rx.disposables import Disposable, SingleAssignmentDisposable from .scheduler import Scheduler class CatchScheduler(Scheduler): def __init__(self, scheduler, handler): self._scheduler = scheduler self._handler = handler self._recursive_original = None self._recursive_wrapper =...
data/RoseOu/flasky/venv/lib/python2.7/site-packages/wtforms/ext/sqlalchemy/validators.py
from __future__ import unicode_literals import warnings from wtforms import ValidationError from sqlalchemy.orm.exc import NoResultFound class Unique(object): """Checks field value unicity against specified table field. :param get_session: A function that return a SQAlchemy Session. :param model:...
data/adaptivdesign/django-sellmo/sellmo/contrib/account/apps.py
from sellmo.core.apps import SellmoAppConfig class DefaultConfig(SellmoAppConfig): name = 'sellmo.contrib.account' dependencies = ['sellmo.apps.customer']
data/ProgVal/Limnoria/plugins/Karma/config.py
import supybot.conf as conf import supybot.registry as registry from supybot.i18n import PluginInternationalization, internationalizeDocstring _ = PluginInternationalization('Karma') def configure(advanced): from supybot.questions import expect, anything, something, yn conf.registerPlugin('...
data/Yaoshicn/decaptcha/svmMLiA.py
import os from numpy import * from time import sleep def loadDataSet(fileName): dataMat = []; labelMat = [] fr = open(fileName) for line in fr.readlines(): lineArr = line.strip().split('\t') dataMat.append([float(lineArr[0]), float(lineArr[1])]) labelMat.append(float(lineArr[2]...
data/Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/usage/views.py
from horizon import tables from openstack_dashboard.usage import base class UsageView(tables.DataTableView): usage_class = None show_terminated = True def __init__(self, *args, **kwargs): super(UsageView, self).__init__(*args, **kwargs) if not issubclass(self.usage_class, base.BaseUsage):...
data/JasonMillward/Autorippr/classes/testing.py
""" Configuration and requirements testing Released under the MIT license Copyright (c) 2012, Jason Millward @category misc @version $Id: 1.7-test4, 2015-11-09 12:30:44 ACDT $; @author Jason Millward @license http://opensource.org/licenses/MIT """ import sys import os import subprocess def perform_tes...