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
aaugustin/websockets
tests/test_auth.py
Python
bsd-3-clause
38
0
f
rom websockets.auth import * # no
qa
delcypher/klee-runner
tools/invocation-info-bc-stats.py
Python
mit
7,740
0.003876
#!/usr/bin/env python # Copyright (c) 2016, Daniel Liew # This file is covered by the license in LICENSE-SVCB.txt # vim: set sw=4 ts=4 softtabstop=4 expandtab: """ Read an invocation info files and display information about it. """ from load_klee_runner import add_KleeRunner_to_module_search_path add_KleeRunner_to_modu...
]) parser.add_argument(
"--bc-stats", dest='bc_stats', type=str, help='path to bc-stats tool', default="bc-stats") parser.add_argument("--categories", nargs='+', default=[], help='One of more categories to keep', ) parser.add_argument('invocation_info_file', ...
Kovak/KivyNBT
flat_kivy/fa_icon_definitions.py
Python
mit
15,461
0.000065
fa_icons = { 'fa-glass': u"\uf000", 'fa-music': u"\uf001", 'fa-search': u"\uf002", 'fa-envelope-o': u"\uf003", 'fa-heart': u"\uf004", 'fa-star': u"\uf005", 'fa-star-o': u"\uf006", 'fa-user': u"\uf007", 'fa-film': u"\uf008", 'fa-th-large': u"\uf009", 'fa-th': u"\uf00a", 'f...
05d", 'fa-ban': u"\uf05e", 'fa-arrow-left': u"\uf060", 'fa-arrow-right': u"\uf061", 'fa-arrow-up': u"\uf062", 'fa-arrow-down': u"\uf063", 'fa-mail-forward': u"\uf064", 'fa-share': u"\uf064", 'fa-expand': u"\uf065"
, 'fa-compress': u"\uf066", 'fa-plus': u"\uf067", 'fa-minus': u"\uf068", 'fa-asterisk': u"\uf069", 'fa-exclamation-circle': u"\uf06a", 'fa-gift': u"\uf06b", 'fa-leaf': u"\uf06c", 'fa-fire': u"\uf06d", 'fa-eye': u"\uf06e", 'fa-eye-slash': u"\uf070", 'fa-warning': u"\uf071", ...
rpappalax/ff-tool
fftool/firefox_run.py
Python
mpl-2.0
849
0
import os from outlawg import Outlawg from fftool import ( DIR_CONFIGS, local ) from ini_handler import IniHandler Log = Outlawg() env = IniHandler() env.load_os_config(DIR_CONFIGS) def launch_firefox(profile_path, channel, logging, nspr_log_modules=''): """relies on the other functions (download, instal...
file) having completed. """ FIREFOX_APP_BIN = env.get(channel, 'PATH_FIREFOX_BIN_ENV') Log.header('LAUNCH FIREFOX') print("Launching Firefox {0} with profile: {1}".format( channel, profile_path) ) cmd = '"{0}" -profile "{1}"'.format(FIREFOX_APP_BIN, profile_path) print...
_log_modules local(cmd, logging)
msincenselee/vnpy
vnpy/api/easytrader/remoteclient.py
Python
mit
5,338
0.003075
# -*- coding: utf-8 -*- import requests from .utils.misc import file2dict from vnpy.rpc import RpcClient TIMEOUT = 10 class RemoteClient: def __init__(self, broker, host, port=1430, **kwargs): self._s = requests.session() self._api = "http://{}:{}".format(host, port) self._broker = broke...
adan.exe' if config_path is not None: account = file2dict(config_path) params["user"] = account["user"] params["password"] = account["password"] params["broker"] = self._broker # prepare需要启动同花顺客户端,需要的时间比较长,所以超时给长一些时间 response = self._s.post(self._api...
eout=60) if response.status_code >= 300: raise Exception(response.json()["error"]) return response.json() @property def balance(self): return self.common_get("balance") @property def position(self): return self.common_get("position") @property def t...
carolFrohlich/nipype
nipype/interfaces/utility.py
Python
bsd-3-clause
22,277
0.001481
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Various utilities Change directory to provide relative paths for doctests >>> import os >>> filepath = os.path.dirname( os.path.realpath( __file__ ) ) >>> datadir = o...
(TraitedSpec): out = traits.List(desc='Merged output') class Merge(IOBase): """Basic interface class to merge inputs into a single list Examples -------- >>> fro
m nipype.interfaces.utility import Merge >>> mi = Merge(3) >>> mi.inputs.in1 = 1 >>> mi.inputs.in2 = [2, 5] >>> mi.inputs.in3 = 3 >>> out = mi.run() >>> out.outputs.out [1, 2, 5, 3] """ input_spec = MergeInputSpec output_spec = MergeOutputSpec def __init__(self, numinputs=0...
vhf/django-disqus
disqus/templatetags/disqus_tags.py
Python
bsd-3-clause
4,607
0.005644
from django import template from django.conf import settings from django.contrib.sites.models import Site from django.utils.functional import curry from django.utils.encoding import force_unicode register = template.Library() class ContextSetterNode(template.Node): def __init__(self, var_name, var_value): ...
development server if settings.DEBUG is True. """ if settings.DEBUG: return """<script type="text/javascript"> var disqus_developer = 1; var disqus_url = 'http://%s/'; </script>""" % Site.objects.get_current().domain return "" def disqus_num_replies(context, shortname=''): """ ...
ransforms links that end with an #disqus_thread anchor into the threads comment count. """ shortname = getattr(settings, 'DISQUS_WEBSITE_SHORTNAME', shortname) return { 'shortname': shortname, 'config': get_config(context), } def disqus_recent_comments(context, shortname='', nu...
ExaScience/smurff
python/test/test_scarce.py
Python
mit
1,034
0.005803
#!/usr/bin/env python import unittest import numpy as np import scipy.sparse as sp import smurff def matrix_with_explicit_zeros(): matrix_rows = np.array([0, 0, 1, 1, 2, 2]) matrix_cols = np.array([
0, 1, 0, 1, 0, 1])
matrix_vals = np.array([0, 1, 0, 1, 0, 1], dtype=np.float64) matrix = sp.coo_matrix((matrix_vals, (matrix_rows, matrix_cols)), shape=(3, 4)) return matrix class TestScarce(unittest.TestCase): """ We make sure that we do not eliminate zeros in SMURFF accidentally """ def test_simple(self...
RidgeRun/gstd-1.x
tests/libgstc/python/test_libgstc_python_list_elements.py
Python
gpl-2.0
2,117
0
#!/usr/bin/env python3 # GStreamer Daemon - gst-launch on steroids # Python client library abstracting gstd interprocess communication # Copyright (c) 2015-2020 RidgeRun, LLC (http://www.ridgerun.com) # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the ...
NG IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. import unittest from pygstc.gstc import * from pygstc.logger import * class TestGstcListElementsMethods(unittest.TestCase): def test_list_elements(self): pipeline = 'videotestsrc name=v0 ! fakesink name=x0' s...
mic4ael/indico
indico/modules/announcement/views.py
Python
mit
373
0
# This file is part of Indico. # Copyright (C) 2002 - 20
20 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from indico.modules.admin.views import WPAdmin class
WPAnnouncement(WPAdmin): template_prefix = 'announcement/'
fritsvanveen/QGIS
python/utils.py
Python
gpl-2.0
20,592
0.002865
# -*- coding: utf-8 -*- """ *************************************************************************** utils.py --------------------- Date : November 2009 Copyright : (C) 2009 by Martin Dobias Email : wonder dot sk at gmail dot com ************************...
ram 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. * * ...
*********************************** """ from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import str __author__ = 'Martin Dobias' __date__ = 'November 2009' __copyright__ = '(C) 2009, Martin Dobias' # This will get replaced with a git SHA1 when ...
USGSDenverPychron/pychron
pychron/dvc/cache.py
Python
apache-2.0
2,303
0
# =============================================================================== # Copyright 2018 ross # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICE...
ror: pass def clean(self): t = 60 * 15 # 15 minutes now = datetime.now() remove = ( k for k, v in self._cache.items() if (now - v["date_accessed"]).total_seconds() > t ) for k in remove: del self._cache[k] de...
if obj: obj["date_accessed"] = datetime.now() return obj["value"] def update(self, key, value): if key not in self._cache and len(self._cache) > self.max_size: self.remove_oldest() self._cache[key] = {"date_accessed": datetime.now(), "value": value} ...
mezz64/home-assistant
homeassistant/components/aurora_abb_powerone/sensor.py
Python
apache-2.0
4,749
0.000211
"""Support for Aurora ABB PowerOne Solar Photvoltaic (PV) inverter.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from aurorapy.client import AuroraError, AuroraSerialClient from homeassistant.components.sensor import ( SensorDeviceClass, Sens...
.entry_id] data = config_entry.data for sens in
SENSOR_TYPES: entities.append(AuroraSensor(client, data, sens)) _LOGGER.debug("async_setup_entry adding %d entities", len(entities)) async_add_entities(entities, True) class AuroraSensor(AuroraEntity, SensorEntity): """Representation of a Sensor on a Aurora ABB PowerOne Solar inverter.""" d...
botswana-harvard/edc-sync
edc_sync/migrations/0004_auto_20180104_1158.py
Python
gpl-2.0
3,466
0.001443
# Generated by Django 2.0 on 2018-01-04 11:58 import _socket from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('edc_sync', '0003_auto_20170518_1233'), ] operations = [ migrations.AlterModelOptions( name='incomingtransaction', ...
, default=_socket.gethostname, help_text='System field. (modified on create only)', max_length=60), ), migrations.AlterField( model_name='incomingtransaction', name='hostname_created', field=models.CharField(blank=True, default=_socket.gethostname, help_text='System f...
ed on create only)', max_length=60), ), migrations.AlterField( model_name='outgoingtransaction', name='hostname_created', field=models.CharField(blank=True, default=_socket.gethostname, help_text='System field. (modified on create only)', max_length=60), ), ...
poderomedia/kfdata
kgrants/spiders/grants.py
Python
gpl-2.0
3,682
0.008148
# -*- coding: utf-8 -*- from scrapy.spider import Spider from scrapy.selector import Selector from kgrants.items import KgrantsItem from scrapy.http import Request import time class GrantsSpider(Spider): name = "grants" allowed_domains = ["www.knightfoundation.org"] pages = 1 base_url = 'http://www.k...
if normalized_field == 'community': grants[normalized_field] = values.xpath('a/text()').extract()[1] elif normalized_field == 'focus_area': grants[normalized_field] = values.xpath('a/text()').extract()[0] count += 1 ...
''.join( item.xpath('section[@id="grant_contact"]/ul/li[@class="email"]/a/@href').extract()).replace('mailto:','').strip() grants['grantee_contact_name'] = ''.join( item.xpath('section[@id="grant_contact"]/ul/li[@class="email"]/a/text()').extract()).strip() grant...
brj424/nector
malware/migrations/0001_initial.py
Python
gpl-3.0
1,104
0.001812
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-09-12 15:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [
] operations = [ migrations.CreateModel( name='Malware', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('alert_id', models.CharField(max_length=90)), ('alert_type', models.C...
puter', models.CharField(max_length=80)), ('contact_group', models.CharField(max_length=80)), ('virus', models.CharField(max_length=80)), ('actual_action', models.CharField(max_length=80)), ('comment', models.CharField(max_length=100)), ('n...
kiseyno92/SNU_ML
Practice7/code/eval.py
Python
mit
1,438
0.017385
import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data from IPython import embed from tensorflow import flags def main(_): mnist = input_data.read_data_sets("./data", one_hot=True) # defien model input: image and ground-truth label model_inputs = tf.placeholder(dty...
) # define cross entropy loss term loss = tf.losses.softmax_cross_entropy( onehot_labels=labels, logits=predictions) dense_predictions = tf.argmax(predictions, axis=1) dense_labels = tf.argmax(labels, axis=1) equals = tf.cast(tf.equal(dense_predictions, dense_labels), tf.float32) acc = tf.reduce_m...
on() as sess: final_acc = 0.0 sess.run(tf.global_variables_initializer()) for step in range(50): images_val, labels_val = mnist.validation.next_batch(100) feed = {model_inputs: images_val, labels: labels_val} acc = sess.run(acc, feed_dict=feed) final_acc += acc final_acc /= 50.0 ...
myt00seven/svrg
nips2017_mnist/mnist.py
Python
mit
14,964
0.004945
#!/usr/bin/env python """ Batch Normalization + SVRG on MNIST CPU Version Independent Study May 18, 2016 Yintai Ma """ from __future__ import print_function import sys import os import time import matplotlib import matplotlib.pyplot as plt import pylab import numpy as np import theano import theano.tensor as T i...
that takes a Theano variable representing the input and returns # the output layer of a neural network model built in Lasagne. def build_mlp(input_var=None): l_in = lasagne.layers.InputLayer(shape=(None, 1, 28, 28), input_var=input_var) l_hid = lasagne.layers.DenseLayer( ...
_hid = lasagne.layers.DenseLayer( # l_hid, num_units=NUM_HIDDEN_UNITS, # nonlinearity=lasagne.nonlinearities.rectify) l_out = lasagne.layers.DenseLayer( l_hid, num_units=10, nonlinearity=lasagne.nonlinearities.softmax) return l_out def build_mlpbn(input_var=None)...
astrobin/astrobin
astrobin/migrations/0004_userprofile_updated.py
Python
agpl-3.0
432
0
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-02-17 10:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [
('astrobin', '0003_auto_20180217_0933'), ] operations = [ migrations.AddField( model_name='userprofile', name='updated', field=models.DateTimeField(auto_now=True, null=True),
), ]
mgarciafernandez/magnipy
magnipy.py
Python
gpl-3.0
4,413
0.046
import numpy, math, json, os, ROOT, scipy.special, scipy.interpolate __GRAPHIX__ = 'ROOT' def GetNSigmas(chi2): sigmas = numpy.linspace(0,20,1000) prob = map(lambda x : scipy.special.erf(x/math.sqrt(2)), sigmas) f = scipy.interpolate.interp1d(prob,sigmas,kind='linear') return f(1-chi2) class CorrelationFuncti...
lf.w_) == len(self.angle_)): print
'Dimension does not agree. Chech angle and w.' raise Exception elif __GRAPHIX__ == 'ROOT' : for th in xrange(self.Nth_): self.plot_.SetPoint(th,self.angle_[th],self.w_[th]) self.plot_.SetPointError(th,0.,self.error_[th]) class DataW(CorrelationFunction): def __init__(self,name=''): CorrelationFunc...
ghchinoy/tensorflow
tensorflow/python/training/saving/functional_saver_test.py
Python
apache-2.0
5,040
0.002778
# Copyright 2018 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...
sor_name), fetches=wrapped.graph.get_operation_by_name(proto.restore_op_name)) save_path = save(constant_op.constant(prefix)) v1.assign(1.) restore(constant_op.constant(save_path)) self.assertEqual(2., self.evaluate(v1)) v2 = resource_variable_ops.ResourceVariable(3.) second_saver = fun...
@test_util.run_v1_only( "Needs an API to setup multiple devices, b/124805129") # Set up multiple devices when graph building. Before test.main() we configure # the devices for eager execution. @test_util.run_in_graph_and_eager_modes( config=config_pb2.ConfigProto(device_count={"CPU": 3})) def tes...
jaa2015/FlaskProject
flaskproject/users/models.py
Python
mit
1,443
0
from flask_security import UserMixin, RoleMixin from ..core import db roles_users = db.Table( 'roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('users
.id')), db.Column('role_id', db.Integer(), db.ForeignKey('roles.id'))) class Role(db.Model, RoleMixin): __tablename__ = 'roles' id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) def __init__(self, name): ...
id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(120)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) la...
tongpa/PollSurveyWeb
pollandsurvey/service/interfacewebservice.py
Python
gpl-2.0
1,487
0.014122
# -*- coding: utf-8 -*- from tg.configuration import AppConfig, config from tg import request from pollandsurvey import model from tgext.pyutilservice import Utility import logging log = logging.getLogger(__name__) from tgext.pylogservice import LogDBHandler class InterfaceWebService(object): def __init__(self...
FACESERVICE.WEBSERVICE' dh = LogDBHandler( config=config,requ
est=request) log.addHandler(dh) self.utility = Utility() def mapVoterUser(self, voter): """ Check Voter and User in table sur_member_user is Empty will create again. if not will pass. Keyword arguments: voter -- Object Voter """ sel...
sio2project/oioioi
oioioi/problems/forms.py
Python
gpl-3.0
9,816
0.001324
from collections import OrderedDict from django import forms from django.conf import settings from django.db import transaction from django.utils.translation import ugettext_lazy as _ from oioioi.base.utils.input_with_generate import TextInputWithGenerate from oioioi.base.utils.inputs import narrow_input_field from oi...
orm): class Meta(object): fields = '__all__' model = ProblemStatementConfig widgets = {'visible': forms.RadioSelect()} class RankingVisibilityConfigForm(forms.ModelForm): class Meta(object): fields = '__all__' model = RankingVisib
ilityConfig widgets = {'visible': forms.RadioSelect()} class ProblemSiteForm(forms.ModelForm): class Meta(object): fields = ['url_key'] model = ProblemSite widgets = {'url_key': TextInputWithGenerate()} class ProblemsetSourceForm(forms.Form): url_key = forms.CharField(label=_...
tensor-tang/Paddle
python/paddle/fluid/incubate/fleet/collective/__init__.py
Python
apache-2.0
14,141
0.001061
# Copyright (c) 2019 PaddlePaddle 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 app...
d and grad_allreduce can be used under collective mode" def _transpile(self, startup_program, main_program): """ Transpile the programs to distributed programs. And add the variables. """ worker_endpoints = fleet.worker_endpoints()
trainer_id = fleet.worker_index() current_endpoint = fleet.worker_endpoints()[trainer_id] worker_endpoints_env = ','.join(worker_endpoints) trainers_num = fleet.worker_num() if self.print_config: print("worker_endpoints:{} trainers_num:{} current_endpoint:{} \ ...
kbaseIncubator/catalog
lib/biokbase/catalog/local_function_reader.py
Python
mit
13,976
0.003864
import json import os ''' Class responsible for parsing/validating the local function specs, processing the specs, and returning something that can be saved to the DB. Typical usage is to initialize and the read_and_validate. Then, once a compilation report is made, you can perform a full validation. Finally, to cr...
hors to module owners for o in module_details['ow
ners']: authors.append(o['kb_username']) # could probably make this code cleaner, but for now just do brute force if/else to validate tags = {'categories': [], 'input': {'file_types': [], 'kb_types': []}, 'o...
max-ionov/russian-anaphora
resolute-text.py
Python
gpl-3.0
1,079
0.032437
#!/usr/bin/python2.7 # -!- coding: utf-8 -!- # usage: resolute-text.py input pronouns model import os, sys, codecs import lemmatizer, anaphoramllib usage = 'usage: resolute-text.py input pronouns model' if(__name__ == '__main__'): if len(sys.argv) < 4: print (usage) sys.exit() text = '' pronouns = anaphoraml...
r.SetWindow(20, 0) mlResolutor.LoadModel(sys.argv[3], sys.argv[3] + '.labels') for group in groups: if group[1] in mlResolutor.pronounIndex: antecedent = mlResolutor.FindAntecedent(group, groups) if len(antecedent) == 0: print 'no results for group at offset %d' %
group[-2] else: print group[0], ' ---> ', antecedent[0][1][0] #print antecedent
kevingu1003/python-pptx
pptx/opc/spec.py
Python
mit
978
0
# encoding: utf-8 """ Provides mappings that embody aspects of the Open XML spec ISO/IEC 29500. """ from .constants import CONTENT_TYPE as CT default_content_types = ( ('bin', CT.PML_PRINTER_SETTINGS), ('bin', CT.SML_PRINTER_SETTINGS), ('bin', CT.WML_PRINTER_SETTINGS), ('bmp', CT.BMP...
', CT.JPEG), ('png', CT.PNG), ('rels', CT.OPC_RELATIONSHIPS), ('tif', CT.TIFF), ('tiff', CT.TIFF), ('wdp', CT.MS_PHOTO), ('wmf', CT.X_
WMF), ('xlsx', CT.SML_SHEET), ('xml', CT.XML), ) image_content_types = { 'bmp': CT.BMP, 'emf': CT.X_EMF, 'gif': CT.GIF, 'jpe': CT.JPEG, 'jpeg': CT.JPEG, 'jpg': CT.JPEG, 'png': CT.PNG, 'tif': CT.TIFF, 'tiff': CT.TIFF, 'wdp': CT.MS_PHOTO, 'wmf': CT.X_W...
ganga-devs/ganga
ganga/GangaLHCb/test/Unit/DiracAPI/TestDiracCommands.py
Python
gpl-3.0
16,423
0.003532
import datetime from collections import namedtuple import os import tempfile import time import uuid import random import stat from textwrap import dedent import pytest from GangaCore.Utility.logging import getLogger from GangaDirac.Lib.Utilities.DiracUtilities import execute from GangaCore.testlib.mark import ex...
) logger.info('Waiting for DIRAC job to finish') timeout = 1200 end_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=timeout) status = execute('status([%s], %s)' % (job_id, repr(statusmapping)), return_raw_dict=True) while (status['OK'] and statusmapping[status['Value'][0][1]] not in ...
atusmapping)), return_raw_dict=True) print("Job status: %s" % status) assert 'OK' in status, 'Failed to get job Status!' assert status['OK'], 'Failed to get job Status!' assert statusmapping[status['Value'][0][1]] == 'completed', 'job not completed properly: %s' % status logger.info("status: ...
Kalimaha/pact-test
tests/runners/pact_tests_runner.py
Python
mit
767
0
from pact_test.runners import pact_tests_runner def test_consumer_tests(mocker): mocker.spy(pact_tests_runner, 'run_consumer_tests') pact_tests_runner.verify(v
erify_consumers=True) assert pact_tests_runner.run_consumer_tests.call_count == 1 def test_provider_tests(mocker):
mocker.spy(pact_tests_runner, 'run_provider_tests') pact_tests_runner.verify(verify_providers=True) assert pact_tests_runner.run_provider_tests.call_count == 1 def test_default_setup(mocker): mocker.spy(pact_tests_runner, 'run_consumer_tests') mocker.spy(pact_tests_runner, 'run_provider_tests') pa...
Parcks/core
src/domain/model/post_install/post_install_runnable.py
Python
gpl-2.0
1,228
0.004072
""" Scriptable Packages Installer - Parcks Copyright (C) 2017 JValck - Setarit This program is free software; you can redistribute it and/or modify it under the te
rms of the GNU General Public License as published by the Fr
ee Software Foundation; either version 2 of the License, or (at your option) any later version. 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 FOR A PARTICULAR PURPOSE. See the GNU General Public License for mor...
juanAFernandez/project-S
mongoDBAPI/try.py
Python
gpl-2.0
32
0
fro
m api import * s
imulaUnDia()
webmasterraj/FogOrNot
flask/lib/python2.7/site-packages/pandas/tests/test_internals.py
Python
gpl-2.0
42,078
0.002139
# -*- coding: utf-8 -*- # pylint: disable=W0102 import nose import numpy as np from pandas import Index, MultiIndex, DataFrame, Series, Categorical from pandas.compat import OrderedDict, lrange from pandas.sparse.array import SparseArray from pandas.core.internals import * import pandas.core.internals as internals im...
pass def test_insert(self): pass def test_delete(self): newb = self.fblock.copy() newb.delete(0) assert_almost_equal(newb.mgr_locs, [2, 4]) self.assertTrue((newb.values[0] == 1).all()) newb = self.fblock.copy() newb.de
lete(1) assert_almost_equal(newb.mgr_locs, [0, 4]) self.assertTrue((newb.values[1] == 2).all()) newb = self.fblock.copy() newb.delete(2) assert_almost_equal(newb.mgr_locs, [0, 2]) self.assertTrue((newb.values[1] == 1).all()) newb = self.fblock.copy() sel...
SReiver/django-taggit-autocomplete-jqueryui
taggit_autocomplete_jqueryui/managers.py
Python
bsd-2-clause
818
0.002445
# coding=utf-8 from taggit.forms import TagField from taggit.managers import TaggableManager from django.conf import settings from widgets import TagAutocomplete class TaggableManagerAutocomplete(TaggableManager): def formfield(self, form_class=TagField, **kwargs): field = (super(TaggableManagerAutocompl...
da v: v.strip(), value) getattr(instance, self.name).set(*value) if 'south' in settings.INSTALLED_APPS: try: from south.modelsinspector import add_ignored_fields exc
ept ImportError: pass else: add_ignored_fields(["^taggit_autocomplete_jqueryui\.managers"])
Guanghan/ROLO
ROLO_evaluation.py
Python
apache-2.0
54,621
0.015159
# Copyright (c) <2016> <GUANGHAN NING>. 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 applicable l...
[locations, st_frame_num, ed_frame_num] = load_mat_results(mat_file, True, False, False, locations_id) ct_frames= 0
total_score_over_frames= 0 for id in range(st_frame_num-1, ed_frame_num): id_offset= id - st_frame_num + 1 location= locations[id_offset] # id_offset, not id gt_location = utils.find_gt_location(lines, id) #id, not id_offset ...
p4apple/sphinx_gt4g
api/sphinxapi.py
Python
gpl-2.0
34,870
0.053628
# # $Id: sphinxapi.py 4522 2014-01-30 11:00:18Z tomat $ # # Python version of Sphinx searchd client (Python API) # # Copyright (c) 2006, Mike Osadnik # Copyright (c) 2006-2014, Andrew Aksyonoff # Copyright (c) 2008-2014, Sphinx Technologies Inc # All rights reserved # # This program is free software; you can redistribu...
find it at http://www.gnu.org/ # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # WARNING # We strongly recommend you to use SphinxQL instead of the API # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! import sys import select import socket import re from struct import * # known searc...
ARCHD_COMMAND_FLUSHATTRS = 7 # current client-side command implementation versions VER_COMMAND_SEARCH = 0x11E VER_COMMAND_EXCERPT = 0x104 VER_COMMAND_UPDATE = 0x103 VER_COMMAND_KEYWORDS = 0x100 VER_COMMAND_STATUS = 0x101 VER_COMMAND_FLUSHATTRS = 0x100 # known searchd status codes SEARCHD_OK = 0 SEARCHD_ERROR ...
agry/NGECore2
scripts/mobiles/generic/faction/imperial/imp_sandtrooper_75.py
Python
lgpl-3.0
1,432
0.027933
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from resources.datatables import FactionStatus from java.util import Vector def addTemplate(co...
bileTemplate = MobileTemplate() mobileTemplate.setCreatureName('crackdown_sand_trooper') mobileTemplate.setLevel(75) mobileTemplate.s
etDifficulty(Difficulty.ELITE) mobileTemplate.setMinSpawnDistance(4) mobileTemplate.setMaxSpawnDistance(8) mobileTemplate.setDeathblow(False) mobileTemplate.setScale(1) mobileTemplate.setSocialGroup("imperial") mobileTemplate.setAssistRange(6) mobileTemplate.setStalker(False) mobileTemplate.setFaction("imperial...
hkpeprah/git-achievements
app/achievement/migrations/0001_initial.py
Python
gpl-2.0
27,950
0.007048
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Difficulty' db.create_table(u'achievement_difficulty', ( ...
('custom', self.gf('django.db.models.fields.BooleanField')(default=False)), )) db.send_create_si
gnal('achievement', ['ConditionType']) # Adding model 'CustomCondition' db.create_table(u'achievement_customcondition', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('event_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['service...
jmartinm/InvenioAuthorLists
modules/bibclassify/lib/bibclassify_config.py
Python
gpl-2.0
9,775
0.003376
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2008, 2009, 2010, 2011 CERN. ## ## Invenio 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 ...
tLogger(name) hdlr = l
ogging.StreamHandler(sys.stderr) formatter = logging.Formatter('%(levelname)s %(name)s:%(lineno)d %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging_level) logger.propagate = 0 if logger not in _loggers: _loggers.append(logge...
altendky/canmatrix
src/canmatrix/tests/test_sym.py
Python
bsd-2-clause
3,192
0
# -*- coding: utf-8 -*- import io import textwrap import pytest import canmatrix.canmatrix import canmatrix.formats.sym def test_colliding_mux_values(): f = io.BytesIO( textwrap.dedent( '''\ Forma
tVersion=5.0 // Do not edit this line! Title="a file" {SEND} [MuxedId] ID=0h Mux=TheMux 0,1 0h Var=Signal unsigned 1,1 [MuxedId] Mux=FirstMux 0,1 1h Var=Signal unsigned 1,1 [MuxedId] M...
ror, = matrix.load_errors line_number = 16 assert len(matrix.load_errors) == 1 assert isinstance(error, canmatrix.formats.sym.DuplicateMuxIdError) assert error.line_number == line_number error_string = str(error) assert error_string.startswith( 'line {line_number}: '.format(line_numb...
zhoutong/wwag
serve.py
Python
mit
83
0
from wsgiref.handle
rs import C
GIHandler from wwag import app CGIHandler().run(app)
fivejjs/inasafe
scripts/generate_volcano_evac_zone.py
Python
gpl-3.0
376
0
from safe.engine.interpolation import make_circular_polygon from safe.storage.core import read_layer H = read_layer('/data_area/InaSA
FE/public_data/hazard/Marapi.shp') print H.get_geometry() # Generate evacuation circle (as a polygon): radius = 3000 center = H.get_geometry()[0] Z = make_circular_polygon(center, radius) Z.write_to_file('Marapi_evac_zone_%im.shp'
% radius)
GabrielFortin/ansible-module-f5bigip
library/f5bigip_gtm_monitor_smtp.py
Python
apache-2.0
5,320
0.003383
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2016-2018, Eric Jacob <[email protected]> # # 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/LICENS...
: true parti
tion: description: - Specifies the administrative partition in which the component object resides. default: Common probe_timeout: description: - Specifies the number of seconds after which the BIG-IP system times out the probe request to the BIG-IP system. def...
pylixm/liBlog
liBlog/visitor/middleware.py
Python
mit
8,071
0.000373
# -*- coding:utf-8 -*- from datetime import timedelta from django.utils import timezone import logging import re import traceback from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.core.cache import cache from django.core.urlresolvers import reverse, NoReverseMatch from d...
hing pass settings.NO_TRACKING_PREFIXES = self._prefixes settings._FREEZE_TRACKING_PREFIXES = True return self._prefixes def process_request(self, request): # create some useful variables ip_address = utils.get_ip(request) user_a...
# retrieve untracked user agents from cache ua_key = '_tracking_untracked_uas' untracked = cache.get(ua_key) if untracked is None: log.info('Updating untracked user agent cache') untracked = UntrackedUserAgent.objects.all() cache.set(ua_key, untracked, 36...
apache/aurora
src/main/python/apache/thermos/monitoring/resource.py
Python
apache-2.0
13,377
0.009793
# # 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 # distributed under ...
of pids initiated by the process """
@abstractmethod def sample(self): """ Return a sample of the resource consumption of the task right now Returns a tuple of (timestamp, AggregateResourceResult) """ @abstractmethod def sample_at(self, time): """ Return a sample of the resource consumption as close as possible to the specified ti...
hbhdytf/mac
swift/obj/reconstructor.py
Python
apache-2.0
41,578
0
# Copyright (c) 2010-2015 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 required by applicable law or agree...
st_from_csv, get_hub, tpool_reraise, GreenAsyncPile, Timestamp, remove_file) from swift.common.swob import HeaderKeyDict from swift.common.bufferedhttp import http_connect from swift.common.daemon import Daemon from swift.common.ring.utils import is_local_device from swift.obj.ssync_sender import Sender as ssync_se...
m swift.common.storage_policy import POLICIES, EC_POLICY from swift.common.exceptions import ConnectionTimeout, DiskFileError, \ SuffixSyncError SYNC, REVERT = ('sync_only', 'sync_revert') hubs.use_hub(get_hub()) def _get_partners(frag_index, part_nodes): """ Returns the left and right partners of the ...
Empire-of-Code-Puzzles/checkio-empire-pawn-brotherhood
_old/verification/referee.py
Python
mit
510
0
from checkio.signals import ON_CONNECT from checkio import api from checkio.referees.io import CheckiOReferee from checkio.referees import cover_codes from checkio.referees import checkers from tests import TESTS cover = """def cover(func, data): return func(set(data)) """ api.add_listener
( ON_CONNECT, CheckiOReferee( tests=TESTS, cover_code={ 'python-27': cover, 'python-3': cover }, DEFAULT_FUNCTION_NAME="safe_pawns" ).on
_ready)
kylebebak/Requester
core/responses.py
Python
mit
11,912
0.002015
import sublime import re from urllib import parse from concurrent import futures from collections import namedtuple, deque from ..deps import requests from .parsers import PREFIX from .helpers import truncate, prepend_scheme, is_instance, is_auxiliary_view Request_ = namedtuple('Request', 'request, method, url, ar...
try: if
req.session: session = self.env.get(req.session) if is_instance(session, 'requests.sessions.Session'): res = getattr(session, req.method.lower())(*req.args, **req.kwargs) else: err = 'Session Error: there is no session `{}` defined ...
xiaq/jadepy
jade/compile.py
Python
mit
7,708
0
from sys import stdout from collections import defaultdict from .parse import main, HTMLTag def maybe_call(f, *args, **kwargs): if callable(f): return f(*args, **kwargs) return f class Compiler(object): def __init__(self, stream): self.stream = stream self.blocks = [] se...
ag): self.stream.write('</%s>' % tag.name) elif tag.name in ('if', 'elif'): self.deferred_endif = [u'{% endif %}', ''] elif tag.name == 'case': if not tag.seen_when: raise self.parser.error('case tag has no when child') self.stream.write('{...
tag.name in ('when', 'default'): pass else: self.stream.write(maybe_call(control_blocks[tag.name][1], tag)) def literal(self, text): """ Called by the parser to output literal text. The parser doesn't keep track of active blocks. """ self.put...
nkuttler/flaskwallet
doc/conf.py
Python
bsd-3-clause
7,774
0.007461
# -*- coding: utf-8 -*- # # Flaskwallet documentation build configuration file, created by # sphinx-quickstart on Thu Oct 17 14:33:26 2013. # # 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. # #...
anguage for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |tod
ay|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_bu...
hzlf/openbroadcast
website/cms/test_utils/project/sampleapp/urls.py
Python
gpl-3.0
842
0.008314
from django.conf.urls.defaults import * """ Also used in cms.tests.ApphooksTestCase """ urlpatterns = patterns('cms.test_utils.project.sampleapp.views', url(r'^$', 'sample_view', {'message': 'sample root page',}, name='sample-root'), url(r'^settings/$', 'sample_view', kwargs={'message': 'sample settings page'...
='sample-profile'), url(r'^(?P<id>[0-9]+)/$', 'category_view', name='category_view'), url(r'^notfound/$', 'notfound'
, name='notfound'), url(r'^extra_1/$', 'extra_view', {'message': 'test urlconf'}, name='extra_first'), url(r'^', include('cms.test_utils.project.sampleapp.urls_extra')), )
sup95/zulip
zproject/settings.py
Python
apache-2.0
39,590
0.000707
from __future__ import absolute_import # Django settings for zulip project. ######################################################################## # Here's how settings for the Zulip project work: # # * settings.py contains non-site-specific and settings configuration # for the Zulip Django app. # * settings.py impor...
ULIP_COM': False, 'SHOW_OSS_ANNOUNCEMENT': False,
'REGISTER_LINK_DISABLED': False, 'LOGIN_LINK_DISABLED': False, 'ABOUT_LINK_DISABLED': False, 'CUSTOM_LOGO_URL': None, 'VERBOSE_SUPPORT_OFFERS': False, 'STATSD_HOST': '', 'OPEN_REALM_CREATI...
apoikos/servermon
hwdoc/management/commands/hwdoc_license.py
Python
isc
1,809
0.002765
# -*- coding: utf-8 -*- vim:fileencoding=utf-8: # vim: tabstop=4:shiftwidth=4:softtabstop=4:expandtab # Copyright © 2010-2012 Greek Research and Technology Network (GRNET S.A.) # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that th...
copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND # FITNESS. IN NO EV
ENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. ''' Djan...
timothycrosley/instantly
instantly/main.py
Python
gpl-2.0
8,313
0.003609
""" instantly/main.py Defines the basic terminal interface for interacting with Instantly. Copyright (C) 2013 Timothy Edmund Crosley 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 rest...
print("%(name)s has been installed as a local template. Run 'instantly %(name)s' to expand it." % \ {"name":template_name}) sys.exit(0) else: print("Sorry: no one has thought of a way to instantly '%s'," % template_name) print(" but you cou...
if not template: print("Sorry: no one has thought of a way to instantly '%s'," % template_name) print(" but you could always create one ;)") sys.exit(1) print("Expanding the following template:") print(template) arguments = {} for argument, argu...
adamhaney/airflow
airflow/utils/log/logging_mixin.py
Python
apache-2.0
5,510
0.000544
# -*- coding: utf-8 -*- # # 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 #...
ef redirect_stdout(logger, level): writer = StreamLogWriter(logger, level) try: sys.stdout = writer yield finally:
sys.stdout = sys.__stdout__ @contextmanager def redirect_stderr(logger, level): writer = StreamLogWriter(logger, level) try: sys.stderr = writer yield finally: sys.stderr = sys.__stderr__ def set_context(logger, value): """ Walks the tree of loggers and tries to set th...
pepincho/Python101-and-Algo1-Courses
Algo-1/week3/5-Bandwidth-Manager/bandwidth_manager.py
Python
mit
1,423
0
# Priority Queue import heapq class Packet: PROTOCOL_PRIORITY = { 'ICMP': 10, 'UDP': 9, 'RTM': 8, 'IGMP': 7, 'DNS': 6, 'TCP': 5 } def __init__(self, protocol, payload, sequence_number): self.priority = Packet.PROTOCOL_PRIORITY[protocol] sel...
and payload def rcv(self, protocol, payload): new_packet = Packet(protocol, payload, self.sequence_number) heapq.heappush(self.heap, new_packet) self.sequence_number += 1 # returns the payload of the packet which should be sent def send(self): if len(self.heap) == 0: ...
return heapq.heappop(self.heap).payload def main(): N = int(input()) bm = BandwidthManager() while N != 0: line = input().split() if line[0] == 'rcv': bm.rcv(line[1], line[2]) else: print(bm.send()) N -= 1 if __name__ == '__main__': m...
skoli0/vmbuilder
helper/helper.py
Python
apache-2.0
5,599
0.003215
import re import os, sys import json import csv import shutil import ctypes import logging import datetime import fileinput import subprocess import xml.etree.ElementTree as etree DEFAULT_HELPER_PATH = "helper" class Logger(object): def __init__(self): """Init method """ ...
rip().decode('utf-8')), p.stdout.close() p.wait() #print(cmd)
#p = subprocess.run(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.STDOUT) #print('returncode:', p.returncode) #print('{}'.format(p.stdout.decode('utf-8'))) except (subprocess.CalledProcessError, KeyboardInterrupt) as e: print("Received keyboard interrupt, ter...
simar7/build-mozharness
configs/developer_config.py
Python
mpl-2.0
1,008
0.001984
# This config file can be appended to any other mozharness job # running under tbpl. The purpose of this config is to override # values that are specific to Release Engineering machines # that can reach specific hosts within their network. # In other words, this config allows you to run any job # outside of the Release...
ol/pvt/build"], "replace_urls": [ ("http://pvtbuilds.pvt.buil
d", "https://pvtbuilds"), ("http://tooltool.pvt.build.mozilla.org/build", "https://secure.pub.build.mozilla.org/tooltool/pvt/build") ], # Talos related "python_webserver": True, "virtualenv_path": '%s/build/venv' % os.getcwd(), }
havardgulldahl/jottalib
src/jottalib/scanner.py
Python
gpl-3.0
5,128
0.010541
#!/usr/bin/env python # encoding: utf-8 """A service to sync a local file tree to jottacloud. Copies and updates files in the cloud by comparing md5 hashes, like the official client. Run it from crontab at an appropriate interval. """ # This file is part o
f jottacloudclient. # # jottacloudclient 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. # # jottacloudclient is distributed in the hop...
ESS 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 jottacloudclient. If not, see <http://www.gnu.org/licenses/>. # # Copyright 2014-2015 Håvard Gulldahl <[email protected]> #import included batteries...
ArcherSys/ArcherSys
Lib/encodings/iso2022_jp_ext.py
Python
mit
3,347
0.012549
<<<<<<< HEAD <<<<<<< HEAD # # iso2022_jp_ext.py: Python Unicode Codec for ISO2022_JP_EXT # # Written by Hye-Shik Chang <[email protected]> # import _codecs_iso2022, codecs import _multibytecodec as mbc codec = _codecs_iso2022.getcodec('iso2022_jp_ext') class Codec(codecs.Codec): encode = codec.encode decode ...
rementalDecoder): codec = codec class StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader): codec = codec class StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter): codec = codec def getregentry(): return codecs.CodecInfo( name='iso2022_jp_ext', encode=C...
e=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ======= # # iso2022_jp_ext.py: Python Unicode Codec for ISO2022_JP_EXT # # Written by Hye-Shik Chang <[email protected]> # import _...
olielvewen/QDvGrab
qdvgrab/images/qdvgrabressources_rc.py
Python
gpl-3.0
599,843
0.000008
# -*- coding: utf-8 -*- # Resource object code # # Created by: The Resource Compiler for PyQt5 (Qt v5.15.0) # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore qt_resource_data = b"\ \x00\x00\x23\x1c\ \x89\ \x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ \x00\x00\x80\x...
xe0\x29\x26\x51\x5e\x90\x7e\ \x55\xae\x1e\xf6\x30\x33\x27\x71\xb4\x97\xf1\x5d\x5a\x0a\x01\x18\ \x38\x3f\x43\x98\x23\x21\x44\x29\xd3\xe5\x07\x85\x8c\xa0\x9e\x87\ \x8b\xf8\xce\x7a\x21\xfe\x45\xb7\xeb\x6c\xf0\x03\x89\x79\x4f\x62\ \xbc\x58\xc5\xf9\xe9\x32\x98\xdb\x01\x30\x01\x14\xf6\x80\xd3\x82\ \xce\xf1\xdf\x63\xeb\x5e\x4...
5c\x2c\xb9\ \xce\x82\x94\x5d\x1e\x7a\x59\x62\x4b\x5f\x68\x38\x70\xc3\xbd\xff\ \x18\x61\xa1\x4f\x08\x0f\x99\x2e\xc7\x29\xf4\x93\x33\xf0\x95\x8a\ \xf8\xd1\xce\xd5\xb9\xef\xe9\x1b\x56\x03\x14\xab\x12\x44\x01\x26\ \x05\x2d\x05\x74\xfb\x61\x92\x01\xad\x8d\x5e\x6e\x1b\x47\x01\x9b\ \xf4\x98\x05\x7a\xb2\xef\x72\x22\x2f\x8f\x55...
jonparrott/google-cloud-python
logging/google/cloud/logging/entries.py
Python
apache-2.0
11,279
0
# Copyright 2016 Google LLC # # 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, s...
('log_name', None), ('labels', None), ('insert_id', None), ('severity', None), ('http_request', None
), ('timestamp', None), ('resource', _GLOBAL_RESOURCE), ('trace', None), ('span_id', None), ('trace_sampled', None), ('source_location', None), ('operation', None), ('logger', None), ('payload', None), ) _LogEntryTuple = collections.namedtuple( 'LogEntry', (field for field,...
annarev/tensorflow
tensorflow/python/data/util/nest.py
Python
apache-2.0
16,774
0.004292
# Copyright 2017 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...
ence) or isinstance(flat_sequence, list)): raise TypeError("flat_sequence must be a sequence") if not is_sequence(structure): if len(flat_sequence) != 1: raise ValueError("Structure is a scalar but len(flat_sequence) == %d > 1" % len(flat_sequence)) return flat_sequence[0] ...
) if len(flat_structure) != len(flat_sequence): raise ValueError( "Could not pack sequence. Structure had %d elements, but flat_sequence " "had %d elements. Structure: %s, flat_sequence: %s." % (len(flat_structure), len(flat_sequence), structure, flat_sequence)) _, packed = _packed_nes...
chengdh/openerp-ktv
openerp/addons/ktv_sale/room_checkout.py
Python
agpl-3.0
9,855
0.039058
# -*- coding: utf-8 -*- import logging from osv import fields, osv import decimal_precision as dp import ktv_helper _logger = logging.getLogger(__name__) #包厢结账对象 class room_checkout(osv.osv): _name="ktv.room_checkout" _columns = { "room_operate_id" : fields.many2one("ktv.room_operate","room_opera...
nteger("free_persons_count",help="按位消费免单人数"), #挂账 "on_crediter_id" : fields.many2one("res.users","on_crediter_id",help="挂账人"), "on_credit_fee" : fields.float("on_credit_fee",digits_compute = dp.get_precision('Ktv Room Default Precision'),help="免单费用"), #欢唱券 "so...
lds.float("song_ticket_fee",digits_compute = dp.get_precision('Ktv Room Default Precision'),help="欢唱券抵扣费用"), "song_ticket_fee_diff" : fields.float("song_ticket_fee_diff",digits_compute = dp.get_precision('Ktv Room Default Precision'),help="欢唱券抵扣费用差额"), "act_pay_fee" : fields.float("act_pay_fee"...
balajikris/autorest
Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py
Python
mit
1,496
0
# coding=utf-8 # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- from msrest.serialization import Model class Usage(Model): """Describes Storage Resource Usage. :param unit: Gets the unit of measurement. ...
untsPerSecond',
'BytesPerSecond' :type unit: str or :class:`UsageUnit <petstore.models.UsageUnit>` :param current_value: Gets the current count of the allocated resources in the subscription. :type current_value: int :param limit: Gets the maximum count of the resources that can be allocated in the subscri...
tspus/python-matchingPursuit
data/signalGenerator.py
Python
gpl-3.0
6,621
0.050295
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' # This file is part of Matching Pursuit Python program (python-MP). # # python-MP 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 ...
= 0.5 frequency1 = 12.0 frequency2 = 15.0 phase = 0.0 gaborParams = np.array([[numberOfSamples,samplingFreq,amplitude,position1,width,frequency1,phase],[numberOfSamples,samplingFreq,amplitude,position2,width,frequency2,phase]]) sinusParams = np.array([[5.0,5.0,0.0]]) noiseRatio = 0.0 ...
mples = 1000 samplingFreq = 250.0 amplitude1 = 12 amplitude2 = 20 freq1 = 10.0 freq2 = 20.0 pos1 = 250 pos2 = 500 sigma = 500 asymetry = 0.45 asymetricParams = np.array([[amplitude1,freq1,pos1,sigma,asymetry],[amplitude2,freq2,pos2,sigma...
beyondblog/kubernetes
hack/boilerplate/boilerplate.py
Python
apache-2.0
4,733
0.004014
#!/usr/bin/env python # Copyright 2015 The Kubernetes 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 # # Unle...
ref_file = open(path, 'r') ref = ref_file.read().splitlines() ref_file.close() refs[extension] = ref return refs def file_passes(filename, refs, regexs): try: f = open(filename, 'r') except: return False data = f.read() f.close() extension = file_ext...
n("", data, 1) # remove shebang from the top of shell files if extension == "sh": p = regexs["shebang"] (data, found) = p.subn("", data, 1) data = data.splitlines() # if our test file is smaller than the reference it surely fails! if len(ref) > len(data): return False ...
cc-archive/commoner
src/commoner/registration/tests.py
Python
agpl-3.0
12,845
0.007318
""" Unit tests for django-registration. These tests assume that you've completed all the prerequisites for getting django-registration running in the default setup, to wit: 1. You have ``registration`` in your ``INSTALLED_APPS`` setting. 2. You have created all of the templates mentioned in this application's doc...
.create_inactive_user(username='signal_test', password='foo', email='[email protected]',
send_email=False) RegistrationProfile.objects.activate_user(RegistrationProfile.objects.get(user__username='signal_test').activation_key) self.assertEqual(received_signals, expected_signals) class RegistrationFormTests(RegistrationTestCase): ...
chris-sanders/layer-haproxy
tests/unit/test_libhaproxy.py
Python
gpl-3.0
22,253
0.001438
#!/usr/bin/python3 """Test the helper library used by the charm.""" import os def test_pytest(): """Test pytest works.""" assert True def test_ph(ph): """Test the ph fixture works to load charm configs.""" assert isinstance(ph.charm_config, dict) def test_proxy_config(ph): """Check that defaul...
g])["cfg_good"] is True backend = ph.get_backend("unit-mock-8-0", create=False) forward_for_found = False for option in backend.options(): if "forwardfor" in option.keyword: forward_for_found = True a
ssert forward_for_found forward_proto_found = False for cfg in backend.configs(): if "X-Forwarded-Proto https" in cfg.keyword: forward_proto_found = True assert forward_proto_found ssl_found = False for server in backend.servers(): if "ssl verify none" in server.attribute...
anneline/Bika-LIMS
bika/lims/tools/bika_ar_import.py
Python
agpl-3.0
11,059
0.013835
from DateTime import DateTime from AccessControl import ClassSecurityInfo from App.class_init import InitializeClass from OFS.SimpleItem import SimpleItem from Products.CMFCore import permissions from Products.CMFCore.utils import UniqueObject, getToolByName from bika.lims.config import ManageAnalysisRequests from bika...
te(self.progress_bar(REQUEST = REQUEST)) REQUEST.RESPONSE.write('<input style="display: none;" id="progressType" value="Analysis request import">')
REQUEST.RESPONSE.write('<input style="display: none;" id="progressDone" value="Validating...">') REQUEST.RESPONSE.write(pad + '<input style="display: none;" id="inputTotal" value="%s">' % len(samples)) row_count = 0 next_id = self.generateUniqueId('ARImportItem', batch_size = len(sample...
davelab6/pyfontaine
fontaine/charsets/noto_chars/notoserifgeorgian_bold.py
Python
gpl-3.0
8,189
0.015631
# -*- coding: utf-8 -*- class Charset(object): common_name = 'NotoSerifGeorgian-Bold' native_name = '' def glyphs(self): chars = [] chars.append(0x0000) #null ???? chars.append(0x000D) #nonmarkingreturn ???? chars.append(0x0020) #space SPACE chars.append(0x00A0)...
chars.append(0x10C0) #uni10C0 GEORGIAN CAPITAL LETTER HAE chars.append(0x10C1) #uni10C1 GEORGIAN CAPITAL LETTER HE chars.append(0x10C2) #uni10C2 GEORGIAN CAPITAL LETTER HIE chars.append(0x10C3) #uni10C3 GEORGIAN CAPITAL LETTER WE cha
rs.append(0x10C4) #uni10C4 GEORGIAN CAPITAL LETTER HAR chars.append(0x10C5) #uni10C5 GEORGIAN CAPITAL LETTER HOE chars.append(0x10D0) #uni10D0 GEORGIAN LETTER AN chars.append(0x10D1) #uni10D1 GEORGIAN LETTER BAN chars.append(0x10D2) #uni10D2 GEORGIAN LETTER GAN chars.append(...
jeffFranklin/uw-restclients
restclients/canvas/external_tools.py
Python
apache-2.0
1,719
0.000582
from restclients.canvas import Canvas #from restclients.models.canvas import ExternalTool class ExternalTools(Canvas): def get_external_tools_in_account(self, account_id): """ Return external tools for the passed canvas account id. https://canvas.inst
ructure.com/doc/api/external_tools.html#method.external_tools.index """ url = "/api/v1/accounts/%s/external_tools" % account_id external_tools = [] for data in self._get_resource(url): external_tools.append(self._external_tool_from_json(data)) return external_tools ...
.get_external_tools_in_account(self._sis_id(sis_id, "account")) def get_external_tools_in_course(self, course_id): """ Return external tools for the passed canvas course id. https://canvas.instructure.com/doc/api/external_tools...
project-chip/connectedhomeip
src/controller/python/chip/setup_payload/setup_payload.py
Python
apache-2.0
4,568
0.002627
# # Copyright (c) 2021 Project CHIP 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 applica...
s += ["BLE"] if int(value) & 0b100: rendezvous_methods += ["OnNetwork"] return ', '.join(rendezvous_methods) return None def __InitNativeFunctions(self, chipLib): if chipLib.pychip_SetupPayload_ParseQrCode is not None: return setter = Nat...
setter.Set("pychip_SetupPayload_ParseQrCode", c_int32, [c_char_p, SetupPayload.AttributeVisitor, SetupPayload.VendorAttributeVisitor]) setter.Set("pychip_SetupPayload_ParseManualPairingCode", c_int32, [c_char_p, SetupPayload.Attribut...
vighneshbirodkar/scikit-image
skimage/filters/tests/test_thresholding.py
Python
bsd-3-clause
11,985
0.000334
import numpy as np from numpy.testing import (assert_equal, assert_almost_equal, assert_raises) import skimage from skimage import data from skimage._shared._warnings import expected_warnings from skimage.filters.thresholding import (threshold_adaptive, ...
threshold = threshold_isodata(camera) assert np.floor((camera[camera <= threshold].mean() + camera[camera > threshold].mean()) / 2.0) == threshold assert threshold == 87 assert threshold_isodata(camera, return_all=True) == [87] def test_isodata_coins_image(): coins = skimage.im
g_as_ubyte(data.coins()) threshold = threshold_isodata(coins) assert np.floor((coins[coins <= threshold].mean() + coins[coins > threshold].mean()) / 2.0) == threshold assert threshold == 107 assert threshold_isodata(coins, return_all=True) == [107] def test_isodata_moon_image():...
paninetworks/neutron
neutron/db/migration/models/head.py
Python
apache-2.0
3,435
0
# Copyright (c) 2014 OpenStack Foundation. # 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...
oqa from neutron.db.metering import metering_db # noqa from neutron.db import model_base from neutron.db import models_v2 # noqa from neutron.db import portbindings_db # noqa from neutron.db import portsecurity_db # noqa from neutron.db.quota import models # noqa from neutron.db impor
t rbac_db_models # noqa from neutron.db import securitygroups_db # noqa from neutron.db import servicetype_db # noqa from neutron.ipam.drivers.neutrondb_ipam import db_models # noqa from neutron.plugins.bigswitch.db import consistency_db # noqa from neutron.plugins.bigswitch import routerrule_db # noqa from neutr...
cortesi/qtile
libqtile/extension/dmenu.py
Python
mit
7,038
0.001705
# Copyright (C) 2016, zordsdavini # # 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 without limitation the rights # to use, copy, modify, merge, publish, distri...
nd._configure(self, qtile) dmenu_command = self.dmenu_command or self.command if
isinstance(dmenu_command, str): self.configured_command = shlex.split(dmenu_command) else: # Create a clone of dmenu_command, don't use it directly since # it's shared among all the instances of this class self.configured_command = list(dmenu_command) if...
avicizhu/Load-balancer
src/visualizer/visualizer/base.py
Python
gpl-2.0
3,793
0.005537
import ns.point_to_point import ns.csma import ns.wifi import ns.bridge import ns.internet import ns.mesh import ns.wimax import ns.wimax import ns.lte import gobject import os.path import sys PIXELS_PER_METER = 3.0 # pixels-per-meter, at 100% zoom level class PyVizObject(gobject.GObject): __gtype_name__ = "PyVi...
t KeyError: sys.stderr.write("WARNING: no NetDeviceTraits registered for device type %r; " "I wil
l assume this is a non-virtual wireless device, " "but you should edit %r, variable 'netdevice_traits'," " to make sure.\n" % (class_type.__name__, __file__)) t = NetDeviceTraits(is_virtual=False, is_wireless=True) netdevice_traits[class_type] = t ...
pat-coady/trpo
trpo/utils.py
Python
mit
4,103
0.002194
""" Logging and Data Scaling Utilities Written by Patrick Coady (pat-coady.github.io) """ import numpy as np import os import shutil import glob import csv class Scaler(object): """ Generate scale and offset based on running mean and stddev along axis=0 offset = running mean scale = 1 / (stddev ...
self.log_entry = {} self.f = open(path, 'w') self.writer = None # DictWriter created with first call to write() method def write(self, display=True): """ Write 1 log entry to file, and optionally to stdout Log fields preceded by '_' will not be printed to stdout Args: ...
lf.disp(self.log_entry) if self.write_header: fieldnames = [x for x in self.log_entry.keys()] self.writer = csv.DictWriter(self.f, fieldnames=fieldnames) self.writer.writeheader() self.write_header = False self.writer.writerow(self.log_entry) self....
csm0042/rpihome
rpihome/devices/device_wemo_lrlt1.py
Python
gpl-3.0
3,812
0.006558
#!/usr/bin/python3 """ wemo_lrlt1.py: """ # Import Required Libraries (Standard, Third Party, Local) ************************************************************ import copy import datetime import logging import multiprocessing import time from .device_wemo import DeviceWemo # Authorship Info *********************...
if key == "home": self.home = value if key == "utcOffset": self.utcOffset = value if key == "sunriseOffset": self.sunriseOffset = value if key == "s
unsetOffset": self.sunsetOffset = value if key == "timeout": self.timeout = value # Calculate sunrise / sunset times self.sunrise = datetime.datetime.combine(datetime.datetime.today(), sel...
iraklikhitarishvili/data2class
base/base.py
Python
bsd-2-clause
2,011
0.001989
from validation.validationresult.resultenum import ResultType from validation.validationresult.result import Result class BaseMixin: def __init__(self, result_type: ResultType = ResultType.Base) -> None: self._validators = [] self._result_type = result_type @property def validators(self)...
1. ``is_valid`` indicates whether data in object is valid or not 2. ``errors`` dictionary of errors :rtype: dict """ # data.errors.clear() # todo-urgent dependency in validation and stop when encountering specific errors validations = [validator(se...
s): return Result.factor_result(self._result_type, True, None) return Result.factor_result( self._result_type, False, [Result.get_error(result) for result in validations if not Result.is_valid(result)] )
gercordero/va_de_vuelta
src/estadisticas.py
Python
gpl-3.0
1,023
0.036168
import pilas import json from pilas.escena import Base from general import General from individual import Individual class jugadores(Base):
def __init__(self): Base.__init__(self) def fondo(self): pilas.fondos.Fondo("data/img/fondos/aplicacion.jpg") def general(self): self.sonido_boton.reproducir() pilas.almacenar_escena(General()) def individual(self): self.sonido_boton.reproducir()
pilas.almacenar_escena(Individual()) def volver(self): self.sonido_boton.reproducir() pilas.recuperar_escena() def iniciar(self): self.fondo() self.sonido_boton = pilas.sonidos.cargar("data/audio/boton.ogg") self.interfaz() self.mostrar() def interfaz(self): opcion= [("General",self....
ENCODE-DCC/encoded
src/encoded/upgrade/gene.py
Python
mit
437
0.002288
from snovault
import upgrade_step @upgrade_step('gene', '1', '2') def gene_1_2(value, system): # https://encodedcc.atlassian.net/browse/ENCD-5005 # go_annotations are replaced by a link on UI to GO value.pop('go_annotations', None) @upgrade_step('gene', '2', '3') def gene_2_3(value, system): # h
ttps://encodedcc.atlassian.net/browse/ENCD-6228 if value.get('locations') == []: value.pop('locations', None)
waveFrontSet/box_management
box_management/boxes/urls.py
Python
mit
1,131
0.000884
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.conf.urls import url from . import views urlpatterns = [ url( regex=r'^$', view=views.BoxListView.as_view(), name='boxlist', ), url( regex=r'^(?P<box>[\w-]+)/$', view=view...
.as_view(), name='item_take', ), url( regex=r'^(?P<box>[\w-]+)/return/(?P<pk>[\d]+)$', view=views.
BoxItemReturnView.as_view(), name='item_return', ), url( regex=r'^(?P<box>[\w-]+)/(?P<category>[\w-]+)/$', view=views.BoxCategoryItemListView.as_view(), name='items_by_category', ), ]
Eddy0402/Environment
vim/ycmd/third_party/jedi/test/completion/goto.py
Python
gpl-3.0
2,526
0.032462
# goto_assignments command tests are different in syntax definition = 3 #! 0 ['a = definition'] a = definition #! [] b #! ['a = definition'] a b = a c = b #! ['c = b'] c cd = 1 #! 1 ['cd = c'] cd = c #! 0 ['cd = e'] cd = e #! ['module math'] import math #! ['import math'] math #! ['import math'] b = math #! ['b =...
module import_tree'] import import_tree #! ["a = ''"] import_tree.a #! ['module mod1'] import import_tree.mod1 #! ['a = 1'] import_tree.mod1.a #! ['module pkg'] import import_tree.pkg #! ['a = list'] import_tree.pkg.a #! ['module mod1'] import import_tree.pkg.mod1 #! ['a = 1.0'] import_tree.pkg.mod1.a
#! ["a = ''"] import_tree.a #! ['module mod1'] from import_tree.pkg import mod1 #! ['a = 1.0'] mod1.a #! ['module mod1'] from import_tree import mod1 #! ['a = 1'] mod1.a #! ['a = 1.0'] from import_tree.pkg.mod1 import a #! ['import os'] from .imports import os #! ['some_variable = 1'] from . import some_variable ...
pjkundert/mincemeatpy
example-sf-daemon.py
Python
mit
15,126
0.008528
#!/usr/bin/env python import mincemeat import glob import logging import repr import socket import errno import asyncore import threading import time import traceback import sys """ example-sf-daemon -- elect a server, become a client; uses daemons To run this test, simply start an instances of this script:...
# Collect, Reduce, or Finish Functions. # # Take (key,value) or (key,[value,...]) pairs, or an iterable # producing such, and return the single value mapped to that key. The # func
tional version returns just the value; the iterable version must # return the (key,value) pair. # # If the function is resilient to taking a value that is either an # iterable OR is a single value, then the same function may be used # for any of the Collect, Reduce or Finish functions. Collect and # Reduce will a...
iAddz/allianceauth
services/modules/market/models.py
Python
gpl-2.0
664
0
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.contrib.auth.models import User from dja
ngo.db import models @python_2_unicode_compatible class MarketUser(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE, related_name='market') username = models.CharField(max...
e Evernus Market service"), )
JoshMayberry/Numerical_Methods
Bisection/bisection plotable 2.py
Python
mit
2,124
0.015066
import math from equations import * from my_functions import * import numpy as np def function(fn,x): x = [x] fx = fn(x) return fx def bip(fn,xaxis=[-1,1],inc=0.1,edes=0.01): """This function runs bi(), but first shows you a plot and lets you choose the roots you want. 'fn' is the name of a
n equation in 'equations.py' 'coeff' are the coefficents for the function as a list 'xax
is' is [min x on graph, max x on graph]. The default is [-1,1] 'inc' is what the tickmarks(increments) will increase by. The default is 0.1. 'edes' is the desired margin of error. The default is 1% error. Example Input: bip(eq1,0.001) """ plot(fn,xaxis,inc) xbounds = [0,0] xbounds[0] = eval(inp...
underloki/Cyprium
kernel/brainfuck.py
Python
gpl-3.0
32,233
0.000093
######################################################################## # # # Cyprium is a multifunction cryptographic, steganographic and # # cryptanalysis tool developped by members of The Hackademy. # # French White Hat Hackers...
= 1 cells[cellptr] = (cells[cellptr] + val) % 255 elif cmd == self.DEC: if val is None: val = 1
cells[cellptr] = (cells[cellptr] - val) % 255 elif cmd == self.BOPEN and cells[cellptr] == 0: codeptr = bracemap[codeptr] elif cmd == self.BCLOSE and cells[cellptr] != 0: codeptr = bracemap[codeptr] elif cmd == self.OUTPUT: ...
brousch/opencraft
instance/tests/views/test_index.py
Python
agpl-3.0
1,651
0
# -*- coding: utf-8 -*- # # OpenCraft -- tools to aid developing and hosting free software projects # Copyright (C) 2015 OpenCraft <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Soft...
ts.base import WithUserTestCase # Tests ####################################################################### class IndexViewsTestCase(WithUserTestCase): """ Test cases for views """ def test_index_unauthenticated(self):
""" Index view - Unauthenticated users go to login page """ response = self.client.get('/') self.assertRedirects(response, 'http://testserver/admin/login/?next=/') def test_index_authenticated(self): """ Index view - Authenticated """ self.client....
ashutoshvt/psi4
tests/pytests/test_geometric.py
Python
lgpl-3.0
3,139
0.010831
import pytest from .utils import * import psi4 from qcengine.testing import using @pytest.mark.parametrize('engine', [ pytest.param('optking'), pytest.param('geometric', marks
=using('geometric')), ]) # yapf: disable @pytest.mark.parametrize('inp', [ pytest.param({'name': 'hf', 'options': {'scf_type': 'df'}, 'ref_ene' : -76.027032783717, 'ref_nuc': 9.300794299874}, id='rhf(df)'), pytest.param(
{'name': 'hf', 'options': {'scf_type': 'pk'}, 'ref_ene' : -76.027053512764, 'ref_nuc': 9.300838770294}, id='rhf(pk)'), pytest.param({'name': 'mp2', 'options': {'mp2_type': 'df'}, 'ref_ene' : -76.230938589591, 'ref_nuc': 9.133271168193}, id='mp2(df)'), pytest.param({'name': 'mp2', 'options': {'mp2_type': 'conv'}...
endlessm/chromium-browser
tools/clang/scripts/goma_ld.py
Python
bsd-3-clause
2,071
0.01014
#! /usr/bin/env python # Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Linker wrapper that performs distributed ThinLTO on Goma. # # Usage: Pass the original link command as parameters to this
script. # E.g. original: clang++ -o foo foo.o # Becomes: goma-ld clang++ -o foo foo.o from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import goma_link import os import re import sys class GomaLinkUnix(goma_link.Gom...
SEP = '=' GROUP_RE = re.compile(WL + '--(?:end|start)-group') MACHINE_RE = re.compile('-m([0-9]+)') OBJ_PATH = '-plugin-opt=obj-path' + SEP OBJ_SUFFIX = '.o' PREFIX_REPLACE = TLTO + '-prefix-replace' + SEP XIR = '-x ir ' WHITELISTED_TARGETS = { 'chrome', } def analyze_args(self, args, *posar...
madisonmay/Tomorrow
setup.py
Python
mit
521
0
from setuptools import setup, find_packages setup( na
me="tomorrow", version="0.2.4", author="Madison May", author_email="[email protected]", packages=find_packages( exclude=[ 'tests' ] ), install_requires=[ "futures >= 2.2.0" ], description=""" Ma
gic decorator syntax for asynchronous code. """, license="MIT License (See LICENSE)", long_description=open("README.rst").read(), url="https://github.com/madisonmay/tomorrow" )
henrywm/URI
src/beginner/1759.py
Python
apache-2.0
73
0.041096
N =
int(input()) gemido = (N-1) * "Ho " print("{0}Ho!".format(ge
mido))
qdev-dk/Majorana
alazar_controllers/acq_helpers.py
Python
gpl-3.0
1,250
0.0016
import numpy as np import math def sample_to_volt_u12(raw_samples, bps, input_range_volts): """ Applies volts conversion for 12 bit sample data stored in 2 bytes return: samples_magnitude_array samples_phase_array """ # right_shift 16-bit sample by 4 to get 12 bit sample s...
up the 'num' to the nearest multiple of 'to_nearest', all int Args: num: to be rounded up to_nearest: value to be rounded to int multiple of return: rounded up value """ remainder = num % to_nearest
divisor = num // to_nearest return int(num if remainder == 0 else (divisor + 1)*to_nearest) # there seems to be alignment related issues with non power of two # buffers so restrict to power of two for now # smallest_power = 2 ** math.ceil(math.log2(num)) # return max(smallest_power, 256)
pawl/CalendarAdmin
application/views/__init__.py
Python
mit
416
0
__all__ = [] import pkgutil import inspect # http://stackoverflow.com/questions/22209564/python-qualified-import-all-in-package for loader, name, is_pkg in pkgutil.walk_packages(__path__): mod
ule = loader.find_module(name).load_module(name) for name, value in inspect.getmembers(module): if name.start
swith('__'): continue globals()[name] = value __all__.append(name)
GiantSteps/essentia
src/python/essentia/extractor/relativeioi.py
Python
agpl-3.0
3,063
0.024159
# Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Essentia # # Essentia is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation (FSF), either version 3 of the ...
onsets[0] for i in range(1,len(onsets)): riois += [ round( (onsets[i] - onsets[i-1]) / interval ) ] for i in range(2,len(onsets)): riois += [ round( (onsets[i] - onsets[i-2]) / interval ) ] for i in range(3,len(onsets)): riois += [ round( (onsets[i] - onsets[i-3]) / interval ) ] for i in range(4,len(ons...
range(len(ioidist))], [ioi/sum(ioidist) for ioi in ioidist])) fullioidist = fullioidist[0:interp*5] peak_detection = essentia.PeakDetection(minPosition = 0., maxPosition = len(ioidist), maxPeaks = 5, range = len(ioidist) - 1., ...
702nADOS/sumo
tools/webWizard/SimpleWebSocketServer.py
Python
gpl-3.0
23,861
0.000838
""" @file SimpleWebSocketServer.py @author Dave Pallot @date 2013 @version $Id: SimpleWebSocketServer.py 22608 2017-01-17 06:28:54Z behrisch $ A web socket server implementation to be used by the osm server.py Originally distributed under the MIT license at https://github.com/dpallot/simple-websocket-server/tre...
elf.frag_buffer.append(utf_str) else: self.frag_buffer = bytearray() self.frag_buffer.extend(self.data) else: if self.frag_start is False: raise Exception('fragmentation protocol error') if self.fra...
self.frag_buffer.append(utf_str) else: self.frag_buffer.extend(self.data) else: if self.opcode == STREAM: if self.frag_start is False: raise Exception('fragmentation protocol error') if se...
iwob/pysv
pysv/smt_synthesis.py
Python
mit
17,716
0.005532
from pysv.smtlib.synth import SynthesisConstr from pysv.smtlib.synth import SynthesisConstrTestCases from pysv.templates import * from pysv.contract import * from pysv import solvers from pysv import smt_common # # Python ast package documentation: https://docs.python.org/2/library/ast.html # Python _ast package doc...
ral Z3 tutorial: http://rise4fun.com/z3/tutorial/guide # - python Z3 tutorial: http://cpl0.net/~argp/papers/z3py-guide.pdf # - Advanced python materials: http:
//www.cs.tau.ac.il/~msagiv/courses/asv/z3py/ # # *** z3 binding for Scala: http://lara.epfl.ch/~psuter/ScalaZ3/ # # z3.parse_smt2_string() - a function which can use smt2 code instead of explicitly using python api. # (set-option :macro-finder true) - allows for filling bodies of functions. # class SynthesizerSMT(ob...
GoogleCloudPlatform/repo-automation-playground
xunit-autolabeler-v2/ast_parser/lib/test_data/appengine/gae_sample.py
Python
apache-2.0
695
0
# Copyright 2020 Google LLC. # # 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, ...
D, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # [START gae_detected_tag] # [END gae_detected_tag] """ [ST
ART gae_block_comment_tag] [END gae_block_comment_tag] """
rnirmal/savanna
savanna/tests/unit/utils/test_api_validator.py
Python
apache-2.0
6,499
0
# Copyright (c) 2013 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 agreed to in writ...
"a" * 64) self._validate_failure(schema, "") def test_validate_configs(self): schema = { "type": "object", "properties": { "configs": { "type": "configs", } }, "additionalProperties": False }...
"c-2": 1, "c-3": True, }, "at-2": { "c-4": "c", "c-5": 1, "c-6": True, }, }, }) self._validate_failure(schema, { "configs": { ...