repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
cscashby/pi-showcontrol | src/modules/_Module.py | Python | mit | 772 | 0.014249 | import threading
import time
import logging
class _Module(threading.Thread):
def __init__(self, parent, name):
threading.Thread.__init__(self)
self.logger = logging.getLogger()
self.parent = parent
self.daemon = False
self.event = threading.Event()
self.running = True
self._className = se... |
def handleEvent(self):
self.logger.debug("{} handling event".format(self.name))
pass
def stop(self):
self.running = False
self.logger | .debug("{} stopping".format(self.name))
|
dk00/old-stuff | csie/10computer-networks/hdi-cnl/ui.py | Python | unlicense | 299 | 0.023411 | class bas | eUI:
def __init__(self, serv):
self.serv = serv
def setup(self, out):
self.out = out
class HTM | L(baseUI):
def show(self, what):
self.out.send_header('Content-Type', 'text/plain; charset=utf-8')
print 'test'
class Java(baseUI):
def show(self, what):
print 'test'
|
Pathal/ShadowCraft-Engine | setup_dm.py | Python | lgpl-3.0 | 473 | 0.010571 | from distutils.core import setup
setup(
name='ShadowCraft-Eng | ine',
url='http://github.com/dazer/ShadowCraft-Engine/',
version='0.1',
packages=['shadowcraft',
'shadowcraft.calcs', 'shadowcraft.calcs.rogue', 'shadowcraft.calcs.rogue.Aldriana',
'shadowcraft.calcs.darkmantle', 'shadowcraft.calcs.darkmantle.classes',
'shadowcraft.core',
'sh... | owcraft.objects'],
license='LGPL',
long_description=open('README').read(),
)
|
pycontribs/powertape | powertape/tests/tests.py | Python | mit | 527 | 0.001898 | #!/usr/bin/env python
from __future__ import print_function
import os
import pickle
import platform
import random
import re
import string
import sys
from time import sleep
import traceback
import unittest
#from flaky import flaky
import py
import pytest
class FooTests( | unittest.Te | stCase):
def test_foo_one(self):
result = os.system('python -V')
self.assertEqual(result, 0)
if __name__ == '__main__':
dirname = "test-reports-%s%s" % (sys.version_info[0], sys.version_info[1])
unittest.main()
|
roberthawdon/miscellaneous-scripts | MaxMind GeoIP2 Lite Zone File Generator/mmzonefile.py | Python | unlicense | 1,761 | 0.003975 | #!/usr/bin/env python
import pandas as pd
import zipfile
import requests
import shutil
import tempfile
import glob
import atexit
from argparse import ArgumentParser
maxmindname = "GeoLite2-Country-CSV"
maxmindfile = maxmindname + ".zip"
maxmindlocation = "http://geolite.maxmind.com/download/geoip/database/"
maxmindur... | le, tmpdir):
# tmpdir = TempDir(tempfile.mkdtemp())
response = requests.get(maxmindurl, stream=True, allow_redirects=True)
with open(tmpdir + "/" + ma | xmindfile, 'wb') as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
zip_ref = zipfile.ZipFile(tmpdir + "/" + maxmindfile, 'r')
zip_ref.extractall(tmpdir)
zip_ref.close()
for name in glob.glob(tmpdir + "/" + maxmindname + "_*"):
mmdir = name
return mmdir
def p... |
jawilson/home-assistant | tests/components/unifi/test_sensor.py | Python | apache-2.0 | 10,710 | 0.000654 | """UniFi Network sensor platform tests."""
from datetime import datetime
from unittest.mock import patch
from aiounifi.controller import MESSAGE_CLIENT, MESSAGE_CLIENT_REMOVED
import pytest
from homeassistant.components.device_tracker import DOMAIN as TRACKER_DOMAIN
from homeassistant.components.sensor import DOMAIN... | ate update
wireless_client["rx_bytes"] = 3456000000
wireless_client["tx_bytes"] = 7891000000 |
mock_unifi_websocket(
data={
"meta": {"message": MESSAGE_CLIENT},
"data": [wireless_client],
}
)
await hass.async_block_till_done()
assert hass.states.get("sensor.wireless_client_rx").state == "3456.0"
assert hass.states.get("sensor.wireless_client_tx").sta... |
kayhayen/Nuitka | nuitka/utils/StaticLibraries.py | Python | apache-2.0 | 5,115 | 0.001564 | # Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language go | verning permissions and
# limitations under the License.
#
""" This module deals with finding and information about static libraries.
"""
import os
from nuitka.containers.oset import OrderedSet
from nuitka.PythonVersions import (
getPythonABI,
getSystemPrefixPath,
isDebianPackagePython,
isNuitkaP... |
pjdelport/django | django/core/urlresolvers.py | Python | bsd-3-clause | 21,379 | 0.003087 | """
This module converts requested URLs to callback view functions.
RegexURLResolver is the main class here. Its resolve() method takes a URL (as
a string) and returns a tuple in this format:
(view_function, function_args, function_kwargs)
"""
from __future__ import unicode_literals
import re
from threading impo... | f __getitem__(self, index):
return (self.func, self.args, self.kwargs)[index]
def __repr__(self):
return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name='%s', app_name='%s', namespace='%s')" % (
self.func, self.args, self.kwargs, self.url_name, self.app_name, self.namespace)
class... | # Don't make this raise an error when used in a template.
silent_variable_failure = True
def get_callable(lookup_view, can_fail=False):
"""
Convert a string version of a function name to the callable object.
If the lookup_view is not an import path, it is assumed to be a URL pattern
label and t... |
deepmind/interval-bound-propagation | interval_bound_propagation/__init__.py | Python | apache-2.0 | 5,157 | 0.002327 | # coding=utf-8
# Copyright 2019 The Interval Bound Propagation Authors.
#
# 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/LICENSE-2.0
#
# Unless required ... | wrapper import BatchNormWrapper
from interval_bound_propagation.src.verifiabl | e_wrapper import BatchReshapeWrapper
from interval_bound_propagation.src.verifiable_wrapper import ConstWrapper
from interval_bound_propagation.src.verifiable_wrapper import ImageNormWrapper
from interval_bound_propagation.src.verifiable_wrapper import IncreasingMonotonicWrapper
from interval_bound_propagation.src.veri... |
thierry1985/project-1022 | translate/tools.py | Python | mit | 1,267 | 0.018942 | def cartesian_product(sequences):
# This isn't actually a proper cartesian product because we
# concatenate lists, rather than forming sequences of atomic elements.
if not sequences:
yield []
else:
temp = list(cartesian_product(sequences[1:]))
for item in sequences[0]:
for sequence in temp:
... | t is changed in place as the algorithm is performed.
# The original value is restored when we | are done.
# Since this is a generator, the caller must be aware
# of this side effect and copy the input parameter if necessary.
# This is Knuth's "Algorithm P" ("plain changes").
N = len(alist)
if N <= 1: # Special-case small numbers for speed.
yield alist
elif N == 2:
yield alist
... |
mlflow/mlflow | mlflow/store/artifact/local_artifact_repo.py | Python | apache-2.0 | 5,055 | 0.004946 | import distutils.dir_util as dir_util
import os
import shutil
from mlflow.store.artifact.artifact_repo import ArtifactRepository, verify_artifact_path
from mlflow.utils.file_utils import (
mkdir,
list_all,
get_file_info,
local_file_uri_to_path,
relative_path_to_artifact_path,
)
class LocalArtifac... | gs, **kwargs)
self._artifact_dir = local_file_uri_to_path(self.artifact_uri)
@property
def artifact_dir(self):
return self._artifact_dir
def log_artifact(self, local_file, artifact_path=None):
verify_artifact_path(artifact_path)
# NOTE: The artifact_path is expected to be i... | hs work fine on windows but just in case we normalize it here.
if artifact_path:
artifact_path = os.path.normpath(artifact_path)
artifact_dir = (
os.path.join(self.artifact_dir, artifact_path) if artifact_path else self.artifact_dir
)
if not os.path.exists(artifa... |
thearn/printable_ramps | lib/ramp.py | Python | mit | 3,747 | 0.020817 | from solid import *
import numpy as np
import subprocess
def multiple_ramp_strings(Rs, width=30):
"""
Joins together source code strings for multiple ramps.
"""
s = ''.join(Rs)
cp = ['\ntranslate([0, %i, 0]) ramp%i();' % (i*width, i) for i in xrange(len(Rs))]
return s + ''.join(cp)
def rende... | y y.
y can be a single curve or list of curves.
"""
if hasattr(y, '__iter__') and | hasattr(y[0], '__iter__'):
codes = []
max_y = max([y_[-1] for y_ in y])
for i, y_ in enumerate(y[::-1]):
code = ramp(y_, length=length, n=n, thickness=thickness,
start_backheight=start_backheight,
start_backdepth=start_backdepth,
... |
godiard/pathagar | books/epubinfo.py | Python | gpl-2.0 | 3,947 | 0.006081 | # Copyright (C) 2010, One Laptop Per Child
# Copyright (C) 2010, Kushal Das
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later ver... | uage = self._get_language()
self.summary = self._get_description()
self.cover_image = self._get_cover_image()
def _get_data(self, tagname):
element = self._e_metadata.find(tagname)
return element.text
def _get_description(self):
try:
| ret = self._get_data('.//{http://purl.org/dc/elements/1.1/}description')
except AttributeError:
return None
return ret
def _get_title(self):
try:
ret = self._get_data('.//{http://purl.org/dc/elements/1.1/}title')
except AttributeError:
ret... |
damnMeddlingKid/opendoor | src/House.py | Python | mit | 2,787 | 0.003947 | __author__ = 'Franklyn'
from pandas import DataFrame
from collections import namedtuple
from Model import Model
import math
class House(Model):
"""House model defines the attributes and behaviours of a House
"""
DWELLING_TYPES = {'single-family', 'townhouse', 'apartment', 'patio', 'loft'}
POOL_TYPES ... | ar houses to this house.
:param num_listings: Number of house | s to return
:param similarity_callback: A function that compares the similarity between two houses, must take in two parameters
and return a number where smaller values are more similar.
:return: DataFrame of similar houses.
"""
if similarity_callback is None:
simi... |
renecnielsen/twitter-diy | getTweetsByID.py | Python | mit | 4,835 | 0.01241 | """
NOTE: You must have Python Twitter Toolbox (https://github.com/sixohsix/twitter)
installed on the machine running this script. You can install it using
setuptools/easy_install (https://pypi.python.org/pypi/setuptools)
Run this on the command line:
easy_install twitter
"""
from twitter import *
import csv, ... | ccess Tokens" (https://apps | .twitter.com/app/[you-twitter-app-id]/keys)
consumer_key = "" #Consumer Key (API Key)
consumer_secret = "" #Consumer Secret (API Secret)
access_token = "" #Access Token
access_secret = "" #Access Token Secret
## Establish Twitter OAuth connection
t = Twitter(auth=OAuth(access_token, access_secret, consumer_key, consum... |
project-hypr/hypr2 | hypr/serializers/json_serializer.py | Python | bsd-2-clause | 1,374 | 0 | # Copyright 2014-2016 Morgan Delahaye-Prat. All Rights Reserved.
#
# Licensed under the Simplified BSD License (the "License");
# you may not use this file except in compliance with the License.
"""JSON serializer."""
import json
from datetime import tzinfo, timedelta
class _simple_utc(tzinfo): # pragma: no cover
... |
if request is not None:
pretty_print = request.args.get('_pprint', '').lower() | in ('true', '1')
indent = None
if pretty_print: # pragma: no cover
indent = 4
if default is None:
default = encoder
return json.dumps(obj, default=default, sort_keys=True, indent=indent)
|
salopensource/sal | datatableview/exceptions.py | Python | apache-2.0 | 215 | 0 | # -*- encoding: utf-8 -*-
class ColumnError(Exception):
""" Some kind of | problem with a datatable column. """
class SkipRecord(Exception):
""" User- | raised problem with a record during serialization. """
|
wbg-optronix-lab/pyapi-emergence | setup.py | Python | gpl-2.0 | 357 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try | :
from setuptools import setup
except ImportError:
from distutils.core import setup
se | tup(
name='pyapi-emergence',
url='',
author='Neil Newman, Jonathan Marini',
author_email='nnewman2@albany.edu, jmarini@ieee.org',
packages=['emergence'],
install_requires=['requests'],
)
|
tuanavu/python-cookbook-3rd | src/11/interacting_with_http_services_as_a_client/example3.py | Python | mit | 467 | 0.012848 | # A POST | request using requests library
import requests
# Base URL being accessed
url = 'http://httpbin.org/post'
# Dictionary of query parameters (if any)
parms = {
'name1' : 'value1',
'name2' : 'value2'
}
# Extra headers
headers = {
'User-agent' : 'none/ofyourbusiness',
'Spam' : 'Eggs'
}
resp = requests.pos... | text returned by the request
text = resp.text
from pprint import pprint
pprint(resp.json)
|
bbc/kamaelia | Sketches/DL/modules/DL_Util.py | Python | apache-2.0 | 1,725 | 0.002319 | # -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Lice... | gen):
""" Generates Hello World0, Hello World1, Hello World2, ....."""
def main(self):
"""Main loop."""
count = 0
while 1:
self.s | end("Hello World" + str(count), "outbox")
count += 1
yield 1
class Pickle(Component.component):
def main(self):
while 1:
if self.dataReady("inbox"):
data = self.recv("inbox")
self.send(pickle.dumps(data), "outbox")
... |
mvaled/sentry | src/sentry/utils/imports.py | Python | bsd-3-clause | 1,880 | 0.003191 | from __future__ import absolute_import
import pkgutil
import six
MODEL_MOVES = {
"sentry.models.tagkey.TagKey": "sentry.tagstore.legacy.models.tagkey.TagKey",
"sentry.models.tagvalue.tagvalue": "sentry.tagstore.legacy.models.tagvalue.TagValue",
"sentry.models.grouptagkey.GroupTagKey": "sentry.tagstore.le... | e_name, {}, {}, [class_name])
handler = getattr(module, class_name)
# We cache a NoneType for missing imports to avoid repeated lookups
self[key] = handler
return | handler
_cache = ModuleProxyCache()
def import_string(path):
"""
Path must be module.path.ClassName
>>> cls = import_string('sentry.models.Group')
"""
path = MODEL_MOVES.get(path, path)
result = _cache[path]
return result
def import_submodules(context, root_module, path):
"""
... |
joshmoore/zeroc-ice | cpp/test/Freeze/dbmap/run.py | Python | gpl-2.0 | 1,137 | 0.006157 | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# IC | E_LICENSE file included in this distribution.
#
# **********************************************************************
import os, sys
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspat... | ath[0]))
from scripts import *
dbdir = os.path.join(os.getcwd(), "db")
TestUtil.cleanDbDir(dbdir)
client = os.path.join(os.getcwd(), "client")
if TestUtil.appverifier:
TestUtil.setAppVerifierSettings([client])
clientProc = TestUtil.startClient(client, ' --Freeze.Warn.Rollback=0 "%s"' % os.getcwd())
clientProc.w... |
pgroudas/pants | tests/python/pants_test/python/test_resolver.py | Python | apache-2.0 | 667 | 0.002999 | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import unittest
fro... | .backend.python.resolver import get_platforms
class ResolverTest(unittest.TestCase):
def test_get_current_platform(self):
expected_platforms = [Platform.current(), 'linux-x86_64']
self.assertEqual(set(expected_platfor | ms),
set(get_platforms(['current', 'linux-x86_64'])))
|
vmanoria/bluemix-hue-filebrowser | hue-3.8.1-bluemix/apps/beeswax/src/beeswax/migrations/0003_auto__add_field_queryhistory_server_name__add_field_queryhistory_serve.py | Python | gpl-2.0 | 7,185 | 0.007655 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'QueryHistory.server_name'
db.add_column('beeswax_queryhistory', 'server_name', self.gf('django.db.... | ,
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], | {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('dja... |
Juniper/nova | nova/tests/unit/virt/vmwareapi/test_configdrive.py | Python | apache-2.0 | 7,344 | 0.000545 | # Copyright 2013 IBM Corp.
# Copyright 2011 OpenStack Foundation
#
# 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/LICENSE-2.0
#
# Unless ... | ake_instance
import nova.tests.unit.image.fake
from nova.tests.unit import utils
from nova.tests.unit.virt.vmwareapi import fake as vmwareapi_fake
from nova.tests.unit.virt.vmwareapi import stubs
from nova.tests import uuidsentinel
from nova.virt import fake
from nova.virt.vmwareapi import driver
from nova.virt.vmwarea... | igDriveTestCase(test.NoDBTestCase):
REQUIRES_LOCKING = True
@mock.patch.object(objects.Service, 'get_by_compute_host')
@mock.patch.object(driver.VMwareVCDriver, '_register_openstack_extension')
def setUp(self, mock_register, mock_service):
super(ConfigDriveTestCase, self).setUp()
vm_ut... |
pascalgutjahr/Praktikum-1 | Fourier/rechteck.py | Python | mit | 1,202 | 0.000832 | import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy. | optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.linewidth'] = 1
csfont = {'fontname': 'Times New Roman'}
# U_mess = b_n
n, b_n = np.genfromtxt('rechteck.txt', unpack= | True, skip_header=2)
x = np.log(n)
y = np.log(b_n)
def f(x, a, b):
return a * x + b
params, covariance = curve_fit(f, x, y)
errors = np.sqrt(np.diag(covariance))
print('a =', params[0], '+-', errors[0])
print('b =', params[1], '+-', errors[1])
# a =-1.19204784746 +- 0.0898910034039
# b = 0.326461420388 +- 0.1... |
widdowquinn/find_differential_primers | tests/test_03b_subcmd_primer3.py | Python | mit | 8,352 | 0.001078 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""test_03b_subcmd_primer3.py
Test primer3 subcommand for pdp script. These tests require primer3 v2+.
This test suite is intended to be run from the repository root using:
pytest -v
(c) The James Hutton Institute 2017-2019
Author: Leighton Pritchard
Contact:
leighton... | os.path.join(self.ou | tdir, "subset"), os.path.join(self.targetdir, "subset")
)
@pytest.mark.skipif(PRIMER3_VERSION[0] < 2, reason="requires primer3 v2+")
def test_primer3_02_force(self):
"""primer3 subcommand executes and overwrites existing output.
This is the same test as test_primer3_01_run:
p... |
Emantor/syslog2irc | tests/test_irc_channel.py | Python | mit | 791 | 0.007585 | # -*- coding: utf-8 -*-
"""
:Copyright: 2007-2015 `Jochen Kupperschmidt <http://homework.nwsnet.de/>`_
:License: MIT, see LICENSE for details.
"""
from __future__ import u | nicode_literals
from unittest import TestCase
from nose2.tools import params
from syslog2irc.irc import Channel
class IrcChannelTestCase(TestCase):
@params(
(Channel('#example'), '#example', None ),
(Channel('#example', password=None), '#example', N... | e ),
(Channel('#headquarters', password='secret'), '#headquarters', 'secret'),
)
def test_irc_channel_creation(self, channel, expected_name, expected_password):
self.assertEqual(channel.name, expected_name)
self.assertEqual(channel.password, expected_password)
|
IBMPredictiveAnalytics/SPSSINC_SPLIT_DATASET | src/SPSSINC_SPLIT_DATASET.py | Python | apache-2.0 | 31,294 | 0.008117 |
"""SPSSINC SPLIT DATASET extension command"""
#Licensed Materials - Property of IBM
#IBM SPSS Products: Statistics General
#(c) Copyright IBM Corp. 2010, 2020
#US Government Users Restricted Rights - Use, duplication or disclosure
#restricted by GSA ADP Schedule Contract with IBM Corp.
__author__ = 'spss, JKP'
__ve... | # If there are no labels for the row dimension, the number of rows in Cells is used.
tmpRowLabels.extend(["row"+str(x) for x in range(nRows)])
else:
tmpRowLabels.extend(["row"+str(x) for x in range(nRows)])
| tmpColLabels.extend(["col"+str(x) for x in range(nCols)])
tmpRowLabels = list(map(CellText._CellText__ToCellText,tmpRowLabels))
tmpColLabels = list(map(CellTex |
ArcherSys/ArcherSys | Lib/test/test_importlib/import_/test_fromlist.py | Python | mit | 16,364 | 0.002017 | <<<<<<< HEAD
<<<<<<< HEAD
"""Test that the semantics relating to the 'fromlist' argument are correct."""
from .. import util
from . import util as import_util
import unittest
class ReturnValue:
"""The use of fromlist influences what import returns.
If direct ``import ...`` statement is used, the root module... | ule')
def test_nonexistent_object(self):
# [bad object]
with util.mock_modules('module') as importer:
with util.import_state(meta_path=[importer]):
module = self.__import__('module', fromlist=['non_existent'])
self.assertEqual(module.__name__, 'module')
... |
def test_module_from_package(self):
# [module]
with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
with util.import_state(meta_path=[importer]):
module = self.__import__('pkg', fromlist= |
PhonologicalCorpusTools/SLP-Annotator | slpa/gui/functional_load.py | Python | gpl-3.0 | 15,434 | 0.004341 | from collections import defaultdict
from math import log2 as log
from gui.transcriptions import STANDARD_SYMBOLS
from imports import (QDialog, QHBoxLayout, QVBoxLayout, QGroupBox, QRadioButton, QButtonGroup, QPushButton,
QStackedWidget, QWidget, QComboBox, QMessageBox, QLabel, QLineEdit, QTableWidge... | self.calcCustom(slots)
super().accept( | )
def calculateEntropy(self, corpus=None):
corpus_size = len(corpus) if corpus is not None else len(self.corpus)
return corpus_size, sum([1 / corpus_size * log(1 / corpus_size) for n in range(corpus_size)]) * -1
def calcByDuction(self):
corpus_size, starting_h = self.calculateEntropy(... |
r0x0r/pywebview | webview/js/event.py | Python | bsd-3-clause | 512 | 0.007813 | # IE 11 CustomEvent polyfill
src = r"""
(fu | nction () {
if ( typeof window.CustomEvent === "function" ) return false; //If not IE
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params | .cancelable, params.detail );
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
""" |
kesiena115/nbproject | apps/polls/admin.py | Python | mit | 116 | 0.008621 | from django.contrib import admin
import models as M
admin.site.register(M.Con | sent)
ad | min.site.register(M.Message)
|
wooga/airflow | tests/www/api/experimental/test_endpoints.py | Python | apache-2.0 | 21,328 | 0.000328 | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | te()
session.commit()
session.close()
dagbag = DagBag(include_examples=True)
for dag in dagbag.dags.values():
dag.sync_to_db()
SerializedDagModel.write_dag(dag)
def tearDown(self):
ses | sion = Session()
session.query(DagRun).delete()
session.query(TaskInstance).delete()
session.commit()
session.close()
super().tearDown()
def test_info(self):
url = '/api/experimental/info'
resp_raw = self.client.get(url)
resp = json.loads(resp_raw.da... |
woutervanwijk/mopidy | tests/test_models.py | Python | apache-2.0 | 38,697 | 0 | from __future__ import unicode_literals
import json
import unittest
from mopidy.models import (
Album, Artist, ModelJSONEncoder, Playlist, Ref, SearchResult, TlTrack,
Track, model_json_decoder)
class GenericCopyTest(unittest.TestCase):
def compare(self, orig, other):
self.assertEqual(orig, other... | ='uri', name='name').serialize()
artist['foo'] = 'foo'
serialized = json.dumps(artist)
with self.assertRaises(TypeError):
json.loads(serialized, object_hook=model_json_decoder)
def test_to_json_and_back_with_field_matching_method(self):
artist = Artist(uri='uri', name='n... | t_hook=model_json_decoder)
def test_to_json_and_back_with_field_matching_internal_field(self):
artist = Artist(uri='uri', name='name').serialize()
artist['__mro__'] = 'foo'
serialized = json.dumps(artist)
with self.assertRaises(TypeError):
json.loads(serialized, object_h... |
RestComm/restcomm-sdk-python | Restcomm_Python_SDk/Test/CreateLocalServer/createServer.py | Python | mit | 1,604 | 0.003741 | '''
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2016, Telestax Inc and individ | ual contributors
* by the @authors tag.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is ... | WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Softw... |
flavour/ssf | tests/selenium/scripts/locationsTest.py | Python | mit | 13,090 | 0.006494 | from sahanaTest import SahanaTest
import unittest, time, re
import copy
class LocationTest(SahanaTest):
"""
Test the locationWidget - This is done using the shelter registry
All tests can assume that they will be logged in with the admin account at the start.
Any test that requires a d... | selectID="cr_shelter_shelter_service_id")
LocationTest.crShelterTemplate.addInput(inputID="cr_shelter_location_id", visible=False)
LocationTest.crShelterTemplate.addInput(inputID="gis_location_search_ac", visible=False)
LocationTest.crShelterTempla... | nTest.crShelterTemplate.addInput(inputID="gis_location_name")
LocationTest.crShelterTemplate.addTextArea(textID="gis_location_street")
LocationTest.crShelterTemplate.addInput(inputID="gis_location_postcode")
LocationTest.crShelterTemplate.addInput(inputID="gis_location_postcode_search", visible=... |
eedf/jeito | booking/admin.py | Python | mit | 1,743 | 0.001721 | from django.contrib import admin
from .models import BookingState, Booking, BookingItem, TrackingEvent, TrackingValue, Agreement, Payment
@admin.register(BookingState)
class BookingStateAdmin(admin.ModelAdmin):
list_display = ('title', 'color', 'income')
@admin.register(Agreement)
class AgreementAdmin(admin.Mod... | te', 'amount', 'scan')
extra = 1
@admin.register(Booking)
class BookingAdmin(admin.ModelAdmin):
inlines = (AgreementInline, BookingItemInline, PaymentInline)
list_display = ('title', 'year', 'state', 'contact', 'email', 'tel', 'agreement')
list_filter = ('state', 'year')
search_fields = ( | 'title', 'contact', 'email')
class TrackingValueInline(admin.TabularInline):
model = TrackingValue
fields = ('field', 'value')
@admin.register(TrackingEvent)
class TrackingEventAdmin(admin.ModelAdmin):
list_display = ('user', 'date', 'obj')
inlines = (TrackingValueInline, )
@admin.register(Payment... |
monkpit/pyfocas | aggregator.py | Python | mit | 3,926 | 0.002038 | #!/usr/bin/env python
import logging
import time
import pymongo
from pyfocas.Collector import Collector
from pyfocas.Machine import Machine
from FanucImplementation.DriverImplementations import Fanuc30iDriver
from pyfocas import Exceptions
THREE_SIXTEEN = "10.108.7.41"
THREE_TWENTY = "10.108.7.42"
THREE_TWENTY_TWO ... | #Machine(driver=driver30i, ip=THREE_TWENTY_TWO, name="322"),
#Machine(driver=driver30i, ip=THREE_TWENTY_SIX, name="326"),
#Machine(driver=driver30i, ip=FOUR_SIXTEEN, name="416"),
#Machine(driver=driver30i, ip=FOUR_EIGHTEEN, name="418"),
Machine(driver=... | ip=THREE_EIGHTY_SEVEN, name="387"),
Machine(driver=driver30i, ip=THREE_NINETY_SEVEN, name="397"),
Machine(driver=driver30i, ip=THREE_NINETY_SIX, name="396"),
Machine(driver=driver30i, ip=THREE_NINETY_THREE, name="393"), ]
""" Create the Collector """
collector = C... |
delmic/odemis | src/odemis/driver/semcomedi.py | Python | gpl-2.0 | 173,060 | 0.002774 | # -*- coding: utf-8 -*-
'''
Created on 15 Oct 2012
@author: Éric Piel
Copyright © 2012-2015 Éric Piel, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License version 2 as published by the Free Software
Foundation.
Odem... | ple samples, or moving the e-beam around the pixel (in which
# it's exactly equivalent to reducing the image resolution).
#
# Note about using comedi in Python:
# There are two available bindings for comedi in Python: python-comedilib
# (provided with comedi) and pycomedi. python-comedilib provides just a direct
# map... | of the C functions. It's quite verbose because every name starts with
# comedi_ (not anymore in the latest version), and not object oriented.
# You can directly use the C documentation. The
# only thing to know is that parameters which are a simple type and used as output
# (e.g., int *, double *) are not passed as par... |
DevangS/CoralNet | utils.py | Python | bsd-2-clause | 2,240 | 0.003125 | # General utility functions can go here.
import os
import random
import string
from django.utils import functional
from django.utils.http import urlencode
def rand_string(numOfChars):
"""
Generates a string of lowercase letters and numbers.
That makes 36^10 = 3 x 10^15 possibilities.
If we generate f... | ople to guess filenames
and type in their URLs directly to bypass permissions.
"""
return ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(numOfChars))
def generate_random_filename(directory, originalFilename, numOfChars):
"""
Generate a random filename for a file upload... | repends the directory
argument to get a filepath which is only missing the MEDIA_ROOT
part at the beginning.
The return value can be used as an upload_to argument for a FileField
ImageField, ThumbnailerImageField, etc. An upload_to argument is
automatically prepended with MEDIA_ROOT to get the upl... |
ulope/nearest_pypi | config.py | Python | mit | 1,600 | 0.001875 | import logging
impor | t socket
from unipath import Path
class BaseConfig(object):
DEBUG = False
TESTING = False
LOG_LEVEL = logging.INFO
SITE_ROOT = Path(__file__).absolute().parent
STDNET_DB_URL = "redis://localhost:6379?db=0"
GEOIP_DB_URL_IPV4 = "http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat... | H_V4 = SITE_ROOT.child("data", "GeoLiteCity.dat")
GEOIP_PATH_V6 = SITE_ROOT.child("data", "GeoLiteCityv6.dat")
UNOFFICIAL_MIRRORS = [
"pypi.crate.io",
]
FALLBACK_MIRROR = "a.pypi.python.org"
REDIS = {
'HOST': "localhost",
'PORT': 6379,
'DB': 0,
}
KEY_LAST_UP... |
ceos-seo/Data_Cube_v2 | agdc-v2/utils/modisprepare.py | Python | apache-2.0 | 5,331 | 0.002814 | # coding=utf-8
"""
Ingest data from the command-line.
"""
from __future__ import absolute_import, division
import uuid
import logging
from xml.etree import ElementTree
from pathlib import Path
import yaml
import click
from osgeo import gdal, osr
from dateutil import parser
def get_coords(geo_ref_points, spatial_ref)... | '])
def fill_image_data(doc, granule_path):
format_ = None
bands = {}
gran_file = gdal.Open(str(granule_path))
quoted = '"' + str(granule_path) + '"'
for subds in gr | an_file.GetSubDatasets():
index = subds[0].find(quoted)
if not format_:
ds = gdal.Open(subds[0])
projection = ds.GetProjection()
t = ds.GetGeoTransform()
bounds = t[0], t[3], t[0] + t[1] * ds.RasterXSize, t[3] + t[5] * ds.RasterYSize
del ds
... |
SimonGreenhill/NexusMaker | nexusmaker/CognateParser.py | Python | bsd-3-clause | 2,824 | 0.000708 | import re
from nexusmaker.tools import natsort
is_combined_cognate = re.compile(r"""(\d+)([a-z]+)""")
class CognateParser(object):
UNIQUE_IDENTIFIER = "u_"
def __init__(self, strict=True, uniques=True, sort=True):
"""
Parses cognates.
- strict (default=True): remove dubious cognat... | value = value.replace('.', ',').replace("/", ",")
# parse out subcognates
value = [
self._split_combined_cognate(v.strip()) for v in value.split(",")
]
value = [item for sublist in value for item in sublist]
if self.strict:
... | state
if len(value) == 0:
return self.get_next_unique()
else:
value = [v.replace("?", "") for v in value]
# remove any empty things in the list
value = [v for v in value if len(v) > 0]
if self.sort:
va... |
othersite/document | machinelearning/deep-learning-book/ann/np/activations.py | Python | apache-2.0 | 7,369 | 0 | """ Activation functions implemented in NumPy
"""
# Sebastian Raschka 2016-2017
#
# ann is a supporting package for the book
# "Introduction to Artificial Neural Networks and Deep Learning:
# A Practical Guide with Applications in Python"
#
# Author: Sebastian Raschka <sebastianraschka.com>
#
# License: MIT
import nu... | .clip(x, -250, 250)))
def logistic_derivative(x):
""" Derivative of the logistic sigmoid activation function
Parameters
----------
x : numpy array, shape=(n_samples, )
Input values
Returns
----------
float
logistic(x) * (1 - logistic(x))
Examples
----------
>>... | _derivative(np.array([-1, 0, 1]))
array([ 0.19661193, 0.25 , 0.19661193])
>>>
"""
x_logistic = logistic_activation(x)
return x_logistic * (1. - x_logistic)
def logistic_derivative_from_logistic(x_logistic):
""" Derivative of the logistic sigmoid activation function
Parameters
-... |
ssato/python-anyconfig | tests/processors/common.py | Python | mit | 800 | 0 | #
# Copyright (C) 2018 - 2021 Satoru SATOH <satoru.satoh@gmail.com>
# SPDX-License-Identifier: MIT
#
# pylint: disable=missing-docstring, invalid-name
import anyconfig.models.processor
class A(anyconfig.models.processor.Processor):
_cid = 'A'
_type = 'json'
_extensions = ['json', 'jsn', 'js']
class A2(A... | ity than A and A2.
class B(anyconfig.models.processor.Processor):
_cid = 'B | '
_type = 'yaml'
_extensions = ['yaml', 'yml']
_priority = 99 # Higher priority than C.
class C(anyconfig.models.processor.Processor):
_cid = 'dummy'
_type = 'yaml'
_extensions = ['yaml', 'yml']
PRS = [A, A2, A3, B, C]
# vim:sw=4:ts=4:et:
|
Widiot/simpleblog | venv/lib/python3.5/site-packages/selenium/webdriver/common/actions/key_input.py | Python | mit | 1,782 | 0.000561 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyrig | ht ownership. The SFC licenses this file
# to you 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/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | ted on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from . import interaction
from .input_device import InputDevice
from .interaction import (Interaction,
... |
huzheng001/stardict-3 | tools/src/KangXiZiDian-djvu2tiff.py | Python | gpl-3.0 | 677 | 0.014771 | # This tool convert KangXiZiDian djvu files to tiff files.
# Download djvu files: http://bbs.dartmouth.edu/~fangq/KangXi/KangXi.tar
# Character page info: http://wenq.org/unihan/Unihan.txt as kIRGKangXi field.
# Character seek position in Unihan.txt http://wenq.org/unihan/unihandata.txt
# DjVuLibre package provides the... | 50 KangXiZiDian.dj | vu"+ " tif/" + page + ".tif")
|
callowayproject/django-cookiesession | setup.py | Python | apache-2.0 | 1,070 | 0.017757 | import os
from setuptools import setup, find_packages
def read_file(filename):
"""Read a file into a string"""
path = os.path.abspath(os.path.dirname(__file__))
filepath = os.path.join(path, filename)
try:
return open(filepa | th).read()
except IOError:
return ''
# Use the docstring of the __init__ file to be the description
DESC = " ".join(__import__('cookiesession').__doc__.splitlines()).strip()
setup(
name = 'django-cookiesess | ion',
version = __import__('cookiesession').get_version().replace(' ', '-'),
url = 'http://github.com/washingtontimes/django-cookiesession',
author = 'Justin Quick, Corey Oordt, The Washington Times',
author_email = 'webdev@washingtontimes.com',
description = DESC,
long_description = read_file('... |
zhreshold/mxnet | example/distributed_training-horovod/resnet50_imagenet.py | Python | apache-2.0 | 17,959 | 0.000724 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | IND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import argparse
import logging
import math
import os
import time
from gluoncv.model_zoo import get_model
import horovod.mxnet as hvd
import mxnet as mx
import numpy as np
from mxnet ... | r
# Training settings
parser = argparse.ArgumentParser(description='MXNet ImageNet Example',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--use-rec', action='store_true', default=False,
help='use image record iter for data input (def... |
yiannist/ganeti | lib/server/rapi.py | Python | bsd-2-clause | 11,924 | 0.008051 | #
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2012, 2013 Google 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:
#
# 1. Redistributions of source code must retain the above copyright no... | impor | t asyncnotifier
from ganeti import constants
from ganeti import http
from ganeti import daemon
from ganeti import ssconf
import ganeti.rpc.errors as rpcerr
from ganeti import serializer
from ganeti import compat
from ganeti import utils
from ganeti import pathutils
from ganeti.rapi import connector
from ganeti.rapi imp... |
mgarg1/ecg | ecg_visualizer_ble_PC/galry/visuals/plot_visual.py | Python | agpl-3.0 | 7,738 | 0.008529 | import numpy as np
from galry import get_color, get_next_color
from visual import Visual
__all__ = ['process_coordinates', 'PlotVisual']
def process_coordinates(x=None, y=None, thickness=None):
# handle the case where x is defined and not y: create x
if y is None and x is not None:
if x.ndim == 1:
... | he default color
if color is None:
if nprimitives <= 1:
color = self.default_color
# automatic color with color map
if autocolor is not None:
if nprimitives <= 1:
| color = get_next_color(autocolor)
else:
color = [get_next_color(i + autocolor) for i in xrange(nprimitives)]
# # handle the case where the color is a string where each character
# # is a color (eg. 'ry')
# if isinstance(color, basestring):... |
p2pu/learning-circles | studygroups/migrations/0085_studygroup_place_id.py | Python | mit | 433 | 0 | # | -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-02-20 04:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0084_auto_20180215_0747'),
]
operations = [
migrations.AddField(
model_name='studygroup'... | name='place_id',
field=models.CharField(blank=True, max_length=256),
),
]
|
jbeliao/SLAM | SLAM_utils/praatUtil.py | Python | lgpl-3.0 | 6,253 | 0.034064 | # -*- coding: utf-8 -*-
"""
@package praatUtil This module contains some utility functions to seamlessly
incorporate Praat analysis functionality into Python
@copyright GNU Public License
@author written 2009-2014 by Christian Herbst (www.christian-herbst.org)
@author Partially supported by the SOMACCA advanced ERC ... | raise
return(data['x'], data['y'])
def readPitchTier(fileName):
"""
reads Praat PitchTier data, saved as "short text file" within Praat
@param fileName
@return a tuple containing two lists: the time offset, and the
corresponding F0 (inaccurately call | ed "pitch" in Praat) data
"""
dataX, dataY, metaData = readPraatShortTextFile(fileName, 'PitchTier')
return dataX, dataY
def readIntensityTier(fileName):
"""
reads Praat IntensityTier data, saved as "short text file" within Praat
@param fileName
@return a tuple containing two lists: the time offset, and data
"... |
rupertnash/subgrid | python/d3q15/delta.py | Python | mit | 510 | 0.001961 | """Simple python implementation of Peskin's delta function | .
"""
from numpy import abs, sqrt
def delta(x):
"""Discretised Dirac delta function.
Returns an approximation to the delta function, as explained in
Peskin Acta Numerica (2002) pp. 479-517, chapter 6.
"""
abs_x = abs(x)
| if abs_x <= 1.0:
return (3 - 2*abs_x + sqrt(1 + 4*abs_x - 4*abs_x*abs_x))/8.
elif abs_x <= 2.0:
return (5 - 2*abs_x-sqrt(-7 + 12*abs_x - 4*abs_x*abs_x))/8.
else:
return 0.0
|
davidcox/genson | genson/functions.py | Python | mit | 8,655 | 0.000809 | import numpy as np
from util import resolve, genson_dumps, get_global_seed, assert_kwargs_consumed
from internal_ops import GenSONOperand
from internal_ops import GenSONFunction
from internal_ops import registry
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def register_fun... | log.debug('registering: %s' % name)
f = fun
else:
def wrapper(*args, **kwargs):
return GenSONFunction(fun, name, args, kwargs)
f = wrapper
# make the wrapper available to the parser
registry[name] = f
# make the wrapper available in this module
current_mo... | return f
register_function('sin', np.sin)
register_function('cos', np.cos)
register_function('tan', np.tan)
class ParameterGenerator(GenSONOperand):
def __init__(self, draws=1, random_seed=None):
self.draws = draws
self.counter = 0
self.random_seed = random_seed
self.seed()
... |
stonebig/bokeh | bokeh/io/tests/test_notebook.py | Python | bsd-3-clause | 5,073 | 0.005914 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... | -------
def test__origin_url():
assert binb._origin_url("foo.com:8888") == "foo.com:8888"
assert binb._origin_url("http://foo.com:8888") == "foo.com:8888"
assert binb._origin_ur | l("https://foo.com:8888") == "foo.com:8888"
def test__server_url():
assert binb._server_url("foo.com:8888", 10) == "http://foo.com:10/"
assert binb._server_url("http://foo.com:8888", 10) == "http://foo.com:10/"
assert binb._server_url("https://foo.com:8888", 10) == "https://foo.com:10/"
#-----------------... |
tencrance/cool-config | test_tools/test_web.py | Python | mit | 766 | 0.005348 | # -*- coding:utf-8 -*-
# date:2018-03-14 16:27
# auther:yang
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
class SearchWithBaidu(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome()
def | test_search_in_python_org(self):
driver = self.driver
driver.get("http://www.baidu.com")
self.assertIn("百度一下,你就知道", driver.title)
elem = driver.find_element_by_name("wd")
| elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
sleep(3)
assert "No results found." not in driver.page_source
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main() |
rawrgulmuffins/presentation_notes | pycon2016/tutorials/measure_dont_guess/handout/pi/numpy_pi.py | Python | mit | 834 | 0.008393 | # file: numpy_pi.py
"""Calculating pi with Monte Carlo Method and NumPy.
"""
from __future__ import print_function
import numpy #1
@profile
def pi_numpy(total): #2
"""Compute pi.
"""
x = numpy.random | .rand(total) #3
y = numpy.random.rand(total) #4
dist = numpy.sqrt(x * x + y * y) #5
count_inside = len(dist[dist < 1]) #6
return | 4.0 * count_inside / total
if __name__ == '__main__':
def test():
"""Time the execution.
"""
import timeit
start = timeit.default_timer()
pi_numpy(int(1e6))
print('run time', timeit.default_timer() - start)
test()
|
ashvina/heron | heron/tools/tracker/src/python/handlers/__init__.py | Python | apache-2.0 | 1,378 | 0 | ''' __init__ '''
from basehandler import BaseHandler
from clustershandler import ClustersHandler
from containerfilehandler import ContainerFileDataHandler
from containerfilehandler import ContainerFileDownloadHandler
from containerfilehandler import ContainerFileStatsHandler
from defaulthandler import DefaultHandler
fr... | port RuntimeStateHandler
from schedulerlocationhandler import SchedulerLocationHandler
from stateshandler import StatesHandler
from topolo | gieshandler import TopologiesHandler
from topologyconfighandler import TopologyConfigHandler
from topologyhandler import TopologyHandler
|
davidam/python-examples | elasticsearch/elasticsearch-example.py | Python | gpl-3.0 | 635 | 0.001575 | f | rom datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch()
doc = {
'author': 'kimchy',
'text': 'Elasticsearch: cool. bonsai cool.',
'timestamp': datetime.now(),
}
res = es.index(index="test-index", doc_type='tweet', id=1, body=doc)
#print(res['created'])
res = es.get(index=... | % res['hits']['total'])
for hit in res['hits']['hits']:
print("%(timestamp)s %(author)s: %(text)s" % hit["_source"])
|
andersroos/rankedftw | pg_test/get_teams_ranking_test.py | Python | agpl-3.0 | 5,555 | 0.00126 | import gc
import aid.test.init_django_postgresql
from aid.test.db import Db
from aid.test.base import DjangoTestCase
from main.models import *
from lib import sc2
from django.conf import settings
class Test(DjangoTestCase):
@classmethod
def setUpClass(self):
super(Test, self).setUpClass()
s... | FO, 0)
def tearDown(self):
# Null and garbage collect to disconnect c++ code from the database (RAII).
self.c = None
gc.collect()
super().tearDown()
def test_get_team_from_ranking_with_only_one_team(self):
self.db.create_ranking()
self.db.create_ranking_data(da... | _for_team(self.t1.id)
self.assertEqual(1, len(rankings))
self.assertEqual(8912, rankings[0]["points"])
rankings = self.c.rankings_for_team(self.t1.id + 1)
self.assertEqual(0, len(rankings))
def test_get_team_from_tanking_with_two_different_teams(self):
self.db.create_rank... |
CLVsol/odoo_addons | clv_employee/__openerp__.py | Python | agpl-3.0 | 1,966 | 0.008647 | # -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... | #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRA | NTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU Affero General Public License for more details. #
# #
# You should have r... |
TakayukiSakai/tensorflow | tensorflow/python/training/training.py | Python | apache-2.0 | 8,011 | 0.000624 | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# 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/LICENSE-2.0
#
# Unless required by applica... | orm
@@clip_by_global_norm
@@global_norm
## Decaying the learning rate
@@exponential_decay
## Moving Averages
Some training algorithms, such as GradientDescent and Momentum often benefit
from maintaining a moving average of variables during optimization. Using the
moving averages for evaluations often improve result... | _queues/index.md)
for how to use threads and queues. For documentation on the Queue API,
see [Queues](../../api_docs/python/io_ops.md#queues).
@@Coordinator
@@QueueRunner
@@add_queue_runner
@@start_queue_runners
## Distributed execution
See [Distributed TensorFlow](../../how_tos/distributed/index.md) for
more infor... |
ChinaQuants/zipline | tests/pipeline/test_frameload.py | Python | apache-2.0 | 7,612 | 0 | """
Tests for zipline.pipeline.loaders.frame.DataFrameLoader.
"""
from unittest import TestCase
from mock import patch
from numpy import arange, ones
from numpy.testing import assert_array_equal
from pandas import (
DataFrame,
DatetimeIndex,
Int64Index,
)
from zipline.lib.adjustment import (
Float64Ad... | first_col=1,
last_col=1,
value=1.0,
),
],
7: [
Float64Add(
first_row=5,
last_row=6,
first_col=1,
last_col=1,
value=1.0,
... | rst_row=6,
last_row=7,
first_col=2,
last_col=2,
value=99.0,
)
],
}
self.assertEqual(formatted_adjustments, expected_formatted_adjustments)
mask = self.mask[dates_slice, sids_slice]
... |
sonofeft/XYmath | xymath/examples/fit_Patmos.py | Python | gpl-3.0 | 4,252 | 0.027516 | """
the website
http://www.engineeringtoolbox.com/air-altitude-pressure-d_462.html
Calculates air pressure above sea level as:
pressure(Pa) = 101325 * (1 - 2.25577E-5 * h)**5.25588
where x=altitude(m)
1) run script and get slightly improved answer from web site
(Note that Percent Error fit has better %StdDev b... | _full_description())
print('='*55)
# To set parameters to reference values from www.engineeringtoolbox.com do this:
print('..........Reference Curve Fit............')
CFit_ref = NonLinCurveFit(DS, rhs_eqnStr='A*(c - d*x)**n', constDinp=guessD)
CFit_ref.constD.update( {'A':101325, 'c':1, 'd':2.25577E-5, 'n':5.25588 } ... | )
xPlotArr, yPlotArr = CFit_ref.get_xy_plot_arrays( Npoints=100, logScale=False)
plt.plot( xPlotArr, yPlotArr, '--', linewidth=5, label='Reference' )
xPlotArr, yPlotArr = CFit_toterr.get_xy_plot_arrays( Npoints=100, logScale=False)
plt.plot( xPlotArr, yPlotArr, '-', label='Total Error' , linewidth=3 ... |
bill-mccloskey/mozsearch | infrastructure/aws/terminate-indexer.py | Python | mpl-2.0 | 257 | 0 | # Shuts down the ind | exer instance.
# Usage: terminate-indexer.py <indexer-instance-id>
import sys
import boto3
|
client = boto3.client('ec2')
indexerInstanceId = sys.argv[1]
terminate = [indexerInstanceId]
client.terminate_instances(InstanceIds=terminate)
|
asascience-open/paegan | tests/test_asarandom.py | Python | gpl-3.0 | 424 | 0.004717 | import os
import unittest
fro | m urlparse import urlparse
from paegan.utils.asarandom import AsaRandom
class AsaRandomTest(unittest.TestCase):
def test_create_random_filename(self):
temp_filename = AsaRandom.filename(prefix="superduper", suffix=".nc")
path = urlparse(temp_filename).path
name, ext = os.path.splitext(path... | ssert ext == ".nc" |
ynsta/steamcontroller | src/cheader.py | Python | mit | 5,714 | 0.004725 | #!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (c) 2015 Stany MARCEL <stanypub@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including withou... | val = eval_expr(expr)
out[name] = val
excep | t (SyntaxError, TypeError):
pass
elif tok == 'include':
tok = lexer.get_token()
if tok == '<':
name = ''
while True:
tok = lexer.get_token()
if tok == '>':
break
... |
newmediamedicine/indivo_server_1_0 | doc/sphinx/localext/httpdomain.py | Python | gpl-3.0 | 11,915 | 0.000587 | """
Indivo-specific extensions to httpdomain
for loading autogenerated API docs.
Adapted from:
sphinxcontrib.httpdomain
~~~~~~~~~~~~~~~~~~~~~~~~
The HTTP domain for documenting RESTful HTTP APIs.
:copyright: Copyright 2011 by Hong Minhee
:license: BSD, see LICENSE for details.
"""
... | =('shortname', 'sn', 'view_func')),
Field('returns', label='Returns',
rolename='returns',
has_arg=False,
n | ames=('returns', 'ret', 'retval')),
]
method = NotImplemented
def handle_signature(self, sig, signode):
method = self.method.upper() + ' '
signode += addnodes.desc_name(method, method)
offset = 0
for match in http_sig_param_re.finditer(sig):
path = sig[offset:m... |
thomasballinger/old-bpython-with-hy-support | bpython/curtsiesfrontend/coderunner.py | Python | mit | 4,839 | 0.003513 | import code
import signal
import sys
import greenlet
import logging
class SigintHappened(object):
pass
class SystemExitFromCodeThread(SystemExit):
pass
class CodeRunner(object):
"""Runs user code in an interpreter, taking care of stdout/in/err"""
def __init__(self, interp=None, stuff_a_refresh_reques... | request = self.code_greenlet.switch()
else:
assert self.code_is_wai | ting
self.code_is_waiting = False
signal.signal(signal.SIGINT, self.sigint_handler)
if self.sigint_happened:
self.sigint_happened = False
request = self.code_greenlet.switch(SigintHappened)
else:
request = self.code_greenlet... |
barriquello/iotstack | openwsn-fw-work/firmware/openos/openwsn/07-App/udpecho/udpecho.py | Python | mit | 2,057 | 0.026738 | import time
import socket
NUM_TRIES = 10
request = "poipoipoipoi"
myAddress = '' #means 'all'
myPort = 21568
hisAddress = 'bbbb::1415:92cc:0:2'
hisPort = 7
delays = []
succ = 0
fail = 0
print "Testing udpEcho..."
for i in range(NUM_TRIES):
# log
output = []
output... | {0}'.format(fail)]
output += ['- min/max/avg delay {0:.03f}/{1:.03f}/{2:.03f}'.format(
min(delays),
max(delays),
float(sum(d | elays))/float(len(delays)),
)
]
output = '\n'.join(output)
print output
raw_input("\nPress return to close this window...")
|
rakeshmi/cinder | cinder/tests/unit/test_smbfs.py | Python | apache-2.0 | 25,888 | 0.000039 | # Copyright 2014 Cloudbase Solutions Srl
#
# 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/LICENSE-2.0
#
# Unless required by applicable ... | (self):
self._test_setup(config=self._FAKE_SMBFS_CONFIG,
share_config_exists=False)
def test_setup_invlid_oversub_ratio(self):
fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
fake_config.smbfs_oversub_ratio = -1
self._test_setup(config=fake_config)
def... | atio(self):
fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
fake_config.smbfs_used_ratio = -1
self._test_setup(config=fake_config)
def _test_create_volume(self, volume_exists=False, volume_format=None):
fake_method = mock.MagicMock()
self._smbfs_driver.configuration = copy.... |
jvantuyl/vertebra-py | tests/test_20_actor.py | Python | lgpl-3.0 | 224 | 0.013393 | from vertebra.actor import actor
class test | _00_actor:
def test_00_instantiate(self):
"""actor: can instantiate a base actor"""
| a = actor()
assert isinstance(a,actor), "instantiated actor is actually an actor"
|
acreations/rockit-server | rockit/core/migrations/0017_hello_done.py | Python | mit | 419 | 0 | # -*- coding: utf | -8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0016_hello'),
]
operations = [
migrations.AddField(
| model_name='hello',
name='done',
field=models.BooleanField(default=False),
preserve_default=True,
),
]
|
jw2100/beginning.github.io | DeepLearning/wuenda/04_ConvolutionalNeuralNetworks/week2-01-Keras-Tutorial.py | Python | gpl-3.0 | 3,412 | 0.01612 | import numpy as np
from keras import layers
from keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D
from keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D
from keras.models import Model
from keras.preprocessing import im... | ercise (including the later portions of this notebook) once. The come back also try out other
# network architectures as well.
# Define the input placeholder as a tensor with shape input_shape. Think of this as your input image!
X_i | nput = Input(input_shape)
# Zero-Padding: pads the border of X_input with zeroes
X = ZeroPadding2D((3, 3))(X_input)
# CONV -> BN -> RELU Block applied to X
X = Conv2D(32, (7, 7), strides = (1, 1), name = 'conv0')(X)
X = BatchNormalization(axis = 3, name = 'bn0')(X)
X = Activation('relu')(X)
... |
Azure/azure-sdk-for-python | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2015_04_01/operations/__init__.py | Python | mit | 1,034 | 0.001934 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | tActivityLogsOperations
from ._alert_rules_operations import AlertRulesOperations
__all__ = [
'ActivityLogsOperations',
'AutoscaleSettingsOperations',
'EventCategoriesOperations',
'Operations',
'TenantActivityLogs | Operations',
'AlertRulesOperations',
]
|
storerjeremy/python-semrush | python_semrush/__init__.py | Python | mit | 670 | 0.001493 | # -*- coding: utf-8 -*-
"""Wrapper around the SEMrush API."""
# :copyright: (c) 2015 Jeremy Storer and individual con | tributors,
# All rights reserved.
# :license: MIT License, see LICENSE for more details.
from collections import namedtuple
version_info_t = namedtuple(
'version_info_t', ('major', 'minor', 'micro', 'releaselevel', 'serial'),
)
VERSION = version_info_t(0, 1, 2, '', '')
__version__ = '{0.major}... | ttp://github.com/storerjeremy/python-semrush'
__docformat__ = 'restructuredtext'
# -eof meta- |
Zidit/Fort_up | polyvox/documentation/conf.in.py | Python | gpl-3.0 | 7,849 | 0.00688 | # -*- coding: utf-8 -*-
#
# PolyVox documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 6 14:46:57 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... | x is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Creat... | using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. Th... |
yihaochen/FLASHtools | grid_analysis/GridAnalysis_Vorticity.py | Python | gpl-2.0 | 2,344 | 0.008532 | #!/usr/bin/env python
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
import numpy as np
import os.path as op
import util
import yt
import MPI_taskpull2
import logging
logging.getLogger('yt').setLevel(logging.ERROR)
# Scan for files
dirs = ['/home/ychen/data/0only_0529_h1/',\
'/hom... | ,\
'/home/ychen/data/0only_0602_hydro/']
dirs = ['/home/ychen/data/0only_0602_hydro/']
#dirs = ['/home/ychen/data/0only_1022_h1_10Myr/',\
# '/home/ychen/data/0only_0204_h0_10Myr/',\
# '/home/ychen/data/0only_0204_hinf_10Myr/',\
# '/home/ychen/data/0only_0413_hydro_10Myr/']
regex = 'MHD_J... | worker_fn(dirname, filepath):
ds = yt.load(filepath)
factor = 4 if '10Myr' in dirname else 8
box = ds.box(ds.domain_left_edge/factor, ds.domain_right_edge/factor)
enstrophy = sum(box['vorticity_squared']*box['cell_mass'])
return int(ds.basename[-4:]), ds.current_time.in_units('Myr'), enstrophy
def... |
jeffwright13/unittest_tutorial | test_foo.py | Python | gpl-2.0 | 2,412 | 0.009121 | #!/usr/bin/python
import unittest
class FooTest(unittest.TestCase):
'''Sample test case -- FooTest()'''
def setUp(self):
'''Set up for testing...'''
print 'FooTest:setUp_:begin'
testName = self.shortDescription()
if (testName == 'Test routine A'):
pri... | OWN TEST ROUTINE'
print 'FooTest:tearDown_:end'
class BarTest(unittest.TestCase):
'''Sample t | est case -- BarTest()'''
def setUp(self):
'''Set up for testing...'''
print 'BarTest:setUp_:begin'
testName = self.shortDescription()
if (testName == 'Test routine A'):
print 'setting up for test A'
elif (testName == 'Test routine B'):
p... |
cloud9ers/gurumate | environment/lib/python2.7/site-packages/IPython/nbformat/v3/tests/test_nbpy.py | Python | lgpl-3.0 | 1,441 | 0.004164 | # -*- coding: utf8 -*-
from unittest import TestCase
from . import formattest
from .. import nbpy
from .nbexamples import nb0, nb0_py
class TestPy(formattest.NBFormatTest, TestCase):
nb0_ref = nb0_py
ext = 'py'
mod = nbpy
ignored_keys = ['collapsed', 'outputs', 'prompt_number', 'metadata']
de... | in self.ignored_keys:
continue
self.assertTrue(k in db)
self.assertSubset(v, db[k])
elif isinstance(da, list):
for a,b in zip(da, db):
self.assertSubset(a,b)
else:
if isinstance(da, basestring) and isinstance(db... | string):
# pyfile is not sensitive to preserving leading/trailing
# newlines in blocks through roundtrip
da = da.strip('\n')
db = db.strip('\n')
self.assertEquals(da, db)
return True
def assertNBEquals(self, nba, nbb):
... |
genonfire/bbgo | accounts/forms.py | Python | mit | 3,484 | 0.000861 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from accounts.models import Profile
from django import forms
from django.conf import settings
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django.utils import formats, timezon... | ension"""
def confirm_login_allowed(self, user):
"""Override confirm_login_allowed"""
if user.is_activ | e:
pass
elif not user.is_active:
now = timezone.now()
if now > user.profile.suspension_till:
user.is_active = True
user.save()
else:
formatted_date = formats.date_format(timezone.localtime(
user.p... |
elliotthill/django-oscar | oscar/core/compat.py | Python | bsd-3-clause | 4,157 | 0.000481 | from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ImproperlyConfigured
from django.utils import six
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from six.moves import map
def get_user_model():
"""
R... | **self.kw)
return self
def __exit__(self, type, value, traceback):
self.f.close()
def | next(self):
row = next(self.reader)
if PY3:
return row
return [s.decode("utf-8") for s in row]
__next__ = next
def __iter__(self):
return self
class UnicodeCSVWriter:
def __init__(self, filename, dialect=csv.excel,
encoding="utf-8", **kw):
... |
sandrafig/addons | calendar_event_meeting_reason/models/__init__.py | Python | agpl-3.0 | 177 | 0.005682 | # -*- coding: utf-8 | -*-
# © <2016> <SANDRA FIGUEROA VARELA sandrafigvar@gmail.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agp | l).
from . import calendar_event |
pigmej/solar | solar/cli/resource.py | Python | apache-2.0 | 6,427 | 0.000311 | # Copyright 2015 Mirantis, 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/LICENSE-2.0
#
# Unless required by applicable law or ... | True)
def tag(add, tags, resource_name):
r = sresource.load(resource_name)
if add:
r.add_tags(*tags)
click.echo('Tag(s) {} added to {}'.format(tags, resource_name))
else:
| r.remove_tags(*tags)
click.echo('Tag(s) {} removed from {}'.format(tags, resource_name))
@resource.command()
@click.argument('name')
@click.argument('args', nargs=-1)
def update(name, args):
args_parsed = {}
for arg in args:
try:
args_parsed.update(json.loads(arg))
... |
zhangziang/MyLeetCodeAlgorithms | python/35-search_insert_position.py | Python | mit | 732 | 0 | # 二分查找,这题应该归为 easy
class Solution(object):
def | searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
end_index = len(nums)-1
start_index = 0
while True:
if start_ind | ex > len(nums)-1:
return len(nums)
if end_index < 0:
return 0
if start_index > end_index:
return start_index
index = (start_index + end_index)/2
if nums[index] == target:
return index
if nums[inde... |
microwaveabletoaster/dunces-and-dungeons | entity/trap/traps.py | Python | gpl-3.0 | 57 | 0.052632 | class WireTrap(Trap):
def __init__(self,damage):
pa | ss
| |
cherrishes/weilai | xingxing/protobuf/python/lib/Python3.4/google/protobuf/internal/cpp_message.py | Python | apache-2.0 | 23,543 | 0.009302 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | .__delitem__(self[slice(None, None, None)].index(value))
def MergeFrom(self, other):
for message in other[:]:
self.add().MergeFrom(message)
def __getitem__(self, key):
cmessages = self._cmsg.GetRepeatedMessage(
self._cfield_descripto | r, key)
subclass = self._subclass
if not isinstance(cmessages, list):
return subclass(__cmessage=cmessages, __owner=self._message)
return [subclass(__cmessage=m, __owner=self._message) for m in cmessages]
def __delitem__(self, key):
self._cmsg.DeleteRepeatedField(
self._cfield_descript... |
healerkx/AdminBuildr | scripts/build_license.py | Python | apache-2.0 | 52 | 0.019231 |
def ad | d_lic | ense(file, lineno, license):
pass
|
google-research/sloe-logistic | sloe_experiments/est_gamma.py | Python | apache-2.0 | 3,474 | 0.010363 | # coding=utf-8
# Copyright 2021 The SLOE Logistic Authors.
#
# 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/LICENSE-2.0
#
# Unless required by applicable... | sions and
# limitations under the License.
"""Run experiment to understand convergence of SLOE estimator of eta.
Tests the SLOE estimator empirically by computing it
over a range of sample sizes for a bunch of different seeds, and storing in
csv files to be analyzed in a colab.
"""
from | absl import app
from absl import flags
import apache_beam as beam
from apache_beam.options import pipeline_options
import numpy as np
import sloe_logistic.sloe_experiments.experiment_helpers as exp_helper
import statsmodels.api as sm
FLAGS = flags.FLAGS
flags.DEFINE_string('output_path', '/tmp/counts.txt', 'The outp... |
nop33/indico | indico/modules/events/timetable/controllers/manage.py | Python | gpl-3.0 | 7,777 | 0.002315 | # This file is part of Indico.
# Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN).
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (a... | id')
if session_block.timetable_entry is None:
raise BadRequest('The session block is not scheduled')
if contribution.session and session_block.session != contribution.session and not data.get('force'):
raise BadRequest('Contribution is assigned to a | nother session')
updates['parent'] = session_block.timetable_entry
contribution.session = session_block.session
else:
updates['object'].session = None
return updates
def _process_POST(self):
"""Create new timetable entry"""
data = request.json
... |
linuxsoftware/dominoes | tests/test_gameserver/test_player.py | Python | agpl-3.0 | 2,374 | 0.012637 | #---------------------------------------------------------------------------
# Players Unit tests
#---------------------------------------------------------------------------
from ..testcase import TestCase
from .helpers import asynctest, UnitTestCase
from flexmock import flexmock
from davezdominoes.gameserver.player ... | ["github:surfking", "Manny Bianco",
self.manny.avatarUrl,
["3|4", "9|1", "4|6"]])
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
#--- | ------------------------------------------------------------------------
|
Tatsh/libipa | ipa/__init__.py | Python | mit | 9,459 | 0.000106 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import logging
import re
from zipfile import (
ZIP_STORED,
ZipFile,
)
from biplist import readPlistFromString
__all__ = [
'BadIPAError',
'IPAFile',
'IPAInfo',
'UnknownDeviceFamilyError',
]
def ... | "{0}" not detected as iOS application distribution file.'
def __init__(self, filename, msg=None):
if msg:
self.msg = msg
| self.msg = self.msg.format(filename)
class InvalidApplicationNameError(Exception):
pass
class InvalidUnicodeApplicationNameError(UnicodeEncodeError):
pass
class UnknownApplicationNameError(Exception):
pass
class UnknownApplicationVersionError(Exception):
pass
class UnknownDeviceFamilyError(Exc... |
pytorch/fairseq | examples/speech_recognition/criterions/__init__.py | Python | mit | 510 | 0.001961 | import importlib
import os
# ASG loss requires flashlight bindings
files_to_skip = set()
try:
import flashlight.lib.sequence.criterion
except ImportError:
files_to_skip.add("ASG_loss.py")
f | or file in sorted(os.listdir(os.path.dirname(__file__))):
if file.endswith(".py") and not file.startswith("_") and file no | t in files_to_skip:
criterion_name = file[: file.find(".py")]
importlib.import_module(
"examples.speech_recognition.criterions." + criterion_name
)
|
aniversarioperu/django-manolo | scrapers/tests/test_minsa_spider.py | Python | bsd-3-clause | 1,311 | 0.000763 | import os
import unittest
from manolo_scraper.spiders.minsa import MinsaSpider
from utils import fake_response_from_file
class TestMinsaSpider(unittest.TestCase):
def setUp(self):
self.spider = MinsaSpider()
def test_parse_item(self):
filename = os.path.join('data/minsa', '18-08-2015.html')... | fake_response_from_file(filename, meta={'date': u'18/08/2015'}))
item = next(items)
self.assertEqual(item.get('full_name'), u'MELENDEZ ARISTA GREIDY')
self.assertEqual(item.get('time_start'), u'18:45:09')
self.asse | rtEqual(item.get('institution'), u'minsa')
self.assertEqual(item.get('id_document'), u'DNI')
self.assertEqual(item.get('id_number'), u'41339966')
self.assertEqual(item.get('entity'), u'DIRESA AMAZONAS')
self.assertEqual(item.get('reason'), u'TRAMITE')
self.assertEqual(item.get('h... |
Bartzi/LabShare | labshare/decorators.py | Python | gpl-2.0 | 486 | 0.010288 | from django | .template import RequestContext
from django.shortcuts import render
#Source: http://lincolnloop.com/blog/2008/may/10/getting-requestcontext-your-templates/
def render_to(template_name, title = ""):
def renderer(func):
def wrapper(request, *args, **kw):
output = func(request, *args, **kw)
... | render(request, template_name, output)
return wrapper
return renderer
|
williballenthin/synapse | synapse/tests/test_lib_filepath.py | Python | apache-2.0 | 12,830 | 0.001325 |
import io
import shutil
import tarfile
import zipfile
import tempfile
from synapse.tests.common import *
import synapse.exc as s_exc
import synapse.lib.filepath as s_filepath
class TestFilePath(SynTest):
def test_filepath_objects(self):
temp_dir = tempfile.mkdtemp()
name = temp_dir
# F... | 0.add(f2_path, arcname='dir0/dir1/dir2/foo2')
tfd0.add(f3_path, arcname='dir0/dir | 1/dir2/junk')
tfd0.close()
zfd1 = zipfile.ZipFile(tzfd1.name, 'w')
zfd1.writestr('dir0/dir1/dir2/bar0', f0)
zfd1.writestr('dir0/dir1/dir2/bar1', f1)
zfd1.writestr('dir0/dir1/dir2/bar2', f2)
zfd1.writestr('dir0/dir1/dir2/junk', 'Z'*20)
zfd1.write(tzfd0.name, arcna... |
kmod/icbd | icbd/type_analyzer/tests/basic.py | Python | mit | 1,818 | 0.047305 | a = a # e 4
a = 1 # 0 int
l = [a] # 0 [int]
d = {a:l} # 0 {int:[int]}
s = "abc"
c = ord(s[2].lower()[0]) # 0 int # 4 (str) -> int
l2 = [range(i) for i in d] # 0 [[int]]
y = [(a,b) for a,b in {1:'2'}.iteritems()] # 0 [(int,str)]
b = 1 # 0 int
if 0:
b = '' # 4 str
else:
b = str(b) # 4 str # 12 int
... | = repr() # e 5 # 0 str
s4 = repr(s) # 0 str
x = 1 if [] else '' # 0 <int|str>
l = [1] # 0 [<int|str>]
l2 = [''] # 0 [str]
l[:] = l2 # 0 [<int|str>]
b = 1 < 2 < 3 # 0 bool
l = sorted(range(5), key=lambda x:-x) # 0 [int]
d = {} # 0 {<bool|int>:<int|str>}
d1 = {1:''} # 0 {int:str}
d.update(d1)
d[True] = 1
d # 0 {<boo... | r>}
l = [] # 0 [int]
l1 = [] # 0 [<unknown>]
l.extend(l1)
l.append(2)
l = [] # 0 [<[str]|int>]
l1 = [[]] # 0 [[str]]
l.extend(l1)
l[0].append('') # e 0
l.append(1)
l = [] # 0 [[<int|str>]]
l2 = [1] # 0 [int]
l3 = [''] # 0 [str]
l.append(l2)
l.append(l3)
for i, s in enumerate("aoeu"): # 4 int # 7 str
pass
x = 1... |
PixelDragon/pixeldragon2 | pixeldragon2/layers/translation.py | Python | gpl-3.0 | 1,232 | 0 | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 ... | POSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
################# | ########################################################
from modeltranslation.translator import translator, TranslationOptions
from geonode.layers.models import Layer
class LayerTranslationOptions(TranslationOptions):
fields = (
'title',
'abstract',
'purpose',
'constraints_other'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.