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
NapoleonWils0n/pilfer
setup.py
Python
gpl-3.0
605
0.003306
#from setuptools import setup from distutils.core import setup setup( name='pilfer', version='2.0', description='pilfer command line tool to record audio and video from Kodi', url='https://github.com/NapoleonWils0n/pilfer', auth
or='NapoleonWils0n', maintainer='NapoleonWils0n', license='GPL', keywords='ffmpeg rtmpdump kodi', packages=['pilfer'], #scripts=['pilfer/pilfer', 'pilfer/pilfer-pla
y'], entry_points={ 'console_scripts': [ 'pilfer = pilfer.pilfer:entry', 'pilferplay = pilfer.pilferplay:entryplay', ], } )
brackjoker/test_l1_pj_rp
scenario_tester.py
Python
apache-2.0
8,201
0.000366
import json import time import re import subprocess import collections import logging import signal from functools import partial from mininet.cli import CLI from mininet.node import RemoteController, OVSSwitch from mininet.net import Mininet from mininet.link import Link from mininet.link import Intf import patch_node...
el_shd_wire_flows_cmd = self._make_command( params, "delete-shared-wire-flows-command" ) except KeyError as err: msg = "Cannot find key:%s in test definition 'l1patch-defs' section." % err.message raise scenario_error.ScenarioTestDefinitionError(msg) def ...
est_env_params(self): try: params = self.testdef_data["test-env-params"] self.mn_ext_intfs = params["mininet-external-interfaces"] self.ofp_version = params["ofs-openflow-version"] except KeyError as err: msg = "Cannot find key:%s in test definition 'test-...
BeyondTheClouds/enoslib
enoslib/service/emul/schema.py
Python
gpl-3.0
4,444
0.0009
from jsonschema import Draft7Validator, FormatChecker CONSTRAINT_SCHEMA = { "type": "object", "description": {"Override constraints between specific groups"}, "properties": { "src": {"type": "string", "description": "Source group"}, "dst": {"type": "string", "description": "Destination gro...
x% loss """ if instance is None: return True if isinstance(instance, float) or isinstance(instance, int)
: return True if instance <= 1 and instance >= 0: return True return False @HTBFormatChecker.checks("ipv4") def is_valid_ipv4(instance): import ipaddress try: # accept ipv4 and ipv6 ipaddress.ip_interface(instance) return True except ipaddress.AddressValueE...
ToonTownInfiniteRepo/ToontownInfinite
toontown/racing/Piejectile.py
Python
mit
10,127
0.00158
import math import random from direct.showbase.PythonUtil import * from direct.showbase.DirectObject import DirectObject from direct.task import Task from pandac.PandaModules import * from direct.fsm import FSM from direct.distributed import DistributedSmoothNode from otp.avatar import ShadowCaster from otp.otpbase imp...
self.race.effectManager.addSplatEffect(spawner=self) taskMgr.remove(self.splat
TaskName) self.removeNode() def __updatePhysics(self, task): if self.deleting: return Task.done self.timeRatio = (globalClock.getFrameTime() - self.startTime) / self.maxTime self.windResistance.setCoef(0.2 + 0.8 * self.timeRatio) if base.cr.doId2do.get(self.targe...
paulscottrobson/string-trainer
resources/graphics/makeframes.py
Python
mit
1,078
0.080705
# # Notebutton graphics creator. # from PIL import Image,ImageDraw height
= 50 roundWidth = 40 y3d = 8 widthGroup = [ 0,10,25,40,66,75,100,150,200,250,300 ] for width in widthGroup: for offset3D in range(1,2): xl = 100+roundWidth/2 xr = xl + width yc = 100 im = Image.new("RGBA",(600,200),0x00000000) draw = ImageDraw.Draw(im) if (offset3D != 0): c1 = 0xFF808080 y = yc + y...
height/2,xr+roundWidth/2,y+height/2),fill = c1) draw.rectangle((xl,y-height/2,xr,y+height/2),fill = c1) c1 = 0xFFFFFFFF y = yc draw.ellipse((xl-roundWidth/2,y-height/2,xl+roundWidth/2,y+height/2),fill = c1) draw.ellipse((xr-roundWidth/2,y-height/2,xr+roundWidth/2,y+height/2),fill = c1) draw.rectangle((xl,y...
bundgus/python-playground
matplotlib-playground/examples/pylab_examples/print_stdout.py
Python
mit
233
0.004292
# -*- noplot -*- # print png to standard out # usage: python print_stdout.py > somefile.png import sys import matplotlib matplotlib.use(
'Agg') import matplotlib.pyplot as plt plt.plot([1, 2, 3]) plt.savefig(sy
s.stdout) plt.show()
teltek/edx-platform
openedx/core/djangoapps/user_api/validation/tests/test_views.py
Python
agpl-3.0
8,785
0.001594
# -*- coding: utf-8 -*- """ Tests for an API endpoint for client-side user data validation. """ import unittest import ddt from django.conf import settings from django.contrib.auth.models import User from django.urls import reverse from django.test.utils import override_settings from six import text_type from opened...
'username': username, 'email': email }, { "username": accounts.USERNAME_CONFLICT_MSG.format( username=user.username ) if username == use
r.username else '', "email": accounts.EMAIL_CONFLICT_MSG.format( email_address=user.email ) if email == user.email else '' } ) @ddt.data('', ('e' * accounts.EMAIL_MAX_LENGTH) + '@email.com') def test_email_bad_length_validation_decision(se...
Pinecast/pinecast
accounts/migrations/0007_auto_20160118_0017.py
Python
apache-2.0
726
0
# -*- coding: utf-8 -*- from __future__ import absolute_impo
rt # Generated by Django 1.9 on 2016-01-18 00:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies
= [ ('accounts', '0006_auto_20151218_1741'), ] operations = [ migrations.AddField( model_name='usersettings', name='stripe_customer_id', field=models.CharField(blank=True, max_length=128, null=True), ), migrations.AddField( model_...
melmorabity/streamlink
src/streamlink/plugins/livestream.py
Python
bsd-2-clause
1,433
0.000698
import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils.parse import parse_json log = logging.getLogger(__name__) @pluginmatcher(re.compile( r"https?://(?:www\.)?livestream\.com/" )) cla...
eam_info = parse_json(m.group(1), "config JSON", schema=self._stream_config_schema) log.trace("stream_info: {0!r}".format(stream_info)) if not (stream_info and stream_info["is_live"]): log.debug("Stream might be Off Air") return m3u8_url...
n__ = Livestream
kodexlab/reliure
reliure/pipeline.py
Python
lgpl-3.0
20,560
0.002919
#-*- coding:utf-8 -*- """ :mod:`reliure.pipeline` ========================= inheritance diagrams -------------------- .. inheritance-diagram:: reliure.pipeline Class ----- """ import logging from collections import OrderedDict from functools import wraps, update_wrapper from reliure.options import ValueOption cla...
name) @property def logger(self): self.init_logger() return self._logger def __or__(self, other): if not callable(other): raise ValueError("%r is not co
mposable with %r" % (self, other)) return Pipeline(self, other) def __and__(self, other): if not callable(other): raise ValueError("%r is not composable with %r" % (self, other)) return MapSeq(self, other) def __call__(self, *args, **kwargs): if hasattr(self, "_...
kgiusti/qpid-proton
python/examples/recurring_timer_tornado.py
Python
apache-2.0
1,383
0.002169
#!/usr/bin/env python # # 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 # "...
tornado import Container class Recurring(Handler): def __init__(self, period): self.period = period def on_reactor_init(self, event): self.container = event.container self.container.schedule(self.period, self) def on_timer_task(self, event): print("Tick...") self.c...
curring(1.0)) container.run() except KeyboardInterrupt: container.stop() print()
anttisalonen/freekick
src/tools/Python/stadium/stadium.py
Python
agpl-3.0
5,396
0.00315
#!/usr/bin/python import sys import re import types import random import lxml from lxml import etree from copy import deepcopy def usage(): print "Usage: %s countryfile regionname valuefile clubfile1 [clubfile2...]" % sys.argv[0] print " countryfile: XML file of the country" print " ...
True break if stadfound == False: coun
trystadiumnode = deepcopy(stadiumnode) stadiumcapacity = int(thisvalue**(2.1)/25)/100*100 capnode = etree.Element("capacity", value="%d" % stadiumcapacity) countrystadiumnode.append(capnode) ourregion.append(countrystadiumnode) stadiums.append(countrystadiumno...
the-zebulan/CodeWars
katas/kyu_6/reverse_or_rotate.py
Python
mit
350
0
def revrot(digits, n): if not n: return '' result = [] for a in xrange(0, len(digits) - n + 1, n): current = digits[a:a + n] if not sum(int(b) ** 3 for b in curre
nt) % 2: result.append(current[::-1]) else: result.append('{0
}{0}'.format(current)[1:n + 1]) return ''.join(result)
adammck/rapidsms-community-apps
patterns/admin.py
Python
bsd-3-clause
235
0.008511
#!/usr/bin/env py
thon # vim: ai ts=4 sts=4 et sw=4 from django.contrib import admin from patterns.models import * class PatternAdmin(admin.ModelAdmin): list_display = ['name', 'regex'] admin.site.register(Pattern, PatternAdmin
)
gedman4b/MachineLearning
coursera/KMeansClustering and PrincipalComponentAnalysis/recoverData.py
Python
gpl-3.0
934
0.004283
@mfunction("X_rec") def recoverData(Z=None, U=None, K=None): # RECOVERDATA Recovers an approximation of the original data when using the # projected data # X_rec = RECOVERDATA(Z, U, K) recovers an approximation the # original data that has been reduced to K dimensions. It returns the # ...
approximation of the data by projecting back # onto the original space using the top K eigenvectors in U. # # For the i-th example Z(i,:), the (approximate) # recovered data for dimension j is given as follows: # v = Z(i, :)'; # recovered_j = v' * U(j, 1:K)'; # # Notice that U(j,...
= U(mslice[:], mslice[1:K]) X_rec = Z * Ureduce.cT end
bird-house/pyramid-phoenix
phoenix/tests/conftest.py
Python
apache-2.0
542
0.012915
# -*- coding: utf-8 -*- import pytest # ``py.test --runslow`` causes the entir
e testsuite to be run, including test # that are decorated with ``@@slow`` (scaffolding tests). # see http://pytest.org/latest/example/simple.html#control-skipping-of-tests-according-to-comman
d-line-option # Noqa ## def pytest_addoption(parser): ## parser.addoption("--runslow", action="store_true", help="run slow tests") ## slow = pytest.mark.skipif( ## not pytest.config.getoption("--runslow"), ## reason="need --runslow option to run" ## )
naishe/mastering_cassandra
chapter_3/ch3_1.4.2.2_super_column_groups.py
Python
apache-2.0
1,706
0.017585
#! /usr/bin/env python ''' Demonstrates how simple group can be used as one-to-many relationship using a column family ''' import util from pycassa.columnfamily import ColumnFamily # Load data from data/movies def loadData(): con = util.getConnection() cf = ColumnFamily(con, 'videos') tagCF = ColumnFamily(con, ...
'''.format(username) for k, v in val.iteritems(): print '''\t{{{0}=> {1}}}'''.format(k, v) print ''' }''' con.dispose() if __name__ == '__main__': ge
tByTag('action')
martijnvermaat/wiggelen
setup.py
Python
mit
2,054
0.001947
import os from setuptools import setup import sys if sys.version_info < (2, 6): raise Exception('Wiggelen requires Python 2.6 or higher.') install_requires = [] # Python 2.6 does not include the argparse module. try: import argparse except ImportError: install_requires.append('argparse') # Python 2.6 do...
fo__': value = value.strip('[]()') value = '.'.join(x.strip(' \'"') for x in value.split(',')) else:
value = value.strip('\'"') distmeta[field] = value setup( name='wiggelen', version=distmeta['__version_info__'], description='Working with wiggle tracks in Python', long_description=long_description, author=distmeta['__author__'], author_email=distmeta['__contact__'], url=distmeta['__...
ensime/ensime-sublime
dependencies/sexpdata.py
Python
gpl-3.0
18,501
0.000324
# [[[cog import cog; cog.outl('"""\n%s\n"""' % file('README.rst').read()) ]]] """ S-expression parser for Python ============================== `sexpdata` is a simple S-expression parser/serializer. It has simple `load` and `dump` functions like `pickle`, `json` or `PyYAML` module. >>> from sexpdata import loads, du...
MENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NE
GLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __version__ = '0.0.3' __author__ = 'Takafumi Arakaki' __license__ = 'BSD License' __all__ = [ # API functions: 'load', 'loads', 'dump', 'dumps', # Utility functions: 'car', 'c...
rctk/rctk
rctk/layouts/grid.py
Python
bsd-2-clause
10,125
0.004642
from rctk.layouts.layouts import Layout, LayoutException import types import math class Cell(object): def __init__(self, o, row, column, rowspan=1, colspan=1, **options): self.o = o self.row = row self.column = column self.rowspan = rowspan self.colspan = colspan sel...
: # verify a space is available, possibly expanding the grid if self.columns is not None and colspan > self.columns: raise LayoutException("Colspan of %d too wide for grid with %d columns" % (colspan, self.columns)) if self.rows is not None and rowspan > self.rows: rais...
nto account! if self.columns is not None and column+colspan > self.columns: return False if self.rows is not None and row+rowspan > self.rows: return False for r in range(row, row+rowspan): for c in range(column, column+colspan): if self.grid....
shawncaojob/LC
QUESTIONS/132_palindrome_partitioning_ii.py
Python
gpl-3.0
1,362
0.008076
# 132. Palindrome Partitioning II QuestionEditorial Solution My Submissions # Total Accepted: 58982 # Total Submissions: 256833 # Difficulty: Hard # Given a string s, partition s such that every substring of the partition is a palindrome. # # Return the minimum cuts needed for a palindrome partitioning of s. # # Fo...
: return 0 dp = [ n + 1 for x in xrange(n) ] for i in xrange(n): # i Center, j center len print("i ", i) j = 0 while i - j >= 0 and i + j < n and s[i-j] == s[i+j]: dp[i+j] = min(dp[i+j], dp[i-j-1] + 1) if i - j - 1 >
= 0 else 0 print("1 ", i, j, s[i-j], s[i+j], dp) j += 1 j = 0 while i - j >= 0 and i + j + 1 < n and s[i - j] == s[i + j + 1]: dp[i+j+1] = min(dp[i+j+1], dp[i-j-1] + 1) if i - j - 1 >= 0 else 0 print("2 ", i, j, s[i-j],...
NamPNQ/rethinkengine
rethinkengine/__init__.py
Python
mit
962
0.002079
import rethinkdb as r VERSION = (0, 0, 1) def get_version(): if isinstance(VERSION[-1], basestring): return '.'.join(map(str, VERSION[:-1])) + VERSION[-1] return '.'.join(map(str, VERSION)) __version__ = get_version()
class RethinkEngine(object): _options = {} _connection = None _models = {} def __init__(self, **kwargs): conn_settings = { 'name': kwargs.get('db') or 'test', 'host': kwargs.get('host') or 'localhost', 'port': kwargs.get('port') or 28015, 'auth...
el(self, name, schema, **options): full_options = self._options.copy() for k in options: full_options[k] = options[k] if name in self._models: raise Exception("Cannot redefine a model")
mbdevpl/open-fortran-parser-xml
open_fortran_parser/dependencies.py
Python
apache-2.0
2,086
0.002876
"""Dependency downloader for open_fortran_parser.""" import logging import os import pathlib import platform import typing as t import urllib import wget _LOG = logging.getLogger(__name__) def ensure_dependencies( dependencies: t.Mapping[str, t.Tuple[urllib.parse.ParseResult, pathlib.Path]], target...
_LOG.warning('%s is present already.', dependen
cy) continue if not download: _LOG.warning('%s is not present!', dependency) continue url = urllib.parse.urlunparse(url_root) + str(filename) _LOG.warning('Downloading %s from URL "%s" to path "%s"...', dependency, url, path) wget.download(url, str(pat...
alessiodm/cloudbrain
cloudbrain/connectors/MockConnector.py
Python
agpl-3.0
1,191
0.024349
import time import random fro
m cloudbrain.connectors.ConnectorInterface import Connector from cloudbrain.utils.metadata_info import get_num_channels class MockConnector(Connector): def __init__(self, publ
ishers, buffer_size, device_name, device_port='mock_port', device_mac=None): """ :return: """ super(MockConnector, self).__init__(publishers, buffer_size, device_name, device_port, device_mac) self.data_generators = [self.data_generator_factory(metric, get_num_channels(self.device_name, metric)...
nisavid/bedframe
bedframe/http/__init__.py
Python
lgpl-3.0
292
0
"""Hypertext Transfer Protocol (HTTP)
These objects provide support for :rfc:`HTTP <2616>`. .. seealso:: :mod:`HTTP authentication <bedframe.auth.http>` """ __copyright__ = "Copyright (C) 2014 Ivan D Vasin" __docformat__ = "restructured
text" from ._exc import * from ._services import *
fnp/pylucene
test/test_Similarity.py
Python
apache-2.0
4,026
0.004223
# ==================================================================== # 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 re...
.0, score)
def setNextReader(_self, reader, docBase): pass def acceptsDocsOutOfOrder(_self): return True searcher.search(pq, collector4()) if __name__ == "__main__": import sys, lucene lucene.initVM() if '-loop' in sys.argv: sys.argv.remove('-loop') ...
guardicore/monkey
monkey/infection_monkey/system_info/windows_info_collector.py
Python
gpl-3.0
1,894
0.001584
import logging import sys from common.common_consts.system_info_collectors_names import MIMIKATZ
_COLLECTOR from infection_monkey.system_info.windows_cred_collector.mimikatz_cred_collector import ( MimikatzCredentialCollector, ) sys.coinit_flags = 0 # needed for proper destruction of the wmi python module import infection_monkey.config # noqa: E402 from infection_monkey.system_info import InfoCollector # n...
windows info collector") class WindowsInfoCollector(InfoCollector): """ System information collecting module for Windows operating systems """ def __init__(self): super(WindowsInfoCollector, self).__init__() self._config = infection_monkey.config.WormConfiguration def get_info(se...
joanma100/mieli
mieli/api/nexus.py
Python
agpl-3.0
1,322
0.006808
from mieli.api import organization from identity.models import Nexus from django.db import transaction from django.conf import settings from mieli import registry import slugify def get(**kwargs): try: nexus = Nexus.objects.get(**kwargs) except Nexus.DoesNotExist: nexus = None return nexus ...
def on_organization_creation(**kwargs): registry.signal('organization_init', **kwargs) create(settings.MAIN_NEXUS, kwargs['organization']) def auto_join(user, **kwargs): organization_ = organization.get_
by_username(user.username) nexus = organization_.main_nexus if nexus == None: raise Exception("main nexus '%s' doesn't exist" % settings.MAIN_NEXUS) nexus.join(user)
i32baher/practicas-iss
tubeworld/main/urls.py
Python
gpl-3.0
289
0.00346
from django.conf.urls import url, include, patterns from . import views from django.contrib.staticfiles.urls import st
aticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings urlpatterns = patterns('',
url(r'^$', views.index, name='index'), )
dmonn/socialize
socialize/services/kickstarter_service.py
Python
bsd-3-clause
346
0.011561
from .servic
e import Service class KickstarterService(Service): def get_supporters(self): r = self.get('kickstarter/') self.print_supporters(r) def print_supporters(self, s): for supporter in s: print("%-40s %s" % (str(supporter['name']), str(
supporter['message']))) kick = KickstarterService()
rodgzilla/project-euler
problem_050/problem.py
Python
gpl-3.0
1,428
0.002801
def eratosthene(n): l = range(2, n / 2 + 1) primes = set(range(2, n)) for number in l: if number in primes: current_multiple = 2 * number while current_multiple < n: if current_multiple in primes: primes.remove(current_multiple) ...
t "era fini" prime_list = list(primes) prime_list.sort() print "sort fini" len_longest_seq = [] for i in range(len(prime_list)): if i % 100 == 0: print "prime", i longest_seq_len = 0 current_prime_sum = prime_list[i] j = 1 while i + j <
len(prime_list) and current_prime_sum < max_value: current_prime_sum += prime_list[i + j] if current_prime_sum in primes: longest_seq_len = j + 1 j += 1 len_longest_seq.append(longest_seq_len) index_max = 0 for i in range(len(len_longest_seq)): ...
Azure/azure-linux-extensions
VMEncryption/main/oscrypto/rhel_72_lvm/encryptstates/UnmountOldrootState.py
Python
apache-2.0
7,716
0.004277
#!/usr/bin/env python # # VM Backup extension # # Copyright 2015 Microso
ft Corporation # # 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 agreed to in writing, software # dis...
ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Requires Python 2.7+ # import os import re import sys from time import sleep from OSEncryptionState import * class UnmountOldrootState(OSEncryptionState): def __init__(...
justinpotts/mozillians
mozillians/users/migrations/0042_auto__chg_field_externalaccount_type.py
Python
bsd-3-clause
12,259
0.008239
# -*- coding: 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): # Changing field 'ExternalAccount.type' db.alter_column('users_externalaccount', 'type', self.gf('django.db...
, 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}), 'url': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'blank': 'True'}) }, 'groups.skill': { 'Meta': {'ordering': "['name']", 'object_name'...
ooleanField', [], {'default': 'False'}), 'auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'Tr...
Delwddrylliwr/pebl-project
src/pebl/__init__.py
Python
mit
418
0.009569
# import sub-modules so they're in the namespace and available to # tab-completion in ipython import config, cp
d, data, discretizer, evaluator, network, posterior, prior, \ result, util import learner.base, learner.greedy, learner.custom, learner.simanneal, \ learner.exhaustive # BUT, don't import the taskcontroller su
b-modules because some of them are # optional features with extra dependencies.
thypad/brew
skensemble/selection/dynamic/dsknn.py
Python
mit
3,563
0
import numpy as np from brew.base import Ensemble from brew.metrics.diversity.paired import kuncheva_double_fault_measure from .base import DCS class DSKNN(DCS): """DS-KNN The DS-KNN selects an ensemble of classifiers based on their accuracy and diversity in the neighborhood of the test sample. ...
ouble_fault_measure(oracle[:, [i, j]]) tmp.append(d) div_
scores[i] = np.mean(tmp) z = zip(np.arange(len(ensemble)), acc_scores, div_scores) z = sorted(z, key=lambda e: e[1], reverse=True)[:n_sel_1] z = sorted(z, key=lambda e: e[2], reverse=False)[:n_sel_2] z = zip(*z)[0] classifiers = [classifiers[i] for i in z] return Ensemb...
Soundphy/diapason
diapason/tests/test_notes.py
Python
bsd-3-clause
2,727
0
""" Test diapason notes. """ import pytest from pytest import approx from diapason import note_frequency @pytest.mark.parametrize(('note', 'sharp', 'flat', 'octave', 'frequency'), [ # Exact frequencies (A) ('A', 0, 0, 4, 440.), ('A', 0, 0, 0, 27.5), ('A', 0, 0, 6, 1760.), # Different notes in the...
, 1, 0, 4, 311.127), ('E', 1,
0, 4, 349.228), ('F', 1, 0, 4, 369.994), ('G', 1, 0, 4, 415.305), ('A', 1, 0, 4, 466.164), ('B', 1, 0, 4, 523.251), # Flat ('C', 0, 1, 4, 246.942), ('D', 0, 1, 4, 277.183), ('E', 0, 1, 4, 311.127), ('F', 0, 1, 4, 329.628), ('G', 0, 1, 4, 369.994), ('A', 0, 1, 4, 415.305), ...
cndlhvn/pilotis
dmacro/fabfile.py
Python
gpl-3.0
780
0.02071
# -*- encoding:utf-8 -*- execfile("../config.py") execfile("../method.py") @task def dmacro_install(): """[1]dmacroのインストール""" if not contains(EMACS_FILE,";;;dmacro_setting"): dmacro_setting =""" ;;;dmacro_setting ;;繰り返したい処理をemacs上で2回以上繰り返す ;;C-tで繰り返せる (el-get-bun
dle dmacro :type http :url "http://www.pitecan.com/papers/JSSSTDmacro/dmacro.el") (defconst *dmacro-key* "\C-t" "繰返し指定キー") (global-set-key *dmacro-key* 'dmacro-exec) (autoload 'dmacro-exec "dmacro" nil t)""" file_appendln(EMACS_FILE,dmacro_setting) with cd(EMACS_DIR): run("emacs --batch --script init.el...
croのインストール")
wubr2000/googleads-python-lib
examples/dfp/v201502/label_service/get_all_labels.py
Python
apache-2.0
1,648
0.009102
#!/usr/bin/python # # Copyright 2015 Google Inc. 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 b...
bels by statement. while True: response = label_service.getLabelsByStatement(statement.ToStatement()) if 'results' in response: # Display results. for label in response['results']: print ('Label w
ith id \'%s\' and name \'%s\' was found.' % (label['id'], label['name'])) statement.offset += dfp.SUGGESTED_PAGE_LIMIT else: break print '\nNumber of results found: %s' % response['totalResultSetSize'] if __name__ == '__main__': # Initialize client object. dfp_client = dfp.DfpCli...
IuliiSe/openinterests.eu
openinterests/views/relations.py
Python
mit
468
0.002137
from flask import Blueprint, render_template, request from werkzeug.exce
ptions import NotFound from grano.lib.pager import Pager from grano.model import Relation relati
ons = Blueprint('relations', __name__, static_folder='../static', template_folder='../templates') @relations.route('/relations/<id>') def view(id): relation = Relation.by_id(id) if relation is None: raise NotFound() return render_template('relation.html', relation=relation)
codefisher/djangopress
djangopress/core/templatetags/smart_truncate_chars.py
Python
mit
330
0.012121
from django import template from djangopress.core.util import smart_truncate_chars as _smart_truncate_chars register = template.Library() # truncate chars but leaving last word complete @register.filter(name='smarttruncatechars') def smart_truncate_chars(value, max_length):
return _smart_truncate_chars(value, max_l
ength)
tomasdubec/openstack-cinder
cinder/scheduler/host_manager.py
Python
apache-2.0
10,868
0.000092
# Copyright (c) 2011 OpenStack, LLC. # 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 requi...
an authoritative list of what is permissible. This function checks the filter names against a predefined set of acceptable filters. """ if filter_cls_names is None: filter_cls_names = FLAGS.scheduler_default_filters if not isinstance(filter_cls_names, (list, tuple)): ...
for cls in self.filter_classes: if cls.__name__ == filter_name: found_class = True good_filters.append(cls) break if not found_class: bad_filters.append(filter_name) if bad_filters: msg ...
eerimoq/asn1tools
tests/files/etsi/cam_pdu_descriptions_1_3_2.py
Python
mit
19,027
0.008199
EXPECTED = {'CAM-PDU-Descriptions': {'extensibility-implied': False, 'imports': {'ITS-Container': ['AccelerationControl', 'CauseCode', 'CenDsrcTollingZone', ...
onal': True, 'type': 'VerticalAcceleration'}, {'name': 'performanceClass', ...
'type': 'PerformanceClass'}, {'name': 'cenDsrcTollingZone', 'optional': Tr...
Jeff-Tian/mybnb
Python27/Lib/test/test_smtplib.py
Python
apache-2.0
20,434
0.002251
import asyncore import email.utils import socket import smtpd import smtplib import StringIO import sys import time import select import unittest from test import test_support try: import threading except ImportError: threading = None HOST = test_support.HOST def server(evt, buf, serv): ...
pass else: n = 500 while buf and n > 0: r, w, e = select.select([], [conn], []) if w: sent = conn.send(buf) bu
f = buf[sent:] n -= 1 conn.close() finally: serv.close() evt.set() @unittest.skipUnless(threading, 'Threading required for this test.') class GeneralTests(unittest.TestCase): def setUp(self): self._threads = test_support.threading_setup() sel...
blueskycoco/rt-thread
bsp/nrf5x/nrf52840/rtconfig.py
Python
gpl-2.0
2,265
0.006623
import os # toolchains options ARCH='arm' CPU='cortex-m4' CROSS_TOOL='keil' if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') # cross_tool provides the cross compiler # EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR if CROSS_TOOL == 'gcc': PLATFORM = 'gcc' EX...
: PLATFORM = 'armcc' EXEC_PATH = 'C:/Keil_v5' elif CROSS_TOOL == 'iar': print('================ERROR============================') print(
'Not support iar yet!') print('=================================================') exit(0) if os.getenv('RTT_EXEC_PATH'): EXEC_PATH = os.getenv('RTT_EXEC_PATH') BUILD = 'debug' if PLATFORM == 'gcc': # toolchains PREFIX = 'arm-none-eabi-' CC = PREFIX + 'gcc' AS = PREFIX + 'gcc' AR = PR...
j00bar/ansible
lib/ansible/modules/cloud/amazon/elasticache_subnet_group.py
Python
gpl-3.0
5,426
0.007556
#!/usr/bin/python # This file is part of Ansible # # Ansible 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 # (at your option) any later version. # # Ansible is distributed...
if not region: module.fail_json(msg = str("Either region or AWS_REGION or EC2_REGION environment variable or boto config aws_region or ec2_region must be set.")) """Get an elasticache connection""" try: endpoint = "elasticache.%s.amazonaws.com" % region connect_region = RegionInfo(n...
n = ElastiCacheConnection(region=connect_region, **aws_connect_kwargs) except boto.exception.NoAuthHandlerFound as e: module.fail_json(msg=e.message) try: changed = False exists = False try: matching_groups = conn.describe_cache_subnet_groups(group_name, max_records...
radical-software/mongrey
mongrey/tests/storage/mongo/base.py
Python
bsd-3-clause
1,182
0.005076
# -*- coding: utf-8 -*- import unittest import os from mongoengine import connect from mongrey.storage.mongo import models from mongrey.utils import get_db_config from mongrey import cache from ...base import BaseTestCase def drop_all(): models.User.drop_collection() models.GreylistMetric.drop_collection()...
MongreyBaseTestCase(BaseTestCase): db_settings = { 'host': 'mongodb://localhost/mongrey_test', } de
f setUp(self): BaseTestCase.setUp(self) settings, storage = get_db_config(**self.db_settings) self._db = connect(**settings) self._cache = cache.configure_cache(cache_url='simple') drop_all() def tearDown(self): BaseTestCase.tearDown(self) if self._cache:...
Arabidopsis-Information-Portal/hrgrn_webservices
services/hrgrn_search_path_by_locus/exception.py
Python
gpl-2.0
1,942
0.004634
# HRGRN WebServices # Copyright (C) 2016 Xinbin Dai, Irina Belyaeva # This file is part of HRGRN WebServices API. # # HRGRN API is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public Licen
se as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # HRGRN API is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # ...
ith HRGRN API. If not, see <http://www.gnu.org/licenses/>. """ API Exception Module """ import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) log.setLevel(logging.INFO) no_geneID_parameter_error_msg = "No geneID/locus has been submitted!" no_geneID_error_msg = "No node informati...
pulilab/django-medialibrary
medialibrary/urls.py
Python
bsd-3-clause
450
0.011111
from django.conf.urls import patterns, url from .views import MediaLibraryAPIView, MediaLibraryItemView, AddShelfRelationAPIView urlpatterns = patterns('', url(r'^(?P<type>(audio|video|image))/$', MediaLibraryAPIVi
ew.as_view(), name='media
library'), url(r'^(?P<pk>\d+)/$', MediaLibraryItemView.as_view(), name='medialibrary-shelf'), url(r'^(?P<pk>\d+)/add/$', AddShelfRelationAPIView.as_view(), name='medialibrary-shelf-add-relation') )
jneilaglez/hello-world
mymodule.py
Python
lgpl-3.0
373
0
""" Module that delete file of system. """ import os impor
t dbm import os.path def rm(filename): """ Function for deleting a f
ile :param filename: path of file :return: none """ x = 6 if os.path.isfile(filename): os.remove(filename) elif x < 5: print("hola") def print_log_data(data): for x in data: print(x)
zenx/xhtml2pdf
tests/test_utils.py
Python
apache-2.0
8,136
0.011185
#-*- coding: utf-8 -*- from reportlab.lib.colors import Color from unittest import TestCase from xhtml2pdf.util import getCoords, getColor, getSize, getFrameDimensions, \ getPos, getBox from xhtml2pdf.tags import int_to_roman class UtilsCoordTestCase(TestCase): def test_getCoords_simple(self): ...
ssertEqual(res, 12.00) def test_get_size_for_tuple(self): # TODO: This is a really strange case. Probably should not work this way. res = getSize(("12", ".12")) self.assertEqual(res, 12.12) def test_get_size_for_cm(self): res = getSize("1cm") self.assert...
et_size_for_mm(self): res = getSize("1mm") self.assertEqual(res, 2.8346456692913385) def test_get_size_for_i(self): res = getSize("1i") self.assertEqual(res, 72.00) def test_get_size_for_in(self): res = getSize("1in") self.assertEqual(res, 72.00)...
ahnitz/pycbc
pycbc/workflow/core.py
Python
gpl-3.0
87,602
0.001518
# Copyright (C) 2013, 2017 Ian Harry, Alex Nitz, Duncan Brown # # 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 of the License, or (at your # option) any later version. # # Thi...
the
Job from # the Executable time_dependent_options = [] # This is the default value. It will give a warning if a class is # used where the retention level is not set. The file will still be stored KEEP_BUT_RAISE_WARNING = 5 _warned_classes_list = ['Executable'] # Sub classes, or instances, ...
magul/magulbot
magulbot/magulbot/urls.py
Python
mit
765
0
"""magulbot URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2
. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]
malenkiki/team
team.py
Python
mit
3,108
0.0074
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2013 Michel Petit <petit.michel@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 # w...
s.stderr.write('Translation not implemented yet!\n') sys.stderr.write(e.strerror + '\n') def main(): parser = optpars
e.OptionParser(version="%prog " + APP_VERSION) parser.add_option("-t", "--token", dest="token", help=_("Token you must get from your administrator or by your settings page on Ruche web site you are using."), metavar=_("STRING")) parser.add_option("-u", "--url", dest="url", help=_("URL base to use for the reques...
cloudera/hue
desktop/core/ext-py/lxml-3.3.6/src/lxml/tests/test_builder.py
Python
apache-2.0
954
0.006289
# -*- coding: utf-8 -*- import unittest """ Tests that ElementMaker works properly. """ import sys, os.path from lxml import etree from lxml.builder import E this_dir = os.path.dirname(__file__) if this_dir not in sys.path: sys.path.insert(0, this_dir) # needed for Py3 from common_imports import HelperTestCase,...
tes('<b>Hello</b>'), etree.tostring(wrapped)) def test_unknown_type_raises(self): class UnknownType(object): pass self.assertRaises(TypeError, E.b, UnknownType()) def test_suite(): suite = unittest.TestSuite() suite.addTests([unittest.makeSuite(BuilderTestCase)]) return su...
e if __name__ == '__main__': print('to test use test.py %s' % __file__)
respawner/peering-manager
peering_manager/api/metadata.py
Python
apache-2.0
2,404
0.001248
from django.core.exceptions import PermissionDenied from django.http import Http404 from django.utils.encoding import force_str from rest_framework import exceptions from rest_framework.metadata import SimpleMetadata from rest_framework.request import clone_request from peering_manager.api import ContentTypeField cl...
actions[method] = self.get_serializer_info(serializer) finally: view.request = request return actions class ContentTypeMetadata(BulkOperationMetadata): def get_field_info(self, field): field_info = super().get_field_info(field) if ( ha...
"choices"] = [ { "value": choice_value, "display_name": force_str(choice_name, strings_only=True), } for choice_value, choice_name in field.choices.items() ] field_info["choices"].sort(key=lambda item: item["...
javivi001/horus
src/horus/engine/board.py
Python
gpl-2.0
7,274
0.025853
#!/usr/bin/python # -*- coding: utf-8 -*- #-----------------------------------------------------------------------# # # # This file is part of the Horus Project # # ...
# # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS F
OR A PARTICULAR PURPOSE. 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...
tensorflow/tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_xent_op_test.py
Python
apache-2.0
4,996
0.008006
# 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...
r(sess, ops): # Warm in for _ in range(20): sess.run(ops) # Timing run start = time.time() for _ in range(20): sess.run(ops) end = time.time() return (end - start) / 20.0 # Average runtime per iteration # Using sparse_to_dense and softmax_cross_entropy_with_logits with se...
se_vs_dense_xent_benchmark_dense(labels, logits) else: ops = _sparse_vs_dense_xent_benchmark_dense(labels, logits) delta_dense = _timer(sess, ops) # Using sparse_softmax_cross_entropy_with_logits with session.Session(config=config) as sess: if not use_gpu: with test_util.device("/cpu:0"): ...
dycodedev/taiga-back
taiga/projects/notifications/utils.py
Python
agpl-3.0
6,784
0.003097
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014 David Barragán <bameda@dbarragan.com> # Copyright (C) 2014 Anler Hernández <hello@anler.me> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
/>. from django.apps import apps from .choices import NotifyLevel from taiga.base.utils.text import strip_lines def attach_watchers_to_queryset(queryset, as_field="watchers"): """Attach watching user ids to each object of the queryset. :param queryset: A Django queryset object. :param as_field: Attach th...
l `as_field` field. """ model = queryset.model type = apps.get_model("contenttypes", "ContentType").objects.get_for_model(model) sql = ("""SELECT array(SELECT user_id FROM notifications_watched WHERE notifications_watched.content_type_id = {type_id}...
IfcOpenShell/IfcOpenShell
src/ifcopenshell-python/ifcopenshell/api/root/copy_class.py
Python
lgpl-3.0
4,290
0.003263
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell 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 Foundat...
IfcOpenShell. If n
ot, see <http://www.gnu.org/licenses/>. import ifcopenshell import ifcopenshell.util.element class Usecase: def __init__(self, file, **settings): self.file = file self.settings = {"product": None} for key, value in settings.items(): self.settings[key] = value def execute(...
duthils/osmose-frontend
control.py
Python
gpl-3.0
9,292
0.004843
#! /usr/bin/env python #-*- coding: utf-8 -*- ########################################################################### ## ## ## Copyrights Etienne Chové <chove@crans.org> 2009 ## ## ...
urce, age, country, analyser) = (res[0], res[1], res[2], res[3]) if age: if age >= 0: # TRANS
LATORS: days / hours / minutes since last source update, abbreviated to d / h / m txt = _("{day}d, {hour}h, {minute}m ago").format(day=int(age/86400), hour=int(age/3600)%24, minute=int(age/60)%60) else: txt = _("in {day}d, {hour}h, {minute}m").format(day=int(-age/86400), hour...
gusDuarte/sugar
extensions/cpsection/datetime/model.py
Python
gpl-2.0
2,833
0.000353
# Copyright (C) 2007, 2008 One Laptop Per Child # # 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 version. # # This program is di...
'GMT%d' % offset elif offset > 0: tz = 'GMT+%d' % offset else: tz = 'GMT' timezones.append(tz) for offset in xrange(-12, 13): if offset < 0: tz = 'UTC%d' % offset elif offset > 0: tz = 'UTC+%d' % offset else: ...
t.get_default() return client.get_string('/desktop/sugar/date/timezone') def print_timezone(): print get_timezone() def set_timezone(timezone): """Set the system timezone timezone : e.g. 'America/Los_Angeles' """ timezones = read_all_timezones() if timezone in timezones: os.envir...
vinokurov/salty_tickets
migration/003_salty_recipes_pol_sara.py
Python
mit
2,065
0.002428
import datetime from salty_tickets import database from salty_tickets import models from salty_tickets import products import json # Delete existing products event = models.Event.query.filter_by(event_key='salty_recipes_with_pol_sara').one() for product in event.products: database.db_session.delete(product) data...
20}', workshop_date='29-July-2017', workshop_time='10:30 till 13:00, workshop time: 2h', workshop_level='Improvers/Intermediate', workshop_price='£25 per person, £20 if book both aerial workshops' ).model ) event.products.append( products.CouplesOnlyWorkshop(
name='Aerials Lunch', info='Saturday morning aerials workshop with Pol & Sara. Duration: 2h. Intermediate level. ' 'We allow signs up with partners only.', max_available=20, price=25, discount_prices='{"aerials_full_day": 20}', workshop_date='29-July-2017', ...
CompassionCH/compassion-modules
res_country_statistics/__manifest__.py
Python
agpl-3.0
2,310
0.000433
############################################################################## # # ______ Releasing children from poverty _ # / ____/___ ____ ___ ____ ____ ___________(_)___ ____ # / / / __ \/ __ `__ \/ __ \/ __ `/ ___/ ___/ / __ \/ __ \
# / /___/ /_/ / / / / / / /_/ / /_/ (__ |__ ) / /_/ / / / / # \____/\____/_/ /_/ /_/ .___/\__,_/____/____/_/\____/_/ /_/ # /_/ # in Jesus' name # # Copyright (C) 2021 Compassion CH (http://www.compassion.ch) # @author: David Wulliamoz <dwulliamoz@compassi...
daweim0/Just-some-image-features
lib/networks/net_labeled_features_deeper.py
Python
mit
16,354
0.003975
import tensorflow as tf from networks.network import Network from fcn.config import cfg zero_out_module = tf.load_op_library('lib/triplet_flow_loss/triplet_flow_loss.so') class custom_network(Network): def __init__(self): self.inputs = cfg.INPUT # self.input_format = input_format self.num...
ed('left_labels_2x_avg').round().cast(tf.int32, name="left_labels_2x") self.feed('left_labels_4x_avg').round().cast(tf.int32, name="left_labels_4x") self.feed('left_labels_8x_avg').round().cast(tf.int32, name="left_labels_8x") self.feed('left_labels_16x_avg').round().cast(tf.int32, n...
(self.feed('right_labels').cast(tf.float32) .avg_pool(2, 2, 2, 2, name='right_labels_2x_avg') .avg_pool(2, 2, 2, 2, name='right_labels_4x_avg') .avg_pool(2, 2, 2, 2, name='right_labels_8x_avg') .avg_pool(2, 2, 2, 2, name='right_labels_16x_avg')) self.f...
jonasjberg/autonameow
autonameow/extractors/metadata/__init__.py
Python
gpl-2.0
1,177
0
# -*- coding: utf-8 -*- # Copyright(c) 2016-2020 Jonas Sjöberg <autonameow@jonasjberg.com> # Source repository: https://github.com/jonasjberg/autonameow # # This file is part of autonameow. # # autonameow is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public L...
rranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with autonameow. If not, see <http://www.gnu.org/licenses/>. from .extractor_crossplatform import Cross
PlatformFileSystemExtractor from .extractor_epub import EpubMetadataExtractor from .extractor_exiftool import ExiftoolMetadataExtractor from .extractor_filetags import FiletagsMetadataExtractor from .extractor_guessit import GuessitMetadataExtractor from .extractor_jpeginfo import JpeginfoMetadataExtractor from .extrac...
ianstalk/Flexget
flexget/tests/exec.py
Python
mit
848
0.001179
""" This is a helper script to call from test_exec.py It requires 2 arguments, the output directory and filename. A file will be created in the output directory with the given filename. If there are more arguments to the script, they will be written 1 per line to the file. """ import os import sys if __name__ == "__ma...
') as outfile: for arg in sys.argv[3:]: outfile.write(arg + '\n'
)
jat255/hyperspy
hyperspy/tests/model/test_model_as_dictionary.py
Python
gpl-3.0
8,873
0
# -*- coding: utf-8 -*- # Copyright 2007-2022 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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 # (at y...
umerate(c.parameters): assert p.as_dictionary() == d['parameters'][ip] c.active_is_multidimensional = True d1 = c.as_dictionary() assert d1['active_is_multidimensional'] np.testing.assert_array_equal(d1['_active_array'], c._active_array) def test_load_dictionary(self): ...
unction_expr = "x - 2" d = c.as_dictionary(True) n = Component(self.parameter_names) n._id_name = 'dummy names yay!' _ = n._load_dictionary(d) assert c.name == n.name assert c.active == n.active assert ( c.active_is_multidimensional == n.a...
necaris/embedded-js-in-python-example
setup.py
Python
mit
1,216
0
import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.md')) as f: README = f.read() with open(os.path.join(here, 'CHANGES.md')) as f: CHA
NGES = f.read() requires = [ 'pyramid', 'pyramid_jinja2', 'pyramid_debugtoolbar', 'pyramid_tm', 'SQLAlchemy', 'transaction', 'zope.sqlalchemy', 'waitress', ] setup(name='guestbook', version='0.1', description='guestbook', long_description=README + '\n\n' +
CHANGES, classifiers=[ "Programming Language :: Python :: 3", "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], author='', author_email='', url='', keywords='web wsgi bfg pylons ...
bsmr-eve/Pyfa
eos/effects/shipbonusshtfalloffgf2.py
Python
gpl-3.0
328
0.006098
# shipBonusSHTFalloffGF2 # # Used by: # Ship: Atron # Ship: Daredevil type = "passive" def handler(fit, ship, context): fit.modules.filtere
dItemBoost(lambda mod: mod.item.requiresSkill("Small Hybrid Turret"),
"falloff", ship.getModifiedItemAttr("shipBonusGF2"), skill="Gallente Frigate")
Narrato/mongotron
mongotron/Collection.py
Python
bsd-2-clause
251
0.003984
from __future__ im
port absolute_import from pymongo.collection import Collection as PymongoCollection from .Cursor import Cursor class Collection(PymongoCollection): def find(self, *args, **kwargs): return Cursor(self, *arg
s, **kwargs)
fams/rabbitmq-tutorials
python-puka/worker.py
Python
apache-2.0
575
0.003478
#!/usr
/bin/env python import puka import time client = puka.Client("amqp://localhost/") promise = client.connect() client.wait(promise) promise = client.queue_declare(queue='task_queue', durable=True) client.wait(promise) print ' [*] Waiting for messages. To exit press CTRL+C' consume_promise = client.basic_consume(queue...
'task_queue', prefetch_count=1) while True: msg_result = client.wait(consume_promise) body = msg_result['body'] print " [x] Received %r" % (body,) time.sleep( body.count('.') ) print " [x] Done" client.basic_ack(msg_result)
harikishen/addons-server
src/olympia/migrations/645-collection-backfill-slugs.py
Python
bsd-3-clause
141
0
fr
om mkt.collections.models import Collection
def run(): """Backfill slugs.""" for c in Collection.objects.all(): c.save()
anntzer/numpy
numpy/polynomial/tests/test_classes.py
Python
bsd-3-clause
18,331
0.000218
"""Test inter-conversion of different polynomial classes. This tests the convert and cast methods of all the polynomial classes. """ import operator as op from numbers import Number import pytest import numpy as np from numpy.polynomial import ( Polynomial, Legendre, Chebyshev, Laguerre, Hermite, HermiteE) from ...
t_almost_equal(p2(x), p1(x)) def test_cast(Poly1, Poly2): x = np.linspace(0, 1, 10) coef = random((3,)) d1 = Poly1.domain + random((2,))*.25 w1 = P
oly1.window + random((2,))*.25 p1 = Poly1(coef, domain=d1, window=w1) d2 = Poly2.domain + random((2,))*.25 w2 = Poly2.window + random((2,))*.25 p2 = Poly2.cast(p1, domain=d2, window=w2) assert_almost_equal(p2.domain, d2) assert_almost_equal(p2.window, w2) assert_almost_equal(p2(x), p1(x)) ...
aajanki/yle-dl
tests/utils.py
Python
gpl-3.0
2,189
0.00137
import sys import json from datetime import timedelta, tzinfo from io import BytesIO from yledl import execute_action, StreamFilters, IOContext, StreamAction, RD_SUCCESS from yledl.io import random_elisa_ipv4 from yledl.http import HttpClient from yledl.titleformatter import TitleFormatter # Context manager for captu...
('UTF-8').splitlines()) del self._bytesio # free up some memory sys.stdout = self._stdout class FixedOffset(tzinfo): def __init__(self, offset_hours): self._
_offset = timedelta(hours=offset_hours) def utcoffset(self, dt): return self.__offset def tzname(self, dt): return 'FixedOffset' def dst(self, dt): return timedelta(0) def fetch_title(url, filters=StreamFilters()): return fetch(url, StreamAction.PRINT_STREAM_TITLE, filters) ...
kiddinn/plaso
tests/parsers/docker.py
Python
apache-2.0
4,229
0.001892
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the Docker JSON parser.""" import unittest from plaso.lib import definitions from plaso.parsers import docker from tests.parsers import test_lib class DockerJSONUnitTest(test_lib.ParserTestCase): """Tests for the Docker JSON parser.""" def testParseC...
orage_writer.GetEvents()) expected_timestamps = [ '2016-01-07 16:49:10.000000', '2016-01-07 16:49:10.200000', '2016-01-07 16:49:10.230000', '2016-01-07 16:49:10.237000', '2016-01-07 16:49:10.237200', '2016-01-07 16:49:10.237220', '2016-01-07 16:49:10.237222',...
-01-07 16:49:10.237222'] expected_event_values = { 'container_id': container_identifier, 'data_type': 'docker:json:container:log', 'log_line': ( '\x1b]0;root@e7d0b7ea5ccf: ' '/home/plaso\x07root@e7d0b7ea5ccf:/home/plaso# ls\r\n'), 'log_source': 'stdout'} ...
jasonzliang/dcs
test_tasks/square.py
Python
unlicense
158
0.012658
#!/
usr/bin/env python import sys, time, random # print >> sys.stderr, sys.argv n = int(sys.argv[1]) sys.stdout.write(str(n*n)) sys.stdout.flush() sys.exit
(0)
Vauxoo/e-commerce
website_sale_product_brand/tests/test_ui.py
Python
agpl-3.0
499
0
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). from odoo.tests.common import HttpCase class UICase(HttpCase): def test_ui_website(self): """Test frontend tour.""" tour = "website_sale_product_brand" self.phantom_js( url_path="/shop", code="odoo._...
".tours.%s.ready" % tour)
larsbutler/coveragepy
coverage/xmlreport.py
Python
apache-2.0
7,340
0.000272
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt """XML reporting for coverage.py""" import os import sys import time import xml.dom.minidom from coverage import __url__, __version__, files from coverage.report ...
xline.setAttribute( "condition-coverage", "%d%% (%d/%d)" % (100*taken/total, taken, total) ) if line in missing_branch_arcs: annlines = ["exit" if b < 0
else str(b) for b in missing_branch_arcs[line]] xline.setAttribute("missing-branches", ",".join(annlines)) xlines.appendChild(xline) class_lines = len(analysis.statements) class_hits = class_lines - len(analysis.missing) if self.arcs: class_branches...
bokeh/bokeh
tests/unit/bokeh/model/test_model.py
Python
bsd-3-clause
9,709
0.003296
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
------------------------------------ # Imports #----------------------------------------------------------------------------- # Bokeh imports from bokeh.core.properties import Int, List, String from bokeh.models import * # NOQA from bokeh.models import CustomJS from bokeh.plotting import * # NOQA from bo
keh.document import document # isort:skip # Module under test from bokeh.model import Model # isort:skip #----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- #---------------------------------------------...
Petr-By/qtpyvis
qtgui/widgets/logging.py
Python
mit
5,929
0.001012
# standard imports import os import logging import traceback # Qt imports from PyQt5.QtCore import pyqtSignal, pyqtSlot from PyQt5.QtWidgets import QPlainTextEdit # toolbox imports from dltb.util.debug import edit # GUI imports from ..utils import protect # logging LOG = logging.getLogger(__name__) class QLogHa...
LOG.info(f"Edit command returned: {retcode}") except OSError as error: LOG.error(f"Edit command failed: {error}") class QExceptionView(QPlainTextEdit): """A view for Python exceptions. This is basically a text field in which a :py:class:`BaseException` can be displayed, ...
self.setReadOnly(True) self._exception = None self._traceback = None def setException(self, exception: BaseException) -> None: """Set the :py:class:`BaseException` to be displayed in this :py:class:`QExceptionView` """ self._exception = exception self._trace...
hnakamur/django-bootstrap-table-example
project/bookmarks/management/commands/import_bookmarks.py
Python
mit
1,584
0.002525
from datetime import datetime from html.parser import HTMLParser from django.core.management.base import BaseCommand, CommandError from django.db.utils import IntegrityError from django.utils import timezone from bookmarks.models import Bookmark def unixtime2datetime(t): dt = datetime.fromtimestamp(int(t)) re...
bookmark.save() except IntegrityError: pass def import_bookmarks(html_file): with open(html_file, 'r') as f: parser = MyHTMLParser() for chunk in f: parser.feed(chunk) class Command(BaseCommand): help = 'import delicious format html bookmarks...
add_argument('html_file', nargs=1, type=str) def handle(self, *args, **options): html_file = options['html_file'][0] import_bookmarks(html_file)
irisSchaffer/component-based-asteroids
State/SessionHandler.py
Python
apache-2.0
702
0.002849
''' Created on 24.01.2015 @author: Iris ''' from Component.Component import Component from Network import xprotocol from IdleState import IdleState class SessionHandler(Component): d
ef __init__(self): Component.__init__(self) self.state =
None self.peers = set() self.num_players = 2 def activate(self): Component.activate(self) xprotocol.add_connection_listener(self._onConnection) self.state = IdleState(self) def deactivate(self): xprotocol.remove_connection_listener(self._onConnection) Co...
darrenbilby/grr
client/vfs_handlers/memory.py
Python
apache-2.0
2,466
0.006488
#!/usr/bin/env python """VFS Handler which provides access to the raw physical memory. Memory access is provided by use of a special driver. Note that it is preferred to use this VFS handler rather than directly access the raw handler since this handler protects the system from access to unmapped memory regions such a...
ient as rdf_client from grr.lib.rdfvalues import paths as rdf_paths from grr.lib.rdfvalues import rekall_types as rdf_rekall_types class MemoryVFS(vfs.VFSHandler): ""
"Access memory via the GRR Client VFS abstraction.""" page_size = 0x1000 supported_pathtype = rdf_paths.PathSpec.PathType.MEMORY auto_register = True def __init__(self, base_fd, pathspec=None, progress_callback=None, full_pathspec=None): super(MemoryVFS, self).__init__(None, progress_callba...
trishika/home-monitor
rulesRestServer.py
Python
gpl-3.0
3,020
0.036105
#!/usr/bin/env python2.7 # -*- encoding: utf-8 -*- """ Home-rest ~~~~~~~~~ :copyright: (c) 2013 by Aurélien Chabot <aurelien@chabot.fr> :license: LGPLv3, see COPYING for more details. """ try: from flask import Flask, request, abort, json from subprocess import call, Popen, PIPE from traceback impor...
n.dumps({}) # Add one rule @app.route("/rules/", methods = ["POST"]) def add_rule(): try: c = db.cursor() c.execute('''INSERT INTO rules ( switch_host, switch_id, sensor_host, sensor_id, start_time, end_time, temp) VALUES (:switch_host, :switch_id, :sensor_host, :sensor_id, :start_time, :end_time, ...
" : request.form["switch_host"], "switch_id" : request.form["switch_id"], "sensor_host" : request.form["sensor_host"], "sensor_id" : request.form["sensor_id"], "start_time" : request.form['start_time'], "end_time" : request.form['end_time'], "temp" : request.form['temp']}) db.commit() except: print_exc() ...
karllessard/tensorflow
tensorflow/python/keras/preprocessing/sequence_test.py
Python
apache-2.0
9,727
0.003084
# Copyright 2016 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...
label=['a', 'b', ['c', 'd
']]) self.assertEqual(new_seq, [[[1, 1]], [[2, 1], [2, 2]]]) self.assertEqual(new_label, ['a', 'b']) def test_TimeseriesGenerator(self): data = np.array([[i] for i in range(50)]) targets = np.array([[i] for i in range(50)]) data_gen = preprocessing_sequence.TimeseriesGenerator( data, tar...
psyhomb/malioglasi
malioglasi.py
Python
gpl-2.0
6,894
0.014941
#!/usr/bin/python2 -tt # Author: Milos Buncic # Date: 29.06.2014 # Description: Search for specific article on the specific web page and send an email if you found something import os import sys import re import json import smtplib import requests from telegram import Bot from bs4 import BeautifulSoup from ConfigParse...
uration file for m,n in search.items(): company = n.split('-')[0].strip() model = n.split('-')[1].strip() subject = 'Mobilnisvet - %s %s' % (company, model) d = phoneInfo(url, company, model) if not d: print 'Could not find model %s %s' % (company, model) continue text = '' ...
\n' text = text.encode('utf-8') # Check if there is any blacklisted or whitelisted keywords in the text if filters['black_enabled'] == 'yes' and filters['white_enabled'] == 'no' and keywordMatch(text, bkw): continue elif filters['white_enabled'] == 'yes' and filters['black_enabled'] == 'no' and ...
sporteasy/sporteasy_breaking_mvc
sporteasy_breaking_mvc/core/models.py
Python
mit
665
0.001504
from django.db import models class EventTeam(models.Model): name = models.CharField(max_length=100) class Event(models.
Model): team1 = models.ForeignKey(EventTeam, null=True, related_name='opponent1') team2 = models.ForeignKey(EventTeam, null=True, related_name='opponent2') start_at = models.DateTimeField(null=True, blank=True) day = models.ForeignKey('ChampionshipDay', related_name='events', null=True) class Champion...
ionship(models.Model): name = models.CharField(max_length=100)
anhstudios/swganh
data/scripts/templates/object/static/structure/naboo/shared_elevated_walkway_s02.py
Python
mit
456
0.048246
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object
import * def create(kernel): result = Static() result.template = "object/static/structure/naboo/shared_elevated_walkway_s02.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICA
TIONS #### return result
DySense/DySense
dysense/gui/controller_view_widget_designer.py
Python
gpl-3.0
25,436
0.003813
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'controller_view_widget_designer.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError:...
tatus_label = QtGui.QLabel(controller_view) font = QtGui.QFont() font.setPointSize(16) self.session_status_label.setFont(font) self.session_status_label.setObjectName(_fromUtf8("session_status_label")) self.horizontalLayout.addWidget(self.session_status_label) spacerItem1...
cerItem1) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) spacerItem2 = QtGui.QSpacerItem(5, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self....
qwv/alpha-monkey
surface/website/console/apps.py
Python
gpl-3.0
154
0
#
-*- coding: utf-8 -*- from __future__ import unicode_literals from django.ap
ps import AppConfig class ConsoleConfig(AppConfig): name = 'console'
blzr/enigma2
lib/python/Screens/Setup.py
Python
gpl-2.0
5,693
0.023362
from Screen import Screen from Components.ActionMap import NumberActionMap from Components.config import config, ConfigNothing, ConfigBoolean, ConfigSelection from Components.Label import Label from Components.SystemInfo import SystemInfo from Components.ConfigList import ConfigListScreen from Components.Pixmap import ...
t or "") if b == "": continue #add to configlist item = b # the first b is the item itself, ignored by the configList. # the second one is converted to string. if not isinstance(ite
m, ConfigNothing): self.list.append((item_text, item, item_description)) self["config"].setList(self.list) if config.usage.sort_settings.value: self["config"].list.sort() self.moveToItem(currentItem) def moveToItem(self, item): if item != self["config"].getCurrent(): self["config"].setCurrentIndex(...
ashutoshvt/psi4
psi4/driver/procrouting/dft/dft_builder.py
Python
lgpl-3.0
19,632
0.003566
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package # # Copyright (c) 2007-2021 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files. # # This file is part of Psi4. # # Psi4 is free software; you can redistribute it and/or modify #...
ormat, printed in
output "description": "", description of the method, printed in output "xc_functionals": { definition of a full XC functional from LibXC "XC_METHOD_NAME": {} must match a LibXC method, see libxc_functionals.py for examples }, if present, the x/c_functional...
elifesciences/elife-metrics
src/article_metrics/events.py
Python
gpl-3.0
1,616
0.00495
from article_metrics import models, utils import json from django.conf import settings import
boto3 import logging LOG = logging.getLogger(__name__) def sns_topic_arn(**overrides): "returns an arn path to an AWS event bus. this is used to connect and send/receive events" vals
= {} vals.update(settings.EVENT_BUS) vals.update(overrides) # ll: arn:aws:sns:us-east-1:112634557572:bus-articles--ci arn = "arn:aws:sns:{region}:{subscriber}:{name}--{env}".format(**vals) LOG.info("using topic arn: %s", arn) return arn # # # def event_bus_conn(**overrides): sns = boto3.r...
vandenheuvel/tribler
Tribler/community/tradechain/block.py
Python
lgpl-3.0
177
0
from Trib
ler.community.trustchain.block import TrustChainBlock class TradeChainBlock(TrustChainB
lock): """ Container for TradeChain block information """ pass
andipla/autosub
src/plugins/vels_ob/test/test_pin.py
Python
gpl-2.0
768
0
# coding: utf-8 """ HDL Testing Platform REST API for HDL TP # noqa: E501 OpenAPI spec version: 1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import s
wagger_client from swagger_client.models.pin import Pin # noqa: E501 from swagger_client.rest import ApiException class TestPin(unittest.
TestCase): """Pin unit test stubs""" def setUp(self): pass def tearDown(self): pass def testPin(self): """Test Pin""" # FIXME: construct object with mandatory attributes with example values # model = swagger_client.models.pin.Pin() # noqa: E501 pass ...
TrailingDots/ListeningPort
listeningPort.py
Python
gpl-3.0
6,416
0.000312
#!/bin/env python # Documentation: Please see the usage() function below! import sys import subprocess import platform import psutil # Default ZeroMQ port PORT = 5570 def is_listening(port): """ More proper boolean operator for easier reading. return 1 # Indicate a found listener return 0 ...
inate() # Kill the process. return 1 # Branch on requested output if shortened: sys.stdout.write('%s %s %s\n' % (str(port), pid, ' '.join(items[5:]))) elif pid_only: sys.stdout.write('%s\n' % pid) elif proc_only: ...
sys.stdout.write('Port %s : listening thru pid %s %s\n' % (str(port), pid, ' '.join(items[5:]))) return 1 return 0 def usage(): """Write a usage statment and exit.""" sys.stderr.write(""" List the processes that are listening to a port. Defaults to Z...
GitOnion/climate-commander
django-server/climate_commander/jobs/migrations/0011_jobrunningonserver_result_nums.py
Python
mit
461
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-08-22 20:40 from __future__ import uni
code_literals from django.db import migrations, models class Migration(migrations.Migration): dependencie
s = [ ('jobs', '0010_auto_20160822_1332'), ] operations = [ migrations.AddField( model_name='jobrunningonserver', name='result_nums', field=models.IntegerField(null=True), ), ]
richbrowne/f5-cccl
f5_cccl/resource/ltm/app_service.py
Python
apache-2.0
7,050
0
"""Provides a class for managing BIG-IP Application Service resources.""" # coding=utf-8 # # Copyright 2017 F5 Networks 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....
me, partition, **properties): super(ApiApplicationService, self).__init__(name, partition, **properties) members = [] if 'poolMemberTable' in properties: members = properties['pool...
self._data["variables"] = self._iapp_build_variables(properties) self._data["tables"] = self._iapp_build_tables(members, properties) def _iapp_build_variables(self, config): """Create a list of name-value objects.""" variables = [] for key, value in config['variables'].items...
jpetto/bedrock
tests/functional/firefox/test_new.py
Python
mpl-2.0
1,647
0.002429
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.firefox.new import FirefoxNewPage, FirefoxNewThankYouPage # We don't currently show the down...
ip tests that trigger download bar in IE due to https://github.com/SeleniumHQ/selenium/issues/448 @pytest.mark.
skip_if_internet_explorer @pytest.mark.skipif(reason='https://bugzilla.mozilla.org/show_bug.cgi?id=1245148') @pytest.mark.smoke @pytest.mark.sanity @pytest.mark.nondestructive def test_directly_load_thank_you(base_url, selenium): page = FirefoxNewThankYouPage(base_url, selenium).open() assert page.is_thank_you_...
Orav/kbengine
kbe/src/lib/python/Lib/email/errors.py
Python
lgpl-3.0
3,642
0.005217
# Copyright (C)
2001-2006 Python Software Foundation # Author:
Barry Warsaw # Contact: email-sig@python.org """email package exception classes.""" class MessageError(Exception): """Base class for errors in the email package.""" class MessageParseError(MessageError): """Base class for message parsing errors.""" class HeaderParseError(MessageParseError)...