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
Jumpscale/jumpscale6_core
apps/admin/jumpscripts/varia/upload_root_keys.py
Python
bsd-2-clause
1,949
0.015393
from JumpScale import j descr = """ Fetches the public keys from the vscalers_sysadmin repo and puts them in authorized_keys use '-e system ' to only use the system key (e.g. in production env on a mgmt node) """ organization = "vscalers" author = "[email protected]" license = "bsd" version = "1.0" category = "ssh....
if str(tags)=="system": for name in ["id_dsa","id_dsa.pub"]:
u = j.system.fs.joinPaths(basepath, 'identities',username,name) j.system.fs.copyFile(u,"/root/.ssh/%s"%name) j.system.fs.chmod("/root/.ssh/%s"%name,384) else: # Fetch keys from repo for filename in j.system.fs.listFilesInDir(d, recursive=True, filter='*id.hrd'):...
manuBocquet/ansible-report
callbackplugin/ansible-report.py
Python
gpl-3.0
5,751
0.009216
# (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' callback: debug type: stdout short_description: formated stdout/stderr display...
################ # Add module filter to send data to an sqlite database def init_sqlite(self, file): #self._display.display("init database [%s]" % file) self.db = sqlite3.connect(file) self.cdb = self.db.cursor() self.cdb.execute('''DROP TABLE IF EXISTS ansible''') s...
data, value, epoch, task): self.cdb.execute("INSERT or REPLACE INTO ansible (host,data,value,epoch,task) VALUES (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" % (hostname,data,value,epoch,task)) def module_filter(self, result): #self._display.display("Module filter, action: {}".format(result._task.action))...
cloudtools/troposphere
troposphere/datapipeline.py
Python
bsd-2-clause
2,721
0.002573
# Copyright (c) 2012-2022, Mark Peek <[email protected]> # All right
s reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** from . import AWSObject, AWSProperty, PropsDictType from .validators import boolean class ParameterObjectAttribute(AWSProperty): """ `ParameterObjectAttribute <http://docs.aws.amazon.com/AWSCloudFormati...
tringValue": (str, True), } class ParameterObject(AWSProperty): """ `ParameterObject <http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-datapipeline-pipeline-parameterobjects.html>`__ """ props: PropsDictType = { "Attributes": ([ParameterObjectAttribute], True),...
Mirio/steamstoreprice
steamstoreprice/steamstoreprice.py
Python
bsd-2-clause
2,007
0.002495
from steamstoreprice.exception import UrlNotSteam, PageNotFound, RequestGenericError from bs4 import BeautifulSoup import requests class SteamStorePrice: def normalizeurl(self, url): """ clean the url from referal and other stuff :param url(string): amazon url :return: string(ur...
the url, it doesn't contain store.steampowered.com/app*") def normalizeprice(self, price): """ remove the currenty from price :
param price(string): price tag find on amazon store :return: float(price cleaned) """ listreplace = ["€", "$", "£", "\t", "\r\n"] for replacestring in listreplace: price = price.replace(replacestring, "") return float(price.replace(",", ".")) def getpage(self, ...
Ghost-script/fedmsg_meta_fedora_infrastructure
fedmsg_meta_fedora_infrastructure/buildsys.py
Python
lgpl-2.1
16,007
0.000187
# This file is part of fedmsg. # Copyright (C) 2012 Red Hat, Inc. # # fedmsg is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public #
License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg 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...
e Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Ralph Bean <[email protected]> # from fedmsg_meta_fedora_infrastructure import BaseProcessor from fedmsg_meta_fedora_infrastructure.fasshim import avatar_url import fedmsg.meta.base import datetime from pytz import...
greenape/risky-aging-model
disclosuregame/Util/__init__.py
Python
mpl-2.0
3,317
0.001809
__all__ = ["sqlite_dump", "sqlite_merge"] from random import Random import math def random_expectations(depth=0, breadth=3, low=1,
high=10, random=Random()): """ Generate depth x breadth array of random numbers where each row sums to high, with a minimum of low. """ result = [] if depth == 0: initial = high + 1 for i in range(breadth - 1): n = random.randint(low, initial - (low * (breadth - i))) ...
huffle(result) else: result = [random_expectations(depth - 1, breadth, low, high, random) for x in range(breadth)] return result def rescale(new_low, new_high, low, diff, x): scaled = (new_high-new_low)*(x - low) scaled /= diff return scaled + new_low def weighted_random_choice(choices, ...
andersonsilvade/python_C
Python32/web2py/scripts/bench.py
Python
mit
295
0.016949
import time import
sys import urllib2 import urllib2 n = int(sys.argv[1]) url = sys.argv[2] headers = {"Accept-Language" : "en" } req = urllib2.Request(url, None, headers) t0 = time.time() for k in xrange(n): data = urllib2.urlopen(req).read() print (t
ime.time()-t0)/n if n==1: print data
Debian/openjfx
modules/web/src/main/native/Tools/Scripts/webkitpy/benchmark_runner/benchmark_results_unittest.py
Python
gpl-2.0
16,571
0.006216
# Copyright (C) 2015 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
ER CAUSED AND ON # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import u
nittest from benchmark_results import BenchmarkResults class BenchmarkResultsTest(unittest.TestCase): def test_init(self): results = BenchmarkResults({'SomeTest': {'metrics': {'Time': {'current': [1, 2, 3]}}}}) self.assertEqual(results._results, {'SomeTest': {'metrics': {'Time': {None: {'current'...
MTG/gaia
src/bindings/pygaia/scripts/dataset_to_csv.py
Python
agpl-3.0
1,937
0.002065
#!/usr/bin/env python # Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra # # This file is part of Gaia # # Gaia 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 ve...
NU General Public License for more # details. # # You should have received a copy of the Affero GNU General Public License # version 3 along with this program. If not, see http://www.gnu.org/licenses/ from __future__ import print_function import sys import g
aia2 def dataset_to_csv(filename, csv_filename): ds = gaia2.DataSet() ds.load(filename) out = open(csv_filename, 'w') valueNames = ds.layout().descriptorNames(gaia2.RealType) labelNames = ds.layout().descriptorNames(gaia2.StringType) out.write('Track name;') for name in labelNames: ...
axaxs/pyparted
src/parted/partition.py
Python
gpl-2.0
9,919
0.001512
# # Code modified from original to work with Python 3 # Alex Skinner # [email protected] # 12/28/2012 # # partition.py # Python bindings for libparted (built on top of the _ped Python module). # # Copyright (C) 2009 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redi...
y = property(lambda s: s._geometry, lambda s, v: setattr(s, "_geometry", v)) system = property(lambda s: s.__writeOnly("system"), lambda s, v: s.__partition.set_system(v)) type = property(lambda s: s.__partition.type, lambd
a s, v: setattr(s.__partition, "type", v)) @localeC def getFlag(self, flag): """Get the value of a particular flag on the partition. Valid flags are the _ped.PARTITION_* constants. See _ped.flag_get_name() and _ped.flag_get_by_name() for more help working with partition flags. ...
degoldschmidt/pytrack-analysis
examples/run_post_tracking.py
Python
gpl-3.0
5,316
0.005455
import os import numpy as np import pandas as pd from pytrack_analysis import Multibench from pytrack_analysis.dataio import VideoRawData from pytrack_analysis.profile import get_profile, get_scriptname, show_profile from pytrack_analysis.posttracking import frameskips, get_displacements, mistracks, get_head_tail, get...
start_time':
raw_data.starttime} _yaml = _file[:-4]+'.yaml' with io.open(_yaml, 'w', encoding='utf8') as f: yaml.dump(meta_dict, f, default_flow_style=False, allow_unicode=True) """ if __name__ == '__main__': # runs as benchmark test test = Multibench("", SILENT=False, SLIM=True)...
dpaschall/test_TensorFlow
bin/cifar10test/cifar10_train.py
Python
gpl-3.0
4,167
0.00528
# 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...
.framework.get_or_create_global_step() # Get images and labels for CIFAR-10. images, labels = cifar10.distorted_inputs() # Build a Graph that computes the logits predictions from the # inference model. logits = cifar10.inference(images) # Calculate loss. loss = cifar10.loss(logits, labels...
train_op = cifar10.train(loss, global_step) class _LoggerHook(tf.train.SessionRunHook): """Logs loss and runtime.""" def begin(self): self._step = -1 def before_run(self, run_context): self._step += 1 self._start_time = time.time() return tf.train.SessionRun...
owtf/ptp
tests/tools/robots/robots_reports.py
Python
bsd-3-clause
232
0
report_info = """User-agent: * Disallow: /se
arch Disallow: /sdch Disallow: /groups Disallow: /images Disallow: /admin Disallow: /catalogs Allow: /catalogs/about Allow: /catalogs/p?""" report_unknown = """User-agent: * Allow: /"""
DEAP/deap
doc/code/benchmarks/kursawe.py
Python
lgpl-3.0
855
0.009357
from mpl_toolkits.mplot3d import A
xes3D from matplotlib import cm import matplotlib.pyplot as plt try: import numpy as np except: exit() from deap import benchmarks X = np.arange(-5, 5, 0.1) Y = np.arange(-5, 5, 0.1) X, Y = np.meshgrid(X, Y) Z1 = np.zeros(X.shape) Z2 = np.zeros(X.shape) for i in range(X.shape[0]): for j in range(X.shape...
(1, 2, 1, projection='3d') ax.plot_surface(X, Y, Z1, rstride=1, cstride=1, cmap=cm.jet, linewidth=0.2) plt.xlabel("x") plt.ylabel("y") ax = fig.add_subplot(1, 2, 2, projection='3d') ax.plot_surface(X, Y, Z2, rstride=1, cstride=1, cmap=cm.jet, linewidth=0.2) plt.xlabel("x") plt.ylabel("y") plt.subplots_adjust(left=0, ...
klyap/pipe2py
pipe2py/modules/pipeurlinput.py
Python
gpl-2.0
822
0
# -*- coding: utf-8 -*- # vim: sw=4:ts=4:expandtab """ pipe2py.modules.pipeurlinput ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ http://pipes.yahoo.com/pipes/docs?doc=user_inputs#URL """ from pipe2py.lib import utils def pipe_urlinput(context=None, _INPUT=None, conf=None, **kwargs): """An input that prompts the use...
r. Not loopable. Parameters ---------- context : pipe2py.Conte
xt object _INPUT : unused conf : { 'name': {'value': 'parameter name'}, 'prompt': {'value': 'User prompt'}, 'default': {'value': 'default value'}, 'debug': {'value': 'debug value'} } Yields ------ _OUTPUT : url """ value = utils.get_input(context, conf) ...
asm-products/pants-party
textjokes/migrations/0003_auto_20150323_2213.py
Python
agpl-3.0
1,299
0.00154
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('textjokes', '0002_auto_20150323_1524'), ...
], options={
'ordering': ['-id'], }, bases=(models.Model,), ), migrations.AlterModelOptions( name='textjoke', options={'ordering': ['-id']}, ), ]
CINPLA/expipe-dev
expipe-plugin-cinpla/tests/test_intan.py
Python
gpl-3.0
2,175
0.005057
import pytest import expipe import subprocess import click from click.testing import CliRunner import quantities as pq import os.path as op from expipe_plugin_cinpla.intan import IntanPlugin from expipe_plugin_cinpla.electrical_stimulation import ElectricalStimulationPlugin fr
om expipe_plugin_cinpla.main import CinplaPlugin expipe.ensure_testing() @click.group() @click.pass_context def cli(ctx): pass IntanPlugin().attach_to_cli(cli) ElectricalStimulationPlugin().attach_to_cli(cli) CinplaPlugin().attach_to_cli(cli) def run_command(command_list
, inp=None): runner = CliRunner() result = runner.invoke(cli, command_list, input=inp) if result.exit_code != 0: print(result.output) raise result.exception def test_intan():#module_teardown_setup_project_setup): currdir = op.abspath(op.dirname(__file__)) intan_path = op.join(currd...
ruchee/vimrc
vimfiles/bundle/vim-python/submodules/pylint/tests/functional/t/typing/typing_consider_using_alias_without_future.py
Python
mit
1,918
0.005214
"""Test pylint.extension.typing - consider-using-alias 'py-version' needs to be set to '3.7' or '
3.8' and 'runtime-typing=no'. """ # pylint: disable=missing-docstring,invalid-name,unused-argument,line-too-long,unsubscriptable-object import collections import collections.abc import typing from collections.abc import Awaitable from dataclasses import dataclass from typing import Dict, List, Set, Union, TypedDict va...
ng.OrderedDict[str, int] # [consider-using-alias] var5: typing.Awaitable[None] # [consider-using-alias] var6: typing.Iterable[int] # [consider-using-alias] var7: typing.Hashable # [consider-using-alias] var8: typing.ContextManager[str] # [consider-using-alias] var9: typing.Pattern[str] # [consider-using-alias] va...
tranqui/PyTrajectories
saddle-nucleation.py
Python
gpl-3.0
1,177
0.008496
#!/usr/bin/env python2.7 from configuration import * from pylab import * import copy # Non-dimensional units where D=sigma=1. rho = 25 # good model for hard sphere. def morse_potential(r): return (1 - exp(-rho*(r-1)))^2 def morse_force(r): return -2*exp(-rho*(r-1))*(1 - exp(-rho*(r-1))) # Vector force acting...
n morse_force(r)*(delta_r/r) if __name__ == '__main__': if len(sys.argv) < 2: print "missing parameter: saddle-nucleation.py <in-file>" else: initial_config = Configuration(sys.argv[1]) N = initial_config.num_particles forces = zeros((N, 3))
for i in range(0, N): print "Forces on " + str(i) + ":" for j in range(i+1, N): F = interatomic_force(initial_config.positions[i], initial_config.positions[j]) forces[i,:] += F forces[j,:] -= F copy_conf = copy.deepcopy(initial_con...
tensorflow/graphics
tensorflow_graphics/nn/layer/__init__.py
Python
apache-2.0
984
0
# Copyright 2020 The TensorFlow 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for t
he specific language governing permissions and # limitations under the License. """Layer module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow_graphics.nn.layer import graph_convolution from tensorflow_graphics.nn.layer import pointnet f...
Stavitsky/python-neutronclient
neutronclient/tests/unit/test_utils.py
Python
apache-2.0
3,942
0
# Copyright (C) 2013 Yahoo! 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 ...
' fields = ('name', 'id', 'test user') item = Fake() actual = utils.get_item_properties(item, fields) self.assertNotEqual(('test_name', 'test_id', 'test'), actual) def test_get_object_item_desired_fields_is_empty(self): class Fake(object): def __init__(self): ...
self.id = 'test_id_1' self.name = 'test_name' self.test_user = 'test' fields = [] item = Fake() actual = utils.get_item_properties(item, fields) self.assertEqual((), actual) def test_get_object_item_with_formatters(self): class Fake(o...
Jetzal/Picture
picture.py
Python
mit
1,761
0.014196
""" picture.py Author: Jett Credit: None Assignment: Use the ggame library to "paint" a graphical picture of something (e.g. a house, a face or landscape). Use at least: 1. Three different Color objects. 2. Ten different Sprite objects. 3. One (or more) RectangleAsset objects. 4. One (or more) CircleAsset objects. 5...
thinline, black) chimmney= RectangleAsset(70, 170, thinline, black) Sun=CircleAsset(130, thinline, yellow) Earth=RectangleAsset(10010, 300, thinline, green) Sprite(House,(500,400)) Sprite(polygon,(500,400)) Sprite(Swindow, (850,400)) Sprite(window, (550, 550)) Sprite(window,
(1050, 550)) Sprite(door, (800, 680)) Sprite(ellipse,(850,705)) Sprite(chimmney, (600, 200)) Sprite(Sun, (80, 80)) Sprite(Earth,(-20, 830)) # add your code here /\ /\ /\ myapp = App() myapp.run()
gustavofonseca/inbox
penne_core/contrib/sites/migrations/0002_set_site_domain_and_name.py
Python
bsd-2-clause
1,132
0
""" To understand why this file is here, please read: http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django """ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from djang
o.db import migrations def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model('sites', 'Site') Site.objects.update_or_create( id=settings.SITE_ID, defaults={
'domain': 'example.com', 'name': 'penne_core' } ) def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model('sites', 'Site') Site.objects.update_or_create( id=settings.SITE_ID, defaults={ 'domain'...
yufeldman/arrow
python/pyarrow/tests/test_types.py
Python
apache-2.0
7,112
0
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
type_] = i assert in_dict[type_] == i assert len(in_dict) == len(MANY_TYPES) def test_types_pic
klable(): for ty in MANY_TYPES: data = pickle.dumps(ty) assert pickle.loads(data) == ty @pytest.mark.parametrize('t,check_func', [ (pa.date32(), types.is_date32), (pa.date64(), types.is_date64), (pa.time32('s'), types.is_time32), (pa.time64('ns'), types.is_time64), (pa.int8(), ...
nohona/cron-crm
usr/local/certbot/certbot-apache/certbot_apache/tests/complex_parsing_test.py
Python
gpl-3.0
4,535
0
"""Tests for certbot_apache.parser.""" import os import shutil import unittest from certbot import errors from certbot_apache.tests import util class ComplexParserTest(util.ParserTest): """Apache Parser Test.""" def setUp(self): # pylint: disable=arguments-differ super(ComplexParserTest, self).set...
t being run # until after self.parser.init_modules() # pylint: disable=protected-access def tearDown(self): shutil.rmtree(self.temp_dir) shutil.rmtree(self.config_dir) shutil.rmtree(self.work_dir) def se
tup_variables(self): """Set up variables for parser.""" self.parser.variables.update( { "COMPLEX": "", "tls_port": "1234", "fnmatch_filename": "test_fnmatch.conf", "tls_port_str": "1234" } ) def test_fil...
morishin/alfred-xcfind-workflow
xcfind.py
Python
mit
1,495
0.008027
import os import subprocess import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))+ '/enum') sys.path.append(os.path.dirname(os.path.abspath(__file__))+ '/workflow') from enum import Enum fr
om workflow import Workflow class FileType(Enum): xcodeproj = 'xcode-project_Icon.icns' xcworkspace = 'workspace_Icon.icns' playground = 'playground_Icon.icns' def extension(self): return self.name def icon(self): return self.value def search(query, file_type): find_command ...
rmat(query, file_type.extension()) found_paths = subprocess.check_output(find_command, shell=True).decode("utf-8").rstrip().split("\n") results = [] for path in found_paths: filename = path.split("/")[-1] results.append((filename, path, file_type.icon())) return results def main(wf): ...
shagi/guifiadmin
vpn/migrations/0001_initial.py
Python
agpl-3.0
3,807
0.005779
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-11-01 08:23 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('guifi', '0001_initial'), ('account...
teModel( name='TincClient', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('vpn_address', models.CharField(max_length=200, verbose_name='vpn address')), ('private_key', models.TextField(...
ll=True, verbose_name='public key')), ('upload', models.PositiveSmallIntegerField(default=400, help_text='speed in kbit/s', verbose_name='upload')), ('download', models.PositiveSmallIntegerField(default=4000, help_text='speed in kbit/s', verbose_name='download')), ], ...
jakirkham/volumina
tests/layerwidget_test.py
Python
lgpl-3.0
4,634
0.007553
############################################################################### # volumina: volume slicing and editing library # # Copyright (C) 2011-2014, the ilastik developers # <[email protected]> # # This program is free software; you can redistribute it and/or # modify it und...
# Change the visibility of the *selected* layer self.o2.visible = Tru
e self.w.repaint() # Make sure the GUI is caught up on paint events QApplication.processEvents() # We must sleep for the screenshot to be right. time.sleep(0.1) # Capture the window now that we've changed a ...
aguijarro/DataSciencePython
DataWrangling/CaseStudy/project/analyze_data.py
Python
mit
1,201
0.004163
import matplotlib.pyplot as plt import pandas as pd # Create a list of colors (from iWantHue) colors = ["#E13F29", "#D69A80", "#D63B59", "#AE5552", "#CB5C3B", "#EB8076", "#96624E"] def draw_data(st_types_count, keys, explode): data = st_types_count.fromkeys(keys) for d in data: data[d] = st_types_co...
s.append(value)
raw_data["keys"] = keys raw_data["values"] = values df = pd.DataFrame(raw_data, columns = ['keys', 'values']) print ("data", df) # Create a pie chart plt.pie( # using data total)arrests df['values'], # with the labels being officer names labels=df['keys'], ...
jashandeep-sohi/aiohttp
tests/test_py35/test_client_websocket_35.py
Python
apache-2.0
1,892
0
import pytest import aiohttp from aiohttp import web @pytest.mark.run_loop async def test_client_ws_async_for(loop, create_server): items = ['q1', 'q2', 'q3'] async def handler(request): ws = web.WebSocketResponse() await ws.prepare(request) for i in items: ws.send_str(i)...
next(it) assert resp.closed @pytest.mark.run_loop async def test_client_ws_async_with(loop, create_app_and_client): async def handler(request): ws = web.WebSocketResponse() await ws.prepare(request) msg = await ws.receive() ws.send_str(msg.data + '/answer') await ...
p.router.add_route('GET', '/', handler) async with client.ws_connect('/') as ws: ws.send_str('request') msg = await ws.receive() assert msg.data == 'request/answer' assert ws.closed @pytest.mark.run_loop async def test_client_ws_async_with_shortcut(loop, create_server): async de...
stdweird/aquilon
lib/python2.6/aquilon/worker/formats/cpu.py
Python
apache-2.0
1,186
0.001686
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2013 Contributor # # 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 the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific ...
om aquilon.aqdb.model import Cpu class CpuFormatter(ObjectFormatter): def format_raw(self, cpu, indent=""): details = [indent + "Cpu: %s %s %d MHz" % (cpu.vendor.name, cpu.name, cpu.speed)] if cpu.comments: details.append(indent + " Comments: %s" % cpu.comments) ...
marcelnicolay/pycompressor
compressor/cli.py
Python
lgpl-3.0
2,967
0.006741
# coding: utf-8 # <pycompressor - compress and merge static files (css,js) in html files> # Copyright (C) <2012> Marcel Nicolay <[email protected]> # # This program 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 So...
class CLI(object): color = { "PINK": "", "BLUE": "", "CYAN": "", "GREEN": "", "YELLOW": "", "RED": "", "END": "", } @staticmethod def show_colors(): CLI.color = { "PINK": "\033[35m", "BLUE": "\033[34m", ...
"CYAN": "\033[36m", "GREEN": "\033[32m", "YELLOW": "\033[33m", "RED": "\033[31m", "END": "\033[0m", } def __init__(self): self.__config_parser() def __config_parser(self): self.__parser = OptionParser(usage="usage: %prog [options] start...
anna-effeindzourou/trunk
examples/rotationalResistance.py
Python
gpl-2.0
1,465
0.055328
#!/usr/bin/env python # encoding: utf-8 from yade import utils, plot o = Omega() fr = 0.5;rho=2000 tc = 0.001; en = 0.7; et = 0.7; o.dt = 0.0002*tc r = 0.002 mat1 = O.materials.append(ViscElMat(frictionAngle=fr,mR = 0.05, mRtype = 1, density=rho,tc=tc,en=en,et=et)) mat2 = O.materials.append(ViscElMat(frictionAngle=fr...
[Ig2_Sphere_Sphere_ScGeom(),Ig2_Facet_Sphere_ScGeom()], [Ip2_ViscElMat_ViscElMat_ViscElPhys()], [Law2_ScGeom_ViscElPhys_Basic()], ), NewtonIntegrator(damping=0,gravity=[0,0,-9.81]), PyRunner(command='addPlotDat
a()',iterPeriod=10000, dead = False, label='graph'), ] def addPlotData(): f1 = [0,0,0] s1 = O.bodies[id1].state.pos[1] s2 = O.bodies[id3].state.pos[1] plot.addData(sc=O.time, fc1=s1, fc2=s2) plot.plots={'sc':('fc1','fc2')}; plot.plot() from yade import qt qt.View()
doubledherin/my_compiler
parser.py
Python
mit
8,875
0.001239
import token_names as tokens import abstract_syntax_tree as AST class Parser(object): def __init__(self, lexer): self.lexer = lexer self.current_token = self.lexer.get_next_token() def error(self, message): raise Exception(message) def consume(self, token_type): if self.cu...
return [] parameter_nodes = self.formal_parameters() while self.current_token.type == tokens.SEMI: self.consume(tok
ens.SEMI) parameter_nodes.extend(self.formal_parameters()) return parameter_nodes def formal_parameters(self): """ formal_parameters : ID (COMMA ID)* COLON type_spec """ parameter_nodes = [] parameter_tokens = [self.current_token] self.consume(tokens.ID) ...
ArchieR7/HackerRank
Data Structures/Arrays/Left Rotation.py
Python
mit
204
0.02451
import sys (N, D) = [int(x) for x in
input().split()] nums = [int(x) for x in input().split()] for i in range(0,D): temp = nums[0] nums.pop(0) nums.append(temp) pri
nt(' '.join(str(n) for n in nums))
Vlek/plugins
HexChat/HexStats.py
Python
mit
1,614
0.017968
import hexchat #Based on Weechat's Weestats: https://weechat.org/scripts/source/weestats.py.html/ #By Filip H.F. 'FiXato' Slagter <fixato [at] gmail [dot] com> __module_name__ = 'HexStats' __module_version__ = '0.0.1' __module_description__ = 'Displays HexChat-wide User
Statistics' __module_author__ = 'Vlek' def stats(word, word_to_eol, userdata): print( getstats() ) return hexchat.EAT_ALL def printstats(word, word_to_eol, userdata): hexchat.command('say {}'.format( getstats() )) return hexchat.EAT_ALL def check_opped(ctx, nickprefixes): op_idx = nickprefi...
ctx.get_info('nick') me = [user for user in ctx.get_list('users') if hexchat.nickcmp(user.nick, nick) == 0][0] if me.prefix and nickprefixes.index(me.prefix[0]) <= op_idx: return True return False def getstats(): contexts = hexchat.get_list('channels') channels = 0 servers = 0 q...
daftano/interactive-tutorials
suds/client.py
Python
apache-2.0
25,972
0.002464
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will ...
self): """ Get la
st sent I{soap} message. @return: The last sent I{soap} message. @rtype: L{Document} """ return self.messages.get('tx') def last_received(self): """ Get last received I{soap} message. @return: The last received I{soap} message. @rtype: L{Document}...
robofab-developers/fontParts
Lib/fontParts/base/point.py
Python
mit
10,725
0
from fontTools.misc import transform from fontParts.base.base import ( BaseObject, TransformationMixin, PointPositionMixin, SelectionMixin, IdentifierMixin, dynamicProperty, reference ) from fontParts.base import normalizers from fontParts.base.deprecated import DeprecatedPoint, RemovedPoint...
ormalizers.normalizePointType(value) self._set_type(value) def _get_type(self): """ This is the environment implementation of :attr:`BasePoint.type`. This must return a :ref:`type-string` defining the point type. Subclasses must override this method. ...
self.raiseNotImplementedError() def _set_type(self, value): """ This is the environment implementation of :attr:`BasePoint.type`. **value** will be a :ref:`type-string` defining the point type. It will have been normalized with :func:`normalizers.normalizePointType`...
georgeyk/loafer
tests/test_routes.py
Python
mit
6,121
0.000817
from unittest import mock import pytest from asynctest import CoroutineMock from loafer.message_translators import StringMessageTranslator from loafer.routes import Route def test_provider(dummy_provider): route = Route(dummy_provider, handler=mock.Mock()) assert route.provider is dummy_provider def test_...
lass handler: def handle(self, *args): pass dummy_provider.stop = mock.Mock() handler = handler()
handler.stop = mock.Mock() route = Route(dummy_provider, handler) route.stop() assert dummy_provider.stop.called assert handler.stop.called # FIXME: Improve all test_deliver* tests @pytest.mark.asyncio async def test_deliver(dummy_provider): attrs = {} def test_handler(*args, **kwargs): ...
OpenGov/og-python-utils
tests/loggers_default_test.py
Python
mit
2,700
0.011852
# This import fixes sys.path issues from .parentpath import * import os import re import unittest import logging import StringIO from ogutils.loggers import default from ogutils.system import streams LOCAL_LOG_DIR = os.path.join(os.path.dirname(__file__), 'logs') class FlaskLoggerTest(unittest.TestCase)...
sole_log())), 2) self.assertEqual(len(re.findall(self.log_matcher, stdout.getvalue())), 2) def test_logger_stderr(self): stderr = StringIO.StringIO() with streams.StdRedire
ctor(stderr=stderr): self.assertEqual(len(re.findall(self.log_matcher, self.read_console_log())), 0) self.logger.error('Log Me!') self.assertEqual(len(re.findall(self.log_matcher, self.read_console_log())), 1) self.assertEqual(len(re.findall(self.log_matcher, stderr.g...
heysion/clone-cliapp
example3.py
Python
gpl-2.0
1,359
0.000736
# Copyright (C) 2012 Lars Wirzenius # # 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 distributed i...
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 more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Fou...
te the compute_setting_values method. ''' import cliapp import urlparse class ExampleApp(cliapp.Application): '''A little fgrep-like tool.''' def add_settings(self): self.settings.string(['url'], 'a url') self.settings.string(['protocol'], 'the protocol') def compute_setting_values(s...
ktan2020/legacy-automation
win/Lib/unittest/case.py
Python
mit
43,508
0.001655
"""Test case implementation""" import collections import sys import functools import difflib import pprint import re import warnings from . import result from .util import ( strclass, safe_repr, unorderable_list_difference, _count_diff_all_purpose, _count_diff_hashable ) __unittest = True ...
__init__ method must always be called. It is important that subclasses should not change the signature of their __init__ method, since instances of the classes are instantiated automatically by
parts of the framework in order to be run. """ # This attribute determines which exception will be raised when # the instance's assertion methods fail; test methods raising this # exception will be deemed to have 'failed' rather than 'errored' failureException = AssertionError ...
ujdhesa/unisubs
libs/vidscraper/sites/wistia.py
Python
agpl-3.0
4,955
0.005651
# Miro - an RSS based video player application # Copyright 2009 - Participatory Culture Foundation # # This file is part of vidscraper. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of sour...
'video_id'] apiurl = '%s?%s' % (WISTIA_OEMBED_API_URL, urllib.quote(url)) finalexcept = None backoff = util.random_exponential_backoff(2) for i in range(3):
try: reponse = urllib.urlopen(apiurl) api_raw_data = response.read() api_data = simplejson.loads(api_raw_data) except Exception as e: finalexcept = e continue else: shortmem['oembed'] = api_data break ...
cl0ne/vital-records-registry
registry/vital_records/tests.py
Python
gpl-3.0
7,137
0.002522
from contextlib import contextmanager from django.core.exceptions import ValidationError from django.test import TestCase from django.utils import timezone from .models import Person, Residence, RegistryUser, Registrar from .models import BirthNote, BirthPlace, ApplicantInfo, BirthNoteLaw, BirthEvidence class TestC...
on='Volynska oblast', district='Old republic', city='Urbanstadt' ) self.assertIsNotNone(father_birth_place) father = Person.objects.create( first_name='Ivan', last_name='Ivanov', patronymic='Ivanovich', gender=Person.MALE, residence=home, birth_place=father_birth_place, ...
970, month=3, day=5).date(), family_status=Person.MARRIED, military_service=False ) self.assertIsNotNone(father) mother_birth_place = BirthPlace.objects.create( country='UA', region='Chernihivska oblast', district='Rare gems', city='Golden rain' ) self.as...
Scandie/openprocurement.tender.esco
openprocurement/tender/esco/views/award_complaint_document.py
Python
apache-2.0
769
0.005202
# -*- coding: utf-8 -*- from openprocurement.tender.core.utils import optendersresource from openprocurement.tender.openeu.views.award_complaint_document import TenderEU
AwardComplaintDocumentResource @optendersresource(name='esco.EU:Tender Award Complaint Documents',
collection_path='/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/documents', path='/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/documents/{document_id}', procurementMethodType='esco.EU', description="Tender award complaint ...
google-code-export/evennia
src/help/manager.py
Python
bsd-3-clause
3,168
0.000316
""" Custom manager for HelpEntry objects. """ from django.db import models from src.utils import logger, utils __all__ = ("HelpEntryManager",) class HelpEntryManager(models.Manager): """ This HelpEntryManager implements methods for searching and manipulating HelpEntries directly from the database. Th...
ll return database objects (or QuerySets) directly. Evennia-specific: find_topicmatch find_apropos find_topicsuggestions find_topics_with_category all_to_category search_help (equivalent to ev.search_helpentry) """ def find_topicmatch(self, topicstr, exact=False): """ ...
ls.dbref(topicstr) if dbref: return self.filter(id=dbref) topics = self.filter(db_key__iexact=topicstr) if not topics and not exact: topics = self.filter(db_key__istartswith=topicstr) if not topics: topics = self.filter(db_key__icontains=topics...
repleo/bounca
certificate_engine/apps.py
Python
apache-2.0
126
0
"""App name""" from django
.apps import AppConfig class CertificateEngineConfig(AppConfi
g): name = "certificate_engine"
rocky/python-uncompyle6
test/simple_source/stmts/00_pass.py
Python
gpl-3.0
38
0
#
Tests: # assi
gn ::= expr store pass
superdesk/superdesk-aap
server/aap/macros/abs_indicators.py
Python
agpl-3.0
6,529
0.00337
# -*- coding: utf-8; -*- # # This file is part of Superdesk. # # Copyright 2013, 2014 Sourcefabric z.u. and contributors. # # For the full copyright and license information, please see the # AUTHORS and LICENSE files distributed with this source code, or # at https://www.sourcefabric.org/superdesk/license import reque...
eriod_index -= 1 if last_period_index >= 0: # construct the dimension key of the last data item dimension_key = '0:' * (dimensions - 1) + str(last_period_index) prev_value = response['dataSets'][0]['observations'][dimension_key][0] if raw_value and prev_value: ...
e = 'fell' elif prev_value < raw_value: adjective = 'rose' else: adjective = 'held steady' else: adjective = 'N/A' template_map[value_token[:-1] + 'ADJECTIVE__'] = adjective if prev_value is Non...
emvarun/followup-and-location
Loop_SkyPatch.py
Python
gpl-3.0
681
0.030837
import numpy as np from subprocess import check_output import os import subprocess from subprocess import Popen, PIPE from Sky_Patch import Coverage from params import * #LIST OF LOCATIONS CONSIDERED for i in range (0, len(obsName)): tCoverage = [] for dirpath, dirname, files in os.walk(folddir): for filename
in files: path = os.path.join(dirpath, filename) name = filename.strip().split('.') if(name[-1] == 'gz' ): print obsName[i], path nlist = Coverage(str(path), obsName[i], Texp, NsqDeg, stepsize) tCoverage.append(nlist) f=open( str(outfile) + '-' + str(obsName[i]) + '.txt','w') for item in tCover...
'\n') f.close()
bridgetnoelleee/project2
helpers/functions.py
Python
bsd-3-clause
2,064
0.003391
from flask import _app_ctx_stack from flask import current_app as app from flask import Flask, request, session, url_for, redirect, \ render_template, abort, g, flash, _app_ctx_stack from sqlite3 import dbapi2 as sqlite3 from hashlib import md5 from datetime import datetime def get_db(): """Opens a new databa...
end of the request.""" top = _app_ctx_stack.top if hasattr(top, 'sqlite_
db'): top.sqlite_db.close() def init_db(): """Initializes the database.""" db = get_db() with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() def initdb_command(): """Creates the database tables.""" init_db() print('Initialize...
ampron/nflstat
simulator_NFL.py
Python
gpl-3.0
8,159
0.011157
#!/usr/bin/python # -*- encoding: UTF-8 -*- '''NFL Simulator List of classes: -none- List of functions: main ''' # built-in modules import random import math from pprint import pprint # third-party modules import numpy as np from scipy.stats import skew, kurtosis from scipy.special import erf, er...
turn tm_strength # END rand_tm_stengths #=============================================================================== def predictGm(v_hm, v_vs, pnt_adj=0.0): ''' (P[hm win], finalScore) = predictGm(v_hm, v_vs, ('H
'|'N'), ('M'|'W')) ''' # Standard deviation in score sig = 11.87 sigSqrt2 = sig*math.sqrt(2.0) p_hm = v_hm/(v_hm + v_vs) # final score difference at a neutral location # score difference = home score - visitor score pnts = sigSqrt2*erfinv(2.0*p_hm - 1.0) if pnt_adj != 0: ...
alexliyu/CDMSYSTEM
pyroute2/netlink/rtnl/ifinfmsg.py
Python
mit
36,186
0.000028
import os import time import json import struct import logging import platform import subprocess from fcntl import ioctl from pyroute2.common import map_namespace from pyroute2.common import ANCIENT # from pyroute2.netlink import NLMSG_ERROR from pyroute2.netlink import nla from pyroute2.netlink import nlmsg from pyrou...
, 'rx_bytes', 'tx_bytes', 'rx_errors', 'tx_errors', 'rx_dropped', 'tx_dropped', 'multicast', 'collisions', 'rx_length_errors', 'rx_over_errors', 'rx_crc_e
rrors', 'rx_frame_errors', 'rx_fifo_errors', 'rx_missed_errors', 'tx_aborted_errors', 'tx_carrier_errors', 'tx_fifo_errors', 'tx_heartbeat_errors', 'tx_window_errors', 'rx_compressed', ...
Mxit/python-mxit
mxit/settings.py
Python
bsd-3-clause
78
0
AUTH_ENDPOINT = 'https://a
uth.mxit.com' API_ENDPOINT = 'htt
ps://api.mxit.com'
frague59/wagtailpolls
wagtailpolls/models.py
Python
bsd-3-clause
2,687
0.000372
from __future__ import absolute_import, unicode_literals from six import text_type from django.db import models from django.db.models.query import QuerySet from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.text import slugify from django.utils.translatio...
hon_2_unicode_compatible class Poll(ClusterableModel, models.Model, index.Indexed): title = models.CharField(max_length=128, verbose_name=_('Title')) date_created = models.DateTimeField(default=timezone.now) class Meta: verbose_name = _('poll') verbose_name_plural = _('polls') panels =...
eldPanel('title'), InlinePanel('questions', label=_('Questions'), min_num=1) ] search_fields = ( index.SearchField('title', partial_match=True, boost=5), index.SearchField('id', boost=10), ) objects = PollQuerySet.as_manager() def get_nice_url(self): return slugify...
lucab/security_monkey
security_monkey/__init__.py
Python
apache-2.0
5,751
0.008346
# Copyright 2014 Netflix, 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...
ws.ignore_list import IgnorelistListPost api.add_resource(IgnoreListGetPutDelete, '/api/1/ignorelistentries/<int:item_id>') api.add_resource(IgnorelistListPost, '/api
/1/ignorelistentries') from security_monkey.views.item import ItemList from security_monkey.views.item import ItemGet api.add_resource(ItemList, '/api/1/items') api.add_resource(ItemGet, '/api/1/items/<int:item_id>') from security_monkey.views.item_comment import ItemCommentPost from security_monkey.views.item_commen...
onenameio/utilitybelt
setup.py
Python
mit
747
0
""" Useful Utils ====
========== """ from setuptools import setup, find_packages setup( name='utilitybelt', version='0.2.6', author='Halfmoon Labs', author_email='[email protected]', description='Generally useful tools. A python utility belt.', keywords=('dict dictionary scrub to_dict todict json characters c...
'hex entropy utility'), url='https://github.com/onenameio/utilitybelt', license='MIT', packages=find_packages(), install_requires=[ ], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', ...
fras2560/graph-helper
algorithms/color.py
Python
apache-2.0
14,060
0.003272
""" ------------------------------------------------------- color a module to determine the chromatic number of a graph ------------------------------------------------------- Author: Dallas Fraser ID: 110242560 Email: [email protected] Version: 2014-09-17 ---------------------------------------------------...
n (logging) Returns: chromatic: the chromatic number (int)
''' if logger is None: logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s') logger = logging.getLogger(__name__) valid = False largest = 0 largest_clique = [] # find largest clique for clique in nx.find_cliques(G): if ...
shree-shubham/Unitype
List Comprehensions.py
Python
gpl-3.0
164
0.012195
import filein
put X, Y, Z, N = map(int, fileinput.input()) nums=[[x,
y, z] for x in range(X+1) for y in range(Y+1) for z in range(Z+1) if x + y + z != N] print nums
msunardi/PTVS
Python/Tests/TestData/RemoveImport/FromImport1.py
Python
apache-2.0
31
0.032258
from sys i
mport oar, baz
oar
miurahr/seahub
tests/seahub/notifications/test_models.py
Python
apache-2.0
4,419
0.003847
from seahub.notifications.models import ( UserNotification, repo_share_msg_to_json, file_comment_msg_to_json, repo_share_to_group_msg_to_json, file_uploaded_msg_to_json, group_join_request_to_json, add_user_to_group_to_json, group_msg_to_json) from seahub.share.utils import share_dir_to_user, share_dir_to_g...
_group_msg( self.user.username, repo_share_to_group_msg_to_json('[email protected]', self.repo.id, self.group.id, '/', None)) msg = notice.format_repo_share_to_group_msg() assert msg is not None assert 'bar has shared a library named' in msg assert '/group/%(group_id)s...
share_to_group_msg_with_folder(self): folder_path = self.folder share_dir_to_group(self.repo, folder_path, self.user.username, self.user.username, self.group.id, 'rw', None) notice = UserNotification.objects.add_repo_share_to_group_msg( self.user.username, ...
evanbrumley/psmove-restful
server.py
Python
mit
3,841
0.003645
"""PS Move Restful Server Usage: server.py [--battery-saver] Options: --battery_saver If set, only allows a few seconds without a GET request before shutting off a controllers LEDs and rumble """ from docopt import docopt import datetime import time from threading import Thread from flask import Flask from flas...
ict() def put(self, controller_id): controller = get_controller_by_id(controller_id) if controller is None: abort(404, message=
"Controller {} doesn't exist".format(controller_id)) args = parser.parse_args() red = args['red'] green = args['green'] blue = args['blue'] controller.set_color(red, green, blue) rumble = args['rumble'] if rumble is not None: contr...
garyForeman/LHBassClassifier
mongodb/thread_data.py
Python
agpl-3.0
4,209
0.000475
#! /usr/bin/env python """ Author: Gary Foreman Created: September 18, 2016 This script scrapes image urls, thread titles, user names, and thread ids from thread links in the For Sale: Bass Guitars forum at talkbass.com. Information from each thread is saved as a document in a MongoDB database. """ from __future__ im...
list of lxml.html.HtmlElement containing each for sale thread link extracts thread data we want to keep: user name, thread title, thread id, and thumbnail image url, and returns a list of documents to be inserted into a MongoDB database """ document_list = [] for thread in th...
append(extractor.data) return document_list def main(): # Establish connection to MongoDB open on port 27017 client = pymongo.MongoClient() # Access threads database db = client.for_sale_bass_guitars for i in xrange(1, NUM_PAGES+1): tb_classified_page = get_page_url(i) # in...
dmlc/xgboost
tests/python/test_with_shap.py
Python
apache-2.0
817
0
import numpy as np import xgboost as xgb import pytest try: import shap except ImportError: shap = None pass pytestmark = pytest.mark.skipif(shap is None, reason="Requires shap package") # Check integration is not broken from xgboost side # Changes in binary format may cause problems
def test_with_shap(): from sklearn.datasets import fetch_california_housing X, y = fetch_california_housing(return_X_y=True) dtrain = xgb.DMatrix(X, label=y) model = xgb.train({"learning_rate": 0.01}, dtrain, 10) explainer = shap.TreeExplainer(model) shap_values = explainer.shap_values(X) ma...
lues.shape) - 1), margin - explainer.expected_value, 1e-3, 1e-3)
asedunov/intellij-community
python/helpers/pydev/setup.py
Python
apache-2.0
4,628
0.006914
''' Full setup, used to distribute the debugger backend to PyPi. Note that this is mostly so that users can do: pip install pydevd in a machine for doing remote-debugging, as a local installation with the IDE should have everything already distributed. Reference on wheels: https://hynek.me/articles/sharing-your-lab...
a tested version. Extension('_pydevd_bundle.pydevd_cython', ["_pydevd_bundle/pydevd_cython.c",]) ] )) setup(**args_with_binaries) except: # Co
mpile failed: just setup without compiling cython deps. setup(**args) sys.stdout.write('Plain-python version of pydevd installed (cython speedups not available).\n')
shishaochen/TensorFlow-0.8-Win
tensorflow/python/ops/gen_data_flow_ops.py
Python
apache-2.0
45,781
0.002075
"""Python wrappers around Brain. This file is MACHINE GENERATED! Do not edit. """ from google.protobuf import text_format from tensorflow.core.framework import op_def_pb2 from tensorflow.python.framework import op_def_registry from tensorflow.python.framework import ops from tensorflow.python.ops import op_def_libra...
of type `int32`. Any shape. Indices in the range `[0
, num_partitions)`. num_partitions: An `int` that is `>= 1`. The number of partitions to output. name: A name for the operation (optional). Returns: A list of `num_partitions` `Tensor` objects of the same type as data. """ return _op_def_lib.apply_op("DynamicPartition", data=data, ...
diafygi/pdfformfiller
docs/conf.py
Python
gpl-3.0
9,307
0.006017
# -*- coding: utf-8 -*- # # pdfformfiller documentation build configuration file, created by # sphinx-quickstart on Sat Mar 19 21:38:58 2016. # # 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....
# Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help build
er. htmlhelp_basename = 'pdfformfillerdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX pre...
fro391/Investing
PRAW/Praw.py
Python
gpl-2.0
168
0.017857
import praw
r = praw.Reddit(user_agent='kumaX') #r.login('kumaX','Sho3lick') submissions = r.get_subreddit('worldnews').get_top() print [str(x) for x in submissions]
datagutten/comics
comics/comics/billy.py
Python
agpl-3.0
384
0
from comics.aggregator.crawler import CrawlerBase from comics.core.comic_data import ComicDataBase class ComicData(ComicDataBase): name = 'Billy' language = 'no' url = 'http://www.bill
y.no/' start_date = '1950-01-01' active = False rights = 'Mort Walker' class Crawler(CrawlerBase): def crawl(self, pub_date): pass # Com
ic no longer published
mstepniowski/django-newtagging
newtagging/managers.py
Python
mit
2,765
0.005063
""" Custom managers for Django models registered with the tagging application. """ from django.contrib.contenttypes.models import ContentType from django.db import models class ModelTagManager(models.Manager): """ A manager for retrieving tags for a particular model. """ def __init__(self, tag_model):...
l, num=num) else: return self.intermediary_table_model.objects.get_related(obj, queryset, num=num) def with_all(self, tags, queryset=None): if queryset is None: return self.intermediary_table_model.objects.get_by_model(self.model, tags) else:
return self.intermediary_table_model.objects.get_by_model(queryset, tags) def with_any(self, tags, queryset=None): if queryset is None: return self.intermediary_table_model.objects.get_union_by_model(self.model, tags) else: return self.intermediary_table_model.objects.get...
hekra01/mercurial
tests/hgweberror.py
Python
gpl-2.0
547
0.003656
# A dummy extension that installs an hgweb command that throws an Exception. from mercurial.hgweb import webcommands def raiseerror(web, req, tmpl): '''Dummy web command that raises an uncaught Exception.''' # Simulate an error after partial response. if 'partialresponse' in req.form: req.respond...
I am an uncaught error!') def extsetup(ui): setattr(webcommands, 'raiseerror', raiseerror) webcommands.__all__.append('raiseerror')
okfde/froide-campaign
froide_campaign/listeners.py
Python
mit
1,213
0
from asgiref.sync import async_to_sync from channels.layers import get_channel_layer from .consumers import PRESENCE_ROOM from .models import Campaign def connect_info_object(sender, **kwargs): reference = kwargs.get("reference") if not reference: reference = sender.reference if not reference: ...
try: campaign_pk = int(campaign) except ValueError: return try: campaign = Campaign.objects.get(pk=campaign_pk) except Campaign.DoesNotExist: return provider = campaign.get_provider() iobj = provider.connect_request(ident, sender) if iobj: broadcast_...
dcast_request_made(provider, iobj): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( PRESENCE_ROOM.format(provider.campaign.id), {"type": "request_made", "data": provider.get_detail_data(iobj)}, )
ian-wilson/cron-admin
nextrun/__main__.py
Python
mit
975
0.001026
# -*- coding: utf-8 -*- import argparse from next_run import NextRun if __name__ == u'__main
__': # Parse command line arguments parser = argparse.ArgumentParser( description=u'Cron Admin tool.' ) parser.add_argument( u'-t', dest=u'current_time', default=u'16:10', help=u'The time from which to check' ) parser.add_argument( u'-p', ...
u'Full path to the cron file to check' ) parser.add_argument( u'-s', dest=u'cron_string', default=None, help=u'A newline separated string of cron data' ) args = parser.parse_args() # Call the class controller to run the script next_run_times = NextRun().find_ne...
paxy97/qmk_firmware
layouts/community/ergodox/german-manuneo/compile_keymap.py
Python
gpl-2.0
21,163
0.001512
#!/usr/bin/env python # -*- coding: utf-8 -*- """Compiler for keymap.c files This scrip will generate a keymap.c file from a simple markdown file with a specific layout. Usage: python
compile_keymap.py INPUT_PATH [OUTPUT_PATH] """ from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import os import io import re import sys import json import unicodedata import collections import itertools as it PY2 = s...
PY2: chr = unichr KEYBOARD_LAYOUTS = { # These map positions in the parsed layout to # positions in the LAYOUT_ergodox MATRIX 'ergodox_ez': [ [ 0, 1, 2, 3, 4, 5, 6], [38, 39, 40, 41, 42, 43, 44], [ 7, 8, 9, 10, 11, 12, 13], [45, 46, 47, 48, 49, 50, 51], [14, 15, 16, ...
cpennington/edx-platform
common/djangoapps/student/tests/test_helpers.py
Python
agpl-3.0
6,067
0.004121
""" Test Student helpers """ import logging import ddt from django.conf import settings from django.contrib.sessions.middleware import SessionMiddleware from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from mock import patch from testfixtu...
(logging.INFO, "INFO", static_url + "dummy.png", "image/*", "test/agent", "Redirect to non html content 'image/*' detected from 'test/agent' after login page: '" + static_url + "dummy.png" + "'"), (logging.WARNING, "WARNING", "test.png", "text/html", None, "Redirect to url pat...
WARNING, "WARNING", static_url + "dummy.png", "text/html", None, "Redirect to url path with specified filed type 'image/png' not allowed: '" + static_url + "dummy.png" + "'"), ) @ddt.unpack def test_next_failures(self, log_level, log_name, unsafe_url, http_accept, user_agent, expected_log): ...
tomi77/protobuf-gis
python/tests/test_polygon.py
Python
mit
2,150
0.005581
im
port unittest from gis.protobuf.polygon_pb2 import Polygon2D, Polygon3D, MultiPolygon2D, MultiPolygon3D from gis.protobuf.point_pb2 import Point2D, Point3D class Polygon2DTestCase(unittest.TestCase): def test_toGeoJSON(self): polygon =
Polygon2D(point=[Point2D(x=1.0, y=2.0), Point2D(x=3.0, y=4.0)]) self.assertEqual(polygon.toGeoJSON(), { 'type': 'Polygon', 'coordinates': [[[1.0, 2.0], [3.0, 4.0]]] }) class Polygon3DTestCase(unittest.TestCase): def test_toGeoJSON(self):...
garbear/EventGhost
eg/Classes/IrDecoder/Rcmm.py
Python
gpl-2.0
2,548
0.00314
# This file is part of EventGhost. # Copyright (C) 2009 Lars-Peter Voss <[email protected]> # # EventGhost 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 # (a...
: return 1 # binary 01 elif pause < 694: return 2 # binary 10 elif pause < 861: return 3 # binary 11 else: raise DecodeError("pause too long") def ShiftInBits(self, numBits): data = 0 for dummyCounter in xrange(num...
raise DecodeError("not implemented") if not (200 < data[0] < 600): DecodeError("wrong header pulse") if not (100 < data[1] < 500): DecodeError("wrong header pause") self.pos = 2 self.data = data mode = self.GetBits() if mode != 0:...
jkeifer/pyHytemporal
old_TO_MIGRATE/classifyclips.py
Python
mit
4,401
0.004999
from create_rule_image_multiprocessed_bypx import phenological_classificaion, read_reference_file import os from pyhytemporal.utils import find_files clip1refs = find_files("/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/MODIS_KANSAS_2007-2012/reprojected/Refs/2012/clip1", "mean.ref") clip2refs = find_fil...
"/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/MODIS_KANSAS_2007-2012/repro
jected/clips/KansasEVI_2012_clip1.tif"] clip2imgs = ["/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/MODIS_KANSAS_2007-2012/reprojected/clips/KansasNDVI_2012_clip2.tif", "/Users/phoetrymaster/Documents/School/Geography/Thesis/Data/MODIS_KANSAS_2007-2012/reprojected/clips/KansasEVI_2012_clip2.tif"] clip3img...
MasterScrat/ChatShape
parsers/utils.py
Python
mit
308
0
import os import datetime def export_dataframe(df, filename='exported.pkl'): f
ilepath = os.path.join('data', filename) print('Saving to pickle file %s...' % filepath) df.to_pickle(filepath) def timestamp_to_ordinal(value): ret
urn datetime.datetime.fromtimestamp(float(value)).toordinal()
VPAC/pbs_python
src/PBSQuery.py
Python
gpl-3.0
17,223
0.008303
# # Authors: Roy Dragseth ([email protected]) # Bas van der Vlies ([email protected]) # # SVN INFO: # $Id$ # """ Usage: from PBSQuery import PBSQuery This class gets the info from the pbs_server via the pbs.py module for the several batch objects. All get..() functions return an dictionary with id as key a...
new.name = item.name for a in item.attribs:
if self.OLD_DATA_STRUCTURE: if a.resource: key = '%s.%s' %(a.name, a.resource) else: key = '%s' %(a.name) new[key] = a.value else: values = string.split(a.value, ',') ...
pllim/astropy
astropy/coordinates/tests/test_intermediate_transformations.py
Python
bsd-3-clause
38,779
0.001573
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Accuracy tests for GCRS coordinate transformations, primarily to/from AltAz. """ import os import warnings from importlib import metadata import pytest import numpy as np import erfa from astropy import units as u from astropy.tests.helper import ass...
(cframe1) # should be back to the same
assert_allclose(cirsnod.ra, cirsnod5.ra) assert_allclose(cirsnod.dec, cirsnod5.dec) usph = golden_spiral_grid(200) dist = np.linspace(0.5, 1, len(usph)) * u.pc icrs_coords = [ICRS(usph), ICRS(usph.lon, usph.lat, distance=dist)] gcrs_frames = [GCRS(), GCRS(obstime=Time('J2005'))] @pytest.mark.parametrize('ico...
mindbender-studio/config
polly/plugins/maya/publish/validate_rig_hierarchy.py
Python
mit
515
0
import pyblish.api class ValidateMindbenderRigHierarchy(pyblish.ap
i.InstancePlugin): """A rig must reside under a single assembly called "ROOT" - Must reside within `ROOT` transform """ label = "Rig Hierarchy" order = pyblish.api.ValidatorOrder hosts = ["maya"] families = ["mindbender.rig"]
def process(self, instance): from maya import cmds assert cmds.ls(instance, assemblies=True) == ["ROOT"], ( "Rig must have a single parent called 'ROOT'.")
RonnyPfannschmidt/borg
src/borg/testsuite/crypto.py
Python
bsd-3-clause
13,340
0.003748
from binascii import hexlify, unhexlify from ..crypto.low_level import AES256_CTR_HMAC_SHA256, AES256_OCB, CHACHA20_POLY1305, UNENCRYPTED, \ IntegrityError, blake2b_256, hmac_sha256, openssl10 from ..crypto.low_level import bytes_to_long, bytes_to_int, long_to_bytes from ..crypto.low_lev...
header_len=1, aad_offset=1) hdr_mac_iv_cdata = cs.encrypt(data, header=header) hdr = hdr_mac_iv_cdata[0:1] mac = hdr_mac_iv_cdata[1:17] iv = hdr_mac_iv_cdata[17:29] cdat
a = hdr_mac_iv_cdata[29:] self.assert_equal(hexlify(hdr), b'23') self.assert_equal(hexlify(mac), exp_mac) self.assert_equal(hexlify(iv), b'000000000000000000000000') self.assert_equal(hexlify(cdata), exp_cdata) self.assert_equal(cs.next_iv(), 1) # ...
lao605/product-definition-center
pdc/apps/common/renderers.py
Python
mit
14,144
0.001273
# # Copyright (c) 2015 Red Hat # Licensed under The MIT License (MIT) # http://opensource.org/licenses/MIT # from collections import OrderedDict import logging import re import sys import json from django.conf import settings from django.utils.encoding import smart_text from contrib import drf_introspection from dja...
tifies users using Token which will be generated for all authenticated users. **Please remember to use your token as HTTP header for every requests that need authentication.** If you want to record the reaso
n for change, you can add Header (-H "PDC-Change-Comment: reasonforchange") in request. Responses are available in JSON format. **NOTE:** in order to use secure HTTPS connections, you'd better to add server's certificate as trusted. """ URL_SPEC_RE = re.compile(r'\$(?P<type>URL|LINK):(?P<details>[^$]+)\$') class ...
nanxung/vip_video
setup.py
Python
gpl-3.0
572
0.022727
import sys from cx_Freeze import setup, Executable # Dependencies are automatically detected, but
it might need fine tuning. build_exe_options = {"packages": ["os"], "excludes": ["tkinter"], } # GUI applications require a different base on Windows (the default is for a # console application). base = None if sys.pl
atform == "win32": base = "Win32GUI" setup( name = "guifoo", version = "0.2", description = "luantangui!", options = {"build_exe": build_exe_options}, executables = [Executable("main.py", base=base)])
redsolution/django-generic-ratings
ratings/forms/widgets.py
Python
mit
7,704
0.002207
from decimal import Decimal from django import forms from django.template.loader import render_to_string from django.template.defaultfilters import slugify class BaseWidget(forms.TextInput): """ Base widget. Do not use this directly. """ template = None instance = None def get_parent_id(self,...
<link href="/path/to/jquery.rating.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/path/to/jquery.MetaData.js"></script> <script type="text/javascript" src="/path/to/jquery.rating.js"></script> This widget triggers the following javascript events: - *star_ch...
(fired when the user deletes his vote) It's easy to bind these events using jQuery, e.g.:: $(document).bind('star_change', function(event, value) { alert('New vote: ' + value); }); """ def __init__(self, min_value, max_value, step, instance=None, can_delete_vote=Tr...
bjornaa/roppy
examples/plot_current25.py
Python
mit
2,273
0
# ------------------------------------------------------ # current.py # # Plot a current field at fixed depth # Modified from the spermplot example # # Bjørn Ådlandsvik <[email protected]> # 2020-03-27 # ------------------------------------------------------ # ------------- # Imports # ------------- import numpy as np imp...
------------------------- # User settings # ------------------------ ncfile = "data/ocean_avg_example.nc" timeframe = 3 # Fourth time frame # subgrid = (1,-1,1,-1) # whole grid except boundary cells subgrid = (110, 170, 35, 90) # Depth level [m] z = 25 # Distance between vectors stride = 2 # Speed level (isotac...
1, ...., 0.5 # Colormap for speed speedcolors = "YlOrRd" # -------------------- # Read the data # -------------------- f = Dataset(ncfile) grid = SGrid(f, subgrid=subgrid) # Read 3D current for the subgrid U0 = f.variables["u"][timeframe, :, grid.Ju, grid.Iu] V0 = f.variables["v"][timeframe, :, grid.Jv, grid.Iv] M...
nedbat/cupid
cupid/box.py
Python
mit
5,647
0
"""Box geometry.""" from __future__ import division from .helpers import poparg class Box(object): """A Box holds the geometry of a box with a position and a size. Because of how it is typically used, it takes a single dictionary of arguments. The dictionary of arguments has arguments popped from it, ...
(105.0, 225.0) >>> b.top 175.0 >>> b.bottom 225.0 """ def __init__(self, args): other_box = poparg(args, box=None) if other_box is not None:
# Copy all the attributes of the other box. self.__dict__.update(other_box.__dict__) return size = poparg(args, size=None) assert size, "Have to specify a size!" pos_name = pos = None arg_names = "left center right top topleft topright".split() fo...
boatd/python-boatd
boatdclient/point.py
Python
gpl-3.0
5,843
0.002396
import math from math import sin as sin from math import cos as cos from .bearing import Bearing EARTH_RADIUS = 6371009.0 # in meters class Point(object): '''A point on the face of the earth''' def __init__(self, latitude, longitude): self._lat = latitude self._long = long
itude @classmethod def from_radians(cls, lat_radians, long_radians): ''' Return a new instance of Point from a pair of coordinates in radians. '''
return cls(math.degrees(lat_radians), math.degrees(long_radians)) def __getitem__(self, key): if key == 0: return self._lat elif key == 1: return self._long else: raise IndexError('Point objects can only have two coordinates') def __iter__(sel...
jwren/intellij-community
python/testData/inspections/PyUnresolvedReferencesInspection3K/descriptorAttribute.py
Python
apache-2.0
884
0.020362
from typing import Any class StringDe
scriptor: def __get__(self
, instance, owner): return 'foo' class AnyDescriptor: def __get__(self, instance, owner) -> Any: return 'bar' class ListDescriptor: def __get__(self, instance: Any, owner: Any) -> list: return 'baz' class C: foo = StringDescriptor() bar = AnyDescriptor() baz = ListDescr...
gsvaldes/tequio
districts/serializers.py
Python
gpl-3.0
349
0
from rest_framework_gis.serializers import GeoFeatureModelSerializer from districts.models impor
t AlderDistrict class DistrictSerializer(GeoFeatureModelSerializer): """ Geo Serialize the district model """ class Meta: model = AlderDistrict geo_field = 'mpoly'
fields = ('alder', 'wards_txt', 'wards_desc')
pedrobaeza/odoo
openerp/service/db.py
Python
agpl-3.0
15,507
0.003095
# -*- coding: utf-8 -*- from contextlib import closing from functools import wraps import logging import os import shutil import threading import traceback import tempfile import zipfile import psycopg2 import openerp from openerp import SUPERUSER_ID from openerp.exceptions import Warning import openerp.release impor...
try: cr.execute('DROP DATABASE "%s"' % db_name) except Exception, e: _logger.error('DROP DB: %s failed:\n%s', db_name, e) raise Exception("Couldn't drop database %s: %s" % (db_name, e)) else: _logger.info('DROP DB: %s', db_name) fs = openerp....
ssword_in_environment(func): """ On systems where pg_restore/pg_dump require an explicit password (i.e. when not connecting via unix sockets, and most importantly on Windows), it is necessary to pass the PG user password in the environment or in a special .pgpass file. This decorator handles settin...
warner/python-tweetnacl
setup.py
Python
mit
4,417
0.008836
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Build and install the TweetNaCl wrapper. """ from __future__ import print_function import sys, os from distutils.core import setup, Extension, Command from distutils.util import get_platform def setup_path(): # copied from distutils/command/build.py plat_name...
6; test_verify_16.run() import test_verify_32; test_verify_32.run() class Speed(Test): des
cription = "run benchmark suite" def run(self): setup_path() from timeit import Timer def do(setup_statements, statement): # extracted from timeit.py t = Timer(stmt=statement, setup="\n".join(setup_statements)) # determine number so that 0.2 <= total time...
rizumu/pinax-likes
phileo/urls.py
Python
mit
197
0.005076
from django.conf.urls import url, pa
tterns urlpatterns = patterns( "phileo.views", u
rl(r"^like/(?P<content_type_id>\d+):(?P<object_id>\d+)/$", "like_toggle", name="phileo_like_toggle") )
brookemosby/titanic
TitanicAttempt/__init__.py
Python
mit
28
0.035714
fr
om TitanicAttempt impor
t *
stanta/darfchain
darfchain/models/sale_order.py
Python
gpl-3.0
7,313
0.010666
from openerp import models, fields, api from openerp.tools.translate import _ import logging #from fingerprint import Fingerprint from dateutil import relativedelta from datetime import datetime as dt from dateutil import parser import xlsxwriter import StringIO from io import BytesIO import base64 import hashlib impor...
web3 = Web3(HTTPProvider(ethereum_setting['address_node'])) abi_json = ethereum_setting['ethereum_interface'] ethereum_contract_address = ethereum_setting['ethereum_address'] contract = web3.eth.contract(abi = json.loads(abi_json), address=ethereum_contract_address
) hash_of_synchronaze = '"'+base58.b58encode(str(date_of_synchronization))+'"' md5 = self.getDocumentMD5() md5_for_solidity = '"'+md5[0]+'"' print hash_of_synchronaze try: result_of_gas_estimate = contract.estimateGas().setDocumentHash(str(hash...
eandersson/amqpstorm
amqpstorm/exception.py
Python
mit
4,732
0
"""AMQPStorm Exception.""" AMQP_ERROR_MAPPING = { 311: ('CONTENT-TOO-LARGE', 'The client attempted to transfer content larger than the ' 'server could accept at the present time. The client may ' 'retry at a later time.'), 312: ('NO-ROUTE', 'Undocumented AMQP Soft Error'), 31...
E-ERROR', 'The server could not complete the method because it lacked ' 'sufficient resources. This may be due to the client ' 'creating too many of some type of entity.'), 530: ('NOT-A
LLOWED', 'The client tried to work with some entity in a manner ' 'that is prohibited by the server, due to security ' 'settings or by some other criteria.'), 540: ('NOT-IMPLEMENTED', 'The client tried to use functionality that is ' 'notimplemented in the server.'),...
dennerlager/sepibrews
sepibrews/progressbar/widgets.py
Python
gpl-3.0
31,775
0.000031
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from __future__ import with_statement import abc import sys import pprint import datetime from python_utils import converters import six from ....
object): ... term_width = 0 >>> Width
WidgetMixin(5, 10).check_size(Progress) False >>> Progress.term_width = 5 >>> WidthWidgetMixin(5, 10).check_size(Progress) True >>> Progress.term_width = 10 >>> WidthWidgetMixin(5, 10).check_size(Progress) True >>> Progress.term_width = 11 >>> WidthWidgetMixin(5, 10).check_size(Progr...
Dakhnovskiy/linguistic_analyzer_projects
analyzer_project/report/csv_report.py
Python
apache-2.0
987
0
# -*- coding: utf-8 -*- __author__ = 'Dmitriy.Dakhnovskiy' import csv from .abstract_report import AbstractReport from .save_io_to_file_mixin import SaveIoToFileMixin class CsvReport(AbstractReport, SaveIoToFileMixin): def __init__(self, data_report, headers): """ :param data_report: данные отче...
ame = 'report.csv' def __del__(self): super().__del__() def _make_io_report(self): """ записывает в io_report отчет в строковом виде """ writer = csv.writer(self.io_report, delimiter=' ') writer.writerow(self.headers) writer.writerows(self.data_report) ...
report(self): """ Сформировать отчёт """ self.save_to_file()
bubae/gazeAssistRecognize
lib/BING-Objectness/source/bing.py
Python
mit
10,487
0.023934
''' Created on Jan 2, 2015 @author: alessandro ''' import add_path import os import cv2 import sys import json import getopt import random import numpy as np from filter_tig import FilterTIG EDGE = 8 BASE_LOG = 2 MIN_EDGE_LOG = int(np.ceil(np.log(10.)/np.log(BASE_LOG))) MAX_EDGE_LOG = int(np.ceil(np.log(500.)/np.log(...
ets/VOC2007/BING_Results/sizes.txt", "num_win_psz": 130, "num_bbs": 1500 } """ try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help", "num_bbs_per_size=", "num_bbs=" ]) except getopt.GetoptError as err: # print help...
ized" sys.exit(2) params_file = sys.argv[-2] if not os.path.exists(params_file): print "Specified file for parameters %s does not exist."%params_file sys.exit(2) try: f = open(params_file, "r") params_str = f.read() f.close() except Exception as e: ...