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
Debith/py2traits
src/pytraits/__init__.py
Python
apache-2.0
818
0.001224
#!/usr/bin/python -tt # -*- coding: utf-8 -*- ''' Copyright 2014-2015 Teppo Perä 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 Un...
raits.core import ndict, Singleton from pytraits.combiner import combine_class from pytraits.extendable import
extendable from pytraits.trait_composer import add_traits
pdelsante/thug
thug/DOM/W3C/Events/DocumentEvent.py
Python
gpl-2.0
876
0.010274
#!/usr/bin/env python from thug.DOM.W3C.Core.DOMException import DOMException from .
HTMLEvent import HTMLEvent from .MouseEvent import MouseEvent from .MutationEvent import MutationEvent from .StorageEvent import StorageEvent from .UIEvent import UIEvent EventMap = { "HTMLEvent" : HTMLEvent, "HTMLEvents" : HTMLEvent, "MouseEvent" : MouseEvent, "MouseEvents" : Mou
seEvent, "MutationEvent" : MutationEvent, "MutationEvents" : MutationEvent, "StorageEvent" : StorageEvent, "UIEvent" : UIEvent, "UIEvents" : UIEvent } # Introduced in DOM Level 2 class DocumentEvent(object): def __init__(self, doc): self.doc = doc def createEvent(s...
tlpinney/geomakers
windwaker/skyshaker/migrations/0014_auto_20141011_2142.py
Python
apache-2.0
548
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('skyshaker', '0013_link_embed'), ]
operations = [ migrations.RemoveField( model_name='link', name='embed', ), migrations.AddField( model_name='video', name='embed', field=model
s.TextField(default=b'', null=True, blank=True), preserve_default=True, ), ]
Kingclove/lab5info3180
run.py
Python
mit
10,013
0.010786
#!/usr/bin/env python # -*- coding: utf-8 -*- from datetime import datetime import argparse import json import os import shutil import sys import time import urllib2 from main import config ############################################################################### # Options ####################################...
################################# PARSER = argpars
e.ArgumentParser() PARSER.add_argument( '-w', '--watch', dest='watch', action='store_true', help='watch files for changes when running the development web server', ) PARSER.add_argument( '-c', '--clean', dest='clean', action='store_true', help='recompiles files when running the development web server'...
fpradah/change_data_structure
src/cyclomatic.py
Python
gpl-2.0
1,610
0.048447
import sys import csv def intersect(a, b): """ return the intersection of two lists """ return list(set(a) & set(b)) def union(a, b): """ return the union of two lists """ return list(set(a) | set(b)) def combinarA(x,y): return (x,y,"A") def combinarB(x,y): return (x,y,"B") def printCSV(list,file...
t row[0].isdigit() : continue if row[0] in name_exist : break name_exist.append(row[0]) row[1] = row[1].replace("TRUE","1") row[2] = row[2].replace("TRUE"
,"1") row[3] = row[3].replace("TRUE","1") row[4] = row[4].replace("TRUE","1") row[1] = row[1].replace("FALSE",row[1].replace("","0")) row[2] = row[2].replace("FALSE",row[2].replace("","0")) row[3] = row[3].replace("FALSE",row[3].replace("","0")) row[4] = row[4].replace("FALSE",row[4].replace("","0")) if (len(r...
erichschroeter/lieutenant
lieutenant/lieutenant/settings.py
Python
mit
4,114
0.002674
""" Django settings for lieutenant project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...)...
ework', 'taggit', 'favorites', 'taggit_serializer', 'randomslugfield', 'entries', 'tags', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.au...
cationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'dealer.contrib.django.Middleware', ) DEBUG_TOOLB...
teracyhq/flask-boilerplate
app/blueprints.py
Python
bsd-3-clause
289
0
# -*- coding: utf-8 -*- """flask blueprints""" from .main import main_bp from .api_1_0 import api_bp as api_1_0_bp __all__ = ['register_blueprints'] def register_blueprints(app): """register blueprints""" a
pp.register_bluep
rint(main_bp) app.register_blueprint(api_1_0_bp)
kurrik/github-recs
src/apriori/apriori.py
Python
apache-2.0
5,606
0.021584
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'Arne Roomann-Kurrik <kurrik@gmail.com>' import os import sys import math import argparse from subprocess import call def ParseLine(line): # Line format is <screen_name>,"<id1>,<id2>,..."\n split_index = line.index(',') screen_name = line[:split_index]...
t('--minsup', default=80, type=int) parser.add_argument('--minconf', default=50, type=int) parser.add_argument('--minrepos', default=2, type=int) parser.add_argument('--maxrepos', default=1000, type=int) parser.add_argument('--train', default=None, type=str) parser.add_argument('--ruleset', default=Non...
-test', default=None, type=str) parser.add_argument('--clear', action='store_true') args = parser.parse_args() if args.ruleset is None: parser.exit(1, 'Ruleset file must be specified for both train and test') if args.train is not None: if os.path.isfile(args.ruleset) and args.clear == False: ...
sustainableis/python-sis
pysis/workertools/baseWorker.py
Python
isc
2,783
0.00539
from pysis import SIS import os import json import pdb class APITokenException(Exception): pass class BaseWorker(object): def __init__(self, workerID, environment): self.env = environment self.uuid = workerID base_url = o
s.getenv('BASE_URL', None) base_domain = os.getenv('BASE_DOMAIN', None) if base_url and base_domain: self.api = SIS(base_url=base_url, api_domain=base_domain) else: self.api = SIS(base_url='http://api.ndustrial.io/v1/', api_domain='api.ndustrial.io') self.configur...
g = self.loadConfiguration() def loadConfiguration(self): self.worker = self.api.workers.get(uuid=self.uuid) print (self.worker.label) configValues = self.worker.getConfigurationValues(environment=self.env) config = {} for value in configValues: configValu...
aldryn/aldryn-search
aldryn_search/helpers.py
Python
bsd-3-clause
3,579
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import AnonymousUser from django.template import Engine, RequestContext from django.test import RequestFactory from django.utils.text import smart_split from cms.toolbar.toolbar import CMSToolbar from .conf import setting...
nstance, plugin_type = base_plugin.get_plugin_instance() if instance is None or instance.plugin_type in EXCLUDED_PLUGINS: # this is an empty plugin or excluded from search return text_bits search_fields = getattr(instance, 'search_fields', []) if hasattr(instance, 'search_fulltext'): ...
plugin instance has search enabled search_contents = instance.search_fulltext elif hasattr(base_plugin, 'search_fulltext'): # now check in the base plugin instance (CMSPlugin) search_contents = base_plugin.search_fulltext elif hasattr(plugin_type, 'search_fulltext'): # last check...
dsparrow27/zoocore
zoo/libs/utils/modules.py
Python
gpl-3.0
4,491
0.002004
"""This module deals with module paths, importing and the like. """ import inspect import logging import sys import os import imp import importlib logger = logging.getLogger(__name__) def importModule(modulePath, name=None): """Import's the modulePath, if ModulePath is a dottedPath then the function will use impo...
lude and basename not in exclude: modulePath = os.path.join(root, f) if f.endswith(".py") or f
.endswith(".pyc"): yield modulePath def iterMembers(module, predicate=None): """Iterates the members of the module, use predicte to restrict to a type :param module:Object, the module object to iterate :param predicate: inspect.class :return:iterator """ for mod in inspect...
mozata/menpo
menpo/visualize/textutils.py
Python
bsd-3-clause
7,250
0.000276
from __future__ import division, print_function from collections import deque from datetime import datetime import sys from time import time def progress_bar_str(percentage, bar_length=20, bar_marker='=', show_bar=True): r""" Returns an `str` of the specified progress percentage. The percentage is represe...
o be a generator whose length will be assumed to be `n_items`. If not provided, then ``iterator`` needs to b
e `Sizable`. offset : `int`, optional Useful in combination with ``n_items`` - report back the progress as if `offset` items have already been handled. ``n_items`` will be left unchanged. show_bar : `bool`, optional If False, The progress bar (e.g. [========= ]) wil...
paninetworks/neutron
neutron/tests/functional/agent/linux/test_interface.py
Python
apache-2.0
2,526
0
# Copyright (c) 2015 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
id=42, port_id=71, device_name='not_a_device',
mac_address='', bridge='not_a_bridge', namespace='not_a_namespace') def test_plug_succeeds(self): device_name = tests_base.get_rand_name() mac_address = utils.get_random_mac('fa:16:3e:00:00:00'.split(':')) namespace =...
erigones/Ludolph
ludolph/main.py
Python
bsd-3-clause
8,916
0.000673
""" Ludolph: Monitoring Jabber Bot Copyright (C) 2012-2017 Erigones, s. r. o. This file is part of Ludolph. See the LICENSE file for copying permission. """ import os import re import sys import signal import logging from collections import namedtuple try: # noinspection PyCompatibility,PyUnresolvedReferences ...
read_file(fp) fp.close() return config config = load_config(cfg_fp) # Prepare logging configuration logconfig = { 'level':
parse_loglevel(config.get('global', 'loglevel')), 'format': LOGFORMAT, } if config.has_option('global', 'logfile'): logfile = config.get('global', 'logfile').strip() if logfile: logconfig['filename'] = logfile # Daemonize if config.has_option('global', 'daemon'): ...
the01/python-paps
paps/crowd/controller.py
Python
mit
5,482
0.000912
# -*- coding: UTF-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __author__ = "d01" __email__ = "jungflor@gmail.com" __copyright__ = "Copyright (C) 2015-16, Florian JUNG" __license__ = "MIT" __version__ = "0.1.0...
anged) except: self.exception( u"Failed to send new people to {}".format(plugin.name) ) def on_person_leave(self, people): """ People left the audience :param people: People that left :type people: list[paps.person.Per...
if person.id not in self._people: self.warning(u"{} not in audience".format(person.id)) else: del self._people[person.id] changed.append(person) for plugin in self.plugins: try: plugin.on_person_l...
astra-toolbox/astra-toolbox
python/astra/plugins/cgls.py
Python
gpl-3.0
2,821
0.001418
# ----------------------------------------------------------------------- # Copyright: 2010-2022, imec Vision Lab, University of Antwerp # 2013-2022, CWI, Amsterdam # # Contact: astra@astra-toolbox.com # Website: http://www.astra-toolbox.com/ # # This file is part of the ASTRA Toolbox. # # # The ASTRA Toolbo...
cense as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # The ASTRA Toolbox 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. # # You should have received a copy of the GNU General Public License # along with the ASTRA Toolbox. If not, see <http://www.gnu.org/licenses/>. # # ---------------------...
frePPLe/frePPLe
freppledb/common/notifications.py
Python
agpl-3.0
1,606
0.001868
# # Copyright (C) 2020 by frePPLe bv # # This library is free software; you can redistribute i
t 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 library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied...
ore details. # # You should have received a copy of the GNU Affero General Public # License along with this program. If not, see <http://www.gnu.org/licenses/>. # from .models import NotificationFactory, User, Bucket, BucketDetail, Parameter @NotificationFactory.register(User, [User]) def UserNotification(flw, msg)...
algobook/Algo_Ds_Notes
Topological_Sort/Topological_Sort.py
Python
gpl-3.0
1,538
0.006502
class Graph: """ * Creates a adjaceny list for a graph * Implements a function for topological sorting """ def __init__(self, no_vertices): """ Initialises an empty adjaceny list (list of lists) """ self.vertices = no_vertices self.adjlist = [
[] for i in xrange(0, no_vertices)] def add_edge(self, vert1, vert2): """ Creates an edge between two vertices """ self.adjlist[vert1].append(vert2) def topological_sort_util
(self, i, stack, visited): """ Utility function for topological sort """ visited[i] = True for node in self.adjlist[i]: if not visited[node]: self.topological_sort_util(node, stack, visited) stack.append(i) def topological_sort(self): ...
apanda/modeling
mcnet/components/counter.py
Python
bsd-3-clause
3,921
0.023718
from . import NetworkObject import z3 class NetworkCounter (NetworkObject): """OK cannot count: this is sad""" def _init (self, node, net, ctx): super(NetworkCounter, self).init_fail(node) self.node = node.z3Node self.net = net self.ctx = ctx self.constraints = list() ...
z3.Const('_counter_p0_%s'%(self.node), self.ctx.packet) p1 = z3.Const('_counter_p1_%s'%(self.node), self.ctx.packet) n0 = z3.Const('_counter_n0_%s'%(self.node), self.ctx.node) n1 = z3.Const('_counter_n1_%s'%(self.node), self.ctx.node) n2 = z3.Const('_counter_n2_%s'%(self.node), self.ctx....
('_counter_t1_%s'%(self.node)) a0 = z3.Const('_counter_a0_%s'%(self.node), self.ctx.address) a1 = z3.Const('_counter_a1_%s'%(self.node), self.ctx.address) # Make sure all packets sent were first recved self.constraints.append(z3.ForAll([n0, p0], \ z3.Implie...
hb9kns/PyBitmessage
src/bitmessageqt/settings.py
Python
mit
40,025
0.005347
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'settings.ui' # # Created: Thu Dec 25 23:21:20 2014 # by: PyQt4 UI code generator 4.10.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui from languagebox import LanguageBox from sys import platfo...
ut_3 = QtGui.QGridLayout(self.groupBox1) self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3")) #spacerItem = QtGui.QSpacerItem(125, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) #self.gridLayout_3.addItem(spacerItem, 0, 0, 1, 1) self.label = QtGui.QLabel(self.groupBox1...
itTCPPort = QtGui.QLineEdit(self.groupBox1) self.lineEditTCPPort.setMaximumSize(QtCore.QSize(70, 16777215)) self.lineEditTCPPort.setObjectName(_fromUtf8("lineEditTCPPort")) self.gridLayout_3.addWidget(self.lineEditTCPPort, 0, 1, 1, 1, QtCore.Qt.AlignLeft) self.labelUPnP = QtGui.QLabel(se...
bugfree-software/the-internet-solution-python
tests/test_dropdown.py
Python
mit
614
0.032573
from . import TheInternetTestCase from helium.api im
port ComboBox, select class DropdownTest(TheInternetTestCase): def get_page(self): return "http://the-internet.herokuapp.com/dropdown" def test_dropdown_exists(self): self.assertTrue(ComboBox("Dropdown List").exists()) def test_select_value(self): self.assertEqual( ComboBox("Dropdown List").value, u'Please...
tEqual( ComboBox("Dropdown List").value, u'Option 2' )
maniero/SOpt
Python/Operator/OrCondition.py
Python
mit
224
0.008969
letra = input("Qual seu gênero:") if letra == "F" or letra == "f": print("Feminino") elif letra == "M" or letra == "m":
print("Masculino") else: ("sexo invalido") #https://
pt.stackoverflow.com/q/405745/101
Vaidyanath/tempest
tempest/api/messaging/test_claims.py
Python
apache-2.0
4,171
0
# Copyright (c) 2014 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
['location'] self.client.query_claim(claim_uri) # Delete Claimed message claimed_message_uri = body[0]['href'] self.delete_messages(claimed_message_uri) @decorators.skip_because(bug="1328111") @test.attr(type='smoke') def test_update_claim(self): # Post a Claim ...
body = self._post_and_claim_messages(queue_name=self.queue_name) claim_uri = resp['location'] claimed_message_uri = body[0]['href'] # Update Claim claim_ttl = data_utils.rand_int_id(start=60, end=CONF.messaging.max_claim_ttl) update_r...
Senseg/robotframework
src/robot/reporting/logreportwriters.py
Python
apache-2.0
2,447
0.001226
# Copyright 2008-2012 Nokia Siemens Networks Oyj # # 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 ...
IND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import with_statement from os.path import basename, splitext import codecs from robot.htmldata import HtmlFileWriter, ModelWriter, LOG, REPORT from robot.utils impor...
Comunitea/CMNT_00098_2017_JIM_addons
custom_documents/models/stock_picking.py
Python
agpl-3.0
11,479
0.000872
# -*- coding: utf-8 -*- # © 2017 Comunitea # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import models, fields, api from datetime import timedelta from pytz import timezone from odoo.addons import decimal_precision as dp class StockPicking(models.Model): _inherit = 'stock.picking' ...
correctamente el nombre""" res = super(StockMove, self).onchange_product_id() product = self.product_id
.with_context(lang=self.partner_id.lang or self.env.user.lang) if product: self.name = product.name_get()[0][1] return res class StockPackOperation(models.M
changtailiang/xbaydns
xbaydns/tools/dbset.py
Python
bsd-2-clause
760
0.007895
#!/usr/bin/env python # encoding: utf-8 """ dbset.py Created by Razor <bg1tpt AT gmail.com> on 2008-03-31 Copyright (c) 2008 xBayDNS Team. All rights reserved. """ import bsddb, pickle, os class Set(): def __init__(self): self._dbname = os.t
mpnam() try: self._dbobj = bsddb.btopen(self._dbname) except: pass def add(self, element): if element == None: return False element_str = pickle.dumps(element) print type(element_str) self._dbobj[element_str] = '1' return
True def __getitem__(self, element): if element == None: return False element_str = pickle.dumps(element) return self._dbobj[element_str]
zenoss/ZenPacks.zenoss.Puppet
ZenPacks/zenoss/Puppet/interfaces.py
Python
gpl-2.0
1,215
0.002469
########################################################################### # # Copyright (C) 2012 Zenoss Inc. # ########################################################################### from Products.Zuul.form import schema from Products.Zuul.utils import ZuulMessageFactory as _t from Products.Zuul.infos.component ...
'Details') class IPuppetFacade (IFacade): def e
xportDevices(deviceClass): """ Export out devices in zenbatchload format. @parameter deviceClass: location to start exporting devices (default /) @type deviceClass: string @return: zenbatchload format file @rtype: string """ def importDevices(data): ...
ekasitk/sahara
sahara/plugins/cdh/v5_3_0/validation.py
Python
apache-2.0
11,076
0
# Copyright (c) 2014 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
nst_count(cluster, 'SQOOP_SERVER') if s2s_count > 1: raise ex.InvalidComponentCountException('SQOOP_SERVER', _('0 or 1'), s2s_count) if s2s_count == 1: if dn_count < 1: raise ex.RequiredServiceMissingException( 'HDFS_DAT...
'YARN_NODEMANAGER', required_by='SQOOP_SERVER') if hs_count != 1: raise ex.RequiredServiceMissingException( 'YARN_JOBHISTORY', required_by='SQOOP_SERVER') lhbi_count = _get_inst_count(cluster, 'HBASE_INDEXER') if lhbi_count >= 1: if dn_count < 1: ...
Microvellum/Fluid-Designer
win64-vc/2.78/python/lib/unittest/__init__.py
Python
gpl-3.0
3,117
0.003208
""" Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's Smalltalk testing framework. This module contains the core framework classes that form the basis of specific test cases and suites (TestCase, TestSuite etc.), and also a text-based utility class for running the tests and reporting the resu...
IDED HEREUNDER IS ON AN "AS IS" BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. """ __all__ = ['TestResult', 'TestCase', 'TestSuite', 'TextTestRunner', 'TestLoader', 'FunctionTestCase', 'main', 'defaultTestLoader', 'SkipTest',...
e', 'TextTestResult', 'installHandler', 'registerResult', 'removeResult', 'removeHandler'] # Expose obsolete functions for backwards compatibility __all__.extend(['getTestCaseNames', 'makeSuite', 'findTestCases']) __unittest = True from .result import TestResult from .case import (TestCase, FunctionTestCa...
nOkuda/ankura
ankura/tokenize.py
Python
gpl-3.0
1,360
0
"""A collect
ion of tokenizers for use with ankura import pipelines""" import re import bs4 # Note: Each tokenizer takes in a string, and returns a list of tokens def split(data): """A tokenizer which does nothing but splitting""" return data.split() def simple(data,
splitter=split): """A basic tokenizer which splits and does basic filtering. The included filters and transformations include: * lower case each token * filter out non-alphabetic characters """ tokens = splitter(data) tokens = [token.lower() for token in tokens] tokens = [re.sub(r'[^a-...
jstacoder/flask-manage
flask_mrbob/templates/project/+project.name+/basemodels.py
Python
bsd-3-clause
1,359
0.001472
# -*- coding: utf-8 -*- """ basemodels.py ~~~~~~~~~~~ """ from flask.ext.login import UserMixin from sqlalchemy.ext.declarative import declared_attr from werkzeug.security import generate_password_hash, check_password_
hash from ext import db class BaseMixin(object): __table_args__ = {'extend_existing': True} id = db.Column(db.Integer,db.Sequence('user_id_seq'),primary_key=True) @classmethod def get_by_id(cls, id): if any( (isinstance(id, basestring) and id.isdigit(), isinstance(id...
f create(cls, **kwargs): instance = cls(**kwargs) return instance.save() def update(self, commit=True, **kwargs): for attr, value in kwargs.iteritems(): setattr(self, attr, value) return commit and self.save() or self def save(self, commit=True): db.session....
dbmi-pitt/DIKB-Micropublication
scripts/mp-scripts/Bio/DBXRef.py
Python
apache-2.0
9,448
0.006245
class DBXRef: def __init__(self, dbname, dbid, reftype = None, negate = 0): self.dbname = dbname self.dbid = dbid self.reftype = reftype self.negate = negate def __str__(self): if self.reftype is None: reftype = "" else: reftype = self.ref...
sequence # identifier for nucleotide and proteins. # /db_xref="GI:1234567890" "GO": "go", # Gene Ontology Database identifier # /db_xref="GO:123" "IMGT/LIGM": "x-imgt-ligm", # Immunogenetics database, immunoglobulins ...
GT/LIGM:U03895" "IMGT/HLA": "x-imgt-hla", # Immunogenetics database, human MHC # /db_xref="IMGT/HLA:HLA00031" "LocusID": "x-locus-id", # NCBI LocusLink ID. # /db_xref="LocusID:51199" "MaizeDB": "x-maizedb", # Maize Genome Database...
mlperf/training_results_v0.7
Google/benchmarks/dlrm/implementations/dlrm-research-TF-tpu-v4-16/dlrm_main.py
Python
apache-2.0
8,831
0.006115
"""Training script for DLRM model.""" import functools import REDACTED from absl import app as absl_app from absl import flags import numpy as np import tensorflow.compat.v1 as tf from REDACTED.tensorflow.python.tpu import tpu_embedding from REDACTED.tensorflow_models.mlperf.models.rough.dlrm import dataloader from ...
>= _ACCURACY_THRESH mlp_log.mlperf_print( "eval_accuracy", roc_auc, metadata={"epoch_num": eval_num + 1}) if success: mlp_log.mlperf_print("run_stop", None, metadata={"status": "success"}) if summary_writer: summary_writer.add_summary(
utils.create_scalar_summary("auc", roc_auc), global_step=cur_step + FLAGS.steps_between_evals) eval_metrics.append((cur_step + FLAGS.steps_between_evals, roc_auc)) return success def _default_run_finish_fn(success_status): if not success_s
tysonholub/twilio-python
tests/integration/preview/hosted_numbers/authorization_document/test_dependent_hosted_number_order.py
Python
mit
5,011
0.002594
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from tests import IntegrationTestCase from tests.holodeck import Request from twilio.base.exceptions import TwilioException from twilio.http.response import Response class DependentHostedNumberOrde...
w.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0", "key": "items", "next_page_url": null, "page": 0, "page_size": 50, "prev
ious_page_url": null, "url": "https://preview.twilio.com/HostedNumbers/AuthorizationDocuments/PXaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/DependentHostedNumberOrders?PageSize=50&Page=0" }, "items": [ { "account_sid": "ACaaaaaaaaaaaaa...
cjaymes/pyscap
src/scap/model/cpe_naming_2_3/__init__.py
Python
gpl-3.0
821
0
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is ...
even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http://www
.gnu.org/licenses/>. TAG_MAP = { '{http://cpe.mitre.org/naming/2.0}cpe22Type': 'Cpe22Type', '{http://cpe.mitre.org/naming/2.0}cpe23Type': 'Cpe23Type', }
googleapis/python-aiplatform
samples/generated_samples/aiplatform_generated_aiplatform_v1beta1_metadata_service_query_artifact_lineage_subgraph_async.py
Python
apache-2.0
1,632
0.001838
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
e the request response = await client.query_artifact_lineage_subgraph(request=request) # Handle the response print(response) # [END aiplatform_generated_aiplatform_v1beta1_MetadataService_QueryArtifactLi
neageSubgraph_async]
liqd/adhocracy4
adhocracy4/reports/admin.py
Python
agpl-3.0
350
0
from django.contrib import admin from .models import Report @admin.register(Report) class ReportAdmin(admin.ModelAdmin): fields = ('content_type', 'content_
object', 'description', 'creator') readonly_fields = ('creator', 'content_type', 'content_object') list_display = ('__str__', 'creator', 'created')
date_hierarchy = 'created'
vmonteco/YAPT
test_files/uu_cases_regular.py
Python
gpl-3.0
907
0
# -*- coding: utf-8 -*- from tools.factories import generator_factory import ctypes basic_cases = [ [b'%U\n', c
types.c_long(0)], [b'% U\n', c
types.c_long(0)], [b'%+U\n', ctypes.c_long(0)], [b'%-U\n', ctypes.c_long(0)], [b'%0U\n', ctypes.c_long(0)], [b'%#U\n', ctypes.c_long(0)], [b'%10U\n', ctypes.c_long(0)], [b'%.6U\n', ctypes.c_long(0)], [b'%hhU\n', ctypes.c_long(0)], [b'%llU\n', ctypes.c_long(0)], [b'%hU\n', ctypes.c_lo...
andrebellafronte/stoq
stoqlib/gui/dialogs/paymentflowhistorydialog.py
Python
gpl-2.0
8,070
0.00285
# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 ## ## Copyright (C) 2010 Async Open Source <http://www.async.com.br> ## All rights reserved ## ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU Lesser General Public License as published by ## the Free Software F...
if not, write to the Free Software ## Foundation, Inc., or visit: http://www.gnu.org/. #
# ## Author(s): Stoq Team <stoq-devel@async.com.br> ## """Payment Flow History Report Dialog""" from storm.expr import And, Eq, Or from stoqlib.database.expr import Date from stoqlib.gui.dialogs.daterangedialog import DateRangeDialog from stoqlib.gui.utils.printing import print_report from stoqlib.lib.message import ...
mxyue66/ISPRS
extract_all_bus_stop_coordinates.py
Python
mit
2,342
0.032451
import numpy as np from sklearn.cluster import DBSCAN import csv def load_data(fin_path): files = file(fin_path,'r') reader = csv.reader(files) reader.next() res_0 = [] for id,route_id1,route_id2,bus_id1,bus_id2,day1,day2,time1,time2,lon,lat,card_id,guid in reader: temp_0 = [] ...
_mask[db_0.core_sample_indices_] = True labels_0 = db_0.labels_ # Number of c
lusters in labels, ignoring noise if present. n_clusters_0 = len(set(labels_0)) - (1 if -1 in labels_0 else 0) central_points_0 = [] for i in range(1, n_clusters_0): idx = np.where(labels_0 == i) temp_route_id_0 = np.mean(X_0[idx,0]) temp_central_lon...
pcapriotti/pledger
pledger/template.py
Python
mit
4,577
0.001092
from datetime import datetime from .tags import has_tag COLORS = { "bold_white": "\033[1;37m", "red": "\033[0;31m", "yellow": "\033[0;33m", "green": "\033[0;32m", "nocolor": "\033[00m", "blue": "\033[0;34m"} class Template(object): ACCOUNT_COLOR = "blue" def __call__(self, ledgers, r...
if not has_tag(transaction, "cleared"): color = "bold_white" return self.lpad(transaction.label, size, color) def colored(self, color, text):
if color: return COLORS[color] + text + COLORS["nocolor"] else: return text class BalanceTemplate(Template): def generate(self, ledgers, report): it = report.generate(ledgers) # save total total = next(it) count = 0 for entry in it: ...
volpino/Yeps-EURAC
lib/galaxy/model/mapping.py
Python
mit
73,637
0.040021
""" Details of how the data model objects are mapped onto the relational database are encapsulated here. """ import logging log = logging.getLogger( __name__ ) import sys import datetime from galaxy.model import * from galaxy.model.orm import * from galaxy.model.orm.ext.assignmapper import * from galaxy.model.custom...
5 ) ), Column( "hid_counter", Integer, default=1 ), Column( "deleted", Boolean, index=True, default=False ), Column( "purged", Boolean, index=True, default=False ), Column( "genome_build", TrimmedString( 40 ) ), Column( "importable", Boolean, default=False ) ) HistoryUserShareAssociation.table = Ta...
a, Column( "id", Integer, primary_key=True ), Column( "history_id", Integer, ForeignKey( "history.id" ), index=True ), Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True ) ) HistoryDatasetAssociation.table = Table( "history_dataset_association", metadata, Column( "id", Integer,...
cypreess/django-tos
tos_i18n/translation.py
Python
bsd-3-clause
299
0.006689
from modeltranslation.translator import translator, TranslationOptions from tos.models import TermsOfService # Translations for django-tos class Terms
OfServiceTranslationOptions(TranslationOptions): fields = ('content', ) translator.re
gister(TermsOfService, TermsOfServiceTranslationOptions)
dopplershift/MetPy
tests/plots/test_declarative.py
Python
bsd-3-clause
34,530
0.0011
# Copyright (c) 2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Test the simplified plotting interface.""" from datetime import datetime, timedelta from io import BytesIO import warnings import matplotlib import numpy as np import pandas ...
anel.area = 'us'
panel.proj = 'lcc' panel.layers = ['coastline', 'borders', 'usstates'] panel.plots = [contour] pc = PanelContainer() pc.size = (8.0, 8) pc.panels = [panel] pc.draw() return pc.figure @pytest.mark.mpl_image_compare(remove_text=True, tolerance={'3.0': 0.21...
jmons/ramlwrap
tests/RamlWrapTest/tests/test_raml_v1.py
Python
mit
1,448
0.004144
"""Tests for RamlWrap""" import inspect import json import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../"))) from django.test import TestCase, Client def _get_parent_class(method): """Return the class for the given method.""" members = inspect.getmember...
t() def test_raml_with_multiple_examples__only_one_is_returned(self): """Test that a valid get request with no target returns the example json. """ expected_data_1 = {"exampleData": "This is the first example response"} expected_data_2 = {"exampleData2": "Thi
s is a second example"} response = self.client.get("/ramlv1-api/multi-example") reply_data = response.content.decode("utf-8") actual_response = json.loads(reply_data) # Due to the unordered nature of dictionaries in certain Python versions, we are happy if either one of # the e...
tequa/ammisoft
ammimain/WinPython-64bit-2.7.13.1Zero/python-2.7.13.amd64/Scripts/pilconvert.py
Python
bsd-3-clause
2,427
0.000824
#!C:\Users\DMoran\Downloads\WinPython-64bit-2.7.13.1Zero\python-2.7.13.amd64\python.exe # # The Python Imaging Library. # $Id$ # # convert image files # # History: # 0.1 96-04-20 fl Created # 0.2 96-10-04 fl Use draft mode when converting images # 0.3 96-12-30 fl Optimize output (PNG, JPEG) # 0.4 97...
.init() id = sorted(Image.ID) print("Supported formats (* indicates output format):")
for i in id: if i in Image.SAVE: print(i+"*", end=' ') else: print(i, end=' ') sys.exit(1) elif o == "-c": output_format = a if o == "-g": convert = "L" elif o == "-p": convert = "P" elif o == "-r": c...
BurtBiel/azure-cli
src/command_modules/azure-cli-network/azure/cli/command_modules/network/mgmt_lb/lib/operations/lb_operations.py
Python
mit
9,696
0.002063
#--------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. #---------------------------------------------------------------------...
header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] =
str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body ...
Erotemic/vtool
vtool_ibeis/ellipse.py
Python
apache-2.0
15,540
0.003861
""" OLD MODULE, needs reimplemenetation of select features and deprication This module should handle all things elliptical """ from __future__ import absolute_import, division, print_function from six.moves import zip, range from numpy.core.umath_tests import matrix_multiply import scipy.signal as spsignal import nump...
ubscale_list def subscale_peaks(border_vals_sum, kpts, nScales, low, high): peak_list = interpolate_maxima(border_vals_sum) subscale_list = interpolate_between(peak_list, nScales, high, low) subscale_kpts = expand_subscales(kpts, subscale_list) return subscale_kpts def expand_kpts(kpts, scales): ...
= kpts.copy() kpts_.T[2] *= scale kpts_.T[3] *= scale kpts_.T[4] *= scale expanded_kpts_list.append(kpts_) return expanded_kpts_list def expand_subscales(kpts, subscale_list): subscale_kpts_list = [kp * np.array((1, 1, scale, scale, scale, 1)) for kp,...
pacogomez/pyvcloud
tests/vcd_catalog_update.py
Python
apache-2.0
993
0.004028
import os import unittest import yaml from pyvcloud.vcd.client import BasicLoginCredentials from pyvcloud.vcd.client import Client from pyvcloud.vcd.org import Org from pyvcloud.vcd.test import TestCase class UpdateCatalog(TestCase): def test_create_catal
og(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org)
catalog = org.create_catalog(self.config['vcd']['catalog'], 'test catalog') assert self.config['vcd']['catalog'] == catalog.get('name') def test_update_catalog(self): logged_in_org = self.client.get_org() org = Org(self.client, resource=logged_in_org) catalog = org.update_ca...
infinity0/obfsproxy
obfsproxy/network/buffer.py
Python
bsd-3-clause
1,998
0
class Buffer(object): """ A Buffer is a simple FIFO buffer. You write() stuff to it, and you read() them back. You can also peek() or drain() data. """ def __init__(self, data=''): """ Initialize a buffer with 'data'. """ self.buffer = bytes(data) def read(self,...
Read and return 'n' bytes from the buffer. If 'n' is negative, read and return the whole buffer. If 'n' is larger than the size of the buffer, read and return the whole buffer. """
if (n < 0) or (n > len(self.buffer)): the_whole_buffer = self.buffer self.buffer = bytes('') return the_whole_buffer data = self.buffer[:n] self.buffer = self.buffer[n:] return data def write(self, data): """ Append 'data' to the b...
cckim47/kimlab
general/merge_tables2.py
Python
mit
2,357
0.036911
#!/usr/bin/python ##################################################### # example.py - a program to .... # # # # Author: Dave Wheeler # # # # Purpose: merge count tables ...
open(sys.argv[1])
except IndexError: print "No guide file provided" sys.exit() #make dict of genes with list of counts #list is ordered so treatments will be preserved. #genes = {'gene1':[1,2,3,4]} #header keeps track of treatment order, will be as read from config col_header = [] genes = {} #outfile = open('merged_counts.txt','w...
great-expectations/great_expectations
great_expectations/datasource/data_connector/__init__.py
Python
apache-2.0
1,441
0.000694
# isort:skip_file from .data_connector import DataConnector from .runtime_data_connector import RuntimeDataConnector from .file_path_data_connector import FilePathDataConnector from .configured_asset_file_path_data_connector import ( ConfiguredAssetFilePathDataConnector, ) from .infer
red_asset_file_path_data_connector import ( InferredAssetFilePathDataCo
nnector, ) from .configured_asset_filesystem_data_connector import ( ConfiguredAssetFilesystemDataConnector, ) from .inferred_asset_filesystem_data_connector import ( InferredAssetFilesystemDataConnector, ) from .configured_asset_s3_data_connector import ( ConfiguredAssetS3DataConnector, ) from .inferred_as...
mitsei/dlkit
tests/dlkit/primordium/locale/types/test_calendar.py
Python
mit
1,400
0.002857
import pytest from dlkit.abstract_osid.osid import errors from dlkit.primordium.locale.types.calendar import get_type_data class TestCalendar(object): def test_get_type_data_with_celestial(self): results = get_type_data('xhosa') assert results['domain'] == 'Calendar Types' assert results[...
ame'] == 'Xhosa Calendar Type' assert results['display_label'] == 'Xhosa' assert results['description'] == 'The time type for the Xhosa calendar.' def test_get_type_data_with_ancient_calendar(self): results = get_type_data('assyrian') assert resul
ts['domain'] == 'Ancient Calendar Types' assert results['display_name'] == 'Assyrian Calendar Type' assert results['display_label'] == 'Assyrian' assert results['description'] == 'The time type for the Assyrian calendar.' def test_get_type_data_with_alternate_calendar(self): results...
SingularityHA/WebUI
infrastructure/migrations/0017_module_list_widget_setup_js.py
Python
gpl-3.0
420
0.002381
# encoding: utf8 from django.db import models, migrations class Migration(mig
rations.Migration): dependencies = [
('infrastructure', '0016_auto_20140209_0826'), ] operations = [ migrations.AddField( model_name='module_list', name='widget_setup_js', field=models.TextField(null=True, blank=True), preserve_default=True, ), ]
tbattz/logsFlightGearReplay
timeControl.py
Python
gpl-3.0
4,536
0.02425
''' Created on 11 Aug 2016 @author: bcub3d-build-ubuntu ''' from Tkinter import * import ttk from threading import Thread import readLog import socket import sendDataGUI import math import playbackFunctions import matplotlib matplotlib.use('TkAgg') from matplotlib import pyplot as plt from matplotlib.backends.backend...
Button(master,text='Start Replay', command=lambda: simThread.startSim(timeScale.get())).grid(row=1,column=38) Button(master,text='Pause Replay', command=simThread.pauseSim).grid(row=1,column=39) # "Go To" Buttons and Boxes # Go to Entry Box e = Entry(master,width=6) e.grid(row=1,column=1) e.insert(0,"0") # Create Go T...
ckFunctions.goToButton(e, timeScale, simThread)).grid(row=1,column=0) # Seconds Label l = Label(master,text='s') l.grid(row=1,column=2,sticky=W) # Time Marking # Label l2 = Label(master,text="Mark [Set,Jump]:") l2.grid(row=1,column=42,sticky=E) # Button Set 1 c1 = playbackFunctions.createMark(master,'green',10,990) s1...
moijes12/treeherder
treeherder/model/management/commands/init_datasources.py
Python
mpl-2.0
1,226
0.000816
from optparse import make_option from django.core.management.base import BaseCommand from django.utils.six.moves import input from treeherder.model.models import Datasource, Repository class Command(BaseCommand): help = ("Populate the datasource table and" "create the connected databases") opti...
if options["reset"]: confirm = input("""You have requested an init of the datasources. This will IRREVERSIBLY DESTROY all data in the per-project databases. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """) if confirm == "yes": for ds in Data...
projects = Repository.objects.filter(active_status='active').values_list('name', flat=True) for project in projects: Datasource.objects.get_or_create(project=project) Datasource.reset_cache()
caio2k/RIDE
utest/controller/ui/test_treecontroller.py
Python
apache-2.0
6,000
0.000333
import unittest from robot.parsing.model import TestCase, TestCaseFile from robot.utils.asserts import assert_equals from robotide.controller.commands import ChangeTag from robotide.controller.filecontrollers import TestCaseFileController from robotide.controller.macrocontrollers import TestCaseController from robotide...
urce Keyword', 'Sub Suite 0 Fake UK 2'] for name in nodes: self._select_node(name) self._go_back_and_assert_selection('Resource Keyword') self._go_back_and_assert_selection('Top Suite Fake UK 0') self._go_forward_and_assert_selection('Reso
urce Keyword') self._go_forward_and_assert_selection('Sub Suite 0 Fake UK 2') def _go_back_and_assert_selection(self, expected_selection): assert_equals(self._go_back_and_return_selection(), expected_selection) def _go_forward_and_assert_selection(self, expected_selection): assert_equa...
SlashNephy/PyChroner-Bot
plugins/SlashNephy/Swarm.py
Python
mit
3,264
0.004204
# coding=utf-8 import requests import time from pychroner import PluginMeta, PluginType @PluginMeta(PluginType.Thread) def do(pluginApi): db = pluginApi.getMongoDB().getCollection("bot") slack = pluginApi.getSlack() while True: url = f"https://api.foursquare.com/v2/users/63379277/scoreboard?oauth_...
== "self"][0] lastMyObj = [x for x in lastData["users"] if x["user"]["relationship"] == "self"][0] myRank = myObj["ranking"] myScore = myObj["score"] lastMyScore = lastMyObj["score"] text = f"現在のSwarm順位は{myRank}位です。" # 前回のスコアよりも高い i...
["users"][myRank - 2] lastSeniorObj = lastData["users"][myRank - 2] if seniorObj["score"] > lastSeniorObj['score']: seniorName = f"{seniorObj['user']['firstName']} {seniorObj['user']['lastName']}" if "lastName" in seniorObj["user"] else seniorObj["user"]["...
The-Cypherfunks/The-Cypherfunks
share/rpcuser/rpcuser.py
Python
mit
1,117
0.005372
#!/usr/bin/env python2 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import hashlib import sys import os from random import SystemRandom import base64 import hmac if len(s...
n([x[2:] for x in hexseq]) #Create 32 byte b64 password password = base64.urlsafe_b64encode(os.urandom(32)) digestmod = hashlib.sha256 if sys.version_info.major >= 3: password = password.decode('utf-8') digestmod = 'SHA256' m = hmac.new(bytearray(salt, 'utf-8'), bytearray(password, 'utf-8'), digestmod) res...
st() print("String to be appended to cypherfunk.conf:") print("rpcauth="+username+":"+salt+"$"+result) print("Your password:\n"+password)
jctanner/ansibullbot
tests/unit/triagers/plugins/test_rebuild_merge.py
Python
gpl-3.0
3,614
0.00249
#!/usr/bin/env python import json import logging import tempfile import unittest import pytest from tests.utils.issue_mock import IssueMock from tests.utils.repo_mock import RepoMock from tests.utils.helpers import get_issue from ansibullbot.triagers.plugins.ci_rebuild import get_rebuild_merge_facts from ansibullbot...
meta = { u'is_pullrequest': True, u'is_needs_revision': False, u'is_needs_rebase': False, u'needs_rebuild': False, u'ci_run_number': 0 } rbfacts = get_rebuild_merge_facts(iw, meta, [u'superman']) ...
rt rbfacts[u'admin_merge'] == False def test2(self): # command given, time to rebuild but not merge datafile = u'tests/fixtures/rebuild_merge/2_issue.yml' statusfile = u'tests/fixtures/rebuild_merge/2_prstatus.json' with get_issue(datafile, statusfile) as iw: meta = { ...
savi-dev/keystone
tests/test_migrate_nova_auth.py
Python
apache-2.0
5,879
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack 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 requ...
1'}, {'tenant_id': 'proj4', 'user_id': 'user4'}, {'tenant_id': 'proj1', 'user_id': 'user2'}, {'tenant_id': 'proj2', 'user_id': 'user2'}, {'tenant_id': 'proj1', 'user_id': 'user3'}, ], 'ec2_credentials': [ {'access_key': 'acc1', 'secret_key': 'sec1', 'user_id': 'user1'}, ...
t_key': 'sec2', 'user_id': 'user2'}, {'access_key': 'acc3', 'secret_key': 'sec3', 'user_id': 'user3'}, ], 'tenants': [ {'description': 'desc1', 'id': 'proj1', 'name': 'pname1'}, {'description': 'desc4', 'id': 'proj4', 'name': 'pname4'}, {'description': 'desc2', 'id': 'proj2', 'na...
starrify/scrapy
tests/test_utils_python.py
Python
bsd-3-clause
7,687
0.001041
import functools import gc import operator import platform import unittest from datetime import datetime from itertools import count from warnings import catch_warnings from scrapy.utils.python import ( memoizemethod_noargs, binary_is_text, equal_attributes, WeakKeyCache, get_func_args, to_bytes, to_unicode, ...
o_bytes, unittest) def test_errors_argument(self): self.assertEqual( to_bytes('a\ufffdb', 'latin-1', errors='replace'), b'
a?b' ) class MemoizedMethodTest(unittest.TestCase): def test_memoizemethod_noargs(self): class A: @memoizemethod_noargs def cached(self): return object() def noncached(self): return object() a = A() one = a.cach...
CroissanceCommune/autonomie
autonomie/views/admin/accompagnement/activities.py
Python
gpl-3.0
2,419
0
# -*- coding: utf-8 -*- # * Authors: # * TJEBBES Gaston <g.t@majerti.fr> # * Arezki Feth <f.a@majerti.fr>; # * Miotte Julien <j.m@majerti.fr>; import os from pyramid.httpexceptions import HTTPFound from autonomie.forms.admin import ( ActivityConfigSchema, ) from autonomie.models.activity import ( ...
dminActivitiesView(BaseAdminAccompagnement): """ Activities Admin view """ title = u"Configuration du module de Rendez-vous" schema = ActivityConfigSchema(title=u"") route_name = ACTIVITY_URL def before(self, form): query = ActivityType.query() types = query.filter_by(active...
ivityMode.query() query = ActivityAction.query() query = query.filter_by(parent_id=None) actions = query.filter_by(active=True) activity_appstruct = { 'footer': self.request.config.get("activity_footer", ""), 'types': [type_.appstruct() for type_ in types], ...
trel/irods-qgis
irods/connection.py
Python
gpl-2.0
5,101
0.007842
import socket import logging import struct import hashlib from irods.message import (iRODSMessage, StartupPack, AuthResponse, AuthChallenge, OpenedDataObjRequest, FileSeekResponse, StringStringMap) from irods.exception import get_exception_by_code, NetworkException from irods import MAX_PASSWORD_LENGTH from irods....
1') pwd_msg = AuthResponse(response=encoded_pwd, username=self.ac
count.proxy_user) pwd_request = iRODSMessage(type='RODS_API_REQ', int_info=704, msg=pwd_msg) self.send(pwd_request) auth_response = self.recv() def read_file(self, desc, size): message_body = OpenedDataObjRequest( l1descInx=desc, len=size, when...
pirate/bookmark-archiver
archivebox/core/__init__.py
Python
mit
32
0
__packa
ge__ = 'archiveb
ox.core'
mwhooker/messier
messier/lib/aws/resource.py
Python
bsd-2-clause
1,293
0.000773
import boto.regioninfo import datetime from collections import MutableMapping from json import JSONEncoder, dumps from time import mktime def json_encoder(obj): if isinstance(obj, boto.regioninfo.RegionInfo): return obj.name elif isinstance(obj, datetime.datetime): return int(mktime(obj.timet...
_ = Type if not self.__type__: self.__type__ = self.__class__.__name__ self.__encoder__ = encoder self.__store__ = dict() props = dict(**properties) del props["connection"] self.update(props) def __getite
m__(self, key): return self.__store__[key] def __setitem__(self, key, value): self.__store__[key] = value def __delitem__(self, key): del self.__store__[key] def __iter__(self): return iter(self.__store__) def __len__(self): return len(self.__store__) def...
robmcmullen/peppy
peppy/plugins/text_transforms.py
Python
gpl-2.0
25,843
0.003018
# peppy Copyright (c) 2006-2010 Rob McMullen # Copyright (c) 2009 Christopher Barker # Licenced under the GPLv2; see http://peppy.flipturn.org for more info """Some simple text transformation actions. This plugin is a collection of some simple text transformation actions that should be applicable to more than one majo...
ns/text_lowercase.png" default_toolbar = False def mutate(self, txt): """Change to all lower case. """ return txt.lower() class SwapcaseWord(WordOrRegionMutateAction): """Swap the case of the current word or the highlighted region. This will also move the cursor to the sta...
. """ alias = "swapcase-region-or-word" name = "Swap case" default_menu = ("Transform/Case", 103) default_toolbar = False def mutate(self, txt): """Change to the opposite case (upper to lower and vice-versa). """ return txt.swapcase() class Rot13(RegionMutateAction): ...
PorthTechnolegauIaith/moses-smt
scripts/mtdk/mt_update_compress_moses_ini.py
Python
mit
493
0.03854
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys file=str(sys.argv[1]) file2=str(sys.argv[2]) outfile=open(file2,'w') with open (file) as f: for line in f: if line.startswith('PhraseDictionaryMemory'): line = line.replace('PhraseDictionaryMemory','PhraseDictionaryCompact') line = line.replace('tabl...
g'): line = line.replace('bidirectional-fe.gz','bidirectional-fe') outfile.w
rite(line) outfile.close()
dsweet04/rekall
rekall-agent/rekall_agent/flows/__init__.py
Python
gpl-2.0
156
0
from rekall_agent.flows
import artifact_flow from rekall_agent.flows import collect from rekall_agent.flows import find from rekall_agent.flows import yar
a
ericchan2012/django-blog
Blog/views.py
Python
apache-2.0
6,779
0.003772
# -*- coding: UTF-8 -*- from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.detail import DetailView from Blog.models import Article, Category, Tag, BlogComment from Blog.forms import BlogCommentForm from markdown import markdown from django.views.generic.edit im...
list: article.body = markdown(article.body, extras=['fenced-code-blocks'], ) return article_list def get_context_data(self, **kwargs): kwargs['tag_list'] = Tag.objects.all().order_by('name') return super(ArchiveView, self).get_context_data(**kwargs) class CommentPostView(FormV...
get_article = get_object_or_404(Article, pk=self.kwargs['article_id']) comment = form.save(commit=False) comment.article = target_article comment.save() self.success_url = target_article.get_absolute_url() return HttpResponseRedirect(self.success_url) def form_invalid(sel...
kristofvanmoffaert/python-omniture
setup.py
Python
mit
1,204
0.001661
from setuptools import setup, find_packages exec(open('omniture/version.py').read()) setup(name='omniture', description='A wrapper for the Adobe Analytics (Omniture and SiteCatalyst) web analytics API.', long_description=open('README.md').read(), author='Stijn Debrouwere', au
thor_email='stijn@stdout.be', url='http://stdbrouw.github.com/python-omniture/', download_url='http://www.github.com/stdbrouw/python-omniture/tarball/master', version=__version__, license='MIT', packages=find_packages(), keywords='data analytics api
wrapper adobe omniture', install_requires=[ 'requests', 'python-dateutil', ], classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :...
evancich/apm_motor
modules/waf/playground/distnet/server/cgi-bin/upload.py
Python
gpl-3.0
1,298
0.023112
#! /usr/bin/env python import os, sys, tempfile, shutil, hashlib, tarfile import cgi, cgitb cgitb.enable() PKGDIR = os.environ.get('PKGDIR', os.path.abspath('../packages')) # Upload a package to the package directory. # It is meant to contain a list of tar packages: # # PKGDIR/pkgname/pkgver/common.tar # PKGDIR/pkgn...
empfile.mkdtemp(dir=up) try: tf = os.path.join(tmp, 'some_temporary_file') with open(tf, 'wb') as f: f.write(pkgdata) with tarfile.open(tf) as f: f.extractall(tmp) os.remove(tf) os.rename(tmp, dest) finally: # cleanup try: shutil.rmtree(
tmp) except Exception: pass print('''Content-Type: text/plain\n\nok''')
rebelact/mailsync-app
mailsync/api/mailchimp.py
Python
mit
2,198
0.040491
import datetime import logging from mailsnake import MailSnake from mailsync.models.customfield import CustomField class MailChimp
(object): def __init__(self, apikey): self.api_key = apikey self.provider = MailSnake(self.api_key) def test_connection(self): try: self.provider.ping() except Exception, err: logging.error(err) return False return True def get_list_custom_fields(self, listid): custom_fields = [] try:...
id=listid) for custom_field in list_custom_fields: field = custom_field["name"] custom_fields.append(CustomField(field.replace(" ", "-").lower(), field, custom_field["tag"])) except Exception, err: logging.error(err) custom_fields = [] return custom_fields def get_lists(self): lists = []...
kscottz/SkinnerBox
modules/CameraInterface.py
Python
mit
2,818
0.007807
import os import io import cv2 import cv import picamera import threading import numpy as np import time class CameraInterface(threading.Thread): def __init__(self,img_path="/img/live.jpg"): super(CameraInterface, self).__init__() self.setDaemon(True) # set our path for ouput images ...
lor(self._current_image,cv2.cv.CV_BGR2GRAY) # set the last image to this image -- causes no motion # on first iteration self._last_image = temp # make the current
image gray -- faster temp = cv2.cvtColor(self._current_image,cv2.cv.CV_BGR2GRAY) # get the diff of the images diff = self._last_image-temp # get the mean of absolute difference between images change = np.mean(np.abs(diff)) # now filter the image, so we don't jump super ...
SatelliteQE/robottelo
tests/upgrades/test_user.py
Python
gpl-3.0
3,413
0
"""Test for User related Upgrade Scenario's :Requirement: UpgradedSatellite :CaseAutomation: NotAutomated :CaseLevel: Acceptance :CaseComponent: UsersRoles :Assignee: sganar :TestType: Functional :CaseImportance: High :Upstream: No """ import pytest class TestScenarioPositiveCreateSSHKeyInExistingUsers: "...
"""SSH key can be added to existing user post upgrade :id: postupgrade-e4338daa-272a-42e3-be45-77e1caea607f :steps: Postupgrade, Add SSH key to the existing user :expectedresults: SSH Key should be added to the existing user """ class TestScenarioPositiveExistingUserPasswordlessAcc...
rom SuperAdmin create user with all the details 2. Upgrade Satellite to next/latest satellite version 3. Go to the user created in preupgrade satellite 4. Add SSH key in that user 5. Choose provisioning template you would use to provision the host in feature and a...
eyeNsky/qgis-scripts
select-key-frames.py
Python
mit
2,286
0.013561
##[TBT-Tools]=group ##Input_Footprints=vector ##Image_IDs=field Input_Footprints ##Overlap_Threshold_0_to_1=number 0.6 from qgis.utils import * from osgeo import ogr from osgeo import osr KEEP_TRESHOLD=Overlap_Threshold_0_to_1 IMAGE_IDS = Image_IDs def calcIntersection(fpA,fpB): f
pA = fpA.Buffer(0) if not fpA.Intersect(fpB): return False, 0 if fpA.Intersect(fpB): areaOfIntersection = fpA.Intersection(fpB).GetArea() percentOfIntersection = areaOfIntersection/(fpB.GetArea()) return True,percentOfIntersection def getFPs(fpIn,IMAGE_IDS): '''SQLite of Foo...
fp = ogr.Open(fpIn,0) progress.setText(fpIn) fpLayer = fp.GetLayer(0) #assumes the footprints are the first layer newGeom = ogr.Geometry(type=ogr.wkbGeometryCollection) numFps = fpLayer.GetFeatureCount() IMAGE_IDS = IMAGE_IDS.encode('utf-8') # str is imported from future, sets type to newstr. ogr...
Perlence/wikigenre
wikigenre.py
Python
bsd-3-clause
6,223
0.000643
from __future__ import print_function import logging import re import sys from glob import iglob from os.path import join, dirname, normpath from gevent import monkey from gevent import spawn, joinall from gevent.event import AsyncResult monkey.patch_socket() monkey.patch_ssl() import requests from lxml import html ...
return oggvorbis.OggVorbis(track) elif track_lower.endswith('.mpc'): return musepack.Musepack(track) else: raise ValueError("unhandled format '%s'" % track) def wi
kigenre(track, force=False): track = normpath(track) try: audio = load_track(track) audio_genre = audio.get('genre') if audio_genre is not None and not force: logger.info('Skipping %s', track) else: artist = audio.get('artist', [None])[0] album...
percyfal/bokeh
bokeh/layouts.py
Python
bsd-3-clause
19,180
0.00245
''' Functions for arranging bokeh Layout objects. ''' #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import absolute_import from .core.enums import Location, SizingMode from .model...
zing_mode col_children.append(item) else: raise ValueError( """Only LayoutDOM items can be inserted into a column. Tried to insert: %s of type %s""" % (item, type(item)) ) return Column(children=col_children, sizing_mode=sizing_mode, **kwar...
zing_mode, which is required for complex layouts to work. Args: children (list of :class:`~bokeh.models.widgets.widget.Widget` ): A list of widgets for the WidgetBox. sizing_mode (``"fixed"``, ``"stretch_both"``, ``"scale_width"``, ``"scale_height"``, ``"scale_both"`` ): How wi...
jdodds/pyrana
pyrana/players/pygameplayer.py
Python
bsd-3-clause
1,508
0.006631
import pygame.event import pygame.mixer import pygame.display import threading import time from feather import Plugin ENDEVENT=42 class PyGamePlayer(Plugin): listeners = set(['songloaded', 'pause', 'skipsong', 'skipalbum']) messengers = set(['songstart', 'songpause', 'songend', 'songresume']) name = 'PyG...
time.sleep(0.1) def songloaded(self, payload): try: pygame.mixer.music.load(payload) except : pass pygame.mixer.music.play() self.playing = True self.send('songstart', payload) def pause(self, payload=None): if self.playi...
mixer.music.pause() self.playing = False self.send('songpause') else: pygame.mixer.music.unpause() self.playing = True self.send('songresume') def skipsong(self, payload=None): pygame.mixer.music.stop() def skipalbum(self, payload=Non...
EmanueleCannizzaro/scons
test/scons-time/help/options.py
Python
mit
2,071
0.004346
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # 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 us...
ALINGS IN THE SOFTWARE. # __revision__ = "test/scons-time/help/options.py rel
_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" """ Verify that the 'help' subcommand and -h, -? and --help options print the default help. """ import TestSCons_time test = TestSCons_time.TestSCons_time() expect = [ 'Usage: scons-time SUBCOMMAND [ARGUMENTS]\n', 'Type "scons-time help SUBCOMMAND" for ...
Sorrop/py-graph-algorithms
traversal_tests.py
Python
mit
1,800
0
import graph from depth_first_search import depth_first_search from breadth_first_search import breadth_first_search edges = [(0, 1), (0, 2), (0, 3), (1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9), (4, 10), (4, 11)] G, _ = graph.create_graph(edges) start_vertex = G.get_vertex(0) breadth = breadth_fi...
epth.depth_traversal: print((edge.endPoints()[0].element(), edge.endPoints()[1].element())) print(' ') print('=======
=======================') print('==============================') print(' ') edges = [('a', 'b'), ('c', 'a'), ('c', 'b'), ('d', 'c'), ('d', 'e'), ('b', 'e')] G, _ = graph.create_graph(edges, True) start_vertex = G.get_vertex('a') breadth = breadth_first_search(G) breadth...
FCP-INDI/nipype
nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py
Python
bsd-3-clause
2,377
0.027766
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ....testing import assert_equal from ..developer import JistBrainMgdmSegmentation def test_JistBrainMgdmSegmentation_inputs(): input_map = dict(args=dict(argstr='%s', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=di...
nMgdmS
egmentation.output_spec() for key, metadata in list(output_map.items()): for metakey, value in list(metadata.items()): yield assert_equal, getattr(outputs.traits()[key], metakey), value
schinckel/django-countries
django_countries/conf.py
Python
mit
2,772
0
import django.conf class AppSettings(object): """ A holder for app-specific default settings that allows overriding via the project's settings. """ def __getattribute__(self, attr): if attr == attr.upper(): try: return getattr(django.conf.settings, attr) ...
the following arguments: * code * code_upper For example: ``COUNTRIES_FLAG_URL = 'flags/16x10/{code_upper}.png'`` """ COUNTRIES_COMMON_NAMES = True """ Whether to use the common nam
es for some countries, as opposed to the official ISO name. Some examples: "Bolivia" instead of "Bolivia, Plurinational State of" "South Korea" instead of "Korea (the Republic of)" "Taiwan" instead of "Taiwan (Province of China)" """ COUNTRIES_OVERRIDE = {} """ A dictio...
eckardm/archivematica
src/MCPClient/lib/clientScripts/archivematicaCreateMETSRightsDspaceMDRef.py
Python
agpl-3.0
3,954
0.002529
#!/usr/bin/env python2 # # This file is part of Archivematica. # # Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com> # # Archivematica 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,...
etsLocation = os.path.join(os.path.dirname(itemdirectoryPath), "mets.xml") L
ABEL = "mets.xml-%s" % (metsFileUUID) ret.append(createMDRefDMDSec(LABEL, metsLocation, metsLoc)) base = os.path.dirname(os.path.dirname(itemdirectoryPath)) base2 = os.path.dirname(os.path.dirname(filePath)) for dir in os.listdir(base): fullDir = os.path.join(base, dir)...
nextgis-extra/tests
lib_gdal/gcore/pam.py
Python
gpl-2.0
18,275
0.007442
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # $Id: pam.py 33793 2016-03-26 13:02:07Z goatbar $ # # Project: GDAL/OGR Test Suite # Purpose: Test functioning of the PAM metadata support. # Author: Frank Warmerdam <warmerdam@pobox.com> #...
print(xml_md) return 'fail' return 'success' ############################################################################### # Verify that we can write XML to a new file. def pam_2(): driver = gdal.GetDriverByName( 'PNM' ) ds = driver.Create( 'tmp/pam.pnm', 10, 10 ) band = ds.GetRasterBand...
{ 'other' : 'red', 'key' : 'value' } ) expected_xml = """<?xml version="2.0"?> <TestXML>Value</TestXML> """ band.SetMetadata( [ expected_xml ], 'xml:test' ) band.SetNoDataValue( 100 ) ds = None return 'success' ############################################################################### # C...
threeaims/browserstep
browserstep/__init__.py
Python
mit
110
0
# -*- coding: utf-8 -*- __author__ = '
James Gardner' __email__ = 'james@pythonweb.org
' __version__ = '0.1.0'
darneymartin/ChartIT
src/View/Server.py
Python
mit
2,318
0.002157
from flask import Flask, render_template, session, redirect, url_for, escape, request from Model.Gateway.AuthenticationGateway import AuthenticationGateway from Controller.API.ServerController import ServerController from Controller.API.ChartController import ChartController from Controller.API.DataController import Da...
quest.method == 'POST': username = request.form['username'] password = request.form['password'] #Validate Credentials result = AuthenticationGateway().authenticate(username,passw
ord) if result is "true": session['username'] = username return redirect(url_for('index')) return render_template('login.html') @app.route('/logout') def logout(): # remove the username from the session if it's there session.pop('username', No...
samedder/azure-cli
src/azure-cli-core/azure/cli/core/tests/test_cloud.py
Python
mit
10,518
0.002377
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
ed = AZURE_PUBLIC_CLOUD.name actual = get_active_cloud_name() self.assertEqual(expected, actual) def test_known_cloud_missing_endpoint(self): # New endpoints in cloud config should be sav
ed in config for the known clouds with mock.patch('azure.cli.core.cloud.CLOUD_CONFIG_FILE', tempfile.mkstemp()[1]) as\ config_file: # Save the clouds to config to get started init_known_clouds() cloud = get_cloud(AZURE_PUBLIC_CLOUD.name) self.asser...
bswartz/cinder
cinder/tests/unit/api/contrib/test_qos_specs_manage.py
Python
apache-2.0
33,465
0
# Copyright 2013 eBay Inc. # Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LIC...
OT_BE_FOUND_ID: raise exception.QoSSpecsNotFound(specs_id=id) el
if id == fake.ACTION_FAILED_ID: raise exception.QoSSpecsAssociateFailed(specs_id=id, type_id=type_id) elif id == fake.ACTION2_FAILED_ID: raise exception.QoSSpecsDisassociateFailed(specs_id=id, type_id=...
andrewbird/wader
plugins/devices/huawei_k4505.py
Python
gpl-2.0
3,211
0.001558
# -*- coding: utf-8 -*- # Copyright (C) 2006-2011 Vodafone España, S.A. # Author: Andrew Bird # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your o...
ict from core.hardware.huawei import (HuaweiWCDMADevicePlugin, HuaweiWCDMACustomizer, HuaweiWCDMAWrapper, HUAWEI_BAND_DICT) class HuaweiK4505Wrapper(HuaweiWCDMAWrapper): """
:class:`~core.hardware.huawei.HuaweiWCDMAWrapper` for the K4505 """ def enable_radio(self, enable): """ Enables the radio according to ``enable`` It will not enable it if it's already enabled and viceversa """ def check_if_necessary(status): if (status == ...
lhfei/spark-in-action
spark-2.x/src/main/python/ml/count_vectorizer_example.py
Python
apache-2.0
1,595
0.000627
# # 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 u
nder 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 Lic...
HOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function from pyspark.sql import SparkSession # $example on$ from pyspark.ml.feature import CountVectoriz...
ygol/odoo
addons/l10n_fi/models/__init__.py
Python
agpl-3.0
156
0
# -*- coding:utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from . imp
ort account_journal from . import account_move
barentsen/dave
blsCode/yash_bls.py
Python
mit
17,107
0.0318
from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import clean_and_search from ktransit import FitTransit from multiprocessing import Pool from scipy import ndimage import glob, timeit, sys import time as pythonTime # OPTI...
on(period, rho, k) if not duration: duration = S.duration * 24 # Calculating transit depth significance ## fitT.transitmodel sometimes has a NaN value sigma = computePointSigma(time, flux, fitT.transitmodel, period, epoch, duration) depth = k ** 2 significance = depth / sigma phase = getPhase(time, flu...
NR = significance * nTransitPoints**0.5 return S
google/timesketch
timesketch/migrations/versions/654121a84a33_.py
Python
apache-2.0
3,278
0.014033
"""Add Graph and GraphCache models Revision ID: 654121a84a33 Revises: fc7bc5c66c63 Create Date: 2020-11-16 21:02:36.249989 """ # revision identifiers, used by Alembic. revision = '654121a84a33' down_revision = 'fc7bc5c66c63' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto gen...
me(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('sketch_id', sa.Integer(), nullable=True), sa.Column('graph_plugin', sa.UnicodeText
(), nullable=True), sa.Column('graph_config', sa.UnicodeText(), nullable=True), sa.Column('graph_elements', sa.UnicodeText(), nullable=True), sa.Column('num_nodes', sa.Integer(), nullable=True), sa.Column('num_edges', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['sketch_id'], ['sketch.id']...
arsenetar/dupeguru
core/pe/cache_sqlite.py
Python
gpl-3.0
5,161
0.001744
# Copyright 2016 Virgil Dupras # # This software is licensed under the "GPLv3" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.gnu.org/licenses/gpl-3.0.html import os import os.path as op import logging import sqlite3 as sqlite fro...
e import string_to_colors, colors_to_string c
lass SqliteCache: """A class to cache picture blocks in a sqlite backend.""" def __init__(self, db=":memory:", readonly=False): # readonly is not used in the sqlite version of the cache self.dbname = db self.con = None self._create_con() def __contains__(self, key): ...
any1m1c/ipc20161
lista2/ipc_lista2.16.py
Python
apache-2.0
824
0.01699
#EQUIPE 2 #Nahan Trindade Passos - 1615310021 #Ana Beatriz Frota - 1615310027 # # # # # # import math print("Digite os termos da equacao ax2+bx+c") a = float(input("Digite o valor de A:\n")) if(a
==0): print("Nao e uma equacao de segundo grau") else: b = float(input("Valor de B:\n")) c = float(input("Valor de C:\n")) delta = (math.pow(b,2) - (4*a*c)) if(delta<0): print("A equacao nao possui raizes reais") elif(delta == 0): raiz = ((-1)*b + math.
sqrt(delta))/(2*a) print("A equacao possui apenas uma raiz",raiz) else: raiz1 = ((-1)*b + math.sqrt(delta))/(2*a) raiz2 = ((-1)*b - math.sqrt(delta))/(2*a) print("A equacao possui duas raizes") print("Primeira raiz:",raiz1) print("Segunda raiz:",raiz2) ...
googleapis/python-dialogflow
google/cloud/dialogflow_v2/services/session_entity_types/transports/grpc.py
Python
apache-2.0
18,035
0.002384
# -*- coding: utf-8 -*- # Copyright 2022 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...
r_mtls and not ssl_
channel_credentials: cert, key = client_cert_source_for_mtls() self._ssl_channel_credentials = grpc.ssl_channel_credentials( certificate_chain=cert, private_key=key ) # The base transport sets the host, credentials and scopes ...
jairideout/qiime2
qiime2/sdk/tests/test_artifact.py
Python
bsd-3-clause
17,709
0
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2017, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
test_load_and_save(self): fp1 = os.path.join(self.test_dir.name, 'artifact1.qza') fp2 = os.path.join(self.test_dir.na
me, 'artifact2.qza') artifact = Artifact.import_data(FourInts, [-1, 42, 0, 43]) artifact.save(fp1) artifact = Artifact.load(fp1) # Overwriting its source file works. artifact.save(fp1) # Saving to a new file works. artifact.save(fp2) root_dir = str(artif...
ramansbach/cluster_analysis
clustering/scripts/old-scripts/clustering_temp.py
Python
mit
73,255
0.011958
from __future__ import absolute_import, division, print_function import numpy as np import pandas as pd import gsd.hoomd import sklearn import scipy.optimize as opt import os import os.path import pdb from sklearn.neighbors import BallTree from sklearn.neighbors import radius_neighbors_graph from scipy.spatial.distanc...
lrng: a new graph """ dim = np.shape(molrng)[0] sz = np.shape(rng) rng = rng.reshape((1,sz[0]
*sz[1]))[0] molrng = molrng.reshape((1,dim*dim))[0] for i in range(dim): for j in range(i+1,dim): istart = apermol*i; iend = apermol*(i+1); jstart = apermol*j; jend = apermol*(j+1); curr = 0; #pdb.set_trace() for k in ...
alanjds/drf-nested-routers
tests/urls.py
Python
apache-2.0
105
0
from tests.serialize
rs.urls import urlpatterns as serializ
ers_urls urlpatterns = [ ] + serializers_urls