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
semorale/backend-test
django_backend_test/manage.py
Python
mit
262
0.003817
#!
/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_backend_test.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
beernarrd/gramps
gramps/gen/filters/rules/citation/__init__.py
Python
gpl-2.0
2,223
0
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2007 Donald N. Allingham # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2011 Tim G L Lyons # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as publ...
esfilter import MatchesFilter from ._matchespagesubstringof import MatchesPageSubstringOf from ._matchesrepositoryfilter import MatchesRepositoryFilter from ._matchessourcefilter import MatchesSourceFilter from ._regexpidof import RegExpIdOf from ._regexpsourceidof import RegExpSourceIdOf from ._hastag import HasTag e...
HasNote, HasNoteRegexp, HasReferenceCountOf, HasSource, HasSourceIdOf, HasSourceNoteRegexp, MatchesFilter, MatchesPageSubstringOf, MatchesRepositoryFilter, MatchesSourceFilter, RegExpIdOf, RegExpSourceIdOf, HasTag ]
salexkidd/restframework-definable-serializer
definable_serializer/tests/test_compat.py
Python
mit
985
0.001021
from django.db import models from django.test import TestCase from ..models.compat import YAMLField class TestYAMLModel(models.Model): yaml_field = YAMLField() class TestYAMLField(TestCase): ... def test_to_python(self): yaml_data = """ main: - 1 - 2 - 3 ...
= "" yaml_field = YAMLField() self.assertEqual(None, yaml_field.to_python(yaml_data)) yaml_data = """`""" yaml_field = YAMLField() with self.assertRaises(Except
ion): yaml_field.to_python(yaml_data) def test_get_prep_value(self): yaml_field = YAMLField() self.assertEqual("", yaml_field.get_prep_value(None)) yaml_field = YAMLField() data = {"aaa": "aaa😺",} self.assertEqual( "aaa: aaa😺\n", yaml_...
lovasoa/pagelabels-py
pagelabels/pagelabelscheme.py
Python
gpl-3.0
2,320
0.001293
#!/usr/bin/env python3 from collections import namedtuple from pdfrw import PdfName, PdfDict, PdfObject, PdfString PageLabelTuple = namedtuple("PageLabelScheme", "startpage style prefix firstpagenum") defaults = {"style": "arabic", "prefix": '', "firstpagenum": 1} styles = {"arabic": PdfN...
__new__(cls, startpage, style=defaults["style"], prefix=defaults["prefix"], firstpagenum=defaults["firstpagenum"]): if style not in styles: raise ValueError("Pa
geLabel style must be one of %s" % cls.styles()) return super().__new__(cls, int(startpage), style, str(prefix), int(firstpagenum)) @classmethod def from_pdf(cls, pagenum, opts): """Returns a new PageLabel using options from a pdfrw object""" return cls(pagenum, style...
UKTradeInvestment/export-wins-data
fixturedb/utils/hvc.py
Python
gpl-3.0
1,557
0.004496
import operator from functools import reduce from collections import namedtuple from django.db.models import Q from mi.models import Target from wins.models import HVC HVCStruct = namedtuple('HVCStruct', ['campaign_id', 'financial_year']) def get_all_hvcs_referenced_by_targets(financial_years=None): """ Ge...
ign_id in hvc_ids_expected_by_targets for financial_year in financial_years ] filter_q = reduce( operator.or_, [Q(campaign_id=data.campaign_id, financial_year=data.financial_year) for data in to_create] ) already_existing = [ HVCStruct(**data) for data in HVC.object
s.filter(filter_q).values('campaign_id', 'financial_year') ] to_create_without_already_existing = set(to_create) - set(already_existing) return to_create_without_already_existing
boisvert42/npr-puzzle-python
2017/0122_unusual_numbers.py
Python
cc0-1.0
2,574
0.029915
#!/usr/bin/env python """ NPR 2017-01-22 www.npr.org/2017/01/22/511046359/youve-got-to-comb-together-to-solve-this-one The numbers 5,000, 8,000, and 9,000 share a property that only five integers altogether have. Identify the property and the two other integers that have it. """ # The property is that they are superv...
]),int(numStr[i+2]) g = groups-(i/3+1) if h>=1: w
ords.append(units[h]) words.append('hundred') if t>1: words.append(tens[t]) if u>=1: words.append(units[u]) elif t==1: if u>=1: words.append(teens[u]) else: words.append(tens[t]) else: if ...
adamhaney/django-ipython-notebook-reports
testproject/testproject/settings.py
Python
mit
1,987
0
""" Django settings for testproject project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ......
' WSGI_APPLIC
ATION = 'testproject.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1....
google/makani
config/m600/rotor_sensors.py
Python
apache-2.0
1,234
0.001621
# Copyright 2020 Makani Technologies 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, 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. """Rotor sensing parameters.""" from makani.conf...
from makani.control import system_types as m @mconfig.Config def MakeParams(): common_rotor_sensor = { # Calibration for rotor speed and torque. This applies both to # the speed sensed by and commanded to the motor controllers. # # TODO: The sign convention for rotor # velocity shoul...
ixc/glamkit-eventtools
eventtools/tests/views.py
Python
bsd-3-clause
9,613
0.006971
# # -*- coding: utf-8“ -*- # from datetime import date, time, datetime, timedelta # from dateutil.relativedelta import relativedelta # # from django.conf import settings # from django.core.urlresolvers import reverse # from django.test import TestCase # # from eventtools.utils import datetimeify # from eventtools_tes...
super(TestViews, self).setUp() # # def tearDown(self): # if hasattr(self, '_old_OCCURRENCES_PER_PAGE'): # settings.OCCURRENCES_PER_PAGE = self._old_OCCURRENCES_PER_PAGE #
else: # delattr(settings, 'OCCURRENCES_PER_PAGE') # super(TestViews, self).tearDown() # # def test_purls(self): # """ # An occurrence has a pURL based on its id. # You can view a page for an occurrence. # """ # # e = self.daily_tour # ...
davidsminor/gaffer
python/GafferUI/CompoundDataPlugValueWidget.py
Python
bsd-3-clause
7,763
0.064666
########################################################################## # # Copyright (c) 2012, John Haddon. All rights reserved. # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided t...
.append( "/Add/Float", { "command" : IECore.curry( Gaffer.WeakMethod( self.__addItem ), "", IECore.FloatData( 0 ) ) } ) result.append( "/Add/Int", { "command" : IECore.curry( Gaffer.WeakMethod( self.__addItem ), "", IECore.IntData( 0 ) ) } ) result.append( "/Add/NumericDivider", { "divider" : True } ) result.a...
"/Add/StringDivider", { "divider" : True } ) result.append( "/Add/V2i", { "command" : IECore.curry( Gaffer.WeakMethod( self.__addItem ), "", IECore.V2iData( IECore.V2i( 0 ) ) ) } ) result.append( "/Add/V3i", { "command" : IECore.curry( Gaffer.WeakMethod( self.__addItem ), "", IECore.V3iData( IECore.V3i( 0 ) ) ) }...
DamianPilot382/Rubiks-Cube-Solver
opencv/sources/modules/ts/misc/run_suite.py
Python
apache-2.0
6,541
0.005198
#!/usr/bin/env python import datetime from run_utils import * class TestSuite(object): def __init__(self, options, cache): self.options = options self.cache = cache self.nameprefix = "opencv_" + self.options.mode + "_" self.tests = self.cache.gatherTests(self.nameprefix + "*", self...
else: logname = userlog[0][userlog[0].find(":")+1:] log.debug("Running the test: %s (%s) ==> %s in %s", exe, args + more_args, logname, workingDir) if self.options.dry_run: logfile, r = None, 0 else: logfile, r = self.runTest(exe...
: %s ==> %s", r, logfile) if r != 0: ret = r if logfile: logs.append(os.path.relpath(logfile, workingDir)) return logs, ret #=================================================================================================== if __name__ == "__main__": ...
apyrgio/synnefo
snf-cyclades-app/synnefo/volume/management/commands/snapshot-show.py
Python
gpl-3.0
2,301
0.000435
# Copyright (C) 2010-2014 GRNET S.A. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed i...
with PlanktonBackend(userid) as backend: snapshot =
backend.get_snapshot(snapshot_id) except: raise CommandError("An error occurred, verify that snapshot and " "user ID are valid") utils.pprint_table(out=self.stdout, table=[snapshot.values()], headers=snapshot.keys(), vertical=True)
revarbat/snappy-reprap
gen_assembly_index.py
Python
gpl-2.0
7,135
0.001261
#!/usr/bin/env python import re import sys snappy_ver = "v3.0" html_header_string = """\ <html> <head> <title>Snappy Assembly</title> <style> BODY { margin-bottom: 200px; } TABLE TD { vertical-align: middle; } H2 { margin-bottom: 5px; margin-top: 24px; font-size: 20pt; } LI.section { font-size: 20pt; f...
le: self.process_module(module, desc) module = mod_res.group(1) desc = "" desc_res = desc_re.search(line) if desc_res: desc += desc_res.group(1) if module:
self.process_module(module, desc) self.write_index() self.write_markdown() def main(): genidx = GenAssemblyIndex() genidx.generate_index() sys.exit(0) if __name__ == "__main__": main() # vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap
moosemaniam/learning
ud120-projects/k_means/k_means_cluster.py
Python
cc0-1.0
2,570
0.019066
#!/usr/bin/python """ skeleton code for k-means clustering mini-project """ import pickle import numpy import matplotlib.pyplot as plt import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit def Draw(pred, features, poi, mark_poi=False, name="image.png", f1_n...
_ in finance_features: ### (as it's currently written, line below assumes 2 features) for f1, f2 in finance_features: plt.scatter( f1, f2 ) plt.show() from sklearn.cluster import KMeans features_list = ["poi", feature_1, feature_2] data2 = featureFormat(data_dict, features_list ) poi, finance_features = targetF...
_predict( finance_features ) Draw(pred, finance_features, poi, name="clusters_before_scaling.pdf", f1_name=feature_1, f2_name=feature_2) ### cluster here; create predictions of the cluster labels ### for the data and store them to a list called pred try: Draw(pred, finance_features, poi, mark_poi=False, name="cl...
yejia/osl_notebook
social/views.py
Python
mit
62,150
0.02148
# -*- coding: utf-8 -*- from django.http import HttpResponse,HttpResponseRedirect, Http404 from django.shortcuts import get_object_or_404 from django.shortcuts import render_to_response from django import forms from django.forms import ModelForm from django.db.models import Q, F, Avg, Max, Min, Count from django.utils...
ter(notice_type__label='friends_add', recipient=request.user).update(unseen=False) return render_to_response('social/friends.html', { 'profile_username':username, 'friends':sorted_members}, context_instance=RequestContext(request, {})) @login_required def friends_notes2(request, username, bookname): #...
friends = request.user.member.get_friends() q = Q(owner__in=friends, private=False) note_list = getSN(bookname).objects.filter(q) qstr = __getQStr(request) note_list = getSearchResults(note_list, q
heepaz/rePong
joc.py
Python
gpl-3.0
1,394
0.031564
import os.path import pygame from pygame.locals
import * from tecles import * pygame.init() class Joc (object): WIDTH = 600 HEIGHT = 400 screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) background = pygame.image.load(os.path.join("Imatges","fons.jpg")) clock = pygame.time.Clock() dt = 0.05 puntsR = 0 puntsL = 0 font = pygame.font.SysF...
e.sprite.Group() pilotes = pygame.sprite.Group() def toggle_quit(): Joc.quit = not Joc.quit def gol(): for pilota in Joc.pilotes.sprites(): if pilota.posicio[0] > Joc.WIDTH: Joc.puntsR += 1 print(Joc.puntsL, Joc.puntsR) pilota.restart() eli...
barentsen/surveytools
scripts/website/create-vphas-dr2-page.py
Python
mit
1,542
0.000649
"""Produces the
catalogue page for the VPHAS website.""" import os import json import datetime #import httplib from astropy import log from jinja2 import Environment, FileSystemLoader from surveytools import SURVEYTOOLS_DATA # Load the column definitions f
rom the JSON file filename_columns = os.path.join(SURVEYTOOLS_DATA, 'vphas-columns.json') columns = json.loads(open(filename_columns).read()) def get_filesize(host, url): """Returns the filesize of a remote document.""" return 0 """ conn = httplib.HTTPConnection(host) conn.request("HEAD", url) ...
jmuhlich/indra
models/ras_pathway/run_correction.py
Python
bsd-2-clause
855
0
import sys from indra import reach from indra.assemblers import GraphAssembler orig_txt = [ln.strip() for ln in open('ras_pathway.txt', 'rt').readlines()] correct_txt = [ln.strip() for ln in open('correction.txt', 'rt').readlines()] for ln in correct_txt: if ln.startswith('<'): remove_line = ln[2:] ...
rue) st = rp.statements for s in st: print '%s\t%s' % (s, s.evidence[0].text) graphpr = {'rankdir': 'TD'} nodepr = {'fontsize': 12,
'shape': 'plaintext', 'margin': '0,0', 'pad': 0} ga = GraphAssembler(st, graph_properties=graphpr, node_properties=nodepr) ga.make_model() ga.save_dot('rps6ka_correction.dot') ga.save_pdf('rps6k1_correction.pdf')
reedloden/ansible
lib/ansible/executor/task_queue_manager.py
Python
gpl-3.0
13,130
0.003427
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) an...
_callback not in callback_loader: raise AnsibleError("Invalid callb
ack for stdout specified: %s" % self._stdout_callback) else: self._stdout_callback = callback_loader.get(self._stdout_callback) stdout_callback_loaded = True else: raise AnsibleError("callback must be an instance of CallbackBase or the name of a callback p...
passuf/WunderHabit
wunderlist/migrations/0012_auto_20151230_1853.py
Python
mit
631
0.001585
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-30 17:53 from _
_future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wunderlist', '0011_auto_20151230_1843'), ] operations = [ migrations.AlterField( ...
nections', to=settings.AUTH_USER_MODEL), ), ]
psachin/swift
swift/obj/replicator.py
Python
apache-2.0
38,417
0
# Copyright (c) 2010-2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
""" :param conf: configuration object obtained from ConfigParser :param logger: logging object """ self.conf = conf self.logger = logger or get_logger(conf, log_route='object-replicator') self.devices_dir = conf.get('devices', '/srv/node') self.mount_check =...
= conf.get('bind_ip', '0.0.0.0') self.servers_per_port = int(conf.get('servers_per_port', '0') or 0) self.port = None if self.servers_per_port else \ int(conf.get('bind_port', 6200)) self.concurrency = int(conf.get('concurrency', 1)) self.stats_interval = int(conf.get('stats_...
Azure/azure-sdk-for-python
sdk/iothub/azure-mgmt-iothub/azure/mgmt/iothub/v2019_11_04/models/_models_py3.py
Python
mit
123,002
0.003382
# 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 ...
allenge nonce issued for the Proof-Of-Possession flow. Variables are only populated by the server, and will be ignored when sending a request. :ivar subject: The certificate's subject name. :vartype subject: str :ivar expiry: The certificate's expiration date and time. :vartype expiry: ~datetime.d...
r thumbprint: The certificate's thumbprint. :vartype thumbprint: str :ivar is_verified: Determines whether certificate has been verified. :vartype is_verified: bool :ivar created: The certificate's create date and time. :vartype created: ~datetime.datetime :ivar updated: The certificate's last u...
dbentley/pants
src/python/pants/pantsd/process_manager.py
Python
apache-2.0
18,348
0.011609
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging impor...
ocessMetadataManager): """Subprocess/daemon management mixin/superclass. Not intended to be thread-safe.""" class InvalidCommandOutput(Exception): pass class NonResponsiveProcess(Exception): pass class ExecutionError(Exception): def __init__(self, message, output=None):
super(ProcessManager.ExecutionError, self).__init__(message) self.message = message self.output = output def __repr__(self): return '{}(message={!r}, output={!r})'.format(type(self).__name__, self.message, self.output) KILL_WAIT_SEC = 5 KILL_CHAIN = (signal.SIGTERM, signal.SIGKILL) def _...
MLAB-project/satellite-observer
gr-sat_observer/python/__init__.py
Python
gpl-3.0
1,155
0.002597
# # Copyright 2008,2009 Free Software Foundation, Inc. # # This application 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, or (at your option) # any later version. # # This application is di...
l Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # The presence of this file turns this directory into a Python package...
observer namespace try: # this might fail if the module is python-only from sat_observer_swig import * except ImportError: pass # import any pure python here #
fscook/simplevert
simplecoin/__init__.py
Python
mit
4,347
0.00046
from datetime import datetime import subprocess import logging import os from flask import Flask, current_app from flask.ext.sqlalchemy import SQLAlchemy from jinja2 import FileSystemLoader from werkzeug.local import LocalProxy import yaml from flask.ext.cache import Cache from bitcoinrpc import AuthServiceProxy r...
t a datetime object or a int() Epoch timestamp and return a pretty string like 'an hou
r ago', 'Yesterday', '3 months ago', 'just now', etc """ now = datetime.utcnow() if type(time) is int: diff = now - datetime.fromtimestamp(time) elif isinstance(time, datetime): diff = now - time elif not time: diff = now - now ...
avanzosc/avanzosc6.1
avanzosc_french_amortization/__init__.py
Python
agpl-3.0
1,037
0.001929
# -*- encoding: utf-8 -*- #################################
############################################# # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (http://tiny.be). All Rights Reserved # # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pu...
of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # #...
kc0bfv/RankedChoiceRestaurants
manage.py
Python
gpl-3.0
822
0.001217
#!/usr/bin/env python3 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANG
O_SETTINGS_MODULE", "RankedChoiceRestaurants.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some othe
r reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " ...
manpen/thrill
run/ec2-setup/spot.py
Python
bsd-2-clause
3,829
0.00888
#!/usr/bin/env python ########################################################################## # run/ec2-setup/spot.py # # Part of Project Thrill - http://project-thrill.org # # Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> # # All rights reserved. Published under the BSD-2 license in the LICENSE file. #####...
'Placement' : { 'AvailabilityZone': data["ZONE"] 'BlockDeviceMappings' : blockMappings} }) request_ids = [] for request in response['SpotInstanceRequests']: request_ids.append(request['SpotInsta...
= [] loop = True; print "waiting for instances to get fulfilled..." while loop: requests = client.describe_spot_instance_requests(SpotInstanceRequestIds=request_ids) for request in requests['SpotInstanceRequests']: if request['State'] in ['closed', 'cancelled', 'failed']: print request['Spo...
nirzari/review-rot
test/pagure_tests/test_pagure.py
Python
gpl-3.0
16,196
0.000679
import logging from unittest import TestCase try: # Python 3 > from unittest.mock import patch # noqa: F401 except ImportError: from mock import patch # noqa: F401 try: # Python 3.3 > from unittest.mock import MagicMock, ANY # noqa: F401 except ImportError: from mock import MagicMock, ANY # ...
_last_comment' mock_datetime.utcfromtimestamp.return_value = self.mock_utcfromtimestamp mock_datetime.strptime.return_value = 'mock_strptime_date' mock_PagureReview.return_value = '1' mock_call
_api.return_value = mock_pagure.mock_api_
alkivi-sas/nefario-api
nefario/errors.py
Python
lgpl-3.0
804
0
"""Handle nice json resp
onse for error.""" from flask import jsonify def not_found(e): """Send a correct json for 404.""" response = jsonify({'status': 404, 'error': 'Not found', 'message': 'Invalid resource URI'}) response.status_code = 404 return response def method_not_supported(e): """Send ...
n for 405.""" response = jsonify({'status': 405, 'error': 'Method not supported', 'message': 'This method is not supported'}) response.status_code = 405 return response def internal_server_error(e): """Send a correct json for 500.""" response = jsonify({'status': 500, 'erro...
jamestwebber/scipy
scipy/optimize/_linprog_util.py
Python
bsd-3-clause
65,452
0.000993
""" Method agnostic utility functions for linear progamming """ import numpy as np import scipy.sparse as sps from warnings import warn from .optimize import OptimizeWarning from scipy.optimize._remove_redundancy import ( _remove_redundancy, _remove_redundancy_sparse, _remove_redundancy_dense ) from collection...
, n_x) if A is None else A, dtype=float, copy=True ) elif A is None: return np.zeros((0, n_x), dtype=float) else: return np.array(A, dtype=float, copy=True) def _fo
rmat_b_constraints(b): """Format the upper bounds of the constraints to a 1-D array Parameters ---------- b : 1-D array 1-D array of values representing the upper-bound of each (in)equality constraint (row) in ``A``. Returns ------- 1-D np.array 1-D array of values ...
antb/TPT----My-old-mod
src/python/stdlib/test/pickletester.py
Python
gpl-2.0
39,620
0.001514
import unittest import pickle import cPickle import StringIO import cStringIO import pickletools import copy_reg from test.test_support import TestFailed, have_unicode, TESTFN # Tests that try a number of pickle protocols should have a # for proto in protocols: # kind of outer loop. assert pickle.HIGHEST_PROTOCOL...
I-65536 aI2147483647 aI-2147483647 aI-2147483648 a""" + \ """(S'abc' p4 g4 """ + \ """(i__main__ C p5 """ + \ """(dp6 S'foo' p7 I1 sS'bar' p8 I2 sbg5 tp9 ag9 aI5 a. """ # Disassembly of DATA0. DATA0_DIS = """\ 0: ( MARK 1: l LIST (MARK at 0) 2: p PUT 1 5
: I INT 0 8: a APPEND 9: L LONG 1L 13: a APPEND 14: F FLOAT 2.0 17: a APPEND 18: c GLOBAL '__builtin__ complex' 39: p PUT 2 42: ( MARK 43: F FLOAT 3.0 46: F FLOAT 0.0 49: t TUPLE (MARK at 42) ...
kindkaktus/CcPy
ccpy/ccpyconfparser.py
Python
bsd-3-clause
9,656
0.001761
# # Andrei Korostelev <andrei at korostelev dot net> # # Before using this product in any way please read the license agreement. # If you do not agree to the terms in this agreement you are not allowed # to use this product or parts of it. You can read this license in the # file named LICENSE. # """ CcPy project ...
nfigFileName = "/etc/ccpy.conf" def _get_elem_str_value(element, default_value): if element is not None: return element.text else: retu
rn default_value def _get_elem_int_value(element, default_value): if element is not None: return int(element.text) else: return default_value def _get_elem_bool_value(element, default_value): if element is not None: if element.text.lower() in ('on', 'yes', 'true'): re...
rimbalinux/LMD3
user/models.py
Python
bsd-3-clause
383
0.015666
# Sumber: LMD/models.py from google.ap
pengine.ext import db class Users(db.Model): username = db.StringProperty() passwd = db.StringProperty() email = db.StringProperty() fullname = db.StringProperty() address = db.TextProperty() phone = db.StringProperty() role = db.IntegerProperty(default=99) livecenter =
db.ListProperty(db.Key,default=[])
Malizor/deckard
libdeckard.py
Python
agpl-3.0
17,967
0.000223
# Deckard, a Web based Glade Runner # Copyright (C) 2013 Nicolas Delvaux <contact@nicolas-delvaux.org> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, o...
all relevant modules with a list of stored PO files for it on this session, from the oldest to the newest. """ # Very basic check, msgfmt will crash anyway if the file is not valid if not name.lower().endswith(".po"): raise DeckardException( "This is not a PO ...
e.po") po = open(po_path, "bw") if fd is not None: # The file was sent by the user for line in fd: po.write(line) po.close() fd.close() elif len(self.po_urls) > 0: # Let's try to download 'name' response = No...
Filechaser/sickbeard_mp4_automator
delugePostProcess.py
Python
mit
5,303
0.003206
#!/usr/bin/env python import os import sys from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr, radarr from readSettings import ReadSettings from mkvtomp4 import MkvtoMp4 from deluge_client import DelugeRPCClient import logging from logging.config import fileConfig logpath = '/var/log/sic...
eadSett
ings(os.path.dirname(sys.argv[0]), "autoProcess.ini") categories = [settings.deluge['sb'], settings.deluge['cp'], settings.deluge['sonarr'], settings.deluge['radarr'], settings.deluge['sr'], settings.deluge['bypass']] remove = settings.deluge['remove'] if len(sys.argv) < 4: log.error("Not enough command line param...
MGautier/security-sensor
branches/webenv/secproject/secapp/urls.py
Python
mit
2,174
0.00552
from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from . import views from django.views.generic.base import View app_name = 'secapp' urlpatterns = [ # Index view url(r'^$', views.index, name='index'), # List of events for a Log Source url(r'^(?P<id_log_sour...
nformation.as_view()), url(r'^api/events/hour/(?P<pk>[0-9]+)/$', views.EventsInformation().events_source_in_hour, name='events_source_in_hour'), url(r'^api/events/day/(?P<pk>[0-9]+)/$', views.EventsInformation().events_source_in_day, name='events_source_in_day'), url(r'^api/events/week/(?...
mation().events_source_in_month, name='events_source_in_month'), url(r'^api/events/year/(?P<pk>[0-9]+)/$', views.EventsInformation().events_source_in_year, name='events_source_in_year'), url(r'^api/events/last_day/(?P<pk>[0-9]+)/$', views.EventsInformation().events_source_last_day, nam...
dgquintas/vmcontroller.unstable
src/vmcontroller.host/vmcontroller/host/__main__.py
Python
bsd-3-clause
8,090
0.004203
#!python """ VMController Host - a general purpose host-side virtual machine controller via exposed hypervisors apis. """ try: import os import sys import logging import warnings import multiprocessing import time import inject from twisted.internet import reactor from pkg_resource...
("Stomp server stopped by user interrupt.") raise SystemExit() except IOError as ex: logger.error("Exception while starting coilmq broker: '%s'", ex) if m_tries != 0: logger.debug("Retrying coilmq startup i
n %.1f seconds...", m_delay) time.sleep(m_delay) m_delay *= backoff m_tries -= 1 else: logger.debug("Ran out of trials (tried %d times) for coilmq startup. Giving up.", tries) break except Exception, e: logge...
moertle/pyaas
pyaas/io.py
Python
mit
1,515
0.009241
import sys out = sys.stdout class Colors: def black (self, fmt='', *args): self('\x1b[1;30m'+fmt+'\x1b[0m', *args) def red (self, fmt='', *args): self('\x1b[1;31m'+fmt+'\x1b[0m', *args) def green (self, fmt='', *args): self('\x1b[1;32m'+fmt+'\x1b[0m', *args) def yellow (self, fmt='', *args): sel...
fmt='', *args): self('\x1b[1;34m'+fmt+'\x1b[0m', *args) def purple (self, fmt='', *args): self('\x1b[1;35m'+fmt+'\x1b[0m', *args) def cyan (self, fmt='', *args): self('\x1b[1;36m'+fmt+'\x1b[0m', *args) def white (self, fmt='', *args): self('\x1b[1;37m'+fmt+'\x1b[0m', *args) class PrintF(Colors): de...
out.flush() class WriteLine(Colors): def __call__(self, fmt='', *args): out.write(fmt % args) out.write('\n') def hexdump(blob, width=16, offset=0): fmt = '%%.%dx: ' % len('%.x' % (len(blob) - 1)) while blob: line = blob[:width] blob = blob[width:] printf.white(f...
bcrochet/eve
eve/methods/get.py
Python
bsd-3-clause
21,656
0
# -*- coding: utf-8 -*- """ eve.methods.get ~~~~~~~~~~~~~~~ This module implements the API 'GET' methods, supported by both the resources and single item endpoints. :copyright: (c) 2017 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ import math import copy import json fr...
er-restricted access to resources. Support for LAST_UPDATED field missing from documents, because they were created outside the API context. .. versionchanged:: 0.0.4 Added the ``requires_auth`` decorator. .. versionchanged:: 0.0.3 Superflous ``response`` container removed. Collect...
s are now properly JSON formatted. """ datasource = config.DOMAIN[resource]['datasource'] aggregation = datasource.get('aggregation') if aggregation: return _perform_aggregation(resource, aggregation['pipeline'], aggregation['options']) else: ...
alabarga/wos-scrapy
webofknowledge/pipelines.py
Python
gpl-2.0
294
0
# -*- coding: utf-8 -*- # Define your item pipelines here # #
Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class WebofknowledgePipeline(object): def proces
s_item(self, item, spider): return item
drwyrm/Flexget
flexget/plugins/sites/rss.py
Python
mit
1,942
0.00309
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from future.moves.urllib.parse import quote import logging from jinja2 import TemplateSyntaxError from flexget import plugin from flexget.event import event from flexget....
object): """A generic search plugin that can use rss based search feeds. Configure it like rss plugin, but include {{{search_term}}} in the url where the search term should go.""" schema = {'$ref': '/schema/plugin/rss'} def search(self, task, entry, config=None): from flexget.utils.template im...
earch_strings', [entry['title']])] rss_plugin = plugin.get_plugin_by_name('rss') entries = set() rss_config = rss_plugin.instance.build_config(config) try: template = environment.from_string(rss_config['url']) except TemplateSyntaxError as e: raise plugin....
mbrner/funfolding
funfolding/visualization/__init__.py
Python
mit
272
0
from . import visualize_classic_binning from . import visualize_tree_binning from . import visualize_llh from . import visualize_model __all__ = ('visualize_
classic_binning', 'visualize_llh', 'visualize_tr
ee_binning', 'visualize_model')
InakiZabala/odoomrp-wip
product_pricelist_import/__init__.py
Python
agpl-3.0
966
0
# -*- encoding: utf-8 -*- ##############################################################
################ # # Daniel Campos (danielcampos@avanzosc.es) Date: 07/1
0/2014 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the ho...
erdewit/tws_async
tws_async/twsclientqt.py
Python
unlicense
5,611
0.000535
import sys import struct import logging import ibapi from ibapi.client import EClient from ibapi.wrapper import EWrapper, iswrapper import PyQt5.Qt as qt import PyQt5.QtNetwork as qtnetwork import tws_async.util as util util.allowCtrlC() __all__ = ['TWSClientQt', 'iswrapper'] class TWSClientQt(EWrapper, EClient)...
elf._data[msgEnd:] fields = msg.split(b'\0') fields.pop() # pop off last empty element if not self.serverVersion_ and len(fields) == 2:
# this concludes the handshake version, self.connTime = fields self.serverVersion_ = int(version) self.decoder.serverVersion = self.serverVersion_ self.setConnState(EClient.CONNECTED) self.startApi() self.wrapper...
lordmos/blink
Tools/Scripts/webkitpy/layout_tests/port/test.py
Python
mit
29,134
0.002643
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
ge='YYY', is_reftest=True) def keys(self): return self.tests.keys() def __contains__(self, item): return item in self.tests def __getitem__(sel
f, item): return self.tests[item] # # These numbers may need to be updated whenever we add or delete tests. This includes virtual tests. # TOTAL_TESTS = 114 TOTAL_SKIPS = 29 UNEXPECTED_PASSES = 1 UNEXPECTED_FAILURES = 25 def unit_test_list(): tests = TestList() tests.add('failures/expected/crash.html...
europa502/shARP_2.0
mac_decoder.py
Python
gpl-3.0
1,454
0.055021
import socket, sys,os,re from struct import * mymac=sys.argv[1] rmac=sys.argv[2] interface=sys.argv[3] mode=sys.argv[4] def address (a) : b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]) , ord(a[1]) , ord(a[2]), ord(a[3]), ord(a[4]) , ord(a[5])) return b try: s = socket.socket( socket.AF_PACKET , socket.SO...
and rmac != "333300": os.system("bash ./passive.sh '"+rmac+"' '"+interface+"' '"+mode+"' ") elif mymac == address(packet[6:12]) : if rmac
!= address(packet[0:6]) and rmac != "01005e" and rmac != "ffffff" and rmac != "333300": os.system("bash ./passive.sh '"+rmac+"' '"+interface+"' '"+mode+"' ")
hsw5138/bis
backend/helpers.py
Python
mit
2,048
0.027344
import uuid import base64 import re def generate_key(): """ generates a uuid, encodes it with base32 and strips it's padding. this reduces the string size from 32 to 26 chars. """ return base64.b32encode(uuid.uuid4().bytes).strip('=').lower()[0:12] def thousand_separator(x=0, sep='.', dot=','): """ creates a ...
lse (itemgetter(col.strip()), 1)) for col in columns] def comparer(left, right): for fn, mult in comparers: result = cmp(fn(le
ft), fn(right)) if result: return mult * result else: return 0 return sorted(items, cmp=comparer)
Anthirian/script.filecleaner
default.py
Python
gpl-3.0
30,945
0.004007
#!/usr/bin/python # -*- coding: utf-8 -*- import json import sys from reset_exclusions import * from utils import * from viewer import * class Cleaner(object): """ The Cleaner class allows users to clean up their movie, TV show and music video collection by removing watched items. The user can apply a n...
dec", u"audiolanguage", u"subtitlelanguage", u"videoaspect", u"playlist"] supported_filter_field
s = { TVSHOWS: episode_filter_fields, MOVIES: movie_filter_fields, MUSIC_VIDEOS: musicvideo_filter_fields } methods = { TVSHOWS: u"VideoLibrary.GetEpisodes", MOVIES: u"VideoLibrary.GetMovies", MUSIC_VIDEOS: u"VideoLibrary.GetMusicVideos" } properties = { ...
sbhowmik7/PSSEcompare
ext_libs/openpyxl/writer/strings.py
Python
gpl-3.0
3,077
0.0013
# file openpyxl/writer/strings.py # Copyright (c) 2010-2011 openpyxl # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, ...
S", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT 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 A
CTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # # @license: http://www.opensource.org/licenses/mit-license.php # @author: see AUTHORS file """Write the shared string table.""" # Python stdlib imports try: # Python 2 ...
cocodelabs/api.palaverapp.com
palaverapi/models.py
Python
bsd-3-clause
1,143
0
import os import peewee from rivr_peewee import Database DATABASE_URL = os.environ.get('DATABASE_URL') if DATABASE_URL and DATABASE_URL.startswith('postgres://'): DATABASE_URL = DATABASE_URL.replace('postgres://', 'postgres+pool://') # disable auto connection EXTRA_OPTIONS = 'autoconnect=false' if '...
DATABASE_URL += '&' + EXTRA_OPTIONS else: DATABASE_URL += '?' + EXTRA_OPTIONS os.environ['DATABASE_URL'] = DATABASE_URL database = Database() class Device(database.Model): apns_token = peewee.CharFiel
d(max_length=64, unique=True) def __repr__(self) -> str: return '<Device {}>'.format(self.apns_token) class Token(database.Model): PUSH_SCOPE = 'push' ALL_SCOPE = 'all' device = peewee.ForeignKeyField(Device) token = peewee.CharField(max_length=64, unique=True, primary_key=True) scop...
vangalamaheshh/snakemake
snakemake/report.py
Python
mit
3,806
0.000263
__author__ = "Johannes Köster" __copyright__ = "Copyright 2015, Johannes Köster" __email__ = "koester@jimmy.harvard.edu" __license__ = "MIT" import os import mimetypes import base64 import textwrap import datetime import io from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst imp...
s] links = [] for file in _files: data = data_uri(file
) links.append(':raw-html:`<a href="{data}" download="{filename}" draggable="true">{filename}</a>`'.format( data=data, filename=os.path.basename(file))) links = "\n\n ".join(links) attachments.append(''' .. container:: :name: {name} {name}: ...
cloudbase/neutron
neutron/extensions/dns.py
Python
apache-2.0
9,551
0.000419
# Copyright (c) 2015 Rackspace # 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...
ignment' EXTENDED_ATTRIBUTES_2_0 = { 'ports': { DNSNAME: {'allow_post': True, 'a
llow_put': True, 'default': '', 'convert_to': convert_to_lowercase, 'validate': {'type:dns_name': FQDN_MAX_LEN}, 'is_visible': True}, DNSASSIGNMENT: {'allow_post': False, 'allow_put': False, 'is_visible': True}, ...
aur-archive/quasi
setup.py
Python
bsd-3-clause
448
0.049107
#!/usr/bin/env python from distutils.core import setup setup(name = "quasi", version = "0.87", description = "A multiple-context Python shell", author = "Ben Last", author_email = "ben@benlast.com", url = "http://quasi-shell.sourceforge.net/",
license = "BSD", scripts = ["quasi.py"], data_files = [("share/licenses/quasi", ["LICENSE"])], extra_pa
th = "quasi", packages = ["."] )
Mnenmenth/RobotCode
JoystickInput/JoystickServer.py
Python
apache-2.0
458
0.026201
from serial import Serial import time import platform import socket serialPort = Serial('COM3' if platform.system(
) == 'Windows' else '/dev/ttyUSB0', 9600) time.sleep(2) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('', 2222)) server.listen(1) while True: (client, address) = server.accept() print('Connected') while True: data
= client.recv(6)#.decode() if 'CLOSE' in data: break #print(data) serialPort.write(data)
endlessm/eos-event-recorder-daemon
tests/daemon/mock-server.py
Python
gpl-2.0
1,987
0.00151
#!/usr/bin/env python3 # Copyright 2015, 2016 Endless Mobile, Inc. # This file is part of eos-event-recorder-daemon. # # eos-event-recorder-daemon 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 versi...
tdout.buffer.write(decompressed_request_body) sys.stdout.buffer.flush() status_code_str = sys.stdin.readline() status_code = int(status_code_str) self.send_response(status_code) self.end_headers() # A metrics server that simply prints the requests it receives to stdout class Mo...
S = ('localhost', 0) super().__init__(SERVER_ADDRESS, PrintingHTTPRequestHandler) if __name__ == '__main__': mock_server = MockServer() print(mock_server.server_port, flush=True) mock_server.serve_forever()
mbuchove/analysis-tools-m
python/moonDist.py
Python
mit
5,073
0.027991
#! /usr/bin/env python #script that takes an optional argument for the date and target collection and calculates angular separation and elevation of each target from the moon. import ephem, subprocess, operator, argparse #host & port info hostName="veritase.sao.arizona.edu" portNum="" #hostName="lucifer1.spa.umn....
ourceEpoch=source.split("\t")[3] #makes sure same epoch is used veritas.epoch = float(sourceEpoch) #Define ephem moon object and calculate position (ra, dec) and phase TheMoon = ephem.Moon(veritas) TheMoon.compute(veritas) illum = TheMoon.moon_phase*100. #Get angular separation of moon and target degF...
m object for source, to get elevation sourceobj = ephem.FixedBody() sourceobj._ra = float(sourceRA) sourceobj._dec = float(sourceDEC) sourceobj.compute(veritas) sourceALT = sourceobj.alt*180./ephem.pi moonlightsources[sourceName]=[(degFromMoon,sourceALT)] #end of for loop sorted_sources = sorted(moonli...
arulalant/CMIPs-Handler
scripts/mv/rm_dirs_contains_only_if_xml.py
Python
gpl-3.0
427
0.004684
''' This script will remove the directories if that contains only xml files. ''' import os srcpath = raw_input("Enter the source path : ") for root, su
b, files in os.walk(os.path.abspath(srcpath)): if files: files = [f for f in files if not f.endswith('.xml')] if not files: fpath = os.path.join(root)
os.system('rm -rf %s' % fpath) print "removed", fpath
mychris/xbmc-command
xbmc_command/core.py
Python
gpl-3.0
4,244
0.001649
# -*- coding: utf-8 -*- import argparse import time import socket import sys import json __prog__ = 'xbmc-command' PROG = __prog__ __version__ = '0.4.1' VERSION = __version__ class XBMC(object): def __init__(self, host, port): self.address = (host, port) self.__socket = socket.socket(socket.AF_...
): return player['playerid'] return result[
'result'][0]['playerid'] @property def parser(self): parser = argparse.ArgumentParser(add_help=False) self.create_parser(parser) parser.add_argument('--help', action='help', help='show this help message and exit') return parser def create_parser(...
lgarren/spack
var/spack/repos/builtin/packages/r-limma/package.py
Python
lgpl-2.1
1,754
0.00114
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
ANTY OF # MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 ...
lmazuel/autorest
src/generator/AutoRest.Python.Tests/AcceptanceTests/validation_tests.py
Python
mit
5,290
0.002837
# -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ""Software""),...
nse, 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 # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUT...
jgomezc1/FEM_PYTHON
solidspy/__main__.py
Python
mit
119
0.008403
# -*- coding: utf-8 -*- from __fut
ure__ import absolute_im
port from solidspy.solids_GUI import solids_GUI solids_GUI()
ttm/musicLegacy
musicLegacy/effects.py
Python
mit
131
0.030534
class Reverb: pass class ScatterLo
cation: pass class Chorus: pass class Vocoder: pass class
ShuffleSound: pass
w495/python-video-shot-detector
shot_detector/filters/dsl/dsl_filter_mixin.py
Python
bsd-3-clause
6,383
0.00564
# -*- coding: utf8 -*- """ This is part of shot detector. Produced by w495 at 2017.05.04 04:18:27 """ from __future__ import absolute_import, division, print_function import collections import itertools import logging from shot_detector.utils.dsl import DslOperatorMixin from shot_detector.utils.dsl.dsl_kwarg...
elf, *args, **kwargs): """ :param args: :param kwargs: :return: """ return self.intersect(*args, **kwargs) def intersect(self, other, threshold=0): """ :param other: :param threshold: :return: """ from .filter_interse...
parallel_filters=[self, other], threshold=threshold )
flowroute/flowroute-numbers-python
FlowrouteNumbersLib/APIHelper.py
Python
mit
8,902
0.00483
# -*- coding: utf-8 -*- """ FlowrouteNumbersLib.APIHelper Copyright Flowroute, Inc. 2016 """ import jsonpickle import re class APIHelper: """A Helper Class for various functions associated with API Calls. This class contains static methods for operations that need to be perfo...
(obj, name) if isinstance(value, list): # Loop through each item retval[names[name]] = list() for item in value: retval[names[name]].append(APIHelper.resolve_name(item)) elif isinstance(value, dict): ...
retval[names[name]][key] = APIHelper.resolve_name(value[key]) else: retval[names[name]] = APIHelper.resolve_name(value) # Return the result return retval @staticmethod def resolve_name(value): """Resolves name for a given obje
rna-seq/raisin.restyler
setup.py
Python
gpl-3.0
1,531
0.005225
from setuptools import setup, find_packages import sys, os version = '1.3' long_description = """The raisin.restyler package is a part of Raisin, the web application used for publishing the summary statistics of Grape, a pipeline used for processing and analyzing RNA-Seq data.""" setup(name='raisin.restyler', v...
', aut
hor='Maik Roder', author_email='maikroeder@gmail.com', url='http://big.crg.cat/services/grape', license='GPL', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages = ['raisin'], package_data = {'raisin.restyler':['templates/*.pt']}, include_pack...
kbrose/project_euler
p20-29/p28.py
Python
unlicense
304
0.032895
sum = 1 curr = 3 for width in xrange(3,1002,2): inc = width - 1 sum = sum + curr #bottom right curr = curr + inc sum = sum + curr #bo
ttom left curr = curr + inc sum = sum + curr #top left curr = curr + inc sum = sum + cu
rr #top right curr = curr + inc + 2 print sum
COSMOGRAIL/PyCS
pycs/spldiff/rslc.py
Python
gpl-3.0
8,490
0.049706
""" Defines a class that represents a regularly sampled lightcurve """ import sys import numpy as np import splreg import pycs.gen.spl import copy as pythoncopy import scipy.optimize as spopt class rslc(): """ A regularly sampled lightcurve, typically obtained by regression. To make such a rslc from a usual light...
list]) ret = np.sum(tvs) #if verbose: # print timeshifts, ret return ret if verbose: print "Starting time shift optimization ..." print "Initial pars (shifts, not delays) : ", inishifts # Some brute force exploration, like for the dispersion techniques ... res = spopt.brute(errorfct, bruteranges(5,...
... we do not want that. if verbose: print "Brute 1 shifts : %s" % res print "Brute 1 errorfct : %f" % errorfct(res) res = spopt.brute(errorfct, bruteranges(2.5,3,res), full_output = 0, finish=None) if verbose: print "Brute 2 shifts : %s" % res print "Brute 2 errorfct : %f" % errorfct(res) res = spopt....
ryfeus/lambda-packs
Keras_tensorflow_nightly/source2.7/tensorflow/contrib/lite/toco/toco_flags_pb2.py
Python
mit
8,125
0.004062
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/contrib/lite/toco/toco_flags.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from goog...
), _descriptor.FieldDescriptor( name='reorder_across_fake_quant', full_name='toco.TocoFlags.reorder_across_fake_quant', index=7, number=8, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=Fa...
allow_custom_ops', index=8, number=10, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='...
realms-team/basestation-fw
libs/smartmeshsdk-REL-1.3.0.1/external_libs/cryptopy/crypto/cipher/aes.py
Python
bsd-3-clause
1,002
0.015968
""" crypto.aes AES Encryption Algorithm The AES algorithm is just Rijndael algorithm restricted to the default blockSize of 128 bits. Copyright (c) 2002 by Paul A.
Lambert Read LICENSE.txt for license information. 2002-06-01 """ from crypto.cipher.rijndael import Rijndael from crypto.cipher.base import BlockCipher, padWithPadLen, noPadding from crypto.errors import BadKeySizeError class AES(Rijndael): """ The AES algorithm is the Rijndael block cipher ...
bits and key sizes of 128, 192 or 256 bits """ def __init__(self, key = None, padding = padWithPadLen(), keySize=16): """ Initialize AES, keySize is in bytes """ if not (keySize == 16 or keySize == 24 or keySize == 32) : raise BadKeySizeError, 'Illegal AES key size, must be 16, 24, ...
tadamhicks/morpheus-python
setup.py
Python
mit
480
0.04375
from ditutils.core import setup setup( name = 'morpheusapi', packages = ['morpheusapi'], version = '2.11.1', description = 'A python wrapper for Morpheus APIs', author = 'Adam Hic
ks', author_email = 'thomas.adam.hicks@gmail.com', url = 'https://github.com/tadamhicks/morpheus-python', download_url = 'htt
ps://github.com/tadamhicks/morpheus-python/archive/2.11.1.tar.gz', keywords = ['morpheus', 'api', 'morpheus data'], classifiers = [], )
masahir0y/barebox-yamada
scripts/serial/urlhandler/protocol_loop.py
Python
gpl-2.0
9,646
0.002281
#! python # # Python Serial Port Extension for Win32, Linux, BSD, Jython # see __init__.py # # This module implements a loop back connection receiving itself what it sent. # # The purpose of this module is.. well... You can run the unit tests with it. # and it was so easy to implement ;-) # # (C) 2001-2011 Chris Liecht...
self.logger = logging.getLogger('pySerial.loop')
self.logger.setLevel(LOGGER_LEVELS[value]) self.logger.debug('enabled logging') else: raise ValueError('unknown option: %r' % (option,)) except ValueError, e: raise SerialException('expected a string in the form "[loop://][option[/...
crakama/bc_7_twitment
twitment/sendSMS.py
Python
mit
1,600
0.005625
# Import the helper gateway class from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException from twitment.search import ClassTwitter # Specify your login credentials class SMS(object): def __init__(self): pass def send(self,num): sendtweet_obj = ClassTwitter() ...
s to know what we really do message = x # Create a new instance of our awesome gateway class gateway = AfricasTalkingGateway(username, apikey) # Any gateway errors will be captured by our custom Exception class
below, # so wrap the call in a try-catch block try: # Thats it, hit send and we'll take care of the rest. results = gateway.sendMessage(to, message) for recipient in results: # status is either "Success" or "error message" print 'Mess...
OSHADataDoor/OshaBokeh
bokehsamples/osha_files.py
Python
apache-2.0
2,378
0.004626
# Author: Bala Venkatesan # License: Apache 2.0 ######################################################################## # Wrote this file to separate out the loading of the data from the # python file where the actual display happens ######################################################################## impor...
e # the function cleans the data before returning the DataFrame ######################################################################## def state_data(): for row in csvreader: ####################################################################################### # intialize a bunch of index vari...
ates with 2 words # stopat moves corresponding. ####################################################################################### index = 0 startat = 0 stopat=10 statename = row[0] # Initializing pandas series for DataFrame. values = [] for...
scieloorg/scielo-django-extensions
scielo_extensions/formfields.py
Python
bsd-2-clause
1,891
0.006875
# coding: utf-8 # Copyright (c) 2012, SciELO <scielo-dev@googlegroups.com> # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # Redistributions of source code must retain the above copyright not...
T NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT # NOT LIMITED TO, PROCUREMENT OF SUBS...
, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY # OF SUCH DAMAGE. import re from django import forms fr...
rspavel/spack
var/spack/repos/builtin/packages/r-sdmtools/package.py
Python
lgpl-2.1
1,363
0.005869
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. #
# SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RSdmtools(RPackage): """Species Distribution Modelling Tools: Tools for processing data associated with species distribution modelling exercises This packages provides a set of tools for post processing the outcomes of species...
ist_url = "https://cloud.r-project.org/src/contrib/Archive/SDMTools" version('1.1-221.1', sha256='3825856263bdb648ca018b27dc6ab8ceaef24691215c197f8d5cd17718b54fbb') version('1.1-221', sha256='a6da297a670f756ee964ffd99c3b212c55c297d385583fd0e767435dd5cd4ccd') version('1.1-20', sha256='d6a261ce8f487d5d03b193...
tehp/reddit
MessageArchiveSimple/messagearchivesimple.py
Python
mit
1,943
0.021101
#/u/Goldensights import praw import time import datetime '''USER CONFIG''' USERNAME = "" #This is the bot's Username. In order to send mail, he must have some amount of Karma. PASSWORD = "" #This is the bot's Password.
USERAGENT = "" #This is a short description of what the bot does. For example "/u/GoldenSights' Newsletter bot" MAXPOSTS = 1000 #This is how many posts you want to retrieve all at once. PRAW can download 100 at a time. WAIT = 30 #This is how many seconds you
will wait between cycles. The bot is completely inactive during this time. PRINTFILE = 'messages.txt' #This is the file, in the same directory as the .py file, where the messages are stored SUBJECTLINE = "Newsletterly" ITEMTYPE = 't4' #The type of item to gather. t4 is a PM '''All done!''' WAITS = str(WAIT) try: ...
Bismarrck/tensorflow
tensorflow/python/ops/while_v2.py
Python
apache-2.0
38,134
0.007159
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
s) else: shape
_invariants = nest.map_structure(lambda t: t.shape, loop_vars) if not name: name = "while" with ops.name_scope(name) as scope: with ops.name_scope(None): cond_name = util.unique_fn_name(scope, "cond") body_name = util.unique_fn_name(scope, "body") loop_counter = constant_op.constant( ...
kradalby/O2
opos/views.py
Python
mit
2,687
0.04131
from django.shortcuts import render, redirect from django.contrib.auth.decorators import user_passes_test from django.shortcuts import get_object_or_404 from django import forms from django.db.models import Max, Avg, Sum from opos.models import Customers from opos.forms import CustomerAddForm, CustomerForm def is_...
or user.is_superuser: return True else: return False @user_passes_test (is_staff) def dashboard (request): c = {} c['curdebt'] =
Customers.objects.all().aggregate(Sum('curdebt'))['curdebt__sum'] c['maxdebt'] = Customers.objects.all().aggregate(Sum('maxdebt'))['maxdebt__sum'] c['highestcurdebt'] = Customers.objects.all().aggregate(Max('curdebt'))['curdebt__max'] from opos.sql import get_total_sale c['totalsale'] = get_total_sale ()[0] r...
DVSBA/ajenti
plugins/network/recovery.py
Python
lgpl-3.0
305
0.006557
from a
jenti.api import * from ajenti.com import * class DebianNetworkCfg(Plugin): implements(IConfigurabl
e) name = 'Network' id = 'network' platform = ['Debian', 'Ubuntu'] def list_files(self): dir = '/etc/network/' return [dir+'*', dir+'*/*', dir+'*/*/*']
cclai999/rango
tango_with_django_project/populate_rango.py
Python
mit
3,340
0.00479
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','tango_with_django_project.settings') import django django.setup() from rango.models import Category, Page def populate(): # First, we will create lists of dictionaries containing the pages # we want to add into each category. # Then we will create...
"Perl": {"pages": [], "views": 32, "likes": 16}, "Php": {"pages": [], "views": 32, "likes": 16}, "Prolog":
{"pages": [], "views": 32, "likes": 16}, "Programming": {"pages": [], "views": 32, "likes": 16} } # The code below goes through the cats dictionary, then adds each category, # and then adds all the associated pages for that category. # if you are using Python 2.x then use cats.iteri...
mefly2012/platform
test/test.py
Python
apache-2.0
3,173
0.001891
# -*- coding: utf-8 -*- import codecs all_tables = { 'ktgg': ['main'], 'zgcpwsw': ['title', 'casecode'], # # # 'ktgg', # # 'cdfy_sfgk', # # 'newktgg', # # 'zyktgg', # # 'zgcpwsw', # # 'itslaw', # # 'qyxg_zgcpwsw', # # 'qyxg_wscpws', # 'zhixing': ['pname', 'case_co...
'qy
xx_medi_pro_prod_cert': ['company_name', 'certificate_no'], 'qyxx_industrial_production_permit': ['company_name', 'certificate_no'], 'qyxx_nyscqyzzcx': ['company_name', 'validdate'], 'qyxx_tk': ['company_name', 'certificate_no'], 'qyxx_ck': ['company_name', 'certificate_no'], 'xzcf': ['name', 'publi...
ging/fiware-keystone-scim
keystone_scim/contrib/scim/converter.py
Python
apache-2.0
6,230
0.000482
# # Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U # # 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 unde...
s' % ( scim.get('domain_id'), ROLE_SEP, scim.get('name', None)) else: keystone['name'] = scim.get('name', None) return keystone @_remove_dict_nones def role_key2scim(ref, path=DEFAULT_VERSION, schema=True): sc
im = { 'schemas': [get_schema(_EXT_SCHEMA, path)] if schema else None, 'id': ref.get('id', None) } dom_name = ref.get('name', '') if dom_name.find(ROLE_SEP) > -1: (domain, name) = dom_name.split(ROLE_SEP, 1) else: (domain, name) = (None, dom_name) scim['name'] = name ...
guiquanz/msaf
msaf/eval.py
Python
mit
14,384
0.000834
""" Evaluates the estimated results of the Segmentation dataset against the ground truth (human annotated data). """ from joblib import Parallel, delayed import logging import mir_eval import numpy as np import os import pandas as pd import six import sys # Local stuff import msaf import msaf.input_output as io impor...
mir_eval.segment.detection(ann_inter, est_inter, window=.5, trim=True) # Information gain res["D"] = compute_information_gain(ann_inter, est_inter, est_file, bins=bins) # Median Deviations res["DevR2E"], res["DevE2R"] = mir_eval.segment.deviation( ann_in...
_inter, est_inter, trim=True) ### Labels ### if est_labels is not None and len(est_labels) != 0: try: # Align labels with intervals ann_labels = list(ann_labels) est_labels = list(est_labels) ann_inter, ann_labels = mir_eval.util.adjust_intervals(ann_inte...
hefen1/chromium
tools/telemetry/telemetry/results/results_options.py
Python
bsd-3-clause
7,550
0.009669
# Copyright 2014 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. import optparse import os import sys from telemetry.core import util from telemetry.results import buildbot_output_formatter from telemetry.results import c...
ort of progress reporter), # as we plan to enable gtest-style output for all output formatters. output_formatters.append( buildbot_output_formatter.BuildbotOutputFormatter( sys.stdout, trace_tag=options.output_trace_tag)) output_formatters.append(html_output_formatter.HtmlOutpu...
ts, options.browser_type, options.results_label, trace_tag=options.output_trace_tag)) elif output_format == 'json': output_formatters.append(json_output_formatter.JsonOutputFormatter( output_stream, benchmark_metadata)) elif output_format == 'chartjson': output_formatters.append(...
h4ck3rm1k3/FEC-Field-Documentation
fec/version/v2/F7.py
Python
unlicense
1,133
0.001765
import fechbase class Records(fechbase.RecordsBase): def __init__(self): fechbase.RecordsBase.__init__(self) self.fields = [ {'name': 'FORM TYPE', 'number': '1'}, {'name': 'FILER FEC CMTE ID', 'number': '2'}, {'name': 'COMMITTEE NAME', 'number': '3'}, ...
': '6'}, {'name': 'STATE', 'number': '7'}, {'name': 'ZIP', 'num
ber': '8'}, {'name': 'ORGANIZATION TYPE', 'number': '9'}, {'name': 'RPTCODE', 'number': '10'}, {'name': 'OF ELECTION', 'number': '11-'}, {'name': 'STATE (OF ELECTION)', 'number': '12'}, {'name': 'COVERAGE FROM', 'number': '13-'}, {'name': 'COVERAGE...
TQRG/physalia
physalia/tests/test_energy_profiler.py
Python
mit
534
0.001873
"""Test energy_profiler module.""" import unittest from physalia.energy_profiler import AndroidUseCase # pylint: disable=missing-docstring class TestEnergyProfiler(unittest.TestCase): d
ef test_empty_android_use_case(self): # pylint: disable=no-self-use use_case = AndroidUseCase( name="Test", app_apk="no/path", app_pkg="no.package", app_version="0.0.0", run=None, prepare=No
ne, cleanup=None ) use_case.run()
PolygonalTree/Led-control
led-control/setup.py
Python
agpl-3.0
909
0.0011
""" Setup file for led-controller author: Luis Garcia Rodriguez 2017 Licence: GPLv3 """ from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) setup( name='led-controller', version='2.0.0', description='A simple interface for con...
nts', # The project's main homepage. url='https://gith
ub.com/polygonaltree/Led-control', # Author details author='Luis Garcia Rodriguez', author_email='luis.garcia@uni-muenster.de', license='GPLv3', packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: ...
fusionbox/satchless
satchless/contrib/checkout/multistep/tests.py
Python
bsd-3-clause
16,546
0.00278
# -*- coding: utf-8 -*- from decimal import Decimal from django.http import HttpResponse, HttpRequest from django.conf import settings from django.conf.urls import patterns, include, url from django.core.urlresolvers import reverse from django.test import TestCase, Client from ....cart.app import cart_app from ....car...
get_order_items(self, order): order_ite
ms = set() for group in order.groups.all(): order_items.update(group.items.values_list('product_variant', 'quantity')) return order_items def test_order_from_cart_view_creates_proper_order(self): cart = self._get_or_create_cart_for_client(self.anon_client) cart.replace_i...
code-shoily/tornado-cljs
handlers/base.py
Python
mit
264
0.003788
from tornado.web import RequestHandler class BaseHandler(RequestHandler): def initialize(self): _settings = self.application.settings self.db = self.ap
plication.db #self.redis = _settings["redis"] sel
f.log = _settings["log"]
stencila/hub
manager/projects/migrations/0024_auto_20201206_0819.py
Python
apache-2.0
746
0.00134
# Generated by Django 3.1.4 on 2020-12-06 08:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0023_auto_20201202_0349'), ] operations = [ migrations.AlterField( model_name='review', name='status', ...
nding'), ('REQUESTED', 'Requested'), ('CANCELLED', 'Cancelled'), ('ACCEPTED', 'Accepted'), ('DECLINED', 'Declined'), ('COMPLETED', 'Completed'), ('EXTRACTING', 'Retrieval in progress'), ('EXTRACTED', 'Retrieved'), ('FAILED', 'Retrieval failed'), ('REGISTERED', 'Registered')], default
='PENDING', help_text='The status of the review.', max_length=16), ), ]
evernym/plenum
plenum/test/recorder/test_recorder.py
Python
apache-2.0
6,601
0.001666
import random import time from collections import OrderedDict from plenum.common.util import randomString try: import ujson as json except ImportError: import json import pytest from plenum.recorder.recorder import Recorder TestRunningTimeLimitSec = 350 def test_add_to_recorder(recorder): last_check_...
blist(lst1, lst2): ls1 = [element for element in lst1 if element i
n lst2] ls2 = [element for element in lst2 if element in lst1] return ls1 == ls2 for k, v in recorder.store.iterator(include_value=True): p = Recorder.get_parsed(v) assert sublist([i[1:] for i in p] , combined) p = Recorder.get_parsed(v, only_incoming=True) if p: ...
JaeGyu/PythonEx_1
20160124_1.py
Python
mit
473
0.07611
#_*_ coding: utf-8 _*_ t1 = () print type(t1) t3 = 1,2,3 print type(t3) r1 = (1) print r1 print type(r1) r1 = (1,) print r1 print type(r1) t = (1,2,3) print t*2 print t
+('aaa','bbb') print t print print t[0], t[1:3] print len(t) print 1 in t print range(1,3) t= (12345,54321,'hhh') u = t,(1,2,3,4,5) print u t2 = [1,2,3] u2 = t2,(1,2,4) print u2 t3 = {1:'ggg',2:'hhh'} u3 = t3,(1,2,3) print u3 x,y,z=1,2,3 print x print y print z t = 1,
2,'hello' x,y,z = t
GjjvdBurg/HugoPhotoSwipe
hugophotoswipe/__init__.py
Python
gpl-3.0
62
0
# -*- coding: utf-8
-*- from .
__version__ import __version__
henryneu/Python
sample/exten.py
Python
apache-2.0
614
0.034202
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Animal(object): def run(self): print('Animal running...') class Dog(Animal):
def run(self): print('Dog running...') def shout(self): print('Dog wang wang...') class Cat(Animal): def run(self): print('Cat running...') def shout(self): print('Cat miao miao...') class Pig(Animal): def run(self): print('Pig running slowly...') def run_twice(animal): animal.run() animal.run()...
print(run_twice(Cat())) print(run_twice(Pig()))
weidnem/IntroPython2016
Solutions/Session01/codingbat/Warmup-1/pos_neg.py
Python
unlicense
736
0.002717
#!/usr/bin/env python def pos_neg(a, b, negative): if negative: return
a < 0 and b < 0 else: return (a < 0 and b > 0) or (a > 0 and b < 0) if __name__ == "__main__": # run some tests if run as script # (from the codingbat site -- not all, I got bored) assert pos_neg(1, -1, False) is True assert pos_neg(-1, 1, False) is True assert pos_neg(-4, -5, True) is...
neg(-4, -5, True) is True assert pos_neg(-6, -6, False) is False assert pos_neg(-2, -1, False) is False assert pos_neg(1, 2, False) is False assert pos_neg(-5, 6, True) is False assert pos_neg(-5, -5, True) is True print "all tests passed"
landism/pants
src/python/pants/engine/scheduler.py
Python
apache-2.0
21,934
0.008252
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging impor...
s_buf(types) def _to_utf8_buf(self, string): return self._native.context
.utf8_buf(string) def _register_rules(self, rule_index): """Record the given RuleIndex on `self._tasks`.""" registered = set() for product_type, rules in rule_index.rules.items(): # TODO: The rules map has heterogeneous keys, so we normalize them to type constraints # and dedupe them before r...
kevin-coder/tensorflow-fork
tensorflow/python/data/experimental/kernel_tests/serialization/choose_fastest_branch_dataset_serialization_test.py
Python
apache-2.0
3,611
0.008031
# Copyright 2019 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...
optimization._ChooseFastestBranchDataset( dataset, [branch_0, branch_1], num_elements_per_branch=3) self.run_core_tes
ts(build_ds, None, 10) def testWithMoreOutputThanInput(self): def build_ds(): dataset = dataset_ops.Dataset.from_tensors(0).repeat(1000).batch(100) def branch(dataset): return dataset.apply(batching.unbatch()) return optimization._ChooseFastestBranchDataset( dataset, [branc...
5nizza/party-elli
interfaces/LTS.py
Python
mit
2,142
0.004202
from interfaces.labels_map import LabelsMap from helpers.python_ext import to_str class LTS: def __init__(self, init_states, model_by_signal:dict, tau_model:LabelsMap, state_name:str, input_signals, output_signal...
f._init_states @property def states(self): # states = set(k[self._state_name] for k in self._tau_model) # return the range of tau \cup init_states states = set(map(lambda l_v: l_v[1], self._tau_model.items())) states.update(self.init_states) return states @property...
return self._tau_model @property def model_by_signal(self): return self._output_models @property def output_models(self) -> dict: return self._output_models def __str__(self): return 'LTS:\n' \ ' inputs: {inputs}\n' \ ' outputs: {output...
nuagenetworks/tempest
tempest/tests/lib/test_decorators.py
Python
apache-2.0
4,381
0
# Copyright 2013 IBM Corp # Copyright 2015 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENS...
def test_skip_attr_does_not_exist(self): self._test_skip_unless_attr('unexpected_attr') def test_skip_attr_false(self): self._test_skip_unless_attr('expected_attr') def test_no_skip_for_attr_exist_and_true(self): self._test_skip_unless_attr('expected_attr', exp
ected_to_skip=False)