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
brunobord/critica
apps/notes/settings.py
Python
gpl-3.0
652
0.001534
# -*
- coding: utf-8 -*- """ Settings of ``critica.apps.notes`` application. """ from critica.apps.notes import choices # Excluded categories # ------------------------------------------------------------------------------ EXCLUDED_CATEGORIES = [
'epicurien', 'voyages', 'regions', 'coup-de-gueule', ] # Type order # ------------------------------------------------------------------------------ TYPE_ORDER = [ 'vous-saviez', 'fallait-sen-douter', 'ca-cest-fait', 'linfo-off', 'criticons', 'aucun-interet', 'premiere-nouvelle...
wakiyamap/electrum-mona
electrum_mona/lnaddr.py
Python
mit
18,219
0.002744
#! /usr/bin/env python3 # This was forked from https://github.com/rustyrussell/lightning-payencode/tree/acc16ec13a3fa1dc16c07af6ec67c261bd8aff23 import re import time from hashlib import sha256 from binascii import hexlify from decimal import Decimal from typing import Optional, TYPE_CHECKING, Type import random impo...
f k == '9': if v == 0: continue feature_bits = bitstring.BitArray(uint=v, length=v.bit_length()) feature_bits = trim_to_min_length(feature_bits)
data += tagged('9', feature_bits) else: # FIXME: Support unknown tags? raise LnEncodeException("Unknown tag {}".format(k)) tags_set.add(k) # BOLT #11: # # A writer MUST include either a `d` or `h` field, and MUST NOT include # both. if 'd' in tags_s...
wuan/klimalogger
klimalogger/sensor/sht1x_sensor.py
Python
apache-2.0
1,458
0.00206
# -*- coding: utf8 -*- from injector import singleton, inject try: import configparser except ImportError: import configparser as configparser from sht1x.Sht1x import Sht1x as SHT1x @singleton class Sensor: name = "SHT1x" @inject def __init__(self, config_parser: configparser.ConfigParser): ...
mperature, humidity) = self.sht1x.read_temperature_C_and_humidity() if temperature > -40.0: try: dew_point = self.sht1x.calculate_dew_point(temperature, humidity) dew_point = round(dew_point, 2) except ValueError: dew_point = None ...
= None dew_point = None if temperature and humidity and dew_point and -30 < temperature < 80 and 5 < humidity <= 100: data_builder.add(self.name, "temperature", "°C", temperature) if dew_point: data_builder.add(self.name, "dew point", "°C", dew_point, True) ...
rjschwei/azure-sdk-for-python
azure-mgmt-compute/azure/mgmt/compute/compute_management_client.py
Python
mit
7,735
0.002069
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
self.usage = UsageOperations( self._client, self.config, self._serialize, self._deserialize) self.virtual_machine_sizes = VirtualMachineSizesOperations( self._client, self.config, self._serialize, self._deserialize) self.images = ImagesOperat
ions( self._client, self.config, self._serialize, self._deserialize) self.virtual_machines = VirtualMachinesOperations( self._client, self.config, self._serialize, self._deserialize) self.virtual_machine_scale_sets = VirtualMachineScaleSetsOperations( self._client, se...
Alwnikrotikz/numexpr
bench/vml_timing.py
Python
mit
5,758
0.002431
################################################################### # Numexpr - Fast numerical array expression evaluator for NumPy. # # License: MIT # Author: See AUTHORS.txt # # See LICENSE.txt and LICENSES/*.txt for details about copyright and # rights to use. ##########################################...
al_method, 1, array_size, "", "", "", "", array_size) expressions = [] expressions.append('i2 > 0') expressions.append('f3+f4') expressions.append('f3+i2') expressions.append('exp(f3)') expressions.append('log(exp(f3)+1)/f4') expressions.append('0.1*i2 > arctan2(f3, f4)') expressions.ap...
sion=False): if expression: compare_times(expression, 1) sys.exit(0) nexpr = 0 for expr in expressions: nexpr += 1 compare_times(expr, nexpr) print if __name__ == '__main__': import numexpr numexpr.print_versions() numpy.seterr(all='ignore') numexpr.set...
rodo/django-perf
foo/tuna/management/commands/tuna_delete_direct.py
Python
gpl-3.0
1,873
0.000534
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2013,2014 Rodolphe Quiédeville <rodolphe@quiedeville.org> # # 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 ver...
odel) utils.print
_console('direct_delete', count, delta) print "{} : {}".format(name, model.objects.all().count())
Lilykos/invenio
invenio/modules/jsonalchemy/jsonext/engines/cache.py
Python
gpl-2.0
4,277
0.00187
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014 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 (at your option) any later...
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 Invenio; if not, write to the Free S
oftware Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Wrapper for *Flask-Cache* as engine for *JSONAlchemy*.""" import six from invenio.ext.cache import cache from invenio.modules.jsonalchemy.storage import Storage class CacheStorage(Storage): """Implement storage engine for F...
compsoc-ssc/compsocssc
general/models.py
Python
mit
2,517
0.005165
from django.db import models import warnings from django.utils import timezone import requests from image_cropping import ImageRatioField class CompMember(models.Model): """A member of compsoc""" class Meta: verbose_name = 'CompSoc Member' verbose_name_plural = 'CompSoc Members' index = ...
design on Arjoonn's
part so don't fall into the same trap. If you are using this for Orfik, that has already been fixed. If you are using this for logos, same thing. Over a few cycles this entire table will be removed. ''') return self.name name = models.CharField(max_length=100) time = models.Date...
Eldinnie/python-telegram-bot
tests/test_video.py
Python
gpl-3.0
7,707
0.000389
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2018 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
d warranty of # MERCHANTABILITY or FITNESS FOR A PA
RTICULAR PURPOSE. See the # GNU Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. import os import pytest from flaky import flaky from telegram import Video, TelegramError, Voice, PhotoS...
oddbird/gurtel
tests/test_util.py
Python
bsd-3-clause
1,076
0
from gurtel.util import Url class TestUrl(object): def equal(self, one, two): """ For this test, want to ensure that compare-equal implies hash-equal. """ return (one == two) and (hash(one) == hash(tw
o)) def test_no_qs(self): assert self.equal( Url("http://fake.base/path/"), Url("http://fake.base/path/")) def test_same_qs(self): assert self.equal( Url("http://fake.base/path/?foo=bar"), Url("http://fake.base/path/?foo=bar")) def test_diff...
ual( Url("http://fake.base/path/?foo=bar&arg=yo"), Url("http://fake.base/path/?arg=yo&foo=bar")) def test_different_value_order(self): assert not self.equal( Url("http://fake.base/path/?foo=bar&foo=yo"), Url("http://fake.base/path/?foo=yo&foo=bar")) def ...
hrayr-artunyan/shuup
shuup_tests/core/test_shipments.py
Python
agpl-3.0
6,394
0.001251
# This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import decimal import pytest from django.conf import settings from shuup.core.models import Shipm...
in range(0, int(line.quantity)): with pytest.raises(AssertionErro
r): unsaved_shipment = Shipment(supplier=supplier, order=second_order) order.create_shipment({line.product: 1}, shipment=unsaved_shipment) assert order.shipments.count() == 0 @pytest.mark.django_db def test_partially_shipped_order_status(): shop = get_default_shop() supplie...
vtemian/university_projects
practic_stage/hmw4/strategies/insertion.py
Python
apache-2.0
524
0.013359
from copy import deepcopy from .base import Strategy class Inse
rtionSort(Strategy): def sort_by(self, field): return self._sort(lambda x, y: x.grades[field] < y.grades[field]) def sort(self): return self._sort(lambda x, y: x < y) def _sort(self, compare): for first_item in self.items: items = deepcopy(self.items) items.iterator_start = first_item.ne...
if compare(first_item, second_item): self.items.interchange(first_item, second_item)
Crespo911/pyspace
pySPACE/environments/chains/node_chain.py
Python
gpl-3.0
60,058
0.003014
# coding=utf-8 """ NodeChains are sequential orders of :mod:`~pySPACE.missions.nodes` .. image:: ../../graphics/node_chain.png :width: 500 There are two main use cases: * the app
lication for :mod:`~pySPACE.run.launch_live` and the :mod:`~pySPACE.environments.live` using the default :class:`NodeChain` and * the benchmarking with :mod:`~pySPACE.run.launch` using the :class:`BenchmarkNodeChain` with the :mod:`~pySPACE.missions.operations.node_chain` operation. ...
od:`~pySPACE.missions.operations.node_chain` operation .. image:: ../../graphics/launch_live.png :width: 500 .. todo:: Documentation This module extends/reimplements the original MDP flow class and has some additional methods like reset(), save() etc. Furthermore it supports the construction of NodeChains and al...
google/uncertainty-baselines
uncertainty_baselines/datasets/imagenet_test.py
Python
apache-2.0
1,536
0.002604
# coding=utf-8 # Copyright 2022 The Uncertainty Baselines 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 ap...
ts.ImageNetDataset( 'train', include_file_name=True) dataset_with_file_name = builder_with_file_name.load(batch_size=1) self.assertEqual( list(dataset_with_file_name.element_spec.keys()), ['features', 'labels', 'file
_name']) if __name__ == '__main__': tf.test.main()
intenthq/code-challenges
python/connected_graph/connected_graph.py
Python
mit
637
0.00314
class Node(object): """Find if two nodes in a directed graph are connected. Based on http://www.codewars.com/kata/53897d3187c26d42ac00040d For example: a -+-> b -> c -> e
| +-> d a.connected_to(a) == true a.connected_to(b) == true a.connected_to(c) == true b.connected_to(d) == false""" def __init__(self, value, edges=None): self.value = value #What is the purpose of this construct? self.edges = edges or [] def connected_to(self, ...
Error("Not implemented") def __eq__(self, other): return self.value == other.value
karllessard/tensorflow
tensorflow/python/framework/subscribe_test.py
Python
apache-2.0
13,361
0.005838
# 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...
self.assertFalse(subscribe._is_subscribed_identity(idop)) self.assertTrue(subscribe._is_subscribed_identity(c_sub)) @test_util.run_deprecated_v1 def testSubscribeExtend(self): """Confirm side effect are correctly added for different input types.""" a = constant_op.constant(1) b = constant_op.consta...
graph, passing an unsubscribed tensor. sub_graph1 = lambda t: sub(t, 'graph1') c_sub = subscribe.subscribe( c, lambda t: script_ops.py_func(sub_graph1, [t], [t.dtype])) # Add a second side effect graph, passing the tensor returned by the # previous call to subscribe(). sub_graph2 = lambda t...
anhstudios/swganh
data/scripts/templates/object/static/particle/shared_particle_geyser_center.py
Python
mit
451
0.046563
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Static() result.template = "object/static/particle/shared_particle_geyser_center.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### ####...
#### return result
viaict/viaduct
app/views/lang.py
Python
mit
1,481
0
#!/usr/bin/env python # encoding: utf-8 from flask import Blueprint, redirect, session, url_for, flash from flask_babel import _ from fla
sk_babel import refresh from flask_login import current_user from app import db, constants from app.views import redirect_back blueprint = Blueprint('lang', __name__, url_prefix='/lang') @blueprint.route('/set/<path:lang>', methods=['GET']) def set_user_lang(lang=None): if lang not in constants.LANGUAGES.keys()...
rect(url_for('home.home')) if current_user.is_anonymous: flash(_('You need to be logged in to set a permanent language.')) return redirect_back() current_user.locale = lang db.session.add(current_user) db.session.commit() refresh() return redirect_back() @blueprint.route('/<pa...
StackVista/sts-agent-integrations-core
yarn/check.py
Python
bsd-3-clause
20,533
0.00375
''' YARN Cluster Metrics -------------------- yarn.metrics.appsSubmitted The number of submitted apps yarn.metrics.appsCompleted The number of completed apps yarn.metrics.appsPending The number of pending apps yarn.metrics.appsRunning The number of running apps yarn.metrics.apps...
containers reserved yarn.metrics.containersPending The number of containers pending yarn.metrics.to
talNodes The total number of nodes yarn.metrics.activeNodes The number of active nodes yarn.metrics.lostNodes The number of lost nodes yarn.metrics.unhealthyNodes The number of unhealthy nodes yarn.metrics.decommissionedNodes The number of decommissioned nodes yarn.metrics...
lampwins/netbox
netbox/dcim/migrations/0020_rack_desc_units.py
Python
apache-2.0
493
0.002028
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-10-28 15:01 from django.db impo
rt migrations, models class Migration(migrations.Migration): dependencies = [ ('dcim', '0019_new_iface_form_factors'), ] operations = [ migrations.AddField( model_name='rack', name='desc_units', field=models.BooleanField(default=False, help_text=b'Unit...
scending units'), ), ]
nicodv/kmodes
examples/soybean.py
Python
mit
1,461
0.000684
#!/usr/bin/env python import numpy as np from kmodes.kmodes import KModes # reproduce results on small soybean data set x = np.genfromtxt('soybean.csv', dtype=int, delimiter=',')[:, :-1] y = np.genfromtxt('soybean.csv', dtype=str, delimiter=',', usecols=(35, )) kmode
s_huang = KModes(n_clusters=4, init='Huang', verbose=1) kmodes_huang.fit(x) # Print cluster centroids of the trained model. print('k-modes (Huang) centroids:') print(kmodes_huang.cluster_centroids_) # Print training statistics print('Final training cost: {}'.format(kmodes_huang.cost_)) print('Training iterations: {}'....
uang.n_iter_)) kmodes_cao = KModes(n_clusters=4, init='Cao', verbose=1) kmodes_cao.fit(x) # Print cluster centroids of the trained model. print('k-modes (Cao) centroids:') print(kmodes_cao.cluster_centroids_) # Print training statistics print('Final training cost: {}'.format(kmodes_cao.cost_)) print('Training iterati...
CloudNcodeInc/django-phonenumber-field
phonenumber_field/phonenumber.py
Python
mit
3,532
0.001982
#-*- coding: utf-8 -*- import phonenumbers from django.conf import settings from django.core import validators from django.utils.six import string_types from phonenumbers.phonenumberutil import NumberParseException class PhoneNumber(phonenumbers.phonenumber.PhoneNumber): """ A extended version of phonenumbers...
keep_raw_input=True, numobj=phone_number_obj) return phone_number_obj def __unicode__(self): if self.is_valid(): if self.extension: return u"%sx%s" % (self.as_e164, self.e
xtension) return self.as_e164 return self.raw_input def __str__(self): return str(self.__unicode__()) def original_unicode(self): return super(PhoneNumber, self).__unicode__() def is_valid(self): """ checks whether the number supplied is actually valid ...
musicbrainz/picard
picard/util/progresscheckpoints.py
Python
gpl-2.0
1,663
0.001203
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # # Copyright (C) 2020 Gabriel Ferreira # Copyright (C) 2020 Laurent Monin # # 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 Founda...
ation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class ProgressCheckpoints: def __init__(self, num_jobs, num_checkpoints=10): """Create a set of unique an
d evenly spaced indexes of jobs, used as checkpoints for progress""" self.num_jobs = num_jobs self._checkpoints = {} if num_checkpoints > 0: self._offset = num_jobs/num_checkpoints for i in range(1, num_checkpoints): self._checkpoints[int(i*self._offset)]...
yyamano/RESTx
src/python/starter.py
Python
gpl-3.0
2,796
0.011803
""" RESTx: Sane, simple and effective data publishing and integration. Copyright (C) 2010 MuleSoft Inc. http://www.mulesoft.com 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...
mports import restx.settings as settings import restx.logger as logger from restx.core import RequestDispatcher from restx.platform_specifics import * from org.mulesoft.restx import Settings from org.mulesof
t.restx.util import Url from org.mulesoft.restx.component.api import * def print_help(): print \ """ RESTx server (c) 2010 MuleSoft Usage: jython starter.py [options] Options: -h, --help Print this help screen. -P, --port <num> Port on which the server listens ...
Azarn/mytodo
todo/migrations/0007_auto_20160530_1233.py
Python
apache-2.0
593
0.001686
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-30 12:33 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('todo', '0006_auto_20160530_
1210'), ] operations = [ migrations.AlterField( model_name='todo', name='category', field=models.ForeignKey(blank=True, default=1, on_delet
e=django.db.models.deletion.DO_NOTHING, to='todo.Category'), preserve_default=False, ), ]
kubeflow/pipelines
manifests/kustomize/base/installs/multi-user/pipelines-profile-controller/sync.py
Python
apache-2.0
16,824
0.00107
# Copyright 2020-2021 The Kubeflow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
"apiVersion": "v1", "kind": "ConfigMap", "metadata": { "name": "kfp-launcher", "namespace": namespace, }, "data": { "defaultPipelineRoot": kfp_default_pipeline_root, ...
ubeflow-pipelines-ready": len(children["Secret.v1"]) == 1 and len(children["ConfigMap.v1"]) == desired_configmap_count and len(children["Deployment.apps/v1"]) == 2 and len(children["Service.v1"]) == 2 and len(children["D...
devs1991/test_edx_docmode
venv/lib/python2.7/site-packages/sympy/utilities/tests/test_source.py
Python
agpl-3.0
278
0.010791
from sympy.utilities.source import get_mod_func, get_class def t
est_get_mod_func(): assert get_mod_func('sympy.core.basic.Basic') == ('sympy.core.basic', 'Basic') def test_get_class(): _basic = get_class('sympy.core.basic.Basic') assert _basic.__name__ =
= 'Basic'
CoherentLabs/depot_tools
recipes/recipe_modules/gclient/config.py
Python
bsd-3-clause
18,342
0.019082
# Copyright 2013 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. try: _STRING_TYPE = basestring except NameError: # pragma: no cover _STRING_TYPE = str from recipe_engine.config import config_item_context, ConfigGrou...
solution. build(c) c.got_revision_mapping['build'] = 'got_bu
ild_revision' @config_ctx() def master_deps(c): s = c.solutions.add() s.name = 'master.DEPS' s.url = ('https://chrome-internal.googlesource.c
tisnik/fabric8-analytics-common
a2t/src/auth.py
Python
apache-2.0
3,986
0.001254
"""Retrieve temporary access token by using refresh/offline token. Copyright (c) 2019 Red Hat Inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option...
rt item > 0 def check_not_before_policy_attribute(token_structure): """A
dditional check for the not-before-policy attribute.""" assert "token_type" in token_structure item = token_structure["not-before-policy"] assert isinstance(item, int) assert item >= 0 def get_and_check_token_structure(data): """Get the token structure from returned data and check the basic forma...
Eddy0402/Environment
vim/ycmd/third_party/bottle/test/tools.py
Python
gpl-3.0
5,129
0.005069
# -*- coding: utf-8 -*- import bottle import sys import unittest import wsgiref import wsgiref.util import wsgiref.validate import mimetypes import uuid from bottle import tob, tonat, BytesIO, py3k, unicode def warn(msg): sys.stderr.write('WARNING: %s\n' % msg.strip()) def tobs(data): ''' Transforms bytes o...
'].get(name, None)) def assertInError(self, search, route='/', **kargs): bottle.request.environ['wsgi.errors'].errors.seek(0) err = bottle.request.environ['wsgi.errors'].errors.read() if search not in err: self.fail('The search pattern "%s" is not included in wsgi.error: %s' % (...
f multipart_environ(fields, files): boundary = str(uuid.uuid1()) env = {'REQUEST_METHOD':'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary='+boundary} wsgiref.util.setup_testing_defaults(env) boundary = '--' + boundary body = '' for name, value in fields: body += boundar...
qsnake/gpaw
doc/tutorials/lattice_constants/iron.agts.py
Python
gpl-3.0
1,569
0.003187
def agts(queue): iron = queue.add('iron.py', ncpus=8, walltime=8 * 60) queue.add('iron.agts.py', deps=[iron], creates=['Fe_conv_k.png', 'Fe_conv_h.png']) if __name__ == '__main__': import numpy as np import pylab as plt from ase.utils.eos import EquationOfState from ase.io import ...
configs] eos = EquationOfState(volumes
, energies) v0, e0, B = eos.fit() return v0, e0, B kk = [2, 4, 6, 8, 10, 12] plt.figure(figsize=(6, 4)) for width in [0.05, 0.1, 0.15, 0.2]: a = [] for k in kk: v0, e0, B = f(width, k, 12) a.append((2 * v0)**(1.0 / 3.0)) print ('%7.3f ' * 7) ...
open-rnd/ros3d-www
ros3dui/system/__init__.py
Python
mit
1,104
0
# # Copyright (c) 2015 Open-RnD Sp. z o.o. # # 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, includi
ng without limitation the rights to use, copy, # modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in...
UT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE...
AllenInstitute/dipde
dipde/examples/singlepop_exponential_distribution.py
Python
gpl-3.0
2,322
0.009044
# Copyright 2013 Allen Institute # This file is part of dipde # dipde 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. # # dipde is dis...
ort InternalPopulation from dipde.internals.externalpopulation import ExternalPopulation from dipde.internals.network import Network from dipde.internals.connection import Connection as Connection def get_simulation(dv=.001, update_method='approx', approx_order=None, tol=1e-8): import scipy.stats as sps # Cre...
v, update_method=update_method, approx_order=approx_order, tol=tol) b1_i1 = Connection(b1, i1, 1, delays=0.0, weights=(sps.expon(0,.005), 201)) simulation = Network([b1, i1], [b1_i1]) return simulation def example(show=True, save=False): # Settings: t0 = 0. dt = .0001 dv = .0001 tf =...
ammzen/SolveLeetCode
101SymmetricTree.py
Python
mit
1,224
0.00817
# -*- coding: utf-8 -*- # Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). # For example, this binary tree is symmetric: # 1 # / \ # 2 2 # / \ / \ # 3 4 4 3 # But the following is not: # 1 # / \ # 2 2 # \ \ # 3 3 # Definition for a ...
== q.val and isTreeSym(p.left, q.right) and isTreeSym(p.right, q.left) else: return False if __name__ == '__main__': s = Solution() p1 = TreeNode(1) p2 = TreeNode(2) p3 = TreeNode(2)
p4 = None p5 = TreeNode(3) p6 = None p7 = TreeNode(3) p1.left = p2 p1.right = p3 p2.left = p4 p2.right = p5 p3.left = p6 p3.right = p7 print s.isSymmetric(p1)
HEPData/hepdata-converter
hepdata_converter/writers/yaml_writer.py
Python
gpl-2.0
3,048
0.00689
import yaml # We try to dump using the CSafeDumper for speed improvements. try: from yaml import CSafeDumper as Dumper except ImportError: #pragma: no cover from yaml import SafeDumper as Dumper #pragma: no cover from hepdata_converter.common import Option, OptionInitMixin from hepdata_converter.writers import ...
pdata_doi for table in tables: table.metadata['table_doi'] = self.hepdata_doi + '/t' + str(table.index) if not isinstance(data_out, str) and not self.single_file: raise ValueError("output is not string, and single_file flag is not specified") if not self.sing
le_file: self.create_dir(data_out) with open(os.path.join(data_out, 'submission.yaml'), 'w') as submission_file: yaml.dump_all([data] + [table.metadata for table in tables], submission_file, Dumper=Dumper, default_flow_style=None) for table in tables: ...
franklai/lyric-get
lyric_engine/modules/uta_net.py
Python
mit
3,585
0.000561
import logging from utils import common from utils.lyric_base import LyricBase site_class = 'UtaNet' site_index = 'uta_net' site_keyword = 'uta-net' site_url = 'http://www.uta-net.com/' test_url = 'http://www.uta-net.com/song/138139/' test_expect_length = 1089 # current url format # 'http://www.uta-net.com/song/13813...
nfo(self, url): ret = True html = common
.get_url_content(url) patterns = { 'title': '<h2[^>]*>([^<]+)</h2>', 'artist': '歌手:<h3.*?><a href="/artist/[0-9]+/".*?>(.+?)</a></h3>', 'lyricist': '作詞:<h4.*?>([^<]+)</h4>', 'composer': '作曲:<h4.*?>([^<]+)</h4>' } self.set_attr(patterns, html) ...
pypa/warehouse
warehouse/admin/__init__.py
Python
apache-2.0
2,024
0.000988
# 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 Li...
ing for the Admin application config.add_jinja2_search_path("templates", name=".html") # Setup our static assets prevent_http_cache = config.get_settings().get("pyramid.prevent_http_cache", False) config.add_static_view( "admin/static", "warehouse.admin:static/dist", # Don't cac...
x_age=0 if prevent_http_cache else 10 * 365 * 24 * 60 * 60, ) config.add_cache_buster( "warehouse.admin:static/dist/", ManifestCacheBuster( "warehouse.admin:static/dist/manifest.json", reload=config.registry.settings["pyramid.reload_assets"], strict=not preven...
wolfram74/numerical_methods_iserles_notes
venv/lib/python2.7/site-packages/sympy/__init__.py
Python
mit
2,176
0.011949
"""SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python and does not require any external libraries, except optionally for ...
return eval(debug_str) else: raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" % debug_str) SYMPY_DEBUG = __sympy_debug() from .core import * from .logic import * from .assumptions import * from .polys import * from .series import * from .functi
ons import * from .ntheory import * from .concrete import * from .simplify import * from .sets import * from .solvers import * from .matrices import * from .geometry import * from .utilities import * from .integrals import * from .tensor import * from .parsing import * from .calculus import * # Adds about .04-.05 secon...
edgedb/edgedb
tests/test_edgeql_expr_aliases.py
Python
apache-2.0
32,398
0
# # This source file is part of the EdgeDB open source project. # # Copyright 2017-present MagicStack Inc. and the EdgeDB 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...
hemas', 'cards.esdl') SETUP = [os.path.join(os.path.dirname(__file__), 'schemas', 'cards_setup.edgeql')] async def test_edgeql_aliases_basic_01(self): await self.assert_query_resu
lt( r''' SELECT AirCard { name, owners: { name } ORDER BY .name } ORDER BY AirCard.name; ''', [ { 'name': 'Djinn', ...
modelblocks/modelblocks-release
resource-general/scripts/itemmeasures2lineitems.py
Python
gpl-3.0
588
0.001701
import sys sentid_prev = 0 first_line = True first_word = Tr
ue for line in sys.stdin: row = line.strip().split() if first_line: word_ix = row.index('word') sentid_ix = row.index('sentid') first_line = False else: word = row[word_ix] sentid = row[senti
d_ix] if first_word: delim = '' first_word = False elif sentid == sentid_prev: delim = ' ' else: delim = '\n' sentid_prev = sentid sys.stdout.write(delim + word) sys.stdout.write('\n')
geggo/gpyfft
setup.py
Python
lgpl-3.0
3,106
0.00322
import os import platform from setuptools import setup, Extension from distutils.util import convert_path from Cython.Build import cythonize system = platform.system() ## paths settings # Linux if 'Linux' in system: CLFFT_DIR = r'/home/gregor/devel/clFFT' CLFFT_LIB_DIRS = [r'/usr/local/lib64'] CLFFT_INCL_...
CLFFT_DIR = r'/Users/gregor/Devel/clFFT' CLFFT_LIB_DIRS = [r'/Users/gregor/Devel/clFFT/src/library'] CLFFT_INCL_DIRS = [os.path.join(CLFFT_DIR, 'src', 'include'), ] CL_INCL_DIRS = [] EXTRA_COMPILE_ARGS = ['-stdlib=libc++'] EXTRA_LINK_ARGS = ['-stdlib=libc++'] import Cython.Compiler.Options Cython.C...
e_cleanup_code = 2 extensions = [ Extension("gpyfft.gpyfftlib", [os.path.join('gpyfft', 'gpyfftlib.pyx')], include_dirs= CLFFT_INCL_DIRS + CL_INCL_DIRS, extra_compile_args=EXTRA_COMPILE_ARGS, extra_link_args=EXTRA_LINK_ARGS, libraries=['clFFT'],...
RRCKI/panda-server
pandaserver/test/execute.py
Python
apache-2.0
2,194
0.014585
import sys import time import commands import userinterface.Client as Client from taskbuffer.JobSpec import JobSpec from taskbuffer.FileSpec import FileSpec if len(sys.argv)>1: site = sys.argv[1] else: site = None datasetName = 'panda.destDB.%s' % commands.getoutput('uuidgen') destName = 'BNL_ATLAS_2' job...
SE fileOL.dataset = job.destinationDBlock fileOL.type = 'log' job.addFile(fileOL) file
OZ = FileSpec() fileOZ.lfn = "%s.pool.root" % commands.getoutput('uuidgen') fileOZ.destinationDBlock = job.destinationDBlock fileOZ.destinationSE = job.destinationSE fileOZ.dataset = job.destinationDBlock fileOZ.type = 'output' job.addFile(fileOZ) job.jobParameters="""-l %s -...
metpy/MetPy
v0.8/_downloads/upperair_soundings.py
Python
bsd-3-clause
7,536
0.001725
# Copyright (c) 2016,2017 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """ =========================== Upper Air Sounding Tutorial =========================== Upper air analysis is a staple of many synoptic and mesoscale analysis problems. In this...
r analysis or # publication. # # The most basic skew-T can be plotted with only five lines of Python. # These lines perform the following tasks: # # 1. Create a ``Figure`` object and set the size of the figure. # # 2. Create a ``SkewT`` object # # 3. Plot the pressure and temperature (note that the pressure, # the i...
bs at the appropriate pressure using the u and v wind # components. # Create a new figure. The dimensions here give a good aspect ratio fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig) # Plot the data using normal plotting functions, in this case using # log scaling in Y, as dictated by the typical meteorologica...
aolsux/SamuROI
doc/examples/script.py
Python
mit
4,482
0.004685
import numpy from samuroi.gui.samuroiwindow import SamuROIWindow from samuroi.plugins.tif import load_tif from samuroi.plugins.swc import load_swc from samuroi.masks.segmentation import Segmentation as SegmentationMask # requirements for template matching and post processing from samuroi.event.biexponential import Bi...
rve.remove() mainwindow.segmentation.postprocessor = postprocessor # if we click the button in the main window to install the postprocessor action.triggered.connect(install_pp) def redraw_fit(): global fitcurve # the index of the frame of interest i = mainwindow.segmentat...
ame, then go back half the kernel size, because the values in we want to plot # the kernel centered around the selected frame x = numpy.arange(0, len(kernel)) + i - len(kernel) / 2 if fitcurve is not None: fitcurve.remove() # we want to calculate the fit for the first cuve ...
andersonsilvade/python_C
Python32/aulas/hakeandositeprecodescontowhiletemposimounao.py
Python
mit
607
0.013559
import urllib.request import time def pega_preço(): pagina = urllib.r
equest.urlopen('http://beans.itcarlow.ie/prices-loyalty.html') texto = pagina.read().decode('utf8') onde = texto.find('>$') inicio= onde + 2 fim = inicio + 4 return float(texto[inicio:fim]) opção = input("deseja comprar já? (S/N)") if opção == 'S' : preço = pega_preço() print('Você comprou p...
time.sleep(5) print ('comprar ! Preço: %5.2f' %preço)
hiviah/perspectives-observatory
utilities/svg_client.py
Python
gpl-3.0
1,448
0.015884
# This file is part of the Perspectives Notary Server # # Copyright (C) 2011 Dan Wendlandt # # 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, version 3 of the License. # # This progra...
mon import verify_notary_signature, fetch_notary_xml, parse_http_notary_list from generate_svg import get_svg_graph if len(sys.argv) != 4: print "usage: %s <service-id> <notary-list-file> <len-days>" % sys.argv[0] exit(1) sid = sys.argv[1] server_list = parse_http_notary_list(sys.argv[2]) fo
r s in server_list: try: s["results"] = None server = s["host"].split(":")[0] port = s["host"].split(":")[1] code, xml_text = fetch_notary_xml(server,int(port), sid) if code == 200 and verify_notary_signature(sid, xml_text, s["public_key"]): s["results"] = xml_text except Exception, e: pass prin...
brython-dev/brython
www/src/Lib/unittest/test/test_discovery.py
Python
bsd-3-clause
34,059
0.001556
import os.path from os.path import abspath import re import sys import types import pickle from test import support from test.support import import_helper import test.test_importlib.util import unittest import unittest.mock import unittest.test class TestableTestProgram(unittest.TestProgram): module = None e...
'test_directory module tests'], ['test_directory2 module tests']]) # The test module paths should be sorted for reliable execution order self.assertEqual(Module.paths, ['a_directory', 'test_directory', 'test_directory2']) # load_t...
o tests in our stub module itself, so that is [] at # the time of call). self.assertEqual(Module.load_tests_args, [(loader, [], 'test*')]) def test_find_tests_default_calls_package_load_tests(self): loader = unittest.TestLoader() original_listdir = os.listd...
mcepl/rope
rope/refactor/similarfinder.py
Python
lgpl-3.0
12,522
0.00008
"""This module can be used for finding similar code""" import re import rope.refactor.wildcards from rope.base import libutils from rope.base import codeanalyze, exceptions, ast, builtins from rope.refactor import (patchedast, wildcards) from rope.refactor.patchedast import MismatchedTokenError class BadNameInCheck...
_children(expected) children2 = self._get_children(node) if len(children1) != len(children2): return False for child1, child2 in zip(children1, children2): if isinstance(child1, ast.AST): if not self._match_nodes(child1, child2, mapping): ...
return False for c1, c2 in zip(child1, child2): if not self._match_nodes(c1, c2, mapping): return False else: if type(child1) is not type(child2) or child1 != child2: return False retur...
lmazuel/azure-sdk-for-python
azure-mgmt-web/azure/mgmt/web/models/dimension.py
Python
mit
1,562
0.00128
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
r :param internal_name: :type internal_name: str :param to_be_exported_fo
r_shoebox: :type to_be_exported_for_shoebox: bool """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'internal_name': {'key': 'internalName', 'type': 'str'}, 'to_be_exported_for_shoebox': {'key': 'toBeExporte...
Dangetsu/vnr
Frameworks/Sakura/py/apps/reader/dialogs/retest.py
Python
gpl-3.0
5,176
0.010626
# coding: utf8 # retest.py # 12/16/2012 jichi __all__ = 'RegExpTester', if __name__ == '__main__': import sys sys.path.append('..') import debug debug.initenv() import re from PySide.QtCore import Qt from Qt5 import QtWidgets from sakurakit import skqss from sakurakit.skclass import memoizedproperty from sa
kurakit.skdebug import dprint from sakurakit.sktr import tr_ from mytr import mytr_ import rc def create_label(tex
t=""): # unicode -> QLabel ret = QtWidgets.QLabel() if text: ret.setText(text + ":") ret.setAlignment(Qt.AlignRight|Qt.AlignVCenter) return ret class _RegExpTester(object): def __init__(self, q): self._createUi(q) self._refresh() def _createUi(self, q): #url = "http://en.wikipedia.org/wik...
ricorx7/rti_python
ADCP/Predictor/MaxVelocity.py
Python
bsd-3-clause
6,635
0.004823
import json import os import math import pytest def calculate_max_velocity(**kwargs): """ Calculate the maximum velocity the ADCP can measure including the boat speed in m/s. This speed is the speed the ADCP is capable of measuring, if the speed exceeds this value, then the data will be incorrect due...
nfig["DEFAULT"]["38000"]["SAMPLING"] * config["DEFAULT"]["38000"]["CPE"] / _CyclesPerElement_ sampleRate = _SystemFrequency_ * (sumSampling) # Meters Per Sample metersPerSample = 0 if
sampleRate == 0: metersPerSample = 0.0 else: metersPerSample = math.cos(_BeamAngle_ / 180.0 * math.pi) * _SpeedOfSound_ / 2.0 / sampleRate # Lag Samples lagSamples = 0 if metersPerSample == 0: lagSamples = 0 else: lagSamples = 2 * math.trunc((math.trunc(_CWPBB_LagLen...
lukesummer/vnpy
vn.sgit/pyscript/generate_md_functions.py
Python
mit
11,152
0.003639
# encoding: UTF-8 __author__ = 'CHENXY' from string import join from sgit_struct import structDict def processCallBack(line): orignalLine = line line = line.replace(' virtual void ', '') # 删除行首的无效内容 line = line.replace('{};\n', '') # 删除行尾的无效内容 content = line.split('(') cbNa...
ata;\n") ftask.write("\t}\n") ftask.write("\tthis->task_queue.push(task);\n") ftask.write("};\n") ftask.write("\n") def createProcess(cbName, cbArgsTypeList, cbArgsValueList): # 从队列中提取任务,并转化为python字典 fprocess
.write("void " + apiName + '::' + cbName.replace('On', 'process') + '(Task task)' + "\n") fprocess.write("{\n") fprocess.write("\tPyLock lock;\n") onArgsList = [] for i, type_ in enumerate(cbArgsTypeList): if 'CSgitFtdcRspInfoField' in type_: fprocess.write("\t"+ type_ + ' task_err...
pwollstadt/IDTxl
dev/search_GPU/neighbour_search_opencl_old.py
Python
gpl-3.0
12,468
0.000962
"""Provide neighbour searches using OpenCl GPU-code.""" from pkg_resources import resource_filename import numpy as np from . import idtxl_exceptions as ex try: import pyopencl as cl except ImportError as err: ex.package_missing(err, 'PyOpenCl is not available on this system. Install' ...
cl.mem_flags.READ_WRITE, h_bf_indexes.nbytes) # Kernel Launch kernelLocation = resource_filename(__name__, 'gpuKnnBF_kernel.cl') kernelsource = open(kernelLocation).read() program = cl.Program(context, kernelsource).build() kern
elKNNshared = program.kernelKNNshared kernelKNNshared.set_scalar_arg_dtypes([None, None, None, None, np.int32, np.int32, np.int32, np.int32, np.int32, None, None]) # Size of workitems and NDRange if signallength/nchunks <...
CYBAI/servo
components/script/dom/bindings/codegen/parser/tests/test_optional_constraints.py
Python
mpl-2.0
981
0.001019
def WebIDLTest(parser, harness): threw = False try: parser.parse(""" interface OptionalConstraints1 { undefined foo(optional byte arg1, byte arg2); }; """) results = parser.finish() except: threw = True harness.ok(not threw, ...
llowing " "optional argument.") parser = parser.reset() parser.parse(""" interface OptionalConstraints2 { undefined foo(optional byte arg1 = 1, optional byte arg2 = 2, optional byte arg3, optional byte arg
4 = 4, optional byte arg5, optional byte arg6 = 9); }; """) results = parser.finish() args = results[0].members[0].signatures()[0][1] harness.check(len(args), 6, "Should have 6 arguments") harness.check(args[5].defaultValue.value, 9, "Should have correct ...
Kjell-K/AirGym
gym_airsim/envs/myAirSimClient.py
Python
mit
6,563
0.017218
import numpy as np import time import math import cv2 from pylab import array, arange, uint8 from PIL import Image import eventlet from eventlet import Timeout import multiprocessing as mp # Change the path below to point to the directoy where you installed the AirSim PythonClient #sys.path.append('C:/Users/Kjell/Goog...
duration): self.rotateByYawRate(-30, duration) start = time.time() return start, duration def take_action(self, action): #check if copter is on level cause sometimes he goes up without a reason x = 0 while self.getPosition().z_val < -7.0: sel...
start = time.time() duration = 0 collided = False if action == 0: start, duration = self.straight(1, 4) while duration > time.time() - start: if self.getCollisionInfo().has_collided == True: return True ...
InfectedPacket/resyst
resyst/__init__.py
Python
gpl-2.0
262
0.003817
# -*- coding: utf-8 -
*- """Automatic reverse engineering of firmware files for embedded devices.""" from resyst import metadata __version__ = metadata.version __author__ = metadata.authors[0] __license__ = metadata.license __copyri
ght__ = metadata.copyright
lituan/tools
pisa/pisa_same_entity.py
Python
cc0-1.0
5,849
0.014361
#!/usr/bin/env python # -*- coding: utf-8 -*- """ check same interface phos_binding patterns """ import os import sys import urllib import urllib2 import cPickle as pickle from multiprocessing import Pool def get_entityid(p): pdbid,interface_id,chain1,chain2 = p url = 'http://www.rcsb.org/pdb/rest/customRepo...
== 'x,y,z' and p[7][1][2].lower() == 'x,y,z'] pdb_interfaces = [p for p in pdb_interfaces if p[7][0][1] == 'Protein' and p[7][1][1] == 'Protein'] pdb_interfaces = filter_non_one_phos(pdb_interfaces) pdb_interfaces = filter_same_interface(pdb_interfaces) if __name__ == "__main
__": main()
killtheyak/killtheyak.github.io
killtheyak/test/webtest_tests.py
Python
mit
1,412
0.000708
from unittest import TestCase from webtest import TestApp from nose.tools import * # noqa from ..main import app class TestAUser(TestCase): def setUp(self): self.app = TestApp(app) def tearDown(self): pass def test_can_see_homepage(self): # Goes to homepage res = self.ap...
cks on a page res = res.click('install Python 2 and/or 3') # The page has dependency # The dependency titles are listed assert_in("install-homebrew", res) # Clic
ks on the dependency link (full instructions) res = res.click('full instructions', index=0) # Is at the dependency's page assert_in('ruby', res)
houssine78/addons
product_to_scale_bizerba/__openerp__.py
Python
agpl-3.0
1,686
0
# -*- coding: utf-8 -*- # Copyright (C) 2016-Today GRAP (http://www.grap.coop) # @author: Sylvain LE GAL (https://twitter.com/legalsylvain) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': 'Products - Send to Scales', 'summary': 'Synchronize Odoo database with Scales', 'versio...
'views/menu.xml', ], 'demo': [ 'demo/res_users.xml', 'demo/product_scale_system.xml', 'demo/product_scale_system_product_line.xml', 'demo/produc
t_scale_group.xml', 'demo/product_product.xml', 'demo/decimal_precision.xml', ], }
sukharevd/hadoop-install
bin/cherrypy-dns.py
Python
apache-2.0
1,744
0.012615
#!/usr/bin/python import sys service_name = "cherrypy-dns" pidfile_path = "/var/run/" + service_name + ".pid" port = 8001 if len(sys.argv) > 1 and sys.argv[1] == "service_name": print service_name; sys.exit(0) if len(sys.argv) > 1 and sys.argv[1] == "pidfile_path": print pidfile_path; sys.exit(0) if len(sys.argv) > ...
#def lookup(self, attr): # return subprocess.check_output('bash -c "cat $HADOOP_CONF_DIR/slaves"', shell=True) def execute_command(self, command): try: return subprocess.check_output(command, shell=True) except subprocess.CalledProcessError as e: raise cherrypy.HTTPEr...
'server.socket_host': '127.0.0.1', 'server.socket_port': port, 'server.thread_pool': 1 } } cherrypy.quickstart(ScriptRunner(), '/domain-names/', conf)
grap/OCB
addons/purchase/purchase.py
Python
agpl-3.0
71,343
0.007639
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
self, cr, uid, obj, ctx=None: obj['state'] == 'confirmed', 'purchase.mt_rfq_approved': lambda self, cr, uid, obj, ctx=Non
e: obj['state'] == 'approved', }, } _columns = { 'name': fields.char('Order Reference', size=64, required=True, select=True, help="Unique number of the purchase order, computed automatically when the purchase order is created."), 'origin': fields.char('Source Document', size=64, ...
sserrot/champion_relationships
venv/Lib/site-packages/jedi/api/file_name.py
Python
mit
5,707
0.001752
import os from jedi._compatibility import FileNotFoundError, force_unicode, scandir from jedi.api import classes from jedi.api.strings import StringName, get_quote_ending from jedi.api.helpers import match from jedi.inference.helpers import get_str_or_none class PathName(StringName): api_type = u'path' def com...
is_fuzzy=fuzzy, ) def _get_string_additions(module_context, start_leaf): def iterate_nodes(): node = addition.parent was_addition = True for child_node in reversed(node.children[:node.children.index(addition)]): if was_addition: was_addition = Fal...
break was_addition = True addition = start_leaf.get_previous_leaf() if addition != '+': return '' context = module_context.create_context(start_leaf) return _add_strings(context, reversed(list(iterate_nodes()))) def _add_strings(context, nodes, add_slash=False): string = '' ...
efforia/eos-dashboard
pandora-hub/app.py
Python
lgpl-3.0
5,312
0.022779
import re from unicodedata import normalize from datetime import datetime from django.shortcuts import render from django.http import HttpResponse as response from django.http import HttpResponseRedirect as redirect from django.conf import settings from models import Spreadable,Image,Playable,Spreaded,Product from soc...
read.jade",{},content_type='text/html') def create_spread(self,request): u = self.current_user(request) name = u.first_name.lower() text = unicode('%s' % (request.POST['content'])) p
ost = Spreadable(user=u,content=text,name='!'+name) post.save() self.accumulate_points(1,request) return response('Spreadable created successfully') class Uploads(Efforia): def __init__(self): pass def view_upload(self,request): return render(request,'content.jade',{'static_...
edx/edx-ora2
manage.py
Python
agpl-3.0
762
0.001312
#!/usr/bin/env python import os import sys if __name__ == "__main__": if os.environ.get('DJANGO_SETTINGS_MODULE') is None:
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.base' # When using an on-disk database for the test suite, # Django asks us if we want to delete the database. # We do. if 'test' in sys.argv[0:3]: # Catch warnings in te
sts and redirect them to be handled by the test runner. Otherwise build results are too # noisy to be of much use. import logging logging.captureWarnings(True) sys.argv.append('--noinput') sys.argv.append('--logging-clear-handlers') from django.core.management import execute...
edmorley/django
tests/migrations2/test_migrations_2/0001_initial.py
Python
bsd-3-clause
562
0
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("migrations", "0002_second")] operations = [ migrations.CreateModel( "OtherAuthor", [ ("id", mod
els.AutoField(primary_key=True)), ("name", models.CharField(max_length=255)), ("slug", models.SlugFie
ld(null=True)), ("age", models.IntegerField(default=0)), ("silly_field", models.BooleanField(default=False)), ], ), ]
puttarajubr/commcare-hq
custom/api/utils.py
Python
bsd-3-clause
714
0.001401
from requests.auth import HTTPBasicAuth def apply_updates(doc, update_dict): # updates the doc with items from the dict # returns whether or not any updates were made should_save = False for key, value in update_dict.items(): if getattr(doc, key, None) != value:
setattr(doc, key, value) should_save = True return should_save class EndpointMixin(object): @classmethod def from_config(cls, config): return cls(config.url, config.username, config.password) def _auth(self): return HTTPBasicAuth(self.username, self.passwo
rd) def _urlcombine(self, base, target): return '{base}{target}'.format(base=base, target=target)
nemesiscodex/openfonacide
openfonacide/management/commands/actualizar_datasets.py
Python
lgpl-3.0
3,284
0.002134
# encoding: utf-8 import csv from urllib2 import HTTPError import django from django.db import transaction import urllib2 from datetime import datetime from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import BaseCommand from openfonacide.matcher import Matcher from openfonacide.mo...
on, Adjudicacion, Planificacion, Temporal, Institucion __author__ = 'Diego Ramírez' def registrar_ultima_importacion(importacion=None, md5_sum=None): registro = RegistroImportacion(ultimo=True, ultimo_md5=md5_sum, importacion=importacion, fecha=datetime.now()) registro.save() @transaction.atomic def do_imp...
tipo=None): header_flag = True header = list() reader = csv.reader(lines_list.splitlines()) for row in reader: if header_flag: for column in row: header.append(column) header_flag = False else: args = dict() for element in r...
jaygoswami2303/course_dashboard_api
v2/GradeAPI/api.py
Python
mit
27,402
0.006861
from django.http import HttpResponse import pymongo import MySQLdb from course_dashboard_api.v2.dbv import * sql_user = MYSQL_USER sql_pswd = MYSQL_PSWD mysql_db = MYSQL_DB mongo_db = MONGO_DB """ Description: Function to get quiz level grades of all students in a particular course. Input Parameters: ...
nt's grade list
mongo_client.close() # Closing MongoDB connection db_mysql.close() # Closing MySQL connection grade_list = {} grade_list['course_name'] = course_name grade_list['course_organization'] = course_organization grade_list['course_run'] = course_run grade_list['students'] = full_grade_list retur...
iceman1989/Check_mk
web/plugins/userdb/ldap.py
Python
gpl-2.0
48,692
0.010065
#!/usr/bin/python # -*- encoding: utf-8; py-indent-offset: 4 -*- # +------------------------------------------------------------------+ # | ____ _ _ __ __ _ __ | # | / ___| |__ ___ ___| | __ | \/ | |/ / | # | | | | '_ \ / _ \/ __| |/ /...
to be authenticated, is not configured. Please ' 'fix this in the <a href="wato.py?mode=ldap_config">' 'LDAP User Settings</a>.')) try: errors = []
if enforce_server: servers = [ enforce_server ] else: servers = ldap_servers() for server in servers: ldap_connection, error_msg = ldap_connect_server(server) if ldap_connection: break # got a connection! else: ...
tareqalayan/ansible
lib/ansible/module_utils/aws/waiters.py
Python
gpl-3.0
9,345
0.000428
# Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) try: import botocore.waiter as core_waiter except ImportError: pass # caught by HAS_BOTO3 ec2_data = { "version": 2, "waiters": { "RouteTableExists": { ...
tors": [ { "matcher": "path", "expected": True, "argument"
: "length(Subnets[]) > `0`", "state": "retry" }, { "matcher": "error", "expected": "InvalidSubnetID.NotFound", "state": "success" }, ] }, "VpnGatewayExists": { ...
pbrunet/pythran
pythran/transformations/normalize_tuples.py
Python
bsd-3-clause
6,743
0
""" NormalizeTuples removes implicit variable -> tuple conversion. """ from pythran.analyses import Identifiers from pythran.passmanager import Transformation import ast class _ConvertToTuple(ast.NodeTransformer): def __init__(self, tuple_id, renamings): self.tuple_id = tuple_id self.renamings =...
if isinstance(t, ast.T
uple) or isinstance(t, ast.List): renamings = dict() self.traverse_tuples(t, (), renamings) if renamings: gtarget = node.value.id if no_tmp else self.get_new_id() node.targets[i] = ast.Name(gtarget, node.targets[i].ctx) ...
spulec/moto
moto/secretsmanager/urls.py
Python
apache-2.0
166
0
from .responses import SecretsManagerResponse url_bases = [r"https?://secr
etsmanager\.(.+)\.amazonaws\.com"] url_paths = {"{0}/$": SecretsManagerResponse.dispatch}
josherich/mindynode-parsers
mindynode_nltk/migrations/0010_keywordsum_keyword_category.py
Python
mit
519
0.001942
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2017-08-02 20:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mindynode_nltk', '0009_auto_20170802_2046'), ] operations = [ migrations.AddFi...
name='keyword_category', field=models.CharField(default
='china', max_length=255, null=True, verbose_name='类别'), ), ]
czpython/django-cms
cms/admin/forms.py
Python
bsd-3-clause
48,437
0.001755
# -*- coding: utf-8 -*- from django import forms from django.apps import apps from django.contrib.auth import get_user_model, get_permission_codename from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from django.contrib.sites.models import Site from django.core...
orm(BasePageForm): source = forms.ModelChoiceField( label=_(u'Page type'), queryset=Page.objects.filter( is_page_type=True, publisher_is_draft=True, ), required=False, ) parent_node = forms.ModelChoiceField( queryset=TreeNode.objects.all(), ...
*kwargs): super(AddPageForm, self).__init__(*args, **kwargs) source_field = self.fields.get('source') if not source_field or source_field.widget.is_hidden: return root_page = PageType.get_root_page(site=self._site) if root_page: # Set the choicefield's...
rdkit/rdkit-orig
rdkit/ML/test_list.py
Python
bsd-3-clause
523
0.059273
tests=[ ("python","UnitTestBuildComposite.py",{}), ("python","UnitTestScreenComposite.py",{
}), ("python","UnitTestAnalyzeComposite.py",{}), ] for dir in ['Cluster','Composite','Data','DecTree','Descriptors','FeatureSelect','InfoTheory','KNN','ModelPackage','NaiveBayes','Neural','SLT']: tests.append(('python','test_list.py',{'dir':dir})) longTests=[ ] if __name__=='__main__': import sys from...
d))
Vector35/binaryninja-api
python/decorators.py
Python
mit
380
0.026316
def pass
ive(cls): passive_note = ''' .. note:: This object is a "passive" object. Any changes you make to it will not be reflected in the core and vice-versa. If you wish to update a core version of this object you should use the appropriate API. ''' if hasattr(cls, "__doc__") and cls.__doc__: cls.__doc__ += passive_no...
c__ = passive_note return cls
uboness/sublime-plugins
Intellij/Intellij.py
Python
apache-2.0
2,360
0.007627
import sublime, sublime_plugin import functools import os import shutil class IntellijCopyCommand(sublime_plugin.TextCommand): def run(self, edit): v = self.view selection = v.sel(); if len(selection) == 0: v.run_command('expand_selection', { "to": "line" }) v.run_comman...
# v = self.window.find_open_file(o
ld) if view != None: view.retarget(new) except: sublime.status_message("Unable to rename") class IntellijCopyFileCommand(sublime_plugin.WindowCommand): def run(self): window = self.window view = window.active_view() filename = view.file_name(...
tanchao/algo
leetcode/py/75_sort_colors.py
Python
mit
579
0.008636
class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ red, white, blue = 0, 0, len(nums) - 1 while wh
ite <= blue:
if nums[white] == 0: # red nums[red], nums[white] = nums[white], nums[red] red += 1 white += 1 elif nums[white] == 1: # white white += 1 else: # blue nums[blue], nums[white] = nums[white], nums[blue] ...
airanmehr/bio
Scripts/TimeSeriesPaper/Plot/Markov.py
Python
mit
8,854
0.038288
import numpy as np; np.set_printoptions(linewidth=40, precision=5, suppress=True) import pandas as pd; pd.options.display.max_rows=80;pd.options.display.expand_frame_repr=False;pd.options.display.max_columns=20 im
port pylab as plt; import os; home=os.path.expanduser('~') +'/' import sys;sys.path.insert(1,'/home/arya/workspace/bio/') from CLEAR.Libs.Markov import Markov import Utils.Util as utl import Utils.Simulation as Simulation import matplotlib as mpl import seaborn as sns import Utils.Plots as pplt mpl.rc('fo...
et_style("whitegrid", {"grid.color": "1", 'axes.linewidth': .5, "grid.linewidth": ".09"}) subptitle = list('ABCDEFGHI') def createSelectionSimulations(s=0.1,maxGen=100): def runSim(i): try: sim = Simulation.Simulation(maxGeneration=maxGen, generationStep=1, s=s, foldInitialAFs=False, ...
memento7/KINCluster
KINCluster/__init__.py
Python
mit
1,038
0
""" KINCluster is clustering like KIN. release note: - version 0.1.6 fix settings update pipeline delete unused arguments fix convention by pylint now logging - version 0.1.5.5 fix using custom settings support both moudle and dic
t - version 0.1.5.4 Update tokenizer, remove stopwords eff - version 0.1.5.3 now custom setting available. see settings.py - version 0.1.5.2 change item, extractor, pipeline module now, pipeline.dress_item pass just item(extractor.dump) fix prev versions error (too many value to unpack) """ ...
mport KINCluster from KINCluster.core.cluster import Cluster from KINCluster.core.extractor import Extractor from KINCluster.core.item import Item from KINCluster.core.pipeline import Pipeline from KINCluster.lib.tokenizer import tokenizer from KINCluster.lib.stopwords import stopwords
great-expectations/great_expectations
great_expectations/core/evaluation_parameters.py
Python
apache-2.0
17,237
0.002843
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, ...
lues available only at run time. expop :: '^' multop :: '*' | '/' addop :: '+' | '-' integer :: ['+' | '-'] '0'..'9'+ atom :: PI | E | real | fn '(' expr ')' | '(' expr ')' factor :: atom [ expop factor ]* term :: factor [ multop factor ]* expr :: term [ addop term ]* ...
tps://github.com/pyparsing/pyparsing/blob/master/examples/fourFn.py """ # map operator symbols to corresponding arithmetic operations opn = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.truediv, "^": operator.pow, } fn = { ...
tryexceptpass/sofi
sofi/app/__init__.py
Python
mit
23
0
from
.app import Sofi
seanballais/botos
tests/test_results_exporter_view.py
Python
gpl-3.0
18,942
0.00132
import io import openpyxl from django.test import ( Client, TestCase ) from django.urls import reverse from core.models import ( User, Batch, Section, Election, Candidate, CandidateParty, CandidatePosition, Vote, VoterProfile, Setting, UserType ) class ResultsExporter(TestCase): """ Tests the r...
min%2Fresults') def test_voter_get_requests_redirected_to_index(self): self.client.logout() self.client.login(username='user0', password='voter') response = self.client.get(reverse('results-export'), follow=True) self.assertRedirects(response, reverse('index')) def
test_get_all_elections_xlsx(self): response = self.client.get(reverse('results-export')) self.assertEqual(response.status_code, 200) self.assertEqual( response['Content-Disposition'], 'attachment; filename="Election Results.xlsx"' ) wb = openpyxl.load_w...
thegooglecodearchive/phonetooth
phonetooth/bluetoothdiscovery.py
Python
gpl-2.0
1,814
0.012679
# Copyright (C) 2008 Dirk Vanden Boer <dirk.vdb@gmail.com> # # 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 versi...
_str__(self): return self.name + '(' + self.serviceName + ') - ' + self.address + ':' + str(self.port) class BluetoothDiscovery: def findSerialDevices(self): devices = bluetooth.discover_devices(duration = 5, lookup_names = False, flush_cache = True) serialDevices = [] for ...
= bluetooth.DIALUP_NET_CLASS)) for service in services: serialDevices.append(BluetoothDevice(service['host'], service['port'], bluetooth.lookup_name(service['host']), service['name'])) return serialDevices
pyohei/rirakkuma-crawller
tweet.py
Python
mit
565
0.001898
#!/usr/local/bin/python # -*- coding: utf-8 -*- """ Tweet rirra
kuma 4kuma submit. """ import tweepy TWEET_CONTENT = ( "リラックマの4クマ漫画が更新されました!\n" "http://www.shufu.co.jp/contents/4kuma/" ) consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" def main(): auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_...
NTENT) if __name__ == '__main__': main()
openprocurement/openprocurement.auctions.dgf
openprocurement/auctions/dgf/views/other/lot.py
Python
apache-2.0
3,339
0.004193
# -*- coding: utf-8 -*- from openprocurement.auctions.core.utils import ( apply_patch, context_unpack, get_now, json_view, opresource, save_auction, ) from openprocurement.auctions.core.validation import ( validate_lot_data, validate_patch_lot_data, ) from openprocurement.auctions.core.v...
ot in ['active.tenderin
g']: self.request.errors.add('body', 'data', 'Can\'t delete lot in current ({}) auction status'.format(auction.status)) self.request.errors.status = 403 return lot = self.request.context res = lot.serialize("view") auction.lots.remove(lot) if save_auct...
AlexCatarino/Lean
Algorithm.Python/DelistingEventsAlgorithm.py
Python
apache-2.0
3,448
0.007251
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. # Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the Licen...
summary> ### Demonstration of using the Delisting event in your algorithm. Assets are delisted on their last day of trading, or when their contract expires. ### This data is not included in the open source projec
t. ### </summary> ### <meta name="tag" content="using data" /> ### <meta name="tag" content="data event handlers" /> ### <meta name="tag" content="delisting event" /> class DelistingEventsAlgorithm(QCAlgorithm): def Initialize(self): '''Initialise the data and resolution required, as well as the cash and s...
mhorn71/StarinetPythonLogger
utilities/staribuscrc.py
Python
gpl-2.0
2,214
0.004065
__author__ = 'mark' # StarinetPython3Logger a data logger for the Beaglebone Black. # Copyright (C) 2015 Mark Horn # # This file is part of StarinetPython3Logger. # # StarinetPython3Logger is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by the...
<http://www.gnu.org/lic
enses/>. import crcmod import logging import sys ## Set crc16 parameters to polynomial 8408, initial value 0xffff, reversed True, Final XOR value 0x00 crc16 = crcmod.mkCrcFun(0x018408, 0xFFFF, True, 0x0000) ## initialise logger logger = logging.getLogger('utilities.staribuscCrc') def checkcrc(buffer0): logg...
jlrodrig/MyAnalysis
MiniAnalyzer/python/ConfFile_cfg.py
Python
gpl-3.0
471
0.019108
import FWCore.ParameterSet.Config as cms process = cms.Process("Demo") process.load("FWCore.MessageService.MessageLogger_cfi") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) process.source = cms.Source("PoolSource", # replace 'myfile.root' with the source file you want to use file...
th(process.demo)
cliftonmcintosh/openstates
openstates/co/votes.py
Python
gpl-3.0
12,425
0.002334
from openstates.utils import LXMLMixin from billy.scrape.votes import VoteScraper, Vote from billy.scrape.utils import convert_pdf import datetime import subprocess import lxml import os import re journals = "http://www.leg.state.co.us/CLICS/CLICS%s/csljournals.nsf/" \ "jouNav?Openform&%s" date_re = re.compile( ...
ge.xpath("//font//a") for href in hrefs: (path, response) = self.urlretrieve(href.attrib['href']) data = convert_pdf(path, type='text') data = fix_typos(data) cur_bill_id = None cur_vote_count = None in_vote = False cur_questi...
dt = date_re.findall(line) if dt != []: dt, dow = dt[0] dt = dt.replace(',', '') known_date = datetime.datetime.strptime(dt, "%A %B %d %Y") if in_question: line = line.str...
TimBuckley/effective_django
django/db/migrations/loader.py
Python
bsd-3-clause
11,967
0.001588
from importlib import import_module import os import sys from django.apps import apps from django.db.migrations.recorder import MigrationRecorder from django.db.migrations.graph import MigrationGraph from django.db.migrations.migration import Migration from django.db.migrations.state import ModelState from django.db.m...
uth_style_migrations: self.unmigrated_apps.add(app_config.label) def get_migration(self, app_label, name_prefix): "Gets the migration exactly named, or raises KeyError" return self.graph.nodes[app_label, name_prefix] def get_migration_by_prefix(self, a
pp_label, name_prefix): "Returns the migration(s) which match the given app label and name _prefix_" # Do the search results = [] for l, n in self.disk_migrations: if l == app_label and n.startswith(name_prefix): results.append((l, n)) if len(results) ...
wxgeo/geophar
wxgeometrie/sympy/integrals/tests/test_risch.py
Python
gpl-2.0
35,961
0.006173
"""Most of these tests come from the examples in Bronstein's book.""" from sympy import (Poly, I, S, Function, log, symbols, exp, tan, sqrt, Symbol, Lambda, sin, Eq, Ne, Piecewise, factor, expand_log, cancel, expand, diff, pi, atan) from sympy.integrals.risch import (gcdex_diophantine, frac_in, as_poly_1t, ...
st basic option assert derivation((x + 1)/(x - 1), DE, basic=True) == -2/(1 - 2*x + x**2) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(t, t)]}) assert derivation((t + 1)/(t - 1), DE, basic=True) == -2*t/(1 - 2*t + t**2) a
ssert derivation(t + 1, DE, basic=True) == t def test_splitfactor(): p = Poly(4*x**4*t**5 + (-4*x**3 - 4*x**4)*t**4 + (-3*x**2 + 2*x**3)*t**3 + (2*x + 7*x**2 + 2*x**3)*t**2 + (1 - 4*x - 4*x**2)*t - 1 + 2*x, t, field=True) DE = DifferentialExtension(extension={'D': [Poly(1, x), Poly(-t**2 - 3/(2*x)*t +...
calvinchengx/fabriccolors
fabriccolors/main.py
Python
bsd-2-clause
1,828
0.001094
""" This module contains fabriccolor's `main` method plus related subroutines. """ import fnmatch import os import sys def find_fabsettings(): "
"" Look for fabsettings.py, which will contain all information about target servers and distros on each server. i """ matches = [] for root, dirnames, filenames in os.walk(os.getcwd()): for filename in fnmatch.f
ilter(filenames, 'fabsettings.py'): matches.append(os.path.join(root, filename)) number_of_matches = len(matches) if number_of_matches == 1: path_to_fabsettings = matches[0] load_fabsettings(path_to_fabsettings) return True return False def load_fabsettings(path_to_fab...
xuru/pyvisdk
pyvisdk/do/vim_esx_cl_inetworkfirewallrulesetallowediplist_firewall_ruleset_allowedip.py
Python
mit
1,110
0.008108
import logging from pyvisdk.exceptions import InvalidArgumentError # This module is NOT auto-generated # Inspired by decompiled Java classes from vCenter's internalvim25stubs.jar # Unless states otherside, the methods and attributes were not used by esxcli, # and thus not tested log = logging.getLogger(__name__) de...
irewallRulesetAllowedip(vim, *args, **kwargs): obj = vim.client.factory.create('ns0:VimEsxCLInetworkfirewallrulesetallowediplistFirewallRulesetAllowedip') # do some validation checking... if (len(args) + len(kwargs)) < 0: raise IndexError
('Expected at least 1 arguments got: %d' % len(args)) required = [ ] optional = [ 'AllowedIPAddresses', 'Ruleset' ] for name, arg in zip(required + optional, args): setattr(obj, name, arg) for name, value in kwargs.items(): if name in required + optional: setattr(obj, nam...
davedash/mysql-anonymous
anonymize.py
Python
mit
3,818
0.003405
#!/usr/bin/env python # This assumes an id on each field. import logging import hashlib import random log = logging.getLogger('anonymize') common_hash_secret = "%016x" % (random.getrandbits(128)) def get_truncates(config): database = config.get('database', {}) truncates = database.get('truncate', []) sq...
if len(sys.argv) > 1: files = sys.argv[1:] else: files = [ 'anonymize.yml' ] for f in files: print "--" print "-- %s" %f print "--" print "SET @common_hash_secret=rand();" print "" cfg = yaml.load(open(f)) if 'databases' not in cfg: ...
g) else: databases = cfg.get('databases') for name, sub_cfg in databases.items(): print "USE `%s`;" % name anonymize({'database': sub_cfg})
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_application_building_blocks/argparse_fromfile_prefix_chars.py
Python
apache-2.0
435
0.002299
im
port argparse import shlex parser = argparse.ArgumentParser(description='Short sample app', fromfile_prefix_chars='@', ) parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argume...
bandwidthcom/python-bandwidth-iris
iris_sdk/models/account.py
Python
mit
4,216
0.000474
#!/usr/bin/env python from __future__ import division, absolute_import, print_function from future.builtins import super from iris_sdk.models.account_users import AccountUsers from iris_sdk.models.available_npa_nxx import AvailableNpaNxx from iris_sdk.models.available_numbers import AvailableNumbers from iris_sdk.mod...
Subscriptions from iris_sdk.models.portins import PortIns from iris_sdk.m
odels.portouts import PortOuts from iris_sdk.models.reservation import Reservation from iris_sdk.models.site_hosts import SiteHosts from iris_sdk.models.sites import Sites from iris_sdk.models.tn_option_orders import TnOptionOrders XPATH_ACCOUNT = "/accounts/{}" class Account(BaseResource, AccountData): """Iris ...
jawilson/home-assistant
homeassistant/components/hive/light.py
Python
apache-2.0
5,000
0.0002
"""Support for Hive light devices.""" from datetime import timedelta from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, SUPPORT_COLOR_TEMP, LightEntity, ) from homeassistant.helpers.entit
y import DeviceInfo import homeassistant.util.color as color_util from . import HiveEntity, refresh_system from .const import ATTR_MODE, DOMAIN PARA
LLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) async def async_setup_entry(hass, entry, async_add_entities): """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] devices = hive.session.deviceList.get("light") entities = [] if devices: for ...
Neomania/BeeSimulation
fonts.py
Python
mit
808
0.012376
#--------------------------------------
----------------------------------------- # Name: module1 # Purpose: # # Author
: Timothy # # Created: 02/02/2015 # Copyright: (c) Timothy 2015 # Licence: <your licence> #------------------------------------------------------------------------------- import pygame import pygame.freetype pygame.freetype.init() infoFontSize = 18 infoFont = pygame.freetype.SysFont('Consolas',infoFontSi...
PainNarrativesLab/IOMNarratives
IOMDataService.py
Python
mit
5,350
0.002991
import shelve """ Currently unused. All mysql queries are now done via IomDataModels. May be resurrected to help with shelve and pickles """ from USCProjectDAOs import IOMProjectDAO class IOMService(IOMProjectDAO): """ This handles interactions with the IOM data database and storage files. All user appl...
file @param datafile: The path to the datafile @type datafile: C{string} """ # try: db = shelve.open(datafile) db[label] = self.to_save db.close() print(self.to_save) return self.to_save # Check whether the problem was there not being a ...
e to save #except: # try: # self.to_save # print ('Problem saving') # except: # print ('No variable self.to_save set') # def get_data_from_database(self, query, val): # """ # This executes a parameterized query of the mysql database, stores the results in a list of dict...