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
diogocs1/comps
web/openerp/addons/test_impex/models.py
Python
apache-2.0
5,891
0.003225
# -*- coding: utf-8 -*- from openerp.osv import orm, fields def selection_fn(obj, cr, uid, context=None): return list(enumerate(["Corge", "Grault", "Wheee", "Moog"])) def function_fn(model, cr, uid, ids, field_name, arg, context): return dict((id, 3) for id in ids) def function_fn_write(model, cr, uid, id, f...
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100): if isinstance(name, basestring) and name.split(':')[0] == self._name: ids = self.search(cr, user, [['value', operator, int(name.split(':'
)[1])]]) return self.name_get(cr, user, ids, context=context) else: return [] class One2ManyMultiple(orm.Model): _name = 'export.one2many.multiple' _columns = { 'parent_id': fields.many2one('export.one2many.recursive'), 'const': fields.integer(), 'child1...
valmynd/MediaFetcher
src/plugins/youtube_dl/youtube_dl/extractor/mitele.py
Python
gpl-3.0
3,700
0.028116
# coding: utf-8 from __future__ import unicode_literals from .common
import InfoExtractor from ..util
s import ( int_or_none, smuggle_url, parse_duration, ) class MiTeleIE(InfoExtractor): IE_DESC = 'mitele.es' _VALID_URL = r'https?://(?:www\.)?mitele\.es/(?:[^/]+/)+(?P<id>[^/]+)/player' _TESTS = [{ 'url': 'http://www.mitele.es/programas-tv/diario-de/57b0dfb9c715da65618b4afa/player', 'info_dict': { 'id':...
mozilla/mozilla-ignite
apps/challenges/tests/test_views.py
Python
bsd-3-clause
32,366
0.001329
# Note: not using cStringIO here because then we can't set the "filename" from StringIO import StringIO from copy import copy from datetime import datetime, timedelta from django.contrib.auth.models import User, AnonymousUser from django.contrib.messages import SUCCESS from django.core.urlresolvers import reverse from...
set(submissio
ns[1:])) @ignite_only def test_winning_entries(self): """Test the winning entries view.""" create_submissions(5) winners = Submission.objects.all()[1:3] for entry in winners: entry.is_winner = True entry.save() response = self.client.get(rever...
liaorubei/depot_tools
tests/rietveld_test.py
Python
bsd-3-clause
15,103
0.006158
#!/usr/bin/env python # Copyright (c) 2012 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. """Unit tests for rietveld.py.""" import logging import os import ssl import sys import time import traceback import unittest sys...
6', _api({'file_a': _file('B')})), ] try: self.rietveld.get_patch(123, 456) self.fail() except patch.UnsupportedPatchFormat, e: self.assertEqual('file_a', e.filename) def test_add_plus_merge(self): # svn:mergeinfo is dropped. properties = ( '\nAdded: svn:mergeinfo\n' ...
self.requests = [ ('/api/123/456', _api({'pp': _file('A+', property_changes=properties)})), ('/download/issue123_456_789.diff', GIT.COPY), ] patches = self.rietveld.get_patch(123, 456) self.assertEqual(1, len(patches.patches)) self._check_patch( patches.patches[0], ...
maxive/erp
addons/l10n_es/__manifest__.py
Python
agpl-3.0
1,890
0.003178
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # List of contributors: # Jordi Esteve <jesteve@zikzakmedia.com> # Dpto. Consultoría Grupo Opentia <consultoria@opentia.es> # Pedro M. Baeza <pedro.baeza@tecnativa.com> # Carlos Liébana <carlos.liebana@factorlibre.com> #...
==== * Defines the following chart of account templates: * Spanish general chart of accounts 2008 * Spanish general chart of accounts 2008 for small and medium companies * Spanish general chart of acc
ounts 2008 for associations * Defines templates for sale and purchase VAT * Defines tax templates * Defines fiscal positions for spanish fiscal legislation * Defines tax reports mod 111, 115 and 303 """, "depends" : [ "account", "base_iban", "base_vat", ], "data" : [ ...
mne-tools/mne-tools.github.io
0.19/_downloads/0162af27293b0c7e7c35ef85531280ea/plot_55_setting_eeg_reference.py
Python
bsd-3-clause
10,338
0
# -*- coding: utf-8 -*- """ .. _tut-set-eeg-ref: Setting the EEG reference ========================= This tutorial describes how to set or change the EEG reference in MNE-Python. .. contents:: Page contents :local: :depth: 2 As usual we'll start by importing the modules we need, loading some :ref:`example dat...
######################## # If a scalp electrode was used as reference but was not saved alongside the # raw data (reference channels often aren't), you may wish to add it back to # the dataset before re-referencing. For example, if your EEG system recorded # with channel ``Fp1`` as the reference but did not include ``F...
` to set (say) ``Cz`` as the # new reference will then subtract out the signal at ``Cz`` *without restoring # the signal at* ``Fp1``. In this situation, you can add back ``Fp1`` as a flat # channel prior to re-referencing using :func:`~mne.add_reference_channels`. # (Since our example data doesn't use the `10-20 electr...
nicolaevladescu/hootch
workers/Reddit.py
Python
mit
6,671
0.008095
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Reddit worker """ import praw import sys import time import yaml from datetime import datetime from pytz import UTC from pymongo import MongoClient, IndexModel, ASCENDING, DESCENDING, TEXT from pymongo.errors import PyMongoError __version__ = '0.0.1-alpha.1' c...
ata=data) except (TypeError, PyMongoError) as exception: print('Worker {}
: Could not save documents because: {}.'.format(__name__, exception)) sys.exit(1) else: print('Worker {}: Saved {!s} documents.'.format(__name__, len(results.inserted_ids))) if not reddit.indexes_created(): try: reddit.create_indexes() except (...
taikoa/taikoa
taikoa.py
Python
agpl-3.0
2,419
0.002894
import re import time from flask import Flask, render_template, request, flash, redirect from flaskext.babel import Babel from flask.ext.mail import Mail, Message from flask.ext.cache import Cache from flask.ext.assets import Environment from raven.contrib.flask import Sentry import feedparser app = Flask(__name__) ...
me') @cache.cached(t
imeout=50) @app.route("/projects") def projects(): return render_template('projects.html', active='project') @cache.cached(timeout=50) @app.route("/about/me") def about_me(): return render_template('about-me.html', active='about') @cache.cached(timeout=50) @app.route("/contact") def contact(): return re...
hms-dbmi/clodius
scripts/get_hitile.py
Python
mit
1,168
0
#!/usr/bin/python from __future__ import print_function import clodius.hdf_tiles as hdft import h5py import argparse def main(): parser = argparse.ArgumentParser( description=""" python get_hitile.py filename z x """ ) parser.add_argument("filename") parser.add_argument("z", type=int) ...
(f, args.z, args.x) print("tile:", tile_data
) if __name__ == "__main__": main()
nmercier/linux-cross-gcc
win32/bin/Lib/lib2to3/fixes/fix_intern.py
Python
bsd-3-clause
1,451
0
# Copyright 2006 Georg Brandl. # Licensed to PSF under a Contributor Agreement. """Fixer for intern(). intern(s) -> sys.intern(s)""" # Local imports from .. import pytree from .. import fixer_base from ..fixer_util import Name, Attr, touc
h_import class FixIntern(fixer_base.BaseFix): BM_compatible = True order = "pre" PATTERN = """ power< 'intern' trailer< lpar='(' ( not(arglist | argument<any '=' any>) obj=any | obj=arglist<(not argument<any '=' any>) any ','> ) ...
obj = results["obj"].clone() if obj.type == syms.arglist: newarglist = obj.clone() else: newarglist = pytree.Node(syms.arglist, [obj.clone()]) after = results["after"] if after: after = [n.clone() for n in after] new = pytree.Node(s...
spacelis/hrnn4sim
hrnn4sim/data_augmentation.py
Python
mit
3,901
0.001282
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: data_augmentation.py Author: Wen Li Email: spacelis@gmail.com Github: http://github.com/spacelis Description: Augmenting data with some sythetic negative examples. """ # pylint: disable=invalid-name from __future__ import print_function import sys import re impo...
sampleB: cn_addr = change_num(addr) if cn_addr != addr: exD[0].append(addr) exD[1].append(change_num(addr)) return p
d.DataFrame({'addra': exA[0] + exB[0] + exC[0] + exD[0], 'addrb': exA[1] + exB[1] + exC[1] + exD[1]}) def get_pos_examples(df): ''' Make some more positive examples by cloning addresses ''' addrPoolA = list(frozenset(df['addra'])) addrPoolB = list(frozenset(df['addrb'])) retur...
apache/bloodhound
installer/setup.py
Python
apache-2.0
1,462
0
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (th...
staller", version=latest, description=DESC.split('\n', 1)[0], author="Apache Bloodhound", license="Apache License v2", url="https://bloodhound.apache.org/"
, requires=['trac', 'BloodhoundMultiProduct'], packages=['bhsetup'], entry_points=""" [console_scripts] bloodhound_setup = bhsetup.bloodhound_setup:run """, long_description=DESC, )
rbdavid/RMSD_analyses
PCA_RMSD_One_Ref/system_rmsd_plotting.py
Python
gpl-3.0
1,985
0.040302
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python # ---------------------------------------- # USAGE: # ---------------------------------------- # PREAMBLE: import numpy as np import sys import os import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter from mpl_toolkits.mplot3d impo...
.loadtxt(file1) for i in range(nSel): events, edges, patches = plt.hist([ data1[0:650000,i], data1[650000:1300000,i], data1[1300000:1950000,i], data1[1950000:2600000,i], data1[2600000:3250000,i], data1[3250000:3900000,i], data1[3900000:4550000,i]], bins=100, histtype='bar', color=
[frame[0][2],frame[1][2],frame[2][2],frame[3][2],frame[4][2],frame[5][2],frame[6][2]],stacked=True) plt.grid(b=True, which='major', axis='both', color='#808080', linestyle='--') plt.xlabel('RMSD data for %s' %(sel[i][0])) plt.ylabel('Frequency') plt.xlim((min(data1[:,i]),max(data1[:,i]))) leg = plt.legend(legend...
ramcn/demo3
venv/lib/python3.4/site-packages/oauth2_provider/__init__.py
Python
mit
113
0
__version_
_ = '0.8.1' __author__ = "Massimiliano Pippi & Federico
Frenguelli" VERSION = __version__ # synonym
hpe-storage/horizon-hpe-storage-ui
horizon_hpe_storage/storage_panel/overview/tables.py
Python
apache-2.0
850
0
# (c) Copyright [2015] Hewlett Packard Enterprise Development LP # # Licens
ed 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 u...
plied. # See the License for the specific language governing permissions and # limitations under the License. from horizon import tables class OverviewTable(tables.DataTable): def get_object_id(self, obj): return None class Meta(object): name = "overview_panel" # hidden_title ...
thispc/download-manager
module/plugins/accounts/OneFichierCom.py
Python
gpl-3.0
2,134
0.000937
# -*- coding: utf-8 -*- import re import time import pycurl from module.network.HTTPRequest import BadHeader from ..internal.Account import Account class OneFichierCom(Account): __name__ = "OneFichierCom" __type__ = "account" __version__ = "0.23" __status__ = "testing" __description__ = """1fi...
ketmail[DOT]com"), ("Walter Purcaro", "vuolter@gmail.com")] VALID_UNTIL_PATTERN = r'Your Premium offer subscription is valid until <span style="fon
t-weight:bold">(\d+\-\d+\-\d+)' def grab_info(self, user, password, data): validuntil = None trafficleft = -1 premium = None html = self.load("https://1fichier.com/console/abo.pl") m = re.search(self.VALID_UNTIL_PATTERN, html) if m is not None: expireda...
fmarani/spam
tests/spamhaus_tests.py
Python
lgpl-3.0
1,040
0.002885
import unittest import sys from spam.spamhaus import * class MockSpamHausChecker(SpamHausChecker): def set_spam(self, is_spam): """docstring for setSpam""" self.is_spa
m = is_spam def _resolve(self, domain): """docstring for __resolve""" if self.is_spam: return "2.3.4.5" else: return "1.2.3.4" def _query_spamhaus(self, zone): """docstring
for __query_spamhaus""" if zone.startswith("5.4.3.2"): return "127.0.0.2" return None class TestSpamHausChecker(unittest.TestCase): def setUp(self): self.checker = MockSpamHausChecker() def test_spammer(self): self.checker.set_spam(True) result = self.check...
pawlactb/DiffusionModels
LanguageShift/LanguageAgent.py
Python
gpl-3.0
3,360
0.00506
import numpy as np from mesa import Agent class LanguageAgent(Agent): def __init__(self, model, name, unique_id, initial_prob_v): """ A LanguageAgent represents a particular place during a language shift simulation. :param model: the model that the agent is in :param unique_id: Loc...
st of probabilities of speaking partic
ular languages """ super().__init__(unique_id, model) self.name = name self.probability = np.array(initial_prob_v) self.next_probability = np.array(self.probability, copy=True) self.p_probability = np.array(initial_prob_v) self.p_next_probability = np.array(self....
labase/activnce
main/question/database.py
Python
gpl-2.0
1,434
0.007714
# -*- coding: utf-8 -*- """ ################################################ Plataforma ActivUFRJ ################################################ :Author: *Núcleo de Computação Eletrônica (NCE/UFRJ)* :Contact: carlo@nce.ufrj.br :Date: $Date: 2009-2010
$ :Status: This is a "work in progress" :Revision: $Revision: 0.01 $ :Home: `LABASE `__ :Copyright: ©2009, `GPL """ from couchdb.design import ViewDefinition import core.database ################################################ # CouchDB Permanent Views ################################################ # Retorna...
iew('question/by_quiz',startkey=[],endkey=[, {},{}]) question_by_quiz = ViewDefinition('question', 'by_quiz', \ ''' function(doc) { if (doc.type=="quiz") { emit ([doc._id, 0], null)...
bschutze/ALTO-framework-sim
Views/ping_.py
Python
mit
611
0.022913
#!/usr/bin/python #Master-Thesis dot parsing framework (PING MODULE) #Date: 14.01.2014 #Author: Bruno-Johannes Schuetze #uses python 2.7.6 #uses the djikstra algorithm implemented by David Eppstein #Module does calculatio
ns to behave similar to ping, uses delay label defined in the dot file from libraries.dijkstra import * def getSingleValue(src, dst, edgeCostHash): return edgeCostHash[(src*100000)+dst] def getPathTotal(start, end, edgeCostHash, networkDict): #get shortest path between start and end shortPathList = shortestPath(n...
rt, end) print "WE PINGING SHAWTY", shortPathList
textsaurabh/code_base
src/leetcode/script/remove_element_inplace.py
Python
mit
815
0.006135
#! /usr/local/bin/python -u # Given an array and a value, remove all instances of that value in place and return the new length. # The order of elements can be changed. It doesn't matter what you leave beyond the new length. class Solution: # @param A a list of integers # @param elem an integer,...
al_arr
ay_len -= 1 else: curr_idx += 1 return total_array_len if __name__ == '__main__': main([1], 1)
pyupio/octohook
hook/hook.py
Python
mit
3,954
0.000759
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import os import imp import hmac import hashlib import six from flask import Flask, abort, request DEBUG = os.environ.get("DEBUG", False) == 'True' HOST = os.environ.get("HOST", '0.0.0.0') ROOT_DIR = os.path.dirname(os.p...
th.join(REPO_DIR, name + ".py") module = imp.load_source(module_name, full_path) env_var = "{name}_SECRET".format(name=name.upper()) if env_var not in os.environ: if DEB
UG: print("WARNING: You need to set the environment variable {env_var}" " when not in DEBUG mode.".format( env_var=env_var )) else: raise AssertionError( "You need to set {env_var}".format( ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.3/Lib/plat-mac/Carbon/Appearance.py
Python
mit
26,525
0.001018
# Generated from 'Appearance.h' def FOUR_CHAR_CODE(x): return x kAppearanceEventClass = FOUR_CHAR_CODE('appr') kAEAppearanceChanged = FOUR_CHAR_CODE('thme') kAESystemFontChanged = FOUR_CHAR_CODE('sysf') kAESmallSystemFontChanged = FOUR_CHAR_CODE('ssfn') kAEViewsFontChanged = FOUR_CHAR_CODE('vfnt') kThemeDataFileType ...
tureNa
meTag = FOUR_CHAR_CODE('dpnm') kThemeDesktopPictureAliasTag = FOUR_CHAR_CODE('dpal') kThemeDesktopPictureAlignmentTag = FOUR_CHAR_CODE('dpan') kThemeHighlightColorNameTag = FOUR_CHAR_CODE('hcnm') kThemeExamplePictureIDTag = FOUR_CHAR_CODE('epic') kThemeSoundTrackNameTag = FOUR_CHAR_CODE('sndt') kThemeSoundMaskTag = FOU...
mwojcikowski/opendrugdiscovery
oddt/spatial.py
Python
bsd-3-clause
2,224
0.009442
"""Spatial functions included in ODDT Mainly used by other modules, but can be accessed directly. """ import numpy as np from scipy.spatial.distance import cdist as distance __all__ = ['angle', 'angle_2v', 'dihedral', 'distance'] # angle functions def angle(p1,p2,p3): """Returns an angle from a series of 3 point...
s, shape = [n_points, n_dimensions] Quadruplets of points in n-dimensional space, aligned in rows. Returns ------- angles : numpy array, shape = [n_points] Series of angles in degrees
""" v12 = (p1-p2)/np.linalg.norm(p1-p2) v23 = (p2-p3)/np.linalg.norm(p2-p3) v34 = (p3-p4)/np.linalg.norm(p3-p4) c1 = np.cross(v12, v23) c2 = np.cross(v23, v34) out = angle_2v(c1, c2) # check clockwise and anticlockwise n1 = c1/np.linalg.norm(c1) mask = (n1*v34).sum(axis=-1) > 0 i...
TwilioDevEd/api-snippets
twiml/voice/gather/gather-2/gather-2.6.x.py
Python
mit
125
0
from twilio.twim
l.voice_response import Gat
her, VoiceResponse response = VoiceResponse() response.gather() print(response)
dan-gamble/cms
cms/tests/test_pipeline.py
Python
bsd-3-clause
978
0
from django.http import HttpResponse from django.test import TestCase from ..pipeline import make_staff class Backend(object): name = None def __init__(self, name, *args, **kwargs): super(Backend, self).__init__(*args, **kwargs) self.name = name class MockSuperUser(object): is_staff = ...
aff(facebook_backend, user
, response) self.assertFalse(user.is_staff) self.assertFalse(user.is_superuser) make_staff(google_plus_backend, user, response) self.assertTrue(user.is_staff) self.assertTrue(user.is_superuser)
acdh-oeaw/defc-app
defcdb/migrations/0007_auto_20151120_0807.py
Python
mit
2,178
0.001837
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('defcdb', '0006_site_reference'), ] operations = [ migrations.AddField( model_name='dc_country', name...
name='authorityfile_id', field=models.CharField(max_length=100, help_text='Identifier provided by www.GeoNames.org', null=True, blank=True), ), migrations.AlterField( model_name='dc_country', name='authorityfile_id', field=models.CharField(max_l...
, help_text='Identifier provided by www.GeoNames.org', null=True, blank=True), ), migrations.AlterField( model_name='dc_province', name='authorityfile_id', field=models.CharField(max_length=100, help_text='Identifier provided by www.GeoNames.org', null=True, blank=Tru...
nsi-iff/should-dsl
run_examples.py
Python
mit
630
0.009524
#!/usr/bin/env python import doctest import unittest import sys def test_suite(docs): suite = unittest.TestSuite() for doc in docs: suite.addTest(doctest.DocFileSuite(doc, optionflags=flags())) return suite def flags(): flags =
doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS if sys.version_info >= (3,): flags |= doctest.IGNORE_EXCEPTION_DETAIL return flags def run(docs): suite = test_suite(docs) runner = unittest.TextTestRunner(verbosity=2) result = runner.run(suite) sys.exit(int(bool(result.failures or result....
raven47git/readthedocs.org
readthedocs/projects/templatetags/projects_tags.py
Python
mit
554
0
from django import template from proj
ects.version_handling import comparable_version register = template.Library() @register.filter def sort_version_aware(versions): """ Takes a list of versions objects and sort them caring about version schemes """ return sorted( versions, key=lambda version: comparable_
version(version.verbose_name), reverse=True) @register.filter def is_project_user(user, project): """ Return if user is a member of project.users """ return user in project.users.all()
mapado/haversine
haversine/haversine.py
Python
mit
5,961
0.002852
from math import radians, cos, sin, asin, sqrt, degrees, pi, atan2 from enum import Enum from typing import Union # mean earth radius - https://en.wikipedia.org/wiki/Earth_radius#Mean_radius _AVG_EARTH_RADIUS_KM = 6371.0088 class Unit(Enum): """ Enumeration of supported units. The full list can be check...
vg_earth_radius(unit) * numpy.arcsin(numpy.sqrt(d)) def inverse_haversine(point, distance, direction: Union[Direction, float], unit=Unit.KILOMETERS): lat, lng = point lat, lng = map(radians, (lat, lng)) d = distance r = get_avg_earth_radius(unit) brng = direction.value if isinstance(direction, Di...
s(d / r) + cos(lat) * sin(d / r) * cos(brng)) return_lng = lng + atan2(sin(brng) * sin(d / r) * cos(lat), cos(d / r) - sin(lat) * sin(return_lat)) return_lat, return_lng = map(degrees, (return_lat, return_lng)) return return_lat, return_lng
switchkiller/Python-and-Algorithms-and-Data-Structures
src/trees/check_ancestor.py
Python
mit
1,369
0.005113
#!/usr/bin/env python __author__ = "bt3" from binary_search_tree import BST, Node def find_ancestor(path, low_item, high_item): while path: current_item = path[0] if current_item < low_item: try: path = path[2:] except: return current_item...
ht) : return tree.item if tree.left and (n1 < tree.item and n2 < tree.item): return find_ancestor(tree.left, n1, n2) or tree.item if tree.right and (n1 > tree.item and n2 > tree.item): return find_ancestor(tree.right, n1, n2) or tree.item if __name__ == '__main__': bst = BST() ...
8, 2, 1, 11, 9, 4] for i in l: bst.add(i) nodes = bst.preorder_array() print 'Original: ', l print 'Preorder: ', nodes print 'Method 1: ' print 'Ancestor for 3, 11:', find_ancestor(nodes, 3, 11) print 'Method 2: ' print 'Ancestor for 3, 11: ', find_ancestor2(bst.root, 3,...
google-research/federated
generalization/utils/trainer_utils_test.py
Python
apache-2.0
6,847
0.007156
# Copyright 2021, Google LLC. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
3)) def test_create_federated_eval_fns_skips_rounds(self, rounds_per_eval, round_num): """Test that create_federated_eval_fns skips the appropriate rounds.""" part_train_eval_fn, part_val_fn, unpart_fn, _ = trainer_utils.create_federated_eval_fns( tff...
metrics_builder, part_train_eval_cd=create_federated_cd(), part_val_cd=create_federated_cd(), unpart_cd=create_federated_cd(), test_cd=create_federated_cd(), stat_fns=eval_metric_distribution.ALL_STAT_FNS, rounds_per_eval=rounds_per_eval, part_clients_per_eval=2, ...
holly/beretta
lib/beretta/parser.py
Python
mit
1,231
0.004062
from datetime import datetime from argparse import ArgumentParser import pprint import time import warnings import os, sys, io import signal import beretta import importlib __author__ = 'holly' class Parser(object): def __init__(self): self.parser = ArgumentParser(description=beretta.__doc__) ...
parser = self.subparsers.add_parser(plugin.name, help=plugin.help, description=plugin.desc) for args, kwargs in
plugin.arguments(): plugin_parser.add_argument(*args, **kwargs) plugins[name] = plugin args = self.parser.parse_args() if args.subparser_name in plugins: plugins[args.subparser_name].run_plugin(args) else: self.parser.print_help()
bjorskog/majordomo
majordomo/task.py
Python
bsd-3-clause
578
0.00519
#!/usr/bin/env python # -*- coding: utf-8 -*- import abc class Task(object): """ represents work to do """ __metaclass__ = abc.ABCMeta _is_done = False def __init__(self): """ constr
uctor """ pass def run(self): self._is_done = True return self._run() def requires(self): """
dependencies """ return [] def output(self): """ target """ return [] @abc.abstractmethod def _run(self): pass @property def is_done(self): return self._is_done
pism/pism
examples/python/bed_deformation.py
Python
gpl-3.0
5,232
0.001911
#!/usr/bin/env python3 import PISM from PISM.util import convert from math import cos, pi # Simple testing program for Lingle & Clark bed deformation model. # Runs go for 150,000 years on 63.5km grid with 100a time steps and Z=2 in L&C model. # SCENARIOS: run 'python bed_deformation.py -scenario N' where N=1,2,3,4 a...
lift, sea_level def create_grid(): P = PISM.GridParameters(config) P.horizontal_size_from_options() P.horizontal_extent_from_options() P.vertical_grid_from_options(config) P.ownership_ranges_from_options(ctx.size) return PISM.IceGrid(ctx.ctx, P) def run(scenario, plot, pause, save): # ...
mber("grid.Ly", 2000e3) config.set_number("grid.Mz", 2) config.set_number("grid.Lz", 1000) scenarios = {"1": (False, False, 1000.0), "2": (True, False, 1000.0), "3": (False, True, 0.0), "4": (True, True, 1000.0)} elastic, use_uplift, H0 = scenari...
plotly/plotly.py
packages/python/plotly/plotly/validators/splom/_idssrc.py
Python
mit
388
0
import _plotly_utils.bas
eval
idators class IdssrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__(self, plotly_name="idssrc", parent_name="splom", **kwargs): super(IdssrcValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", ...
leewp/TornadoPractice
application.py
Python
apache-2.0
336
0.020833
#!/usr/bin/env python # -*- coding: utf-8 -*- from url import url import tornado.web import os settings = dict( template_path = os.path.join(os.path.dirname(__file__), "templates"), static_path = os.path.join(os.path.dirn
ame(__file__), "statics") ) application = tornado.web.Application( handlers = url, *
*settings )
mcr/ietfdb
ietf/idtracker/migrations/0003_internet_draft_shepred_fk_blank_true.py
Python
bsd-3-clause
37,706
0.007771
from south.db import db from django.db import models from ietf.idtracker.models import * class Migration: def forwards(self, orm): # Changing field 'InternetDraft.shepherd' # (to signature: django.db.models.fields.related.ForeignKey(to=orm['idtracker.PersonOrOrgInfo'], null=True, bla...
', 'db_column': "'area_Name'"}), 'url': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'idtracker.ballotinfo': { 'Meta': {'db_table': "'ballot_info'"}, 'active': ('django.db.models.fields.BooleanField', [], {'de
fault': 'False', 'blank': 'True'}), 'an_sent': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'an_sent_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'ansent'", 'null': 'True', 'db_column': "'an_sent_by'", 'to': "orm['idtracker.IES...
MisterTea/MLPlayground
Python/gd_numpy.py
Python
apache-2.0
5,435
0.014351
import random import math import sys import numpy as np random.seed(1L) labels = [] features = [] NUM_FEATURES = 0 #Parse libsvm fp = open("datasets/a1a/a1a","r") while True: line = fp.readline() if len(line)==0: break tokens = line.split(" ") del tokens[-1] labels.append(0 if int(tokens[...
) print 'UNSCALED L2',unscaled_l2 loss_new += L2_STRENGTH * unscaled_l2 / NUM_INPUTS # Partial derivative of L2 regularization if unscaled_l2 > 1e-6: for y in xrange(1,NUM_FEATURES): weights[y] -= eps * L2_STRENGTH * weights[y] * 2 if True: # L1 ...
l1_strength = 0.005 loss_new += l1_strength * math.fsum(weights) / NUM_INPUTS for y in xrange(1,NUM_FEATURES): if abs(weights[y]) < l1_strength: weights[y] = 0 elif weights[y]>0: weights[y] -= l1_strength else: ...
biomodels/MODEL0912503622
MODEL0912503622/model.py
Python
cc0-1.0
427
0.009368
import os path = os.path.dirname(os.path.realpat
h(__file__)) sbmlFilePath = os.path.join(path, 'MODEL0912503622.xml') with open(sbmlFilePath,'r') as f: sbmlString = f.read()
def module_exists(module_name): try: __import__(module_name) except ImportError: return False else: return True if module_exists('libsbml'): import libsbml sbml = libsbml.readSBMLFromString(sbmlString)
libretro/mgba
src/platform/python/mgba/thread.py
Python
mpl-2.0
1,875
0
# Copyright (c) 2013-2017 Jeffrey Pfau # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from ._pylib import ffi, lib # pylint: disable=no-name-in-module from .core imp...
et = lib.mCoreThreadHasStarted(self._native) else: self._native = ffi.new("struct mCoreThread*") def start(self, core): if lib.mCoreThreadHasStarted(self._native): raise ValueError self._core = core self._native.core = core._core lib.m
CoreThreadStart(self._native) self._core._was_reset = lib.mCoreThreadHasStarted(self._native) def end(self): if not lib.mCoreThreadHasStarted(self._native): raise ValueError lib.mCoreThreadEnd(self._native) lib.mCoreThreadJoin(self._native) def pause(self): ...
Parallel-in-Time/pySDC
pySDC/tutorial/step_8/B_multistep_SDC.py
Python
bsd-2-clause
6,586
0.002885
import os from pySDC.helpers.stats_helper import filter_stats, sort_stats from pySDC.helpers.visualization_tools import show_residual_across_simulation from pySDC.implementations.collocation_classes.gauss_radau_right import CollGaussRadau_Right from pySDC.implementations.controller_classes.controller_nonMPI import con...
_params = dict() step_params['maxiter'] = 50 # initialize space transfer parameters space_transfer_params = dict() space_transfer_params['rorder'] = 2 space_transfer_params['iorder'] = 6 # initialize controller parameters controller_params = dict() controller_params['logger_level'] = 4...
escription dictionary for easy step instantiation description = dict() description['problem_class'] = heat1d # pass problem class description['sweeper_class'] = generic_LU # pass sweeper description['sweeper_params'] = sweeper_params # pass sweeper parameters description['level_params'] = level_p...
LumPenPacK/NetworkExtractionFromImages
win_build/nefi2_win_amd64_msvc_2015/site-packages/numpy/lib/tests/test_twodim_base.py
Python
bsd-2-clause
17,996
0.001
"""Test functions for matrix module """ from __future__ import division, absolute_import, print_function from numpy.testing import ( TestCase, run_module_suite, assert_equal, assert_array_equal, assert_array_max_ulp, assert_array_almost_equal, assert_raises, rand, ) from numpy import ( arange, rot90,...
[0, 1, 0, 0], [0, 0, 1, 0]])) def
test_diag2d(self): assert_equal(eye(3, 4, k=2), array([[0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 0, 0]])) assert_equal(eye(4, 3, k=-2), array([[0, 0, 0], [0, 0, 0], ...
pyfa-org/Pyfa
gui/fitCommands/gui/localDrone/mutatedImport.py
Python
gpl-3.0
1,558
0.001926
import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.drone.localAdd import CalcAddLocalDroneCommand from gui.fitCommands.helpers import InternalCommandHistory, DroneInfo from service.fit import Fit class GuiImportLocalMutatedDroneCommand(wx.Command): def __in...
k=True) success = self.internalHistory.submit(cmd) eos.db.flush() sFit = Fit.getInstance() sFit.recalc(self.fitID) sFit.fill(self.fitID) eos.db.commit() wx.PostEvent(gui.main
Frame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,))) return success def Undo(self): success = self.internalHistory.undoAll() eos.db.flush() sFit = Fit.getInstance() sFit.recalc(self.fitID) sFit.fill(self.fitID) eos.db.commit() wx.PostEv...
asherbar/json-plus-plus
jpp/parser/lex.py
Python
mit
2,482
0
import operator import ply.lex as lex from jpp.parser.operation import Operation from jpp.parser.expression import SimpleExpression res
erved = { 'extends': 'EXTENDS', 'import': 'IMPORT', 'local': 'LOCAL', 'imported': 'IMPORTED', 'user_input': 'USER_INPUT', } N
AME_TOK = 'NAME' tokens = [ 'INTEGER', 'STRING_LITERAL', 'COLON', NAME_TOK, 'COMMA', 'LCURL', 'RCURL', 'LBRAC', 'RBRAC', 'LPAREN', 'RPAREN', 'DOT', 'SEMICOLON', 'BOOLEAN', 'MINUS', 'COMPARISON_OP', 'PLUS', 'MUL_OP', 'BIT_SHIFT_OPS', 'BITWI...
Marwari/spyChat
send_message.py
Python
mit
2,015
0.009429
# importing existing friend, steganography library, and datetime. from select_friend import select_friend from steganography.steganography import Steganography from datetime import datetime from spy_details import friends, ChatMessage #importing regular expression for proper validation import re # importing termcolor...
want to hide a secret message. original_i
mage = raw_input("Provide the name of the image to hide the message : ") pattern_i = '^[a-zA-Z]+\.jpg$' # User validation for image files. if(re.match(pattern_i,original_image)!=None): print # Do Nothing here else: # Provide suggestions to user print colored("Please provide (.jpg...
sdemyanov/tensorflow-worklab
classes/stats.py
Python
apache-2.0
3,985
0.01857
# -*- coding: utf-8 -*- """ Created on Mon May 16 17:14:41 2016 @author: sdemyanov """ import numpy as np from sklearn import metrics def get_prob_acc(probs, labels): return np.mean(np.argmax(probs, axis=1) == labels) def get_auc_score(scores, labels): fpr, tpr, thresholds = metrics.roc_curve(labels, scores, p...
ind]) mat[labind[0], predind[0]] += 1 # mat = np.transpose(mat) return mat def get_prob_confmat(probs, labels): classnum = probs.shape[1] mat = np.zeros((classnum, classnum), dtype=int) for pind in range(probs.shape[0]): mat[int(labels[pind]), np.argmax(probs[pind, :])] +=
1 #mat = np.transpose(mat) return mat def get_block_confmat(confmat, blocks): assert(confmat.shape[0] == confmat.shape[1]) classnum = confmat.shape[0] #assert(np.sum(blocks) == classnum) blocknum = len(blocks) blockconf = np.zeros((blocknum, blocknum)) for bi in range(blocknum): for bj in rang...
sadad111/leetcodebox
Minimum Time Difference.py
Python
gpl-3.0
1,137
0.002639
class Solution(object): def findMinDifference(self, timePoints): """ :type timePoints: List[str] :rtype: int """ def convert(time): return int(time[:2]) * 60 + int(time[3:]) minutes = map(convert, timePoints) minutes.sort() return min( (y ...
er h = Integer.valueOf(timePoints.get(i).substring(0, 2)); # time.add(60 * h + Integer.valueOf(timePoints.get(i).substring(3, 5))); # } # # Collections.sort(time, (Integer a, Integer b) -> a - b); # # for(int i = 1; i < time.size(); i++){ # mm = Math.min(mm, tim
e.get(i) - time.get(i-1)); # } # # int corner = time.get(0) + (1440 - time.get(time.size()-1)); # return Math.min(mm, corner); # } # # }
jseabold/statsmodels
statsmodels/stats/tests/test_descriptivestats.py
Python
bsd-3-clause
6,216
0
import numpy as np from numpy.testing import assert_almost_equal, assert_equal import pandas as pd import pytest from statsmodels.iolib.table import SimpleTable from statsmodels.stats.descriptivestats import ( Describe, Description, describe, sign_test, ) pytestmark = pytest.mark.filterwarnings( "...
index def test_empty_columns(df): df["c"] = np.nan res = Description(df) dropped = res.frame.c.dropna() assert dropped.shape[0] == 2 assert "missing" in dropped assert "nobs" in dropped df["c"] = np.nan res = Description(df.c)
dropped = res.frame.dropna() assert dropped.shape[0] == 2 @pytest.mark.skipif(not hasattr(pd, "NA"), reason="Must support NA") def test_extension_types(df): df["c"] = pd.Series(np.arange(100.0)) df["d"] = pd.Series(np.arange(100), dtype=pd.Int64Dtype()) df.loc[df.index[::2], "c"] = np.nan df.l...
Pikecillo/genna
external/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/rt_20000515.py
Python
gpl-2.0
1,364
0.002199
#"Ron Ten-Hove" <rtenhove@forte.com>, by wondering why he doesn't get the expected result from passing params to unnamed templates, exposes a subtle gotcha. 15 May 2000 from Xml.Xslt import test_harness sheet_1 = """<?xml version="1.
0"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output indent="yes"/> <xsl:template match="/"> <root> <xsl:apply-templates> <xsl:with-param name="param">List</xsl:with-param> </xsl:apply-templates> ...
<xsl:template match="chapter"> <xsl:param name="param">Unset</xsl:param> <chap> <xsl:attribute name="title"><xsl:value-of select="@name"/></xsl:attribute> <xsl:attribute name="cat"><xsl:value-of select="$param"/></xsl:attribute> </chap> </xsl:template> <xsl:template match="t...
onoga/wm
src/gnue/forms/GFObjects/GFLayout.py
Python
gpl-2.0
3,034
0.018128
# GNU Enterprise Forms - GF Object Hierarchy - Layout # # Copyright 2001-2007 Free Software Foundation # # This file is part of GNU Enterprise # # GNU Enterprise 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;...
--------------------------------------------------------------------
----- tabbed = 'none' name = 'layout' # ------------------------------------------------------------------------- # Constructor # ------------------------------------------------------------------------- def __init__(self, parent=None): GFContainer.__init__(self, parent, "GFLayout") self._triggerGloba...
syed/PerfKitBenchmarker
perfkitbenchmarker/static_virtual_machine.py
Python
apache-2.0
10,858
0.005618
# Copyright 2014 PerfKitBenchmarker 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 appli...
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 language governing permissions and # limitations under the License. """Class to represent a Static Virtual Machine objec...
e provided, all of them will be used and one additional non-static VM will be provisioned. The VM's should be set up with passwordless ssh and passwordless sudo (neither sshing nor running a sudo command should prompt the user for a password). All VM specifics are self-contained and the class provides methods to opera...
hexlism/css_platform
sleepyenv/lib/python2.7/site-packages/Flask_Admin-1.2.0-py2.7.egg/flask_admin/contrib/mongoengine/view.py
Python
apache-2.0
20,150
0.000893
import logging from flask import request, flash, abort, Response from flask_admin import expose from flask_admin.babel import gettext, ngettext, lazy_gettext from flask_admin.model import BaseModelView from flask_admin.model.form import wrap_fields_in_fieldlist from flask_admin.model.fields import ListEditableFieldLi...
form fields embedded into ListField:: class Comment(db.EmbeddedDocument): nam
e = db.StringField(max_length=20, required=True) value = db.StringField(max_length=20) class Post(db.Document): text = db.StringField(max_length=30) data = db.ListField(db.EmbeddedDocumentField(Comment)) class MyAdmin(ModelView): ...
wonder-sk/inasafe
safe/impact_statistics/test/test_postprocessor_manager.py
Python
gpl-3.0
5,518
0.000363
# coding=utf-8 """ InaSAFE Disaster risk assessment tool developed by AusAid and World Bank - **GUI Test Cases.** Contact : ole.moller.nielsen@gmail.com .. note:: 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 Fre...
0) DOCK.run_in_thread_flag = False DOCK.show_only_visible_layers_flag = False DOCK.set_layer_from_title_flag = False DOCK.zoom_to_impact_flag = False DOCK.hide_exposure_flag = False DOCK.show_intermediate_layers = False set_jakarta_extent() register_impac...
use a fresh registry, canvas, and dock for each test! QgsMapLayerRegistry.instance().removeAllMapLayers() DOCK.cboHazard.clear() DOCK.cboExposure.clear() # noinspection PyMethodMayBeStatic def test_check_postprocessing_layers_visibility(self): """Generated layers are not added ...
CLVsol/clvsol_odoo_api
__init__.py
Python
agpl-3.0
2,405
0
# -*- encoding: utf-8 -*- # -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public...
ntry_state import * from res_partner import * from res_users import * from survey_survey import * from clv_address import * from clv_address_category import * from clv_address_history import * from clv_address_history_log import * from clv_address_log import * from clv_document import * from clv_document_category impo...
y import * from clv_event_log import * from clv_global_tag import * from clv_history_marker import * from clv_lab_test_criterion import * from clv_lab_test_request import * from clv_lab_test_result import * from clv_lab_test_type import * from clv_lab_test_unit import * from clv_mfile import * from clv_person import * ...
IfcOpenShell/IfcOpenShell
src/ifcopenshell-python/ifcopenshell/api/structural/edit_structural_load_case.py
Python
lgpl-3.0
1,177
0
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2021 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
Public License # along with IfcOpenShell. If not, see <http://www.gnu.org/licenses/>. class Usecase: def __init__(self, file, **settings): self.file = file self.settings = {"load_case": None, "attributes": {}} for key, value in settings.items(): self.settings[key] = value ...
items(): setattr(self.settings["load_case"], name, value)
recipy/recipy
recipy/utils.py
Python
apache-2.0
1,587
0
import six from .log import log_input, log_output def open(*args, **kwargs): """Built-in open replacement that logs input and output Workaround for issue #44. Patching `__builtins__['open']` is complicated, because many libraries use standard open internally, while we only want to log inputs and out...
function, `codecs` is used to open the file with proper encoding. """ try: mode = args[1] except IndexError: mode = kwargs.get('mode', 'r') # open file for reading? for c in 'r+': if c in mode: log_input(args[0], 'recipy.open') # open file for writing? f...
ause otherwise, files will be opened before they is logged. # This causes problems with logging of file diffs, because when a file is # opened for writing, its contents will be discarded. # TODO: add tests for this if six.PY3: f = __builtins__['open'](*args, **kwargs) else: if 'encod...
Jortolsa/l10n-spain
l10n_es_toponyms/wizard/__init__.py
Python
agpl-3.0
1,118
0
# -*- coding: utf-8 -*- ############################################################################## #
# OpenERP, Open Source Management Solution # Copyright (c) 2013-2015 Serv. Tecnol. Avanzados # Pedro M. Baeza <pedro.baeza@serviciosbaeza.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as ...
eful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see...
darthdeus/dotfiles
c_ycm_conf.py
Python
mit
5,178
0.018733
# This file is NOT licensed under the GPLv3, which is the license for the rest # of YouCompleteMe. # # Here's the license text for this file: # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile
, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial or non-commercial, and by any # means. # # In jurisdictions that recognize copyright laws, the author or authors # of this software dedicate any and all copyright interest in the # software to the pu...
# successors. We intend this dedication to be an overt act of # relinquishment in perpetuity of all present and future rights to this # software under copyright law. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY...
AdamStelmaszczyk/pyechonest
doc/source/conf.py
Python
bsd-3-clause
8,757
0.006623
# -*- coding: utf-8 -*- # # pyechonest documentation build configuration file, created by # sphinx-quickstart on Thu Sep 30 15:51:03 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all
possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os, ins
pect # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0,os.path.abspath(...
vmiklos/darcs-hooks
config.py
Python
gpl-2.0
88
0.011364
#!/usr/bin/env python class config: enabled_
plugins = ['cia', 'sendmail', 'sync
hook']
apdjustino/DRCOG_Urbansim
src/opus_core/tools/explore_model.py
Python
agpl-3.0
3,937
0.013462
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE from optparse import OptionParser from opus_core.misc import get_config_from_opus_path from opus_core.logger import logger from opus_core.
configurations.xml_configuration import XMLConfiguration from opus_core.simulation.model_explorer import ModelExplorer class ModelExplorerOptionGroup: def __init__(self, usage="python %prog [options] ", description="Runs the given model for the given year, using data from given directory. Options...
ermore, either -c or -x must be given."): self.parser = OptionParser(usage=usage, description=description) self.parser.add_option("-m", "--model", dest="model_name", default = None, action="store", help="Name of the model to run.") self.parser.add_opti...
wnormandin/bftest_cli
cli/dockcli.py
Python
mit
4,675
0.003422
# Basic command-line interface to manage docker containers which will use an # image stored in a dockerhub registry - 'pokeybill/bftest' import click from click.testing import CliRunner import docker import sys import time import requests this = sys.modules[__name__] BASE_URL = 'unix://var/run/docker.sock' REGISTRY =...
t = 0 while True: cont_status = __check_state() if cont_status == 'healthy': click.echo('[*] Your app is running on http://127.0.0.1:8888') return True eli
f cont_status == 'starting': if repeat > 6: return time.sleep(1) repeat += 1 else: click.echo('[!] Container status: {}'.format(cont_status)) return def start_container(inst_name): this.client.create_container( ...
FDio/vpp
test/vpp_vxlan_tunnel.py
Python
apache-2.0
3,138
0
from vpp_interface import VppInterface from vpp_papi import VppEnum INDEX_INVALID = 0xffffffff DEFAULT_PORT = 4789 UNDEFINED_PORT = 0 def find_vxlan_tunnel(test, src, dst, s_port, d_port, vni): ts = test.vapi.vxlan_tunnel_v2_dump(INDEX_INVALID) src_port = DEFAULT_PORT if s_port != UNDEFINED_PORT: ...
_index, encap_vrf_id=self.encap_vrf_id, instance=self.instance, decap_next_index=self.decap_next_index) def query_vpp_config(self): return (INDEX_INVALID != find_vxlan_tunnel(self._test, self.src, ...
self.dst_port, self.vni)) def object_id(self): return "vxlan-%d-%d-%s-%s" % (self.sw_if_index, self.vni, self.src, self.dst)
karlch/vimiv
tests/window_test.py
Python
mit
1,521
0.001315
# vim: ft=python fileencoding=utf-8 sw=4 et sts=4 """Tests window.py for vimiv's test suite.""" import os from unittest import main, skipUnless from gi import require_version require_version('Gtk', '3.0') from gi.repository import Gdk from vimiv_testcase import VimivTestCase, refresh_gui class WindowTest(VimivTest...
CREEN else False @skipUnless(os.getenv("DISPLAY") == ":42", "Must run in Xvfb") def test_check_resize(self): """Resize window and check winsize.""" self.assertEqua
l(self.vimiv["window"].winsize, (800, 600)) self.vimiv["window"].resize(400, 300) refresh_gui() self.assertEqual(self.vimiv["window"].winsize, (400, 300)) if __name__ == "__main__": main()
aodag/WebDispatch
webdispatch/testing.py
Python
mit
523
0
""" utilities for testing """ def setup_environ(**kwargs): """ setup basic wsgi environ"""
environ = {} from wsgiref.util import setup_testing_defaults setup_testing_defaults(environ) environ.update(kwargs) return environ def make_env(path_info, script_name): """ set up basic wsgi environ""" from wsgiref.util impor
t setup_testing_defaults environ = { "PATH_INFO": path_info, "SCRIPT_NAME": script_name, } setup_testing_defaults(environ) return environ
ArtemBernatskyy/FundExpert.NET
mutual_funds/company/__init__.py
Python
gpl-3.0
66
0
defa
ult_app_config = 'mutual_funds.company.apps.CompanyAppConfig
'
cloudkick/libcloud
libcloud/compute/drivers/dummy.py
Python
apache-2.0
9,524
0.001575
# 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 use ...
.RUNNING True >>> driver.destroy_node(node) True >>> node.state == NodeState.RUNNING False >>> [node for node in driver.list_nodes() if node.name == 'dummy-1'] []
""" node.state = NodeState.TERMINATED self.nl.remove(node) return True def list_images(self, location=None): """ Returns a list of images as a cloud provider might have >>> from libcloud.compute.drivers.dummy import DummyNodeDriver >>> driver = Dummy...
sumyfly/vdebug
plugin/python/vdebug/opts.py
Python
mit
1,365
0.009524
class Options: instance = None def __init__(self,options): self.options = options @classmethod def set(cls,options): """Create an Options instance with the provided dictionary of options""" cls.instance = Options(options) @classmethod def inst(cls): ...
% name) @classmethod def overwrite(cls,name,value): inst = cls.inst() inst.options[name] = value @classmethod def isset(cls,name): """Checks whether the option exists and is set. By set, it means whether the option has length. All the option values are strings....
""" inst = cls.inst() if name in inst.options and \ len(inst.options[name]) > 0: return True else: return False class OptionsError(Exception): pass
arunchandramouli/fanofpython
code/features/datatypes/lists1.py
Python
gpl-3.0
3,368
0.039489
''' Aim :: To demonstrate the use of a list Define a simple list , add values to it and iterate and print it A list consists of comma seperated values which could be of any type which is reprsented as [,,,,] .. all values are enclosed between '[' and ']' ** A list object is a mutable datatype which means it...
odification of vara will result in modifying def_list ''' vara.append("Hero") print "Address of vara and def_list %s and %s "%(id(vara),id(def_list)),'\n\n' print "vara = %s "%(vara),'\n\n' print "def_list = %s "%(def_list),'\n\n' ''' Now creating a Partial Slice ... When a slice is created partially , we are ...
_list[3:] print "Address of getmeasliceofit and def_list %s and %s "%(id(getmeasliceofit),id(def_list)),'\n\n' print "getmeasliceofit = %s "%(getmeasliceofit),'\n\n' print "def_list = %s "%(def_list),'\n\n' ''' Now creating a Full Slice ... When a slice is created fully , we are actually creating a containe...
NOAA-PMEL/PyFerret
pviewmod/cmndhelperpq.py
Python
unlicense
21,512
0.002836
''' CmndHelperPQ is a helper class for dealing with commands sent to a PyQt piped viewer. This package was developed by the Thermal Modeling and Analysis Project (TMAP) of the National Oceanographic and Atmospheric Administration's (NOAA) Pacific Marine Environmental Lab (PMEL). ''' import sys # First try to import ...
_(self, painterpath, isfilled): '
'' Create a SymbolPath representing a symbol. Arguments: painterpath: the QPainterPath representing this symbol isfilled: if True, the symbol should be drawn with a solid brush; if False, the symbol should be drawn with a solid pen ...
banglakit/spaCy
spacy/language_data/punctuation.py
Python
mit
2,781
0.001566
# encoding: utf8 from __future__ import unicode_literals import re _ALPHA_LOWER = """ a ä à á â ǎ æ ã å ā ă ą b c ç ć č ĉ ċ c̄ d ð ď e é è ê ë ė ȅ ȩ ẽ ę f g ĝ ğ h i ı î ï í ī ì ȉ ǐ į ĩ j k ķ l ł ļ m n ñ ń ň ņ o ö ó ò ő ô õ œ ø ō ő ǒ ơ p q r ř ŗ s ß ś š ş ŝ t ť u ú û ù ú ū ű ǔ ů ų ư v w ŵ x y ÿ ý ỳ ŷ ỹ z ź ž ż þ """ ...
m² m³ dm dm² dm³ cm cm² cm³ mm mm² mm³ ha µm nm yd in ft kg g mg µg t lb oz m/s km/h kmh mph h
Pa Pa mbar mb MB kb KB gb GB tb TB T G M K """ _CURRENCY = r""" \$ £ € ¥ ฿ US\$ C\$ A\$ """ _QUOTES = r""" ' '' " ” “ `` ` ‘ ´ ‚ , „ » « """ _PUNCT = r""" … , : ; \! \? ¿ ¡ \( \) \[ \] \{ \} < > _ # \* & """ _HYPHENS = r""" - – — -- --- """ LIST_ELLIPSES = [ r'\.\.+', "…" ] LIST_CURRENCY = list(_CUR...
eduNEXT/edunext-platform
openedx/core/lib/command_utils.py
Python
agpl-3.0
1,739
0.002875
""" Useful utilities for management commands. """ from django.core.management.base import CommandError from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey def get_mutually
_exclusive_required_option(options, *selections): """ Validates that exactly one of the 2 given options is specified. Returns the name of the found option. """ selected = [sel for sel in selections if options.get(sel)] if len(selected) != 1: selection_string = ', '.join(f'--{selection}'...
dError(f'Must specify exactly one of {selection_string}') return selected[0] def validate_mutually_exclusive_option(options, option_1, option_2): """ Validates that both of the 2 given options are not specified. """ if options.get(option_1) and options.get(option_2): raise CommandError(f'B...
rmcdermo/sandbox
oflow.py
Python
mit
2,209
0.018108
#!/usr/bin/python #McDermott #15 Sep 2017 # # Calculations for compressible orifice flow # # Refs: # See my notes from 1996 # Munson, Young, Okishi. Fundamentals of Fluid Mechanics. Wiley, 1990. import
math HOC = 50010. # heat of combustion [kJ/kg] psig = 0.0003 T_F = 100. C_d = 0.85 # orifice discharge coefficient N = 1844 # number of holes D_in = 1./8. # diameter [in] D0_in = 8.*D_in # upstream manifold diameter [in] D = D_in*2.54/100. # fuel port diamet...
ea [m^2] D0 = D0_in*2.54/100. A0 = N*math.pi*(D0/2.)**2 # upstream flow area [m^2] beta = A/A0 # "beta ratio" k = 1.4 # isentropic coefficient W = 16. # molecular weight R = 8314.5 # universal gas constant [Pa*m3/(kmol*K)] T0 = 293. #(T_F+459.67)/1.8 # upstream absolute tem...
TheArchives/Nexus
core/plugins/fetch.py
Python
bsd-2-clause
5,886
0.003738
# The Nexus software is licensed under the
BSD 2-Clause license. # # You should have recieved a copy of this license with the software. # If you did not, you can find one at the following
link. # # http://opensource.org/licenses/bsd-license.php from core.plugins import ProtocolPlugin from ConfigParser import RawConfigParser as ConfigParser from core.decorators import * class FetchPlugin(ProtocolPlugin): commands = { "fetch": "commandFetch", "bring": "commandFetch", "i...
ecoron/SerpScrap
examples/example_csv.py
Python
mit
266
0
#!/
usr/bin/python3 # -*- coding: utf-8 -*- import serpscrap keywords = ['stellar'] config = serpscrap.Config() config.set('scrape_urls', False) scrap = serpscrap.SerpScrap() scrap.init(config=config.get(), keywords=keywords) results = scrap.a
s_csv('/tmp/output')
sdague/home-assistant
tests/components/androidtv/patchers.py
Python
apache-2.0
6,084
0.00263
"""Define patches used for androidtv tests.""" from tests.async_mock import mock_open, patch KEY_PYTHON = "python" KEY_SERVER = "server" ADB_DEVICE_TCP_ASYNC_FAKE = "AdbDeviceTcpAsyncFake" DEVICE_ASYNC_FAKE = "DeviceAsyncFake" class AdbDeviceTcpAsyncFake: """A fake of the `adb_shell.adb_device_async.AdbDeviceT...
f"{__name__}.{ADB_DEVICE_TCP_ASYNC_FAKE}.shell", shell_fail_python ), KEY_SERVER
: patch(f"{__name__}.{DEVICE_ASYNC_FAKE}.shell", shell_fail_server), } PATCH_ADB_DEVICE_TCP = patch( "androidtv.adb_manager.adb_manager_async.AdbDeviceTcpAsync", AdbDeviceTcpAsyncFake ) PATCH_ANDROIDTV_OPEN = patch( "homeassistant.components.androidtv.media_player.open", mock_open() ) PATCH_KEYGEN = patch...
restudToolbox/package
respy/fortran/interface.py
Python
mit
11,491
0.002176
""" This module serves as the interface between the PYTHON code and the FORTRAN implementations. """ import pandas as pd import numpy as np import subprocess import os from respy.python.shared.shared_auxiliary import dist_class_attributes from respy.python.shared.shared_auxiliary import dist_model_paras from respy.pyt...
r in ['FORT-NEWUOA']: optimizer_options[optimizer] = dict() optimizer_options[optimizer]['npt'] = 40 optimizer_options[optimizer]['rhobeg'] = 0.1 optimizer_options[optimizer]['rhoend'] = 0.0001 optimizer_options[optimizer]['maxfun'] = 20 if optimizer ...
optimizer_options[optimizer]['maxiter'] = 10 optimizer_options[optimizer]['stpmx'] = 100.0 respy_obj.unlock() respy_obj.set_attr('optimizer_options', optimizer_options) respy_obj.lock() return respy_obj def get_results(num_periods, min_idx, num_agents_sim, which): """ Add resu...
shagabutdinov/sublime-semicolon
semicolon.py
Python
mit
3,677
0.018493
import sublime import sublime_plugin import re from Statement import statement from Expression import expression try: from SublimeLinter.lint import persist except ImportError as error: print("Dependency import failed; please read readme for " + "Semicolon plugin for installation instructions; to disable this ...
ner[1]: b -= 1 new_sels.append(sublime.Region(a, b)) view.sel().clear() view.sel().add_al
l(new_sels) def is_keyword_statement(view, point): nesting = expression.get_nesting(view, point - 1, expression = r'{') if nesting == None: return False chars_before_nesting = view.substr(sublime.Region( max(nesting[0] - 512, 0), nesting[0] - 1 )) match = re.search(r'\)(\s*)$', chars_before_nes...
robrocker7/h1z1map
server/wsgi.py
Python
apache-2.0
388
0.002577
""" WSGI config for h1z1map project. It exposes the WSGI callable as a module-level variable named ``application``. For
more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") from djang
o.core.wsgi import get_wsgi_application application = get_wsgi_application()
shaded-enmity/dnf
dnf/repo.py
Python
gpl-2.0
27,545
0.001307
# repo.py # DNF Repository objects. # # Copyright (C) 2013-2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program i...
errs = _DownloadErrors() try: librepo.download_packages(targets, failfast=True) except librepo.LibrepoException as e: e
rrs.fatal = e.args[1] or '<unspecified librepo error>' drpm.wait() # process downloading errors errs.recoverable = drpm.err.copy() for tgt in targets: err = tgt.err if err is None or err.startswith('Not finished'): continue payload = tgt.cbdata pkg = payload....
pythonbyexample/PBE
dbetut/conf.py
Python
bsd-3-clause
6,209
0.005315
# -*- coding: utf-8 -*- # # Test documentation build configuration file, created by # sphinx-quickstart on Sat Feb 21 22:42:03 2009. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pi...
----------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('
10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [ ('index', 'Test.tex', ur'Django By Example', ur'lightbird.net', 'manual'), ] # The name...
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/operations/_virtual_hub_route_table_v2_s_operations.py
Python
mit
22,766
0.005183
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
teTableV2, or the result of cls(response) :rtype: ~azure.mgmt.network.v2020_11_01.models.VirtualHubRouteTableV2 :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualHubRouteTableV2"] error_map = { 401: Cl...
accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url...
FinnStutzenstein/OpenSlides
server/docker/settings.py
Python
mit
5,214
0.001534
""" Settings file for OpenSlides. For more information on this file, see https://github.com/OpenSlides/OpenSlides/blob/master/SETTINGS.rst """ import os import json from openslides.global_settings import * class MissingEnvironmentVariable(Exception): pass undefined = object() def get_env(name, default=undef...
will be shown, if there does not exist a user with a given email address. So one # can check, if a email is registered. If
this is not wanted, disable verbose # messages. An success message will always be shown. RESET_PASSWORD_VERBOSE_ERRORS = get_env("RESET_PASSWORD_VERBOSE_ERRORS", True, bool) # OpenSlides specific settings AUTOUPDATE_DELAY = get_env("AUTOUPDATE_DELAY", 1, float) DEMO_USERS = get_env("DEMO_USERS", default=None) DEMO_USE...
Stratoscale/rackattack-api
py/rackattack/tcp/node.py
Python
apache-2.0
1,797
0.001113
from rackattack import api class Node(api.Node): def __init__(self, ipcClient, allocation, name, info): assert 'id' in info assert 'primaryMACAddress' in info assert 'secondaryMACAddress' in info assert 'ipAddress' in info self._ipcClient = ipcClient self._allocatio...
SerialLog(self): connection = self._ipcClient.urlopen("/host/%s/serialLog" % self._id) try: return connection.read() finally: connection.close() def networkInfo(self): return self._info def answerDHCP(self, shou
ldAnswer): return self._ipcClient.call( 'node__answerDHCP', allocationID=self._allocation._idForNodeIPC(), nodeID=self._id, shouldAnswer=shouldAnswer)
AversivePlusPlus/AversivePlusPlus
tools/ik/src/kinematics/__init__.py
Python
bsd-3-clause
55
0
from chain import * from matr
ix_chain_element im
port *
albf/spitz
monitor/Exec.py
Python
gpl-2.0
245
0.008163
from MonitorData import * from Config import * a =
Config() Data = MonitorData(1, 10) Data.startAllNodes(a.subscription_id, a.certificate_path, a.lib_file, a.script, a.s
sh_user, a.ssh_pass, a.jm_address, a.jm_port, upgrade=True, verbose=True)
shumik/skencil-c
Sketch/UI/command.py
Python
gpl-2.0
7,045
0.042725
# Sketch - A Python-based interactive drawing program # Copyright (C) 1997, 1998, 2001 by Bernhard Herzog # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the Lice...
of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public
License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA from types import StringType, TupleType, FunctionType from Sketch import Pub...
Farforr/overlord
overlord/minions/api/v1/urls.py
Python
bsd-3-clause
478
0
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.conf.urls import url, include from rest_framework
.routers import DefaultRouter from rest_framework.urlpatterns import format_suffix_patterns from . import views router = DefaultRouter() router.register(r'minion', views.MinionViewSet, 'minion') router.register(r'data', views.MinionDataViewSet, 'data') urlpatterns = [ url( r'^',
include(router.urls) ), ]
arrayexpress/ae_auto
settings/settings_no_password.py
Python
apache-2.0
2,129
0.001879
__author__ = 'Ahmed G. Ali' ANNOTARE_DB = { 'name': 'annotare2', 'host': 'mysql-annotare-prod.ebi.ac.uk', 'port': 4444, 'username': '', 'password': '' } AE_AUTO_SUB_DB = { 'name': 'ae_autosubs', 'host': 'mysql-ae-autosubs-prod.ebi.ac.uk', 'port': 4091, 'username': '', 'password'...
'password': '' } ANNOTARE_DIR = '/ebi/microarray/ma-exp/AutoSubmissions/annotare/' GEO_ACCESSIONS_PATH = '/ebi/microarray/home/fgpt/sw/lib/perl/supporting_files/geo_import_supporting_files/geo_accessions.yml' TEMP_FOLDER = '/nfs/ma/home/arrayexpress/ae_automation/ae_automation/tmp/' ADF_LOAD_DIR = '/nfs/ma/home/arr...
tion/env_bashrc' EXPERIMENTS_PATH = '/ebi/microarray/home/arrayexpress/ae2_production/data/EXPERIMENT/' ADF_DB_FILE = '/nfs/production3/ma/home/atlas3-production/sw/configs/adf_db_patterns.txt' ENA_SRA_URL = 'https://www.ebi.ac.uk/ena/submit/drop-box/submit/' \ '?auth=' ENA_SRA_DEV_URL = 'https://www-tes...
ingkebil/trost
scripts/maintanance/count_all_tables.py
Python
gpl-2.0
217
0.018433
#!/usr/bin/env python
import sql import sys def main(argv): tables = sql.get_tables() for table in tables:
print "%s: %d" % (table, sql.count(table)) if __name__ == '__main__': main(sys.argv[1:])
willhardy/Adjax
website/urls.py
Python
bsd-3-clause
863
0.010429
from django.conf.urls.defaults import * urlpatterns = patterns('django.views.generic.simple', url(r'^$', 'redirect_to', {'url': '/what/'}, name="home"), url(r'^what/$', 'direct_to_template', {'template': 'what.html', 'extra_context': {'page': 'what'}}, name="what"), url(r'^how/$', 'direct_to_template', {'t...
MEDIA_ROOT}),
)
mikoim/funstuff
codecheck/codecheck-3608/app/plugins/gengo.py
Python
mit
676
0.003077
from datetime import datetime import rfGengou from . import PluginBase __all__ = ['Gengo'] class Gengo(PluginBase): def execute(self, args): if len(args) == 0: target
= datetime.now() elif len(args) == 1: target = datetime.strptime(args[0], '%Y/%m/%d') else: raise ValueError('wrong number of arguments are given') return '{:s}{:d}年{:d}月{:d}日'.format(*rfGengou.s2g(target)) def help(self
): return """[yyyy/mm/dd] Convert from string to Japanese Gengo. If string is not given, use current time. ex) > gengo 平成28年12月2日 > gengo 2000/01/01 平成12年1月1日 """
Teagan42/home-assistant
homeassistant/components/rflink/cover.py
Python
apache-2.0
5,550
0.000541
"""Support for Rflink Cover devices.""" import logging import voluptuous as vol from homeassistant.components.cover import PLATFORM_SCHEMA, CoverDevice from homeassistant.const import CONF_NAME, CONF_TYPE, STATE_OPEN import homeassistant.helpers.config_validation as cv from homeassistant.helpers.restore_state import ...
Turn the device stop.""" await self._async_handle_command("stop_cover") class InvertedRflinkCover(RflinkCover): """Rflink c
over that has inverted open/close commands.""" async def _async_send_command(self, cmd, repetitions): """Will invert only the UP/DOWN commands.""" _LOGGER.debug("Getting command: %s for Rflink device: %s", cmd, self._device_id) cmd_inv = {"UP": "DOWN", "DOWN": "UP"} await super()._a...
culturagovbr/sistema-nacional-cultura
gestao/tests/test_componentes.py
Python
agpl-3.0
11,165
0.004498
import pytest import datetime from django.template import Context from django.template import Engine from django.template import Template from django.template import TemplateDoesNotExist from django.urls import reverse from django.core.files.uploadedfile import SimpleUploadedFile from planotrabalho.models import Plan...
context['sistema_cultura'] = sistema_cultura rendered_template = template.render(context) assert context['sistema_cultura'].ente_federado.nome in rendered_template def test_opcoes_de_classificacao_da_diligencia(template, client, context, login, sistema_cultura): """Testa se a Classificação(Motivo) apre...
form = DiligenciaComponenteForm(componente='orgao_gestor', arquivo="arquivo", usuario=login, sistema_cultura=sistema_cultura) context['form'] = form context['sistema_cultura'] = sistema_cultura context['componente'] = mommy.make("Componente") rendered_template = template.render(context) ...
PaulSec/API-Yatedo
yatedoAPI.py
Python
mit
2,867
0.002093
""" This is the (unofficial) Python API for Yatedo.com Website. Using this code, you can manage to retrieve employees from a specific company """ import requests from bs4 import BeautifulSoup import re class YatedoAPI(object): """ YatedoAPI Main Handler """ _instance = None _verbose = False...
contact = {} contact['name'] = contact_name contact['job'] = contact_job
res.append(contact) return res def get_employees(self, company_name): self.display_message('Fetching result for company "%s"' % (company_name)) num = int(self.get_number_of_results(company_name)) if num == 0: self.display_message('Stopping here, no results for %...
dimagi/commcare-hq
corehq/apps/domain/utils.py
Python
bsd-3-clause
3,824
0.001569
import logging import os import re import sys from collections import Counter import simplejson from django.conf import settings from memoized import memoized from corehq.apps.domain.dbaccessors import iter_all_domains_and_deleted_domains_with_name from corehq.apps.domain.extension_points import custom_domain_module...
ames: for domain in iter_all_domains_and_deleted_domains_with_name(domain_names): domain.delete() def get_serializable_wire_invoice_general_credit(general_credit): if general_credit > 0: return [{ 'type': 'General Credits', 'amount': simplejson.dumps(general_
credit, use_decimal=True) }] return [] def log_domain_changes(user, domain, new_obj, old_obj): logger.info(f"{user} changed UCR permsissions {old_obj} to {new_obj} for domain {domain} ")
wzyy2/HackRFWebtools
func.py
Python
gpl-2.0
6,028
0.019741
import threading,signal ,traceback import random,ctypes,math,time,copy,Queue import numpy from dsp import common from GlobalData import * from common import Rx,Tx _funclist = {} def reg_func(func,param_types,param_defaults): ret = False try: _funclist[func.__name__]=(func,param_types,param_defaults) ...
ret['retstr'] = "hello word" return ret def reset(params): ret = dict() try: stop(None) hackrf_settings.current_status = 0 hackrf.close() hackrf.open() hackrf_reconf() ret['ret'] = 'ok' except: ret['ret'] = 'fail' return ret def get_...
def set_centre_frequency(params): ret = dict() hackrf_settings.centre_frequency = int(params['centre_frequency']) hackrf.set_freq(hackrf_settings.centre_frequency) return ret def waterfall(params): ret = dict() ret['centre_frequency'] = hackrf_settings.centre_frequency ret['sample_rate'] ...
joopert/home-assistant
tests/components/solarlog/test_config_flow.py
Python
apache-2.0
4,982
0.000602
"""Test the solarlog config flow.""" from unittest.mock import patch import pytest from homeassistant import data_entry_flow from homeassistant import config_entries, setup from homeassistant.components.solarlog import config_flow from homeassistant.components.solarlog.const import DEFAULT_HOST, DOMAIN from homeassist...
as mock_setup, patch( "homeassistant.components.solarlog.async_setup_entry", return_value=mock_coro(True), ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {"host": HOST,
"name": NAME} ) assert result2["type"] == "create_entry" assert result2["title"] == "solarlog_test_1_2_3" assert result2["data"] == {"host": "http://1.1.1.1"} await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1 @pytes...
dubrayn/dubrayn.github.io
examples/multiprocessing/example9.py
Python
mit
747
0.037483
#
!/usr/bin/env python3 import logging import multiprocessing import time logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s.%(msecs)03d [%(levelname)s] (%(process)d) %(message)s', datefmt='%Y-%m-%d %H:%M:%S') def worker(n, a, l): logging.debug("lock.acquire()") l.acquire() logging.debug(" lock acq...
red !") b = a.value time.sleep(0.2) a.value = b + 1 logging.debug(" worker %d: a = %d" % (n, a.value)) logging.debug(" lock.release()") l.release() logging.debug(" lock released !") logging.debug("start") lock = multiprocessing.Lock() a = multiprocessing.Value('i', 0, lock = False) for i in range(...