path
stringlengths
23
146
source_code
stringlengths
0
261k
data/RoseOu/flasky/venv/lib/python2.7/site-packages/pygments/styles/default.py
""" pygments.styles.default ~~~~~~~~~~~~~~~~~~~~~~~ The default highlighting style. :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ ...
data/QingdaoU/OnlineJudge/utils/captcha/views.py
from django.http import HttpResponse from utils.captcha import Captcha def show_captcha(request): return HttpResponse(Captcha(request).display(), content_type="image/gif")
data/RDFLib/rdflib/rdflib/plugins/sparql/results/csvresults.py
""" This module implements a parser and serializer for the CSV SPARQL result formats http://www.w3.org/TR/sparql11-results-csv-tsv/ """ import codecs import csv from rdflib import Variable, BNode, URIRef, Literal, py3compat from rdflib.query import Result, ResultSerializer, ResultParser class CSVResultParser(Re...
data/OpenAssets/openassets/openassets/__init__.py
""" Reference implementation of the Open Assets Protocol. """ __version__ = '1.3'
data/JasonGiedymin/Flask-Module-Scaffold/src/myapp/apps/dummy/__init__.py
from myapp import utils module_name = utils.getFinalName(__name__) module = utils.getModule(__name__, subdomain=module_name) import views import views.morepages
data/Yelp/mrjob/tests/test_retry.py
from mrjob.retry import RetryGoRound from mrjob.retry import RetryWrapper from tests.py2 import Mock from tests.py2 import TestCase class RetryGoRoundTestCase(TestCase): def test_empty(self): self.assertRaises( ValueError, RetryGoRound, [], lambda ex: isinstance(ex, IOError)) def test_s...
data/ab77/netflix-proxy/auth/pbkdf2_sha256_hash.py
import sys from passlib.hash import pbkdf2_sha256 from passlib.utils import generate_password try: plaintext = sys.argv[1] except IndexError: plaintext = generate_password() print plaintext, pbkdf2_sha256.encrypt(plaintext, rounds=200000, salt_size=16)
data/TylerTemp/docpie/docpie/example/git/git_clone.py
''' usage: python git.py clone [options] [--] <repo> [<dir>] options: -v, --verbose be more verbose -q, --quiet be more quiet --progress force progress reporting -n, --no-checkout don't create a checkout --bare create a bare repository --mirror ...
data/Parsely/streamparse/streamparse/dsl/__init__.py
""" Python Storm Topology DSL """ from .stream import Grouping, Stream from .topology import Topology
data/Piratenfraktion-Berlin/OwnTube/videoportal/BitTornadoABC/BitTornado/parseargs.py
from types import * from cStringIO import StringIO def splitLine(line, COLS=80, indent=10): indent = " " * indent width = COLS - (len(indent) + 1) if indent and width < 15: width = COLS - 2 indent = " " s = StringIO() i = 0 for word in line.split(): if i == 0: ...
data/SickRage/SickRage/lib/sqlalchemy/dialects/mssql/information_schema.py
from ... import Table, MetaData, Column from ...types import String, Unicode, UnicodeText, Integer, TypeDecorator from ... import cast from ... import util from ...sql import expression from ...ext.compiler import compiles ischema = MetaData() class CoerceUnicode(TypeDecorator): impl = Unicode def process_bi...
data/IanLewis/kay/kay/auth/decorators.py
""" A decorators related authentication. :Copyright: (c) 2009 Accense Technology, Inc., Ian Lewis <IanMLewis@gmail.com> All rights reserved. :license: BSD, see LICENSE for more details. """ from functools import update_wrapper from google.appengine.api import users from werk...
data/Parsely/pykafka/pykafka/balancedconsumer.py
from __future__ import division """ Author: Emmett Butler """ __license__ = """ Copyright 2015 Parse.ly, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICE...
data/OpenSlides/OpenSlides/tests/integration/core/test_views.py
import json from django.core.urlresolvers import reverse from django.dispatch import receiver from rest_framework import status from rest_framework.test import APIClient from openslides import __version__ as version from openslides.core.config import ConfigVariable, config from openslides.core.models import CustomSli...
data/StackStorm/st2/st2common/st2common/util/uid.py
""" Module containing model UID related utility functions. """ from st2common.models.db.stormbase import UIDFieldMixin __all__ = [ 'parse_uid' ] def parse_uid(uid): """ Parse UID string. :return: (ResourceType, uid_remainder) :rtype: ``tuple`` """ if UIDFieldMixin.UID_SEPARATOR not in u...
data/Pylons/substanced/substanced/sdi/views/login.py
from pyramid.httpexceptions import ( HTTPForbidden, HTTPFound ) from pyramid.renderers import get_renderer from pyramid.session import check_csrf_token from pyramid.security import ( remember, forget, Authenticated, NO_PERMISSION_REQUIRED, ) from ...util import get_oid from .. import m...
data/PyTables/PyTables/examples/attributes1.py
import numpy as np import tables fileh = tables.open_file("attributes1.h5", mode="w", title="Testing attributes") root = fileh.root a = np.array([1, 2, 4], np.int32) hdfarray = fileh.create_array(root, 'array', a, "Integer array") hdfarray.attrs.string = "This is an example" hdfarra...
data/SneakersInc/HoneyMalt/src/HoneyMalt/transforms/__init__.py
__author__ = 'catalyst256' __copyright__ = 'Copyright 2014, Honeymalt Project' __credits__ = [] __license__ = 'GPL' __version__ = '0.1' __maintainer__ = 'catalyst256' __email__ = 'catalyst256@gmail.com' __status__ = 'Development' __all__ = [ 'kipposensor', 'kipposearchdate', 'kipposearchip', 'kippofil...
data/SmileyChris/easy-thumbnails/easy_thumbnails/management/commands/thumbnail_cleanup.py
import gc import os import time from datetime import datetime, date, timedelta from optparse import make_option from django.core.files.storage import get_storage_class from django.core.management.base import BaseCommand from easy_thumbnails.conf import settings from easy_thumbnails.models import Source class Thumbna...
data/MirantisWorkloadMobility/CloudFerry/cloudferry/bin/main.py
from fabric import main as fab_main from cloudferry import fabfile def main(): fab = fabfile.__file__ if fab.endswith('.pyc'): fab = fab[:-1] fab_main.main([fab]) if __name__ == '__main__': main()
data/Orange-OpenSource/bagpipe-bgp/bagpipe/exabgp/message/update/attribute/origin.py
""" attributes.py Created by Thomas Mangin on 2009-11-05. Copyright (c) 2009-2012 Exa Networks. All rights reserved. Modified by Orange - 2014 """ from bagpipe.exabgp.message.update.attribute import AttributeID,Flag,Attribute class Origin (Attribute): ID = AttributeID.ORIGIN FLAG = Flag.TRANSITIVE MULTIPLE = Fa...
data/Socialsquare/Franklin/skills/migrations/0009_auto__add_unique_skill_slug__add_unique_project_slug__add_unique_train.py
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models import re from django.utils.text import slugify class Migration(SchemaMigration): def forwards(self, orm): if not db.dry_run: for _class in...
data/ProstoKSI/django-voter/voter/urls.py
try: from django.conf.urls import patterns, url except ImportError: from django.conf.urls.defaults import patterns, url urlpatterns = patterns('voter.views', url(r'^like/(?P<obj_type>[\w]+)/(?P<obj_id>[\d]+)/$', 'set_like', name='ratings_like'), url(r'^dislike/(?P<obj_type>[\w]+)/(?P<obj_id>[\d]+)/$',...
data/Pylons/substanced/substanced/principal/tests/test_subscribers.py
import unittest from pyramid import testing class Test_principal_added(unittest.TestCase): def _callFUT(self, event): from ..subscribers import principal_added return principal_added(event) def test_event_wo_loading_attr(self): event = testing.DummyResource() event.object = tes...
data/Infinidat/gitpy/tests/test_basic.py
import unittest import os import commands from utils import get_temporary_location from utils import delete_repository from gitpy import LocalRepository from gitpy import find_repository from gitpy.exceptions import GitException class EmptyRepositoryTest(unittest.TestCase): def setUp(self): self.dirname = ...
data/Yelp/Testify/test/utils/test_turtle.py
import testify as T from testify.contrib.doctestcase import DocTestCase class TurtleTestCase(T.TestCase): @T.setup def build_turtle(self): self.leonardo = T.turtle.Turtle() def test_call(self): """Just call a turtle""" ret = self.leonardo() assert ret T.assert_leng...
data/XiaoMi/minos/client/deploy_chronos.py
import argparse import os import service_config import subprocess import sys import urlparse import deploy_utils from log import Log ALL_JOBS = ["chronos"] def _get_chronos_service_config(args): args.chronos_config = deploy_utils.get_service_config(args) def generate_zk_jaas_config(args): if not deploy_utils.i...
data/Yubico/u2fval/u2fval/config.py
import sys import imp import errno import os from u2fval import default_settings import logging import logging.config __all__ = [ 'settings' ] SETTINGS_FILE = os.getenv('U2FVAL_SETTINGS', os.path.join( '/etc/yubico/u2fval/u2fval.conf')) LOG_CONFIG_FILE = os.path.join(os.path.dirname(os.p...
data/blueboxgroup/giftwrap/setup.py
import setuptools setuptools.setup( setup_requires=['pbr'], pbr=True)
data/OP2/PyOP2/pyop2/exceptions.py
"""OP2 exception types""" class DataTypeError(TypeError): """Invalid type for data.""" class DimTypeError(TypeError): """Invalid type for dimension.""" class ArityTypeError(TypeError): """Invalid type for arity.""" class IndexTypeError(TypeError): """Invalid type for index.""" class NameTy...
data/Pylons/substanced/substanced/db/tests/test_init.py
import unittest from pyramid import testing class Test_root_factory(unittest.TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown() def _callFUT(self, request, transaction, get_connection, evolve_packages): from .. import root_fact...
data/ImageEngine/gaffer/python/GafferImageUI/__init__.py
from _GafferImageUI import * import DisplayUI from FormatPlugValueWidget import FormatPlugValueWidget from ChannelMaskPlugValueWidget import ChannelMaskPlugValueWidget import OpenImageIOReaderUI import ImageReaderUI import ImageViewToolbar import ImageTransformUI import ConstantUI import ImageSwitchUI import ColorSpa...
data/adamlwgriffiths/Pyrr/pyrr/tests/test_quaternion.py
try: import unittest2 as unittest except: import unittest import numpy as np from pyrr import quaternion class test_quaternion(unittest.TestCase): def test_import(self): import pyrr pyrr.quaternion from pyrr import quaternion def test_create(self): result = quate...
data/OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/datatypes/domain/zone.py
import copy from openmdao.lib.datatypes.domain.flow import FlowSolution from openmdao.lib.datatypes.domain.grid import GridCoordinates CARTESIAN = 'Cartesian' CYLINDRICAL = 'Cylindrical' _COORD_SYSTEMS = (CARTESIAN, CYLINDRICAL) class Zone(object): """ One zone in a possibly multi-zone :class:`DomainObj`. """ ...
data/RobotWebTools/rosbridge_suite/rosbridge_library/test/experimental/complex_srv+tcp/test_non-ros_service_server_complex-srv.py
import sys import socket import time from random import randint from rosbridge_library.util import json tcp_socket_timeout = 10 max_msg_length = 20000 rosbridge_ip = "localhost" rosbridge_port = 9090 service_...
data/Neohapsis/bbqsql/scripts/test_server.py
"""This is a simple webserver vulnerable to SQLi injection make your query string look like this: http://127.0.0.1:8090/time?row_index=1&character_index=1&character_value=95&comparator=>&sleep=1 command line usage: python ./test_server.py [--rows=50 --cols=150] :rows - this controls how many rows of ra...
data/T-002/pycast/pycast/errors/meansquarederror.py
from pycast.errors.baseerrormeasure import BaseErrorMeasure class MeanSquaredError(BaseErrorMeasure): """Implements the mean squared error measure. Explanation: http://en.wikipedia.org/wiki/Mean_squared_error """ def _calculate(self, startingPercentage, endPercentage, startDate, endDate): ...
data/JeremyOT/Toto/toto/workerconnection.py
import toto import cPickle as pickle import zlib import logging from threading import Thread from tornado.options import options from tornado.gen import Task from collections import deque from time import time from uuid import uuid4 from traceback import format_exc from toto.options import safe_define safe_define("wor...
data/Julian/jsonschema/jsonschema/tests/test_validators.py
from collections import deque from contextlib import contextmanager import json from jsonschema import FormatChecker, ValidationError from jsonschema.tests.compat import mock, unittest from jsonschema.validators import ( RefResolutionError, UnknownType, Draft3Validator, Draft4Validator, RefResolver, create, ex...
data/Piratenfraktion-Berlin/OwnTube/videoportal/BitTornadoABC/BitTornado/BT1/StreamCheck.py
from cStringIO import StringIO from binascii import b2a_hex from urllib import quote import Connecter try: True except: True = 1 False = 0 DEBUG = False protocol_name = 'BitTorrent protocol' option_pattern = chr(0)*8 def toint(s): return long(b2a_hex(s), 16) def tohex(s): return b2a_hex(s).uppe...
data/agoragames/haigha/haigha/message.py
''' Copyright (c) 2011-2015, Agora Games, LLC All rights reserved. https://github.com/agoragames/haigha/blob/master/LICENSE.txt ''' class Message(object): ''' Represents an AMQP message. ''' def __init__(self, body='', delivery_info=None, return_info=None, **properties): ''...
data/RobotLocomotion/director/src/python/director/doordemo.py
import os import sys import vtkAll as vtk import math import time import types import functools import numpy as np from director import transformUtils from director import lcmUtils from director.timercallback import TimerCallback from director.asynctaskqueue import AsyncTaskQueue from director.fieldcontainer import Fi...
data/TheGhouls/oct/oct/results/models.py
import json import datetime from peewee import Proxy, TextField, FloatField, CharField, IntegerField, SqliteDatabase, Model, DateTimeField db = Proxy() class Result(Model): """Define a result model """ error = TextField(null=True) scriptrun_time = FloatField() elapsed = FloatField() epoch = F...
data/AppScale/appscale/AppServer/lib/argparse/argparse.py
"""Command-line parsing library This module is an optparse-inspired command-line parsing library that: - handles both optional and positional arguments - produces highly informative usage messages - supports parsers that dispatch to sub-parsers The following is a simple usage example that sums integers f...
data/JeremyOT/Toto/toto/events.py
'''Toto's event framework is used to allow external events to affect client requests, or to run scheduled tasks after a specified signal is received. It can be used to send messages to active requests, even between multiple server processes. The event framework can also be used outside of Toto to send messages to runni...
data/NathanEpstein/Dora/Dora/__init__.py
from .main import Dora
data/OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/mpiwrap.py
import os import sys import numpy from contextlib import contextmanager def _redirect_streams(to_fd): """Redirect stdout/stderr to the given file descriptor. Based on: http://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/ """ original_stdout_fd = sys.stdout.fileno() o...
data/Locu/djoauth2/docs/conf.py
import sys, os sys.path.insert(0, os.path.abspath('..')) import local_settings extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'DJOAuth2' copyright = u'(see the license file)' html_show_copyright = ...
data/Yubico/yubikey-neo-manager/neoman/view/neo.py
import os from PySide import QtGui, QtCore from functools import partial from neoman import messages as m from neoman.storage import settings from neoman.exc import ModeSwitchError from neoman.model.neo import YubiKeyNeo from neoman.model.applet import Applet from neoman.model.modes import MODE from neoman.view.tabs im...
data/Yelp/pyleus/pyleus/cli/build.py
"""Logic for building a jar from a pyleus topology directory. Other modules should only call build_topology_jar passing it the configurations object. The caller function should handle PyleusError exceptions. """ from __future__ import absolute_import import glob import logging import os import re import shutil import...
data/IanLewis/kay/kay/utils/jinja2utils/compiler.py
""" gaefy.jinja2.compiler ~~~~~~~~~~~~~~~~~~~~~ Helper functions to parse Jinja2 templates and store them as Python code. The compiled templates can be loaded using gaefy.jinja2.code_loaders, avoiding all the parsing process. To compile a whole dir: from jinja2 import Environment from gaefy.jinja2.compiler impor...
data/OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/casehandlers/api.py
""" .. _`openmdao.lib.casehandler.api.py`: A central place to access all of the OpenMDAO case recorders, case iterators, and case filters in the standard library. """ from openmdao.lib.casehandlers.caseset import CaseArray, CaseSet, caseiter_to_caseset from openmdao.lib.casehandlers.csvcase import CSVCaseIterator, ...
data/Lispython/human_curl/debug.py
""" human_curl.debug ~~~~~~~~~~~~~~~~~~~~~~~~~~ Debuggging tests for human_curl :copyright: (c) 2011 by Alexandr Lispython (alex@obout.ru). :license: BSD, see LICENSE for more details. """ import logging from .tests import * logger = logging.getLogger("human_curl") logger.setLevel(logging.DEBUG) handler = logg...
data/PressLabs/zipa/examples/iterator_filter.py
from zipa import api_github_com as github repos = github.orgs.django.repos for repo in repos[{'sort': 'created', 'direction': 'desc'}]: print repo.name
data/Relrin/aiorest-ws/aiorest_ws/status.py
""" WebSocket status codes and functions for work with them. For more details check the link below: https://tools.ietf.org/html/rfc6455 """ __all__ = ( 'WS_NORMAL', 'WS_GOING_AWAY', 'WS_PROTOCOL_ERROR', 'WS_DATA_CANNOT_ACCEPT', 'WS_RESERVED', 'WS_NO_STATUS_CODE', 'WS_CLOSED_ABNORMALLY', 'WS...
data/Littel-Laboratory/homes-dataset-tools/imageKit/train_imagenet.py
"""Example code of learning a large scale convnet from ILSVRC2012 dataset. Prerequisite: To run this example, crop the center of ILSVRC2012 training and validation images and scale them to 256x256, and make two lists of space- separated CSV whose first column is full path to image and second column is zero-origin labe...
data/WatchPeopleCode/WatchPeopleCode/wpc/forms.py
from wpc.models import Subscriber, Streamer, YoutubeChannel, YoutubeStream from wpc.flask_utils import get_or_create from utils import youtube_video_id from flask_wtf import Form from wtforms import StringField, SubmitField, validators, TextAreaField from wtforms.validators import ValidationError from flask.ext.login ...
data/Jackeriss/Email_My_PC/shell/demos/servers/column_provider.py
import sys, os, stat import pythoncom from win32com.shell import shell, shellcon import commctrl import winerror from win32com.server.util import wrap from pywintypes import IID IPersist_Methods = ["GetClassID"] IColumnProvider_Methods = IPersist_Methods + \ ["Initialize", "GetColumnInfo", "G...
data/TheTorProject/gettor/process_tweets.py
import sys import logging import gettor.twitter def main(): logging_level = 'DEBUG' logging_file = '/home/ilv/Proyectos/tor/gettor/log/process_tweets.log' logging_format = '[%(levelname)s] %(asctime)s - %(message)s' date_format = "%Y-%m-%d" logging.basicConfig( format=logging_format, ...
data/QuantEcon/QuantEcon.py/quantecon/models/__init__.py
raise ImportError("The code previously contained in the quantecon.models subpackage has been migrated to the QuantEcon.applications (https://github.com/QuantEcon/QuantEcon.applications) repo")
data/HearthSim/python-unitypack/unitypack/engine/renderer.py
from enum import IntEnum from .component import Component from .object import field class ReflectionProbeUsage(IntEnum): Off = 0 BlendProbes = 1 BlendProbesAndSkybox = 2 Simple = 3 class ShadowCastingMode(IntEnum): Off = 0 On = 1 TwoSided = 2 ShadowsOnly = 3 class Renderer(Component): enabled = field("m_...
data/Sage-Bionetworks/synapsePythonClient/synapseclient/team.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from .dict_object import DictObject class UserProfile(DictObject): def __init__(self, **kwargs): super(UserProfile, self).__init__(kwargs) class UserGroupH...
data/SteefH/django-pagination-plus/setup.py
from setuptools import setup, find_packages import os def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() README = read('README.rst') setup( name = "django-pagination-plus", packages = find_packages(), version = "0.0.3", author = "Stefan van der Haven", author_...
data/adieu/allbuttonspressed/minicms/context_processors.py
from django.conf import settings def cms(request): return { 'site_name': settings.SITE_NAME, 'site_copyright': settings.SITE_COPYRIGHT, }
data/PyTables/PyTables/tables/node.py
"""PyTables nodes.""" from __future__ import absolute_import import warnings import functools from .registry import class_name_dict, class_id_dict from .exceptions import (ClosedNodeError, NodeError, UndoRedoWarning, PerformanceWarning) from .path import join_path, split_path, isvisible...
data/acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/geo/data.py
"""Contains the data classes of the Geography Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core GEORSS_TEMPLATE = '{http://www.georss.org/georss/}%s' GML_TEMPLATE = '{http://www.opengis.net/gml/}%s' GEO_TEMPLATE = '{http://www.w3.org/2003/01/geo/wgs84_pos class GeoLat(atom.core.XmlEleme...
data/Yubico/python-pyhsm/test/test_soft_hsm.py
import sys import unittest import pyhsm import test_common class TestSoftHSM(test_common.YHSM_TestCase): def setUp(self): test_common.YHSM_TestCase.setUp(self) self.nonce = "4d4d4d4d4d4d".decode('hex') self.key = "A" * 16 def test_aes_CCM_encrypt_decrypt(self): """ Test decry...
data/PaloAltoNetworks/SplunkforPaloAltoNetworks/bin/panContentPack.py
"""Update app and threat lookup files About this script ----------------- Pulls the latest app and threat information from a firewall or Panorama and outputs it as search results. This can be leveraged to update the app_list.csv and threat_list.csv files in the Palo Alto Networks Add-On (TA). Example usage in Splunk ...
data/OpenKMIP/PyKMIP/kmip/tests/unit/pie/objects/test_opaque_object.py
import binascii import testtools from kmip.core import enums from kmip.pie.objects import ManagedObject, OpaqueObject from kmip.pie import sqltypes from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker class TestOpaqueObject(testtools.TestCase): """ Test suite for OpaqueObject. """...
data/VisTrails/VisTrails/examples/vtk_examples/VisualizationAlgorithms/probeComb.py
import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() pl3d = vtk.vtkPLOT3DReader() pl3d.SetXYZFileName(VTK_DATA_ROOT + "/Data/combxyz.bin") pl3d.SetQFileName(VTK_DATA_ROOT + "/Data/combq.bin") pl3d.SetScalarFunctionNumber(100) pl3d.SetVectorFunctionNumber(202) pl3d.Update() plane = ...
data/OpenMDM/OpenMDM/public_gate/templatetags/app_filters.py
from django import template register = template.Library() @register.filter(name='get_item') def get_item(dictionary, key): return getattr(dictionary, key)
data/STIXProject/python-stix/stix/test/common/information_source_test.py
import unittest from stix.test import EntityTestCase from stix.test.common import structured_text_tests from stix.common import InformationSource class InformationSourceTests(EntityTestCase, unittest.TestCase): klass = InformationSource _full_dict = { 'description': "An amazing source", 'ide...
data/RHInception/jsonstats/JsonStats/Utils.py
import fnmatch import os import os.path import re import sys try: import json except: import simplejson as json def dump_sorted_json_string(input, **kwargs): """ Given a datastructure, return a JSON formatted string of it with all dictionary keys sorted. * `input` - arbitrary Python datastruc...
data/adlibre/Adlibre-DMS/adlibre_dms/apps/browser/forms.py
""" Module: DMS Browser Django Forms Project: Adlibre DMS Copyright: Adlibre Pty Ltd 2011 License: See LICENSE for license information """ from django import forms class UploadForm(forms.Form): file = forms.FileField(widget=forms.FileInput(attrs={'size':40}))
data/PMEAL/OpenPNM/OpenPNM/Geometry/models/throat_vector.py
r""" =============================================================================== Submodule -- throat_vector =============================================================================== """ import scipy as _sp def pore_to_pore(geometry, **kwargs): r""" Calculates throat vector as straight path between ...
data/JoelBender/bacpypes/py27/bacpypes/vlan.py
""" Virtual Local Area Network """ import random from copy import deepcopy from .errors import ConfigurationError from .debugging import ModuleLogger, bacpypes_debugging from .core import deferred from .pdu import Address from .comm import Server _debug = 0 _log = ModuleLogger(globals()) @bacpypes_debugging c...
data/LEAF-BoiseState/SPEED/Module05/PenmanMonteithEx.py
""" Spyder Editor This is a temporary script file. """ from math import * def AirDensity(RH, Tc, P=101.2): Rd = 286.9 q = 0.622*(RH*SatVapor(Tc))/P Tv = (Tc + 273.15)*(1.0 + 0.61*q) P *= 1000.0 rho_a = P/(Rd*Tv) return rho_a def PsychConst(P, cP=1.013, lambda_v=2.26e3): gam...
data/Yelp/pyleus/tests/cli/build_test.py
import glob import os import shutil import zipfile import pytest from pyleus import __version__ from pyleus import exception from pyleus.cli import build from pyleus.testing import mock class TestBuild(object): @mock.patch.object(os.path, 'exists', autospec=True) def test__open_jar_jarfile_not_found(self, ...
data/Juniper/OpenClos/jnpr/openclos/tests/unit/test_report.py
''' Created on Sep 9, 2014 @author: moloyc ''' import unittest import os from jnpr.openclos.report import ResourceAllocationReport, L2Report, L3Report from test_dao import InMemoryDao class Test(unittest.TestCase): def setUp(self): '''Creates with in-memory DB''' self.__conf = {} self....
data/NikolayRag/typeTodo/PyMySQL/pymysql/tests/test_nextset.py
import unittest2 from pymysql.tests import base from pymysql import util class TestNextset(base.PyMySQLTestCase): def setUp(self): super(TestNextset, self).setUp() self.con = self.connections[0] def test_nextset(self): cur = self.con.cursor() cur.execute("SELECT 1; SELECT 2;...
data/SheffieldML/GPy/GPy/plotting/matplot_dep/maps.py
import numpy as np try: from matplotlib import pyplot as pb from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection try: __IPYTHON__ pb.ion() except NameError: pass except: pass import re def plot(shape_records,facecolor='w',edgecol...
data/SamyPesse/glass.py/examples/foursquare/app.py
from flask import request, session, render_template, redirect, url_for import glass import foursquare import config app = glass.Application( client_id=config.GOOGLE_CLIENT_ID, client_secret=config.GOOGLE_CLIENT_SECRET, scopes=config.GOOGLE_SCOPES, template_folder="templates", static_url_path=...
data/SublimeText/VintageEx/tests/test_global.py
import unittest from vex.parsers.g_cmd import GlobalLexer class TestGlobalLexer(unittest.TestCase): def setUp(self): self.lexer = GlobalLexer() def testCanMatchFullPattern(self): actual = self.lexer.parse(r'/foo/p self.assertEqual(actual, ['foo', 'p def testCanMatchEmtpySearch(s...
data/VisTrails/VisTrails/contrib/pc3/info/ipaw/pc3/LoadSql.py
class LoadSql(object): CREATE_DETECTION_TABLE = \ """ CREATE TABLE P2Detection( `objID` bigint NOT NULL, detectID bigint NOT NULL, ippObjID bigint NOT NULL, ippDetectID bigint NOT NULL, filterID smallint NOT NULL, imageID bigint NOT NULL, obsTime float NOT NULL DEFAULT -999, xPo...
data/adaptivdesign/django-sellmo/sellmo/apps/product/__init__.py
from sellmo.core.registry import Module ModelsModule = Module.imports('%s.internal.models' % __name__) IndexesModule = Module.imports('%s.internal.indexes' % __name__) models = ModelsModule('%s.models' % __name__) indexes = IndexesModule('%s.indexes' % __name__) default_app_config = '%s.apps.DefaultConfig' % __name_...
data/Ramblurr/yubi-goog/test.py
import unittest import binascii import struct import yubi_goog class TestYubiGoog(unittest.TestCase): def setUp(self): self.google_secret = "n xu7 v4s qp6 njs gj5" self.test_secret = binascii.hexlify('12345678901234567890'.encode('ascii')) self.test_vectors = [{ 'time': 1111111111, 'otp': '...
data/SuperCowPowers/workbench/workbench/workers/mem_connscan.py
''' Memory Image ConnScan worker. This worker utilizes the Rekall Memory Forensic Framework. See Google Github: http://github.com/google/rekall All credit for good stuff goes to them, all credit for bad stuff goes to us. :) ''' import os import hashlib import pprint import collections from rekall_adapter.rekall...
data/SalesforceEng/Providence/Empire/bugsystems/jira/JiraAPI.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/Microsoft/ApplicationInsights-Python/tests/applicationinsights_tests/exception_tests/__init__.py
from . import TestEnable
data/StackStorm/st2/st2actions/tests/unit/test_mistral_v2_rerun.py
import copy import uuid import mock import six import yaml from mistralclient.api.v2 import executions from mistralclient.api.v2 import tasks from mistralclient.api.v2 import workbooks from mistralclient.api.v2 import workflows from oslo_config import cfg import st2tests.config as tests_config tests_config.parse_ar...
data/Jintin/andle/install.py
import os os.system("sudo python setup.py install")
data/PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/gameobjects/__init__.py
__all__ = [ 'vector2', 'vector3', 'util', 'sphere', 'matrix44', 'color', 'gametime', 'grid' ] __version__ = "0.0.3"
data/QuantEcon/QuantEcon.py/quantecon/tests/test_robustlq.py
""" Author: Chase Coleman Filename: test_lqcontrol Tests for lqcontrol.py file """ import sys import os import unittest import numpy as np from scipy.linalg import LinAlgError from numpy.testing import assert_allclose from quantecon.lqcontrol import LQ from quantecon.robustlq import RBLQ class TestRBLQControl(unitt...
data/OpenKMIP/PyKMIP/kmip/demos/pie/register_opaque_object.py
import logging import sys from kmip.core import enums from kmip.demos import utils from kmip.pie import client from kmip.pie import objects if __name__ == '__main__': logger = utils.build_console_logger(logging.INFO) parser = utils.build_cli_parser() opts, args = parser.parse_args(sys.argv[1:]) co...
data/Netflix-Skunkworks/zerotodocker/genie/2.1.0/example/run_pig_job_2.py
import genie2.client.wrapper import genie2.model.ClusterCriteria import genie2.model.Job import genie2.model.FileAttachment import time genie = genie2.client.wrapper.Genie2("http://localhost:8080/genie", genie2.client.wrapper.RetryPolicy( t...
data/Net-ng/kansha/kansha/events.py
class EventHandlerMixIn(object): """ Mix-in that implements: - `emit_event`, to emit an event; - `handle_event`, a callback for comp.on_answer if comp is expected to emit events. `handle_event` calls a method `on_event(event)` on `self` (if exists) to handle the event and then systemati...
data/OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_hasconstraints.py
import numpy as np import unittest from openmdao.main.api import Assembly, Component, Driver, set_as_top from openmdao.main.datatypes.api import Float, Array from openmdao.main.hasconstraints import HasConstraints, HasEqConstraints, \ HasIneqConstraints, Constraint, Has2SidedConstraints from openmdao.main.interf...
data/adieu/allbuttonspressed/urlrouter/views.py
from .api import handlers from .models import URLRoute from django.shortcuts import get_object_or_404 def show(request, url): route = get_object_or_404(URLRoute, url=url) return handlers[route.handler].dispatch(request, route.target)
data/LibraryOfCongress/chronam/core/tests/ocr_extractor_tests.py
from os.path import dirname, join from django.test import TestCase from chronam.core.ocr_extractor import ocr_extractor class OcrExtractorTests(TestCase): def test_extractor(self): dir = join(dirname(dirname(__file__)), 'test-data') ocr_file = join(dir, 'ocr.xml') text, coord_info = ocr...
data/ImageEngine/gaffer/python/GafferUI/NameLabel.py
import IECore import Gaffer import GafferUI class NameLabel( GafferUI.Label ) : def __init__( self, graphComponent, horizontalAlignment=GafferUI.Label.HorizontalAlignment.Left, verticalAlignment=GafferUI.Label.VerticalAlignment.Center, numComponents=1, formatter=None, parenting = None ) : GafferUI.Label.__ini...