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
welex91/ansible-modules-core
network/nxos/nxos_facts.py
Python
gpl-3.0
7,749
0.000645
#!/usr/bin/python # # 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) any later version. # # Ansible is distribut...
gument_spec = dict() module = get_module(argument_spec=argument_spec, supports_check_mode=True) # Get 'show version' facts. show_version = get_show_version_facts(module) # Get interfaces facts. interfaces_list = get_interface_facts(module) # Get module facts. show_...
. powersupply, fan = get_environment_facts(module) # Get vlans facts. vlan = get_vlan_facts(module) facts = dict( interfaces_list=interfaces_list, module=show_module, power_supply_info=powersupply, fan_info=fan, vlan_list=vlan) facts.update(show_version) ...
c24b/mango
database.py
Python
apache-2.0
5,004
0.034579
#!/usr/bin/env python # -*- coding: utf-8 -*- import pymongo from pymongo import MongoClient from pymongo import errors import re class Database(object): '''Database creation''' def __init__(self, database_name): self.client = MongoClient('mongodb://localhost,localhost:27017') self.db_name = database_name sel...
ources'] #self.jobs = self.db['jobs'] #self.db.x = self.db[x] # def __repr__(self, database_name): # print "Using database: %s" %self.client[database
_name] # return self.db def use_db(self, database_name): return self.client[str(name)] def show_dbs(self): return self.client.database_names() def create_coll(self, coll_name): setattr(self, str(coll_name), self.db[str(coll_name)]) #print "coll : %s has been created in db:%s " %(self.__dict__[str(coll_n...
ccauet/scikit-optimize
skopt/space/space.py
Python
bsd-3-clause
21,426
0.000047
import numbers import numpy as np from scipy.stats.distributions import randint from scipy.stats.distributions import rv_discrete from scipy.stats.distributions import uniform from sklearn.utils import check_random_state from sklearn.utils.fixes import sp_version from .transformers import CategoricalEncoder from .tr...
X): """Transform samples form the original space to a warped space.""" return self.transformer.transform(X) def inverse_transform(self, Xt): """Inverse transform
samples from the warped space back into the original space. """ return self.transformer.inverse_transform(Xt) @property def size(self): return 1 @property def transformed_size(self): return 1 @property def bounds(self): raise NotImplementedEr...
azumimuo/family-xbmc-addon
plugin.video.salts/scrapers/filmikz_scraper.py
Python
gpl-2.0
4,359
0.004818
""" SALTS XBMC Addon Copyright (C) 2014 tknorris 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. T...
ity': None, 'views': None, '
rating': None, 'direct': False} hoster['host'] = urlparse.urlsplit(hoster['url']).hostname # top list is HD, bottom list is SD if hoster['host'] in seen_hosts: quality = QUALITIES.HIGH else: quality = QUALITIES.HD720...
pombredanne/taskflow-1
taskflow/utils/misc.py
Python
apache-2.0
20,033
0.00005
# -*- coding: utf-8 -*- # Copyright (C) 2012 Yahoo! Inc. All Rights Reserved. # Copyright (C) 2013 Rackspace Hosting 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 ...
the found needles (if any). The ordering of the
returned needles is in the order they are located in the haystack. Example input and output: >>> from taskflow.utils import misc >>> hay = [3, 2, 1] >>> misc.look_for(hay, [1, 2]) [2, 1] """ if not haystack: return [] if extractor is None: extractor = lambda v: v ...
jumpstarter-io/cinder
cinder/volume/drivers/emc/emc_vmax_common.py
Python
apache-2.0
94,140
0
# Copyright (c) 2012 - 2014 EMC Corporation. # 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 # # Unle...
"Size: %(size
)lu " % {'volume': volumeName, 'pool': poolInstanceName, 'storageSystem': storageSystemName, 'size': volumeSize}) elementCompositionService = ( self.utils.find_element_composition_service(self.conn, ...
batxes/4Cin
SHH_WT_models/SHH_WT_models_final_output_0.1_-0.1_11000/mtx1_models/SHH_WT_models11760.py
Python
gpl-3.0
17,567
0.025104
import _surface import chimera try: import chimera.runCommand except: pass from VolumePath import markerset as ms try: from VolumePath import Marker_Set, Link new_marker_set=Marker_Set except: from VolumePath import volume_path_dialog d= volume_path_dialog(True) new_marker_set= d.new_marker_set marker_set...
rticle_9 geometry"]=s s= marker_sets["particle_9 geometry"] mark=s.place_marker((1293.
54, 4153.85, 4133.28), (1, 0.7, 0), 821.043) if "particle_10 geometry" not in marker_sets: s=new_marker_set('particle_10 geometry') marker_sets["particle_10 geometry"]=s s= marker_sets["particle_10 geometry"] mark=s.place_marker((2094.48, 3469.18, 5691.58), (0.7, 0.7, 0.7), 873.876) if "particle_11 geometry" not in...
efiop/dvc
tests/unit/ui/test_pager.py
Python
apache-2.0
2,747
0
import pytest from dvc.env import DVC_PAGER from dvc.ui.pager import ( DEFAULT_PAGER, LESS, PAGER_ENV, find_pager, make_pager, pager, ) @pytest.fixture(autouse=True) def clear_envs(monkeypatch): monkeypatch.delenv(DVC_PAGER, raising=False) monkeypatch.delenv(PAGER_ENV, raising=False) ...
_value=True) assert find_pager() == "my-pager" def test_find_pager_uses_custom_pager_when_pager_env_is_defined( mocker, monkeypatch ): monkeypatch.setenv(PAGER_ENV, "my-pager") mocker.patch("sys.stdout.isatty", return_value=True) assert find_pager() == "my-pager" def test_find_pager_uses_defau...
in find_pager() def test_find_pager_fails_to_find_any_pager(mocker): mocker.patch("os.system", return_value=1) mocker.patch("sys.stdout.isatty", return_value=True) assert find_pager() is None @pytest.mark.parametrize("env", [DVC_PAGER, PAGER_ENV, None]) def test_dvc_sets_default_options_on_less_withou...
Mirantis/solar
solar/utils.py
Python
apache-2.0
3,496
0
# Copyright 2015 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 ...
_FILE = os.environ.get('CONFIG_FILE') or '/vagrant/config.yaml' return load_file(CONFIG_FILE) def read_config_file(key): fpath = read_config()[key] return load_file(fpath) def save_to_config_file(key, data): fpath = read_config()[key] with open(fpath, 'w') as f: encoder = ext_encoder(f...
ing return threading.local
manashmndl/dfvfs
tests/path/ewf_path_spec.py
Python
apache-2.0
1,121
0.005352
#!/usr/bin/python # -*- coding: utf-8 -*- """Tests for the EWF image path specification implementation.""" import unittest from dfvfs.path import ewf_path_spec from tests.path import test_lib class EwfPathSpecTest(test_lib.PathSpecTestCase): """Tests for the EWF image path specification implementation.""" def...
(parent=self._path_spec) self.assertNotEqual(path_spec, None) expected_comparab
le = u'\n'.join([ u'type: TEST', u'type: EWF', u'']) self.assertEqual(path_spec.comparable, expected_comparable) if __name__ == '__main__': unittest.main()
iModels/mbuild
mbuild/formats/vasp.py
Python
mit
2,953
0
"""VASP POSCAR format.""" import numpy as np __all__ = ["write_poscar"] def write_poscar( compound, filename, lattice_constant, bravais=[[1, 0, 0], [0, 1, 0], [0, 0, 1]], sel_dev=False, coord="cartesian", ): """Write a VASP POSCAR file from a Compound. See //https://www.vasp.at formo...
toms]) count_list = list() xyz_list = list() if coord == "direct": for atom in structure.atoms: atom.xx = atom.xx / lattice_constant atom.xy = atom.xy / lattice_constant atom.xz = atom.xz / lattice_constant for atom_name in atom_names: atom_count = n...
t) xyz = np.array( [ [atom.xx, atom.xy, atom.xz] for atom in structure.atoms if atom.name == atom_name ] ) xyz = xyz / 10 # unit conversion from angstroms to nm xyz_list.append(xyz) with open(filename, "w") as ...
hgranlund/py-chess-engine
pavement.py
Python
mit
7,367
0.000814
# -*- coding: utf-8 -*- from __future__ import print_function import os import sys import time import subprocess # Import parameters from the setup file. sys.path.append('.') from setup import ( setup_dict, get_project_files, print_success_message, print_failure_message, _lint, _test, _test_all, CODE_DIR...
stemExit(1) import pytest pytest.main(PYTEST_FLAGS + [ '--cov', CODE_DIRECTORY, '--cov-report', 'te
rm-missing', TESTS_DIRECTORY]) @task # NOQA def doc_watch(): """Watch for changes in the docs and rebuild HTML docs when changed.""" try: from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer except ImportError: print_failure_message('I...
skkwan/IC10X2
palomar/TSpec_reductions/TSpec basic plot.py
Python
mit
2,508
0.05303
# -*- coding: utf-8 -*- """ Created on Mon Aug 1 17:14:20 2016 @author: stephaniekwan Plot prominent emission lines of IC 10 X-2 from TripleSpec chop-subtracted data. He I and Pa-Gamma lines fit on one plot, Pa-Beta line goes in a separate plot (comment/uncomment blocks to plot each set). """ import numpy as np im...
co
mments = '\p', skip_header = 2, skip_footer = 4) wl = table[:, 0] - 0.0005 counts = table[:, 1] fig = plt.figure() normFlux = counts / 0.024 # Two subplots, unpack the axes array immediately f, (ax1, ax2) = plt.subplots(1,2, sharey = True) ax1.plot(wl[7100:7500], normFlux[7100:7500], color = 'black') ax1.invert_xa...
ros2/launch
launch/doc/source/conf.py
Python
apache-2.0
6,246
0
# Copyright 2018 Open Source Robotics Foundation, 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...
ges', ] # autodoc settings autodoc_default_options = { 'special-members': '__init__', 'class-doc-from': 'class', } autodoc_class_signature
= 'separated' # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'i...
stdweird/aquilon
lib/python2.6/aquilon/worker/anonwrappers.py
Python
apache-2.0
2,216
0.000451
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Licens
e. # 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...
and # limitations under the License. """Provide an anonymous access channel to the Site.""" from twisted.web import server, http class AnonHTTPChannel(http.HTTPChannel): """ This adds getPrincipal() to the base channel. Since there is no knc in use here, it just returns None. """ def getPrinc...
hsoft/aurdiff
update.py
Python
bsd-3-clause
2,337
0.003851
# Copyright 2013 Virgil Dupras (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. import os.path as op from urllib.request import urlopen import subprocess import json from bs4 import BeautifulSoup HERE =...
gh urlopen, we don't have the checkbox column. Is # this column added through JS? pair = (row('td')[1].text, row('td')[2].text) result.append(pair) return result def download_pkgbuild(pkgname): URL = '%s/packages/%s/' % (BASE_URL, pkgname) with urlopen(URL) as fp: contents =...
kgbuild_url = BASE_URL + soup('div', id='actionlist')[0].ul('li')[0].a['href'] with urlopen(pkgbuild_url) as fp: contents = fp.read() with open(op.join(AUR_FOLDER, pkgname), 'wb') as fp: fp.write(contents) def main(): json_path = op.join(HERE, 'lastupdate.json') with open(json_path, 'rt...
Chasego/cod
lintcode/268-[DUP]-Find-the-Missing-Number/FindtheMissingNumber_001.py
Python
mit
209
0
clas
s Solution: # @param nums: a list of integers # @return: an integer def findMissing(self, nums): # write your code here n = len(nums) return n * (n + 1) / 2 - sum(n
ums)
jkandasa/integration_tests
cfme/services/catalogs/ansible_catalog_item.py
Python
gpl-2.0
16,192
0.002347
f
rom navmazing import NavigateToAttribute, NavigateToSibling from widgetastic.utils import (Parameter, ParametrizedLocator, ParametrizedString, Version, VersionPick) from widgetastic.widget import Checkbox, T
able, Text, View from widgetastic_manageiq import FileInput, SummaryForm, SummaryTable from widgetastic_patternfly import ( BootstrapSelect as VanillaBootstrapSelect, BootstrapSwitch, Button, Input, Tab ) from cfme.services.catalogs.catalog_item import AllCatalogItemView from cfme.utils.appliance i...
appuio/ansible-role-openshift-zabbix-monitoring
vendor/ansible-module-openshift/library/openshift_resource.py
Python
apache-2.0
9,578
0.01493
#!/usr/bin/python import json import tempfile import re import traceback DOCUMENTATION = ''' --- module: openshift_resource short_description: Creates and patches OpenShift resources. description: - Creates and patches OpenShift resources idempotently - based on template or strategic merge patch. options: names...
t: None aliases: [] patch: description: - Strategic merge patch to apply - Mutually exclusive with I(template) required: false default: None aliases: [] author: - "Daniel Tschan <tschan@puzzle.ch>" extends_documentation_fragment: [] ''' EXAMPLES = ''' # TODO ''' class ResourceModule: d...
og = [] self.arguments = [] for key in module.params: setattr(self, key, module.params[key]) def debug(self, msg, *args): if self.module._verbosity >= 3: self.log.append(msg % args) def trace(self, msg, *args): if self.module._verbosity >= 4: self.log.append(msg % args) de...
jhdulaney/dnf
tests/support.py
Python
gpl-2.0
20,691
0.000242
# -*- coding: utf-8 -*- # Copyright (C) 2012-2018 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License
v.2, or (at your option) any later version. # This program is distributed i
n the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this prog...
Hakuba/youtube-dl
youtube_dl/version.py
Python
unlicense
68
0
from
__future__ import unicode_literals __version__ = '2016.0
1.09'
testmana2/test
Plugins/VcsPlugins/vcsMercurial/HgCopyDialog.py
Python
gpl-3.0
2,379
0.004203
# -*- coding: utf-8 -*- # Copyright (c) 2010 - 2015 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing a dialog to enter the data for a copy or rename operation. """ from __future__ import unicode_literals import os.path from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QDialog, QDia...
Picker.text() if not os.path.isabs(target): sourceDir = os.path.dirname(self.sourceEdit.text
()) target = os.path.join(sourceDir, target) return target, self.forceCheckBox.isChecked() @pyqtSlot(str) def on_targetPicker_textChanged(self, txt): """ Private slot to handle changes of the target. @param txt contents of the target edit (string) ...
seaglex/garden
learn_theano/tradition/lr.py
Python
gpl-3.0
5,860
0.003413
import numpy as np import theano import theano.tensor as T import pickle import timeit import os.path import sys class MultiNomialLR(object): def __init__(self, in_dim, out_dim): self.W = theano.shared( np.zeros((out_dim, in_dim), dtype=np.float64), name="W", borrow=True...
for i in range(n_valid_batches)] this_validation_loss = np.mean(validation_losses) print( 'epoch %i, minibatch %i/%i, validation error %f %% (%f)' % ( epoch, mi...
_train_batches, this_validation_loss * 100.0, minibatch_avg_cost ) ) # if we got the best validation score until now if this_validation_loss < best_validation_loss: ...
nayas360/pyterm
bin/cat.py
Python
mit
1,001
0
# type command prints file contents from lib.utils import * def _help(): usage = ''' Usage: cat (file) Print content of (file) Use '%' in front of global vars to use value as file name. ''' print(usage) def main(argv): if len(argv) < 1 or '-h' in argv: _help() return # The shell d...
not required anymore. # argv=replace_vars(argv) argv = make_s(argv) path = get_path() + argv if os.path.isfile(path): with open(path) as f: data = f.readlines() print('_________________<START>_________________\n') print(make_s2(data)) print('_________________...
err(2, path)
ProjectIDA/ical
gui/analysis_progress_window.py
Python
gpl-3.0
4,458
0.005384
####################################################################################################################### # Copyright (C) 2016 Regents of the University of California # # This is free software: you can redistribute it and/or modify it under the terms of the # GNU General Public License (GNU GPL) as publi...
ore.QSize(312, 130)) AnalysisProgressFrm.setMaximumSize(QtCore.QSize(312, 130)) self.progPB = QtWidgets.QProgressBar(AnalysisProgressFrm) self.progPB.setGeometry(QtCore.QRect(20, 60, 272, 23)) self.progPB.setMaximum(0) self.progPB.setProperty("value", -1) self.progPB.setO...
ets.QLabel(AnalysisProgressFrm) self.calDescrLbl.setGeometry(QtCore.QRect(20, 10, 271, 21)) font = QtGui.QFont() font.setFamily("Helvetica Neue") font.setPointSize(14) font.setBold(True) font.setWeight(75) self.calDescrLbl.setFont(font) self.calDescrLbl.se...
googleapis/python-dialogflow-cx
samples/generated_samples/dialogflow_v3_generated_entity_types_list_entity_types_sync.py
Python
apache-2.0
1,518
0.000659
# -*- 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...
he latest published package dependency, execute the following: # python3 -m pip install google-cloud-dialogflowcx # [START dialogflow_v3_generated_EntityTypes_ListEntityTypes_sync] from google.cloud import dialogflowcx_v3 def sample_list_entity_types(): # Create a client client = dialogflowcx_v3.EntityTyp...
ent_value", ) # Make the request page_result = client.list_entity_types(request=request) # Handle the response for response in page_result: print(response) # [END dialogflow_v3_generated_EntityTypes_ListEntityTypes_sync]
activitycentral/ebookreader
src/ReadTab/epubadapter.py
Python
gpl-2.0
17,071
0.002285
from gi.repository import Gtk import os from gi.repository import GObject import shutil from decimal import * from gettext import gettext as _ from documentviewercommonutils import DocumentViewerCommonUtils from utils import is_machine_a_xo from epubview.epub import _Epub from epubview.webkitbackend import Browser TO...
._resume_characteristics_done is True: self._new_file_loaded = True def do_view_specific_sync_operations(self): self.__sync_in_case_internal_bookmarks_are_navigated() self.__update_percentage_of_document_completed_reading() # Always keep calling this function, as this is a ...
_bookmarks_are_navigated(self): if self._new_file_loaded is False: return if self._new_file_loaded is False: return uri_to_test = self.get_currently_loaded_uri() if uri_to_test == self._current_uri: return # Sometimes, the URI could be None ...
agati/chimera
src/chimera/instruments/sk/tests/skdrv_OK_25062015.py
Python
gpl-2.0
8,467
0.006614
#! /usr/bin/env python # -*- coding: iso-8859-1 -*- # Copyright (C) 2006-2015 chimera - observatory automation system # 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 Li...
arm_change.append('parm9') print "*****************************" #check parm30 parm30 = self.read_parm("00.30") print "parm30=",parm30 ra
mp_mode = self.__config__['ramp_mode'] print "ramp_mode=", ramp_mode if parm30 == ramp_mode: print "parm30 ok" else: print "parm30 with parm_change" parm_change.append('parm30') print "*****************************" #check parm32 parm3...
QiJune/Paddle
python/paddle/dataset/tests/flowers_test.py
Python
apache-2.0
1,707
0.000586
# Copyright (c) 2016 PaddlePaddle 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 applic...
uted 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. from __future__ import print_function import paddle.dataset.flowers import unittest class TestFlowers(unittest.T...
e): def check_reader(self, reader): sum = 0 label = 0 size = 224 * 224 * 3 for l in reader(): self.assertEqual(l[0].size, size) if l[1] > label: label = l[1] sum += 1 return sum, label def test_train(self): inst...
mjcollin/ibm_bladecenter
bc_boot_revert.py
Python
mit
393
0
#!/usr/bin/python import sys import lib.ssh_helper as ssh host = sys.argv[1] blade = sys.argv[2] pw = ssh.prompt_password(host) chan, sess = ssh.get_channel(host, pw) # Eat the initial welcome text ssh.get_output(chan) ssh.run(chan, 'tcpcmdmode
-t 3600 -T system:mm[0]') ssh.run(chan, 'env -T system:blade[' + blade + ']') ssh.run(chan, 'bootseq cd usb hd0 nw') chan.close() sess.clos
e()
bossiernesto/melta
test/transactions/test_transactional.py
Python
bsd-3-clause
1,365
0.002198
from unittest import TestCase from melta.transactions.transactional import Transaction class TransactionTestClass(Transaction): def __init__(self): self.plant_type = 'Pointisera' self.plant_age = 3 self.plant_pot = 'plastic' self.combination = 'one\ntwo\nthree' class Transactiona...
another_combination = 'one\nnine\nfive' new_combination = 'one\nnine\nthree' self.test_plant.combination = new_combination self.test_plant.commit() self.assertEqual(self.test_plant.combination, new_combination) self.t
est_plant.start() self.test_plant.combination = another_combination self.test_plant.rollback() self.assertEqual(self.test_plant.combination, new_combination)
bitmazk/django-hero-slider
hero_slider/south_migrations/0001_initial.py
Python
mit
9,348
0.007916
# flake8: noqa # -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'SliderItem' db.create_table('hero_slider_slideritem', ( ('id', se...
, 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {
'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email':...
vizcacha/practicalcv
chapter_10/find-black-pieces.py
Python
mit
426
0.002347
from SimpleCV import Image import time # Get the template and image goBoard = Image('go.png') black = Image('g
o-black.png') black.show() time.sleep(3) goBoard.show() time.sleep(3) # Find the matches and draw them matches = goBoard.findTemplate(black) matches.draw() # S
how the board with matches print the number goBoard.show() print str(len(matches)) + " matches found." # Should output: 9 matches found. time.sleep(3)
lkash/test
dpkt/tns.py
Python
bsd-3-clause
1,079
0.000927
# $Id: tns.py 23 2006-11-08 15:45:33Z dugsong $ # -*- coding: utf-8 -*- """Transparent Network Substrate.""" import dpkt class TNS(dpkt.Packet): __hdr__ = ( ('length', 'H', 0), ('pktsum', 'H', 0), ('type', 'B', 0), ('rsvd', 'B', 0), ('hdrsum', 'H', 0), ('msg', '0s'...
'\xff\x4f\x98\x00\x00\x00\x01\x00\x01\x00\x22\x00\x00\x00\x00\x01\x01X') t = TNS(s) assert t.msg.startswith('\x01\x34') # test a truncated packet try: t = TNS(s[:-1
0]) except dpkt.NeedData: pass if __name__ == '__main__': test_tns() print 'Tests Successful...'
polltooh/FineGrainedAction
nn/cal_accuracy_v3.py
Python
mit
2,845
0.003866
#! /usr/bin/env python import utility_function as uf import sys import cv2 import numpy as np def read_file_list(file_name): # assume the first argument is the image name and the second one is the label name_list = list() label_list = list() with open(file_name, "r") as f: s = f.read()
s = uf.delete_last_empty_line(s) s_l = s.split(
"\n") for ss in s_l: ss_l = ss.split(" ") assert(len(ss_l) == 2) name_list.append(ss_l[0]) label_list.append(int((ss_l[1]))) return name_list, label_list def read_label(label_file): with open(label_file, "r") as f: s = f.read(); s = uf.de...
doerlbh/Indie-nextflu
augur/src/virus_clean.py
Python
agpl-3.0
3,403
0.033206
# clean sequences after alignment, criteria based on sequences # make inline with canonical ordering (no extra gaps) import os, datetime, time, re from itertools import izip from Bio.Align import MultipleSeqAlignment from Bio.Seq import Seq from scipy import stats import numpy as np class virus_clean(object): """doc...
residuals = slope*times + intercept - distances r_iqd = stats.scoreatpercentile(residuals,75) - stats.scoreatpercentile(residuals,25) if self.verbose: print "\tslope: " + str(slope) print "\tr: " + str(r_value) print "\tresidual
s iqd: " + str(r_iqd) new_viruses = [] for (v,r) in izip(self.viruses,residuals): # filter viruses more than n_std standard devitations up or down if np.abs(r)<self.n_iqd * r_iqd or v.id == self.outgroup["strain"]: new_viruses.append(v) else: if self.verbose>1: print "\t\tresidual:", r, "\nrem...
ilogue/niprov
tests/test_add.py
Python
bsd-3-clause
7,954
0.001886
import unittest, os from mock import Mock, patch, call, sentinel from tests.ditest import DependencyInjectionTestBase class AddTests(DependencyInjectionTestBase): def setUp(self): super(AddTests, self).setUp() self.config.dryrun = False self.repo.byLocation.return_value = None sel...
ing(), out.provenance['parents'][0]) self.assertEqual(True, out.provenance['copy-as-parent']) def test_If_only_copy_is_same_location_ignores_it(self): self.img.provenance = {} self.query.copiesOf.return_value = [self.img] out = self.add('p/afile.f') assert not self.inheritFr...
AsParent.called self.assertNotIn('parents', out.provenance) self.assertNotIn('copy-as-parent', out.provenance) def test_Adds_niprov_version(self): with patch('niprov.adding.pkg_resources') as pkgres: dist = Mock() dist.version = '5.4.1' pkgres.get_distrib...
unlessbamboo/grocery-shop
language/python/src/command-line/argv-test.py
Python
gpl-3.0
347
0.006645
#!/usr/bin/env python #coding:utf-8 ## # @file argv-test.py # @brief # 最底层的命令行解析,其他模块应该都是对其
的封装 # @author unlessbamboo # @version 1.0 # @date 2016-03-03 import sys def testSys(): """testSys""" for arg in sy
s.argv[1:]: print (arg) if __name__ == '__main__': testSys()
turbokongen/home-assistant
homeassistant/components/aemet/__init__.py
Python
apache-2.0
1,866
0.002144
"""The AEMET OpenData component.""" impo
rt asyncio import logging from aemet_opendata.interface import AEMET from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF
_NAME from homeassistant.core import HomeAssistant from .const import COMPONENTS, DOMAIN, ENTRY_NAME, ENTRY_WEATHER_COORDINATOR from .weather_update_coordinator import WeatherUpdateCoordinator _LOGGER = logging.getLogger(__name__) async def async_setup(hass: HomeAssistant, config: dict) -> bool: """Set up the A...
vonkarmaninstitute/FreePC
server/restriction_system/utils.py
Python
gpl-3.0
5,215
0.025503
# This file is part of FreePC. # # FreePC 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. # # FreePC 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 FreePC. If not, see <http://www.gnu.org/lic...
stackArmor/security_monkey
security_monkey/auditors/vpc/vpc.py
Python
apache-2.0
1,852
0
# Copyright 2016 Bridgewater Associates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
curity_monkey.auditor import Auditor from security_monkey.watchers.vpc.vpc import VPC from security_monkey.watchers.vpc.flow_log import FlowLog class VPCAuditor(Auditor): index = VPC.index i_am_singular = VPC.i_am_singular i_am_plural = VPC.i_am_plural support_watcher_indexes = [FlowLog.index] de...
debug=False): super(VPCAuditor, self).__init__(accounts=accounts, debug=debug) def check_flow_logs_enabled(self, vpc_item): """ alert when flow logs are not enabled for VPC """ flow_log_items = self.get_watcher_support_items( FlowLog.index, vpc_item.account) ...
kz26/uchicago-hvz
uchicagohvz/game/dorm_migrations/0001_initial.py
Python
mit
11,763
0.003996
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import mptt.fields import uchicagohvz.overwrite_fs from django.conf import settings import django.utils.timezone import uchicagohvz.game.models class Migration(migrations.Migratio...
), migrations.CreateModel( name='Game',
fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=255)), ('registration_date', models.DateTimeField()), ('start_date', models.DateTimeField()), ...
akosyakov/intellij-community
python/testData/copyPaste/singleLine/IndentOnTopLevel.after.py
Python
apache-2.0
83
0.024096
class C: def foo(self): x = 1
y = 2 x = 1 def foo()
: pass
a2ohm/picsou
sub/status.py
Python
gpl-3.0
1,333
0.003751
#! /usr/bin/python3 # -*- coding:utf-8 -*- """ Define the "status" sub-command. """ from lib.transaction import * from lib.color import color import sys import yaml def status(conf, args): """Print staging transactions. """ if not conf: # The account book is not inited print("There is n...
ge) == 1: print("A transaction is waiting to be comited.") else: print("Some transactions are waiting to be comited.") # List transactions to be commited transactions = \ [transaction._make(map(t.get, transaction._fields)) for t in stage]...
nsactions print() printTransactions(transactions) else: print("Nothing to commit.") sys.exit()
dkm/skylines
skylines/tests/test_gjslint.py
Python
agpl-3.0
1,110
0
import os import sys import nose from subprocess import Ca
lledProcessError, check_output as run from functools import partial GJSLINT_COMMAND = 'gjslint' GJSLINT_OPTIONS = ['--strict'] JS_BASE_FOLDER = os.path.join('skylines', 'public', 'js') JS_FILES = [ 'baro.js', 'fix-table.js', 'flight.js', 'general.js', 'map.js', 'phase-table.js', 'topbar....
f.description = 'gjslint {}'.format(filename) yield f def run_gjslint(filename): path = os.path.join(JS_BASE_FOLDER, filename) args = [GJSLINT_COMMAND] args.extend(GJSLINT_OPTIONS) args.append(path) try: run(args) except CalledProcessError, e: print e.output r...
rtrembecky/roots
problems/migrations/0001_initial.py
Python
mit
12,637
0.00459
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import downloads.models import base.storage import base.models from django.conf import settings import problems.models import sortedm2m.fields class Migration(migrations.Migration): dependencies = [ ...
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=50, verbose_name='name')), ('competition', models.ForeignKey(verbose_name='competition', to='competitions.Competition', help_text='The r...
], options={ 'ordering': ['name'], 'verbose_name': 'category', 'verbose_name_plural': 'categories', }, bases=(models.Model,), ), migrations.CreateModel( name='ProblemInSet', fields=[ ...
Calvinxc1/neural_nets
Controller.py
Python
gpl-3.0
7,833
0.010596
#%% Libraries: Built-In from copy import deepcopy as copy import pandas as pd import numpy as np from datetime import datetime as dt from datetime import timedelta as td #% Libraries: Custom from Clusters.Data import DataCluster from Clusters.ClusterGroup import ClusterGroup #%% class NetworkController(object): def...
del_error()[self.train_split] valid_error = self.model_error()[self.valid_split] print('\r %s completed epoc %s in %s sec.\tTrain
Error: %s.\tValid Error:%s' % (self.control_name, self.epocs, round(run_seconds, 1), train_error, valid_error), end = '') def epoc_network(self, learn_weight = 1e-0): self.get_data_cluster().send_forward() self.error_record.append(self.model_error()) self.get_data_cluster().send_backpr...
amlannayak/apollo
src/mic_test.py
Python
gpl-3.0
521
0.015355
import speech_recognition as sr # Obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: print("Say something!") au
dio = r.listen(source, phrase_time_limit=5) # Recognize using w
it.ai WIT_AI_KEY = "GP3LO2LIQ2Y4OSKOXZN6OAOONB55ZLN5" try: print("wit.ai thinks you said " + r.recognize_wit(audio, key=WIT_AI_KEY)) except sr.UnknownValueError: print("wit.ai could not understand audio") except sr.RequestError as e: print("Could not request results from wit.ai servicel {0}".format(e))
messagebird/python-rest-api
examples/voice_message_create.py
Python
bsd-2-clause
1,444
0.018006
#!/usr/bin/env python import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import messagebird ACCESS_KEY = 'test_gshuPaZoeEG6ovbc8M79w0QyM' try: # Create a MessageBird client with the specified ACCESS_KEY. client = messagebird.Client(ACCESS_KEY) # Send a new voice message. vmsg = c...
: %s' % vmsg.language) print(' voice : %s' % vmsg.voice) print(' repeat : %s' % vmsg.repeat) print(' ifMachine : %s' % vmsg.ifMachine) print(' scheduledDatetime : %s' % vmsg.scheduledDatetime) print(' createdDatetime : %s' % vm
sg.createdDatetime) print(' recipients : %s\n' % vmsg.recipients) except messagebird.client.ErrorException as e: print('\nAn error occured while requesting a VoiceMessage object:\n') for error in e.errors: print(' code : %d' % error.code) print(' description : %s' % error.description) ...
pkg-ime/ibus-anthy
setup/anthyprefs.py
Python
gpl-2.0
30,030
0.01582
# -*- coding: utf-8 -*- # vim:set noet ts=4: # # ibus-anthy - The Anthy engine for IBus # # Copyright (c) 2007-2008 Peng Huang <shawn.p.huang@gmail.com> # Copyright (c) 2009 Hideaki ABE <abe.sendai@gmail.com> # Copyright (c) 2007-2011 Red Hat, Inc. # # This program is free software; you can redistribute it and/or modif...
= 'engine/anthy' def __init__(self, bus=None, config=None): super(AnthyPrefs, self).__init__(bus, config) self.default = _config # The keys will be EOSL in the near future. self.__update_key ("common", "behivior_on_focus_out", ...
behivior_on_period", "behavior_on_period") self.fetch_all() def __update_key (self, section, old_key, new_key): file = __file__ if __file__.find('/') >= 0: file = __file__[__file__.rindex('/') + 1:] warning_message = \ "(" + file + ...
testvidya11/ejrf
questionnaire/migrations/0025_auto__add_field_questiongroup_allow_multiples.py
Python
bsd-3-clause
17,416
0.007407
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'QuestionGroup.allow_multiples' db.add_column(u'questionnaire_questiongroup', 'allow_multiple...
'Meta': {'object_name': 'Comment'}, 'answer_group': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'comments'", 'symmetrical': 'False', 'to': "orm['questionnaire.AnswerGroup']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.d...
: 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '100'}), ...
infectiious/Pharaoh_script
Markets/KuCoin/kucoin_api.py
Python
mit
1,648
0.01517
#!/usr/bin/env python3 import argparse import requests import time import datetime import random # import pymysql from connections import hostname, u
sername, password, portnumber, database class MarketKuCoin(object): # Set variables for API String. domain = "https://api.kucoin.com" url = "" uri = "" # Function to build API string. def __init__(self, uri, name, market):
super(MarketKuCoin, self).__init__() self.name = name self.uri = uri self.url = self.domain + uri self.market = market dbstr = market.lower() + "_" + name.lower() # Function to query API string and write to mysql database. def update_data(self): # db = pymysql...
ellisonbg/altair
tools/schemapi/utils.py
Python
bsd-3-clause
12,696
0.001024
"""Utilities for working with schemas""" import json import keyword import pkgutil import re import textwrap import jsonschema EXCLUDE_KEYS = ('definitions', 'title', 'description', '$schema', 'id') def load_metaschema(): schema = pkgutil.get_data('schemapi', 'jsonschema-draft04.json') schema = schema.dec...
m))) elif self.is_anyOf(): return 'anyOf({0})'.format(', '.join(s.short_description for s in self.anyOf)) elif self.is_oneOf(): return 'oneOf({0})'.format(', '.join(s.short_description ...
n(s.short_description for s in self.allOf)) elif self.is_not(): return 'not {0}'.format(self.not_.short_description) elif isinstance(self.type, list): options = [] subschema = SchemaInfo(dict(**self.schema)) ...
anhstudios/swganh
data/scripts/templates/object/tangible/wearables/pants/shared_pants_s14.py
Python
mit
478
0.031381
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLI
NE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/wearables/pants/shared_pants_s14.iff" result.attribute_template_id = 11 result.stfName("wearables_name","pants_s14") #### BEGIN MODIFICATIONS #### result.max_condition = 1000 ##...
#### return result
Azure/WALinuxAgent
tests/common/osutil/test_clearlinux.py
Python
apache-2.0
1,180
0.000847
# Copyright 2019 Microsoft Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You m
ay 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 # dist
ributed 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. # # Requires Python 2.6+ and Openssl 1.0+ # import unittest from azurelinuxagen...
cryspy-team/cryspy
tests/test_utils.py
Python
gpl-3.0
1,181
0.005927
import pytest import sys sys.path.append("../src/") import cryspy from cryspy.fromstr import fromstr as fs import numpy as np def test_Karussell(): metric = cryspy.geo.Cellparameters(1, 1, 1, 90, 90, 90).to_Metric() k = cryspy.utils.Karussell(metric, fs("d 1 0 0"), fs("d 0 1 0")) d1 = k.direction(0) a...
rt float(metric.length(d1 - fs("d 1.0 0.0 0"))) < 1e-9 d2 = k.direction(np.pi / 4) assert float(metric.length(d2 - fs("d 0 1 0"))) < 1e-9 def test_fill(): atomset = cryspy.crystal.Atomset({cryspy.crystal.Atom("Fe1", "Fe", fs("p 1/2 1/2 1/2"))}) atomset = cryspy.utils.fill(atomset, [0.6,
0.6, 0.6]) assert len(atomset.menge) == 27 atomset = cryspy.crystal.Atomset({cryspy.crystal.Atom("Fe1", "Fe", fs("p 0 0 0"))}) atomset = cryspy.utils.fill(atomset, [0.1, 0.1, 0.1]) assert len(atomset.menge) == 8
shawnhermans/cyborgcrm
cyidentity/cyfullcontact/tests/test_activity_stream.py
Python
bsd-2-clause
433
0
from a
ctstream.models import Action from django.test import TestCase from cyidentity.cyfullcontact.tests.util import create_sample_contact_info class FullContactActivityStreamTestCase(TestCase): def test_contact_create(self): contact_info = create_sample_contact_info() action = Action.objects.actor(cont...
qbeenslee/Nepenthes-Server
config/configuration.py
Python
gpl-3.0
1,315
0.001668
# coding:utf-8 """ Author : qbeenslee Created : 2014/12/12 """ import re # 客户端ID号 CLIENT_ID = "TR5kVmYeMEh9M" ''' 传输令牌格式 加密方式$迭代次数$盐$结果串 举个栗子: ====start==== md5$23$YUXQ_-2GfwhzVpt5IQWp$3ebb6e78bf7d0c1938578855982e2b1c ====end====
''' MATCH_PWD = r"md5\$(\d\d)\$([a-zA-Z0-9_\-]{20})\$([a-f0-9]{32})" REMATCH_PWD = re.compile(MATCH_PWD) # 支持的上传文件格式 SUPPORT_IMAGE_TYPE_LIST = ['image/gif', 'image/jpeg', 'image/png', 'image/bmp', 'image/x-png', 'application/octet-stream'] # 最大上传大小 MAX_UPLOAD_FILE_SIZE = 1048576...
图片裁剪的尺寸(THUMBNAIL) THUMB_SIZE_SMALL = {'w': 100, 'h': 100, 'thumb': 's'} THUMB_SIZE_NORMAL = {'w': 480, 'h': 480, 'thumb': 'n'} THUMB_SIZE_LARGE = {'w': 3000, 'h': 3000, 'thumb': 'l'} THUMB_SIZE_ORIGIN = {'w': 0, 'h': 0, 'thumb': 'r'} MAX_SHARE_DESCRIPTION_SIZE = 140 NOW_ANDROID_VERSION_CODE = 7 NOW_VERSION_...
TeamProxima/predictive-fault-tracker
board/board_client.py
Python
mit
909
0
#!/usr/bin/python import argparse from board_manager import BoardManager from constants import * def main(): parser = argparse.ArgumentParser(description='Board client settings') parser.add_argument('-sp', '--PORT', help='server port', type=int, default=80, required=False) parser....
ment('-sip', '--IP', help='server ip', type=str, default='', required=False) parser.add_argument('-pt', '--TO', help='phone to', type=str, default='', required=False) parser.add_argument('-pf', '--FROM', help='phone from', type=str, default...
bm = BoardManager(args) bm.activate() if __name__ == "__main__": main()
GJL/flink
flink-python/pyflink/dataset/tests/test_execution_environment_completeness.py
Python
apache-2.0
3,235
0.004019
################################################################################ # 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...
tions under the License. ################################################################################ import unittest from pyflink.dataset import ExecutionEnvironment from pyflink.testing.test_case_utils import PythonAPICompletenessTestCase class ExecutionEnvironmentCompletenessTests(PythonAPICompletenessTestCas...
: return "org.apache.flink.api.java.ExecutionEnvironment" @classmethod def excluded_methods(cls): # Exclude these methods for the time being, because current # ExecutionEnvironment/StreamExecutionEnvironment do not apply to the # DataSet/DataStream API, but to the Table API conf...
klingtnet/dh-project-ws14
data/particle_parser.py
Python
mit
1,420
0.005634
#!/usr/bin/env python3 from pathlib import Path import pprint pp = pprint.PrettyPrinter() import logging log = logging.getLogger(__name__) def main(): p = Path('particles.txt') if p.exists() and p.is_file(): parse(str(p)) def parse(filepath): raw = '' try: with open(filepath) as f: ...
arts[0] == '**': if category: if parts[1] not in data[category]: particle = parts[1] data[category][particle] = []
else: log.warn('Particle "{}" already contained in category: "{}"'.format(parts[1], category)) else: log.warn('particle without previous category specification: "{}"'.format(parts[1])) pp.pprint(data) if __name__ == '__main__': main()
watsonpy/watson-auth
watson/auth/providers/abc.py
Python
bsd-3-clause
3,673
0.000272
import abc from sqlalchemy.orm import exc from watson.auth import crypto from watson.auth.providers import exceptions from watson.common import imports from watson.common.decorators import cached_property class Base(object): config = None session = None def __init__(self, config, session): self....
except exc.NoResultFound: return None # Authentication def authenticate(self, username, password): """Validate a user against a supplied username and password. Args: username (string): The username of the user. password (strin
g): The password of the user. """ password_config = self.config['password'] if len(password) > password_config['max_length']: return None user = self.get_user(username) if user: if crypto.check_password(password, user.password, user.salt, ...
sebrandon1/nova
nova/tests/unit/virt/hyperv/test_vmops.py
Python
apache-2.0
76,595
0.000052
# Copyright 2014 IBM Corp. # # 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 ...
work.is_neutron') @mock.patch('nova.virt.hyperv.vmops.importutils.import_object') def test_load_vif_driver_neutron(self, mock_import_object, is_neutron): is_neutron.return_value = True self._vmops._load_vif_driver_class() mock_import_object.assert_called_once_with( vmops.NEUT...
mport_object, is_neutron): is_neutron.return_value = False self._vmops._load_vif_driver_class() mock_import_object.assert_called_once_with( vmops.NOVA_VIF_DRIVER) def test_list_instances(self): mock_instance = mock.MagicMock() self._vmops._vmutils.list_instances....
Natgeoed/django-broadcasts
broadcasts/admin.py
Python
mit
1,181
0.001693
from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from broadcasts.models import BroadcastMessage from broadcasts.forms import BroadcastMessageForm class BroadcastAdmin(admin.ModelAdmin): """Admin class for the broadcast messages""" form = BroadcastMessageForm list_d...
'fields': ('title', 'message', 'message_type',) }), (_('Message Targeting'), { 'fields': ('user_target', 'url_target') }), (_("Message Display"), { 'description': _( "Messages will display only if they are published, "
"it is between the start and end times, and the show " "frequency has not been exceeded."), 'fields': ('show_frequency', 'is_published', ('start_time', 'end_time')) }) ) admin.site.register(BroadcastMessage, BroadcastAdmin)
Dymaxion00/KittenGroomer
fs_filecheck/usr/local/bin/pdfid.py
Python
bsd-3-clause
37,276
0.004614
#!/usr/bin/env python __description__ = 'Tool to test a PDF file' __author__ = 'Didier Stevens' __version__ = '0.2.1' __date__ = '2014/10/18' """ Tool to test a PDF file Source code put in public domain by Didier Stevens, no Copyright https://DidierStevens.com Use at your own risk History: 2009/03/27: start 20...
import os.path import sys import json import zipfile import collections import glob try: import urllib2 urllib23 = urllib2 except: import urllib.request urllib23 = urllib.reques
t #Convert 2 Bytes If Python 3 def C2BIP3(string): if sys.version_info[0] > 2: return bytes([ord(x) for x in string]) else: return string class cBinaryFile: def __init__(self, file): self.file = file if file == '': self.infile = sys.stdin elif file.lower...
joaander/hoomd-blue
hoomd/pytest/test_box.py
Python
bsd-3-clause
5,889
0.00017
from math import isclose import numpy as np from pytest import fixture from hoomd.box import Box @fixture def box_dict(): return dict(Lx=1, Ly=2, Lz=3, xy=1, xz=2, yz=3) def test_base_constructor(box_dict): box = Box(**box_dict) for key in box_dict: assert getattr(box, key) == box_dict[key] @...
ox.matrix) assert np.allclose(box.L, [ new_box_matrix_dict['Lx'
], new_box_matrix_dict['Ly'], new_box_matrix_dict['Lz'] ]) assert np.allclose(box.tilts, [ new_box_matrix_dict['xy'], new_box_matrix_dict['xz'], new_box_matrix_dict['yz'] ]) def test_eq(base_box, box_dict): box2 = Box(**box_dict) assert base_box == box2 box2.Lx = 2 ...
Impavidity/text-classification-cnn
configurable.py
Python
mit
4,672
0.026327
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import argparse from configparser import SafeConfigParser class Configurable(object): """ Configuration processing for the network """ def __i...
rser = argparse.ArgumentParser() argparser.add_argument('--config_file') # ====== # [OS] @property def model_type(self): return self._config.get('OS', 'm
odel_type') argparser.add_argument('--model_type') @property def mode(self): return self._config.get('OS', 'mode') argparser.add_argument('--mode') @property def save_dir(self): return self._config.get('OS', 'save_dir') argparser.add_argument('--save_dir') @property def word_file(self): re...
xieyajie/BackHatPython
backhatpython02/server-tcp.py
Python
apache-2.0
707
0.001414
import socket import threading bind_ip = "" bind_port = 60007 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip, bind_port)) server.listen(5) print("[*] Listening on %s:%d" % (bind_ip, bind_port)) def handle_client(client_socket): request = client_socket.recv(1024).decode() p...
send_data.encode()) print(client_socket.getpeername()) client_socket.close() while True: client, addr = server.accept() print("[*] Accepted connect from: %s:%d" % (addr[0], addr[1])) client_handle
r = threading.Thread(target=handle_client, args=(client,)) client_handler.start()
0x47d/atd.id
src/print.py
Python
gpl-3.0
989
0.026342
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import sys def get_color(color): if 'default'==color: return '\x1b[39;01m' elif 'black'==color: return '\x1b[30;01m' elif 'red'==color: return '\x1b[31;01m' elif 'green'==color: return ...
return '\x1b[34;01m' def main(): if 4==len(sys.argv): color,cmd,action=get_color(sys.argv[1]),sys.argv[2],sys.argv[3] if action=='stop': action='exit' template='\x1b[1m%s[ ΔOS : %s : make : %s ]\x1b[0m' else: action='init' template='\x1b[1...
_name__=="__main__": main()
fenderglass/ABruijn
flye/polishing/polish.py
Python
bsd-3-clause
11,547
0.002598
#(c) 2016 by Authors #This file is a part of ABruijn program. #Released under the BSD license (see LICENSE file) """ Runs polishing binary in parallel and concatentes output """ from __future__ import absolute_import from __future__ import division import logging import subprocess import os from collections import de...
_BIN = "flye-modules" logger = logging.getLogger() class PolishException(Exception): pass def check_binaries(): if not which(POLISH_BIN): raise PolishException("polishing binary was not found. " "Did you run 'make'?") try: devnull = open(os.devnull, "w") ...
rocessError as e: if e.returncode == -9: logger.error("Looks like the system ran out of memory") raise PolishException(str(e)) except OSError as e: raise PolishException(str(e)) def polish(contig_seqs, read_seqs, work_dir, num_iters, num_threads, error_mode, output_p...
chippey/gaffer
python/GafferTest/ArrayPlugTest.py
Python
bsd-3-clause
12,836
0.064194
########################################################################## # # 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 that the following conditions are # met: # # * Redistrib...
one - there should always be one free input on the # end (until the maximum is reached). n["in"]["e3"].setInput( a["sum"] ) self.assertEqual( len( n["in"] ), 4 ) n["in"]["e3"].setInput( None ) self.assertEqual( len( n["in"] ), 3 ) def testDeleteAndUndoAndRedo( self ) : s = Gaffer.ScriptNode() s["a"]...
lugNode() s["n"]["in"]["e1"].setInput( s["a"]["sum"] ) s["n"]["in"]["e2"].setInput( s["a"]["sum"] ) s["n"]["in"]["e3"].setInput( s["a"]["sum"] ) self.assertEqual( len( s["n"]["in"] ), 4 ) self.assertTrue( s["n"]["in"]["e1"].getInput().isSame( s["a"]["sum"] ) ) self.assertTrue( s["n"]["in"]["e2"].getInput(...
hacktobacillus/fermenter
kettle/scripts/formatData.py
Python
mit
5,376
0.013207
import simplejson as json, os from sklearn.decomposition import PCA from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from kettle.utils import get_beers import numpy as np class BeerMLData(list): def __init__(self): self.proj = None self.arr = None self.beer_map...
self): self.extend(get_beers(False)) def from_file(self,fpath): with open(fpath,'r') as fp: self.extend(json.load(fp)) def fields(self): return [key for key in self[0]['beer'].keys()] def get_mapping_asarray(self): num_samples = len(self.beer_mapping) s...
enumerate(self.beer_mapping.items()): self.arr[i] = v self.compute_pca() return self.arr def compute_pca(self): self.proj = PCA(n_components=2) self.proj.fit(self.arr) def project(self): return self.proj.transform(self.arr) def create_beer_mapping(sel...
devilry/devilry-django
devilry/devilry_cradmin/tests/test_devilry_listfilter/test_assignmentgroup_listfilter.py
Python
bsd-3-clause
21,241
0.000047
from django import test from model_bakery import baker from devilry.apps.core.models import AssignmentGroup from devilry.devilry_dbcache.customsql import AssignmentGroupDbCacheCustomSql from devilry.devilry_cradmin.devilry_listfilter.assignmentgroup import ExaminerCountFilter, CandidateCountFilter class TestExamine...
group) return assignment_group def __filter_examiners(self, filter_value): queryset = AssignmentGroup.objects.all() examinercountfilter = ExaminerCountFilter() examinercountfilter.values = [filter_value] return examinercountfilter.filter(queryobject=queryset) def test_e...
r_value='eq-0') self.assertEqual(filtered_queryset.count(), 1) self.assertEqual(filtered_queryset[0].id, self.testgroup0.id) def test_exact_1(self): filtered_queryset = self.__filter_examiners(filter_value='eq-1') self.assertEqual(filtered_queryset.count(), 1) self.assertEqu...
jarble/EngScript
libraries/schedulePrioritizer.py
Python
mit
2,752
0.015262
''' http://jsfiddle.net/nvYZ8/1/ ''' from functionChecker import functionChecker functionChecker("schedulePrioritizer.py", "getAllPossibleSchedules") "function name: getNonOverlappingRanges" "requires functions: containsOverlappingRanges, overlapsWithOthers(theArr,theIndex)" "is defined: True" "description: Return...
print contains
OverlappingRanges([[1, 3], [3.1, 5], [6,8], [1,7]]) print getNonOverlappingRanges([[1, 3], [3.1, 5], [9, 10], [7, 10]]) "function name: getAllPossibleSchedules" "requires functions: containsOverlappingRanges, convertToBinary" "is defined: False" "description: Return true if the array contains more than zero overlappi...
auready/django
tests/view_tests/tests/test_csrf.py
Python
bsd-3-clause
4,007
0.000749
from django.template import TemplateDoesNotExist from django.test import ( Client, RequestFactory, SimpleTestCase, override_settings, ) from django.utils.translation import override from django.views.csrf import CSRF_FAILURE_TEMPLATE_NAME, csrf_failure @override_settings(ROOT_URLCONF='view_tests.urls') class Csrf...
self.assertContains(response,
"CSRF verification failed. Request aborted.", status_code=403) with self.settings(LANGUAGE_CODE='nl'), override('en-us'): response = self.client.post('/') self.assertContains(response, "Verboden", status_code=403) self.assertContains(re...
Mausy5043/ubundiagd
daemon15.py
Python
mit
4,996
0.015212
#!/usr/bin/env python # Based on previous work by # Charles Menguy (see: http://stackoverflow.com/questions/10217067/implementing-a-full-python-unix-style-daemon-process) # and Sander Marechal (see: http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/) # Adapted by M.Hendrix [2015] (deprecated)...
('~') s = iniconf.read(home + '/' + leaf + '/config.ini') if DEBUG: print "config file : ", s if DEBUG: print iniconf.items(inisection) reportTime = iniconf.getint(inisection, "report
time") cycles = iniconf.getint(inisection, "cycles") samplesperCycle = iniconf.getint(inisection, "samplespercycle") flock = iniconf.get(inisection, "lockfile") fdata = iniconf.get(inisection, "resultfile") samples = samplesperCycle * cycles # total number of samples averaged sampl...
rogeriofalcone/treeio
script/testmodel.py
Python
mit
810
0.008642
# encoding: utf-8 # Copyright 2011 Tree.io Limited # This file is part of Treeio. # License www.tree.io/license #!/usr/bin/python OBJECTS_NUM = 100 # setup environment import sys, os sys.path.append('../') os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from django.core.management import setup_environ from treeio...
settings) user = User.objects.all()[0] for i in range(0, OBJECTS_NUM)
: project = Project(name='test'+unicode(i)) project.set_user(user) project.save() objects = Object.filter_permitted(user, Project.objects) allowed = 0 for obj in objects: if user.has_permission(obj): allowed += 1 print len(list(objects)), ':', allowed
chainer/chainercv
tests/visualizations_tests/test_vis_bbox.py
Python
mit
4,256
0
import unittest import numpy as np from chainer import testing from chainercv.utils import generate_random_bbox from chainercv.visualizations import vis_bbox try: import matplotlib # NOQA _available = True except ImportError:
_available = False @testing.parameterize( *testing.product_dict([ { 'n_bbox': 3, 'label':
(0, 1, 2), 'score': (0, 0.5, 1), 'label_names': ('c0', 'c1', 'c2')}, { 'n_bbox': 3, 'label': (0, 1, 2), 'score': None, 'label_names': ('c0', 'c1', 'c2')}, { 'n_bbox': 3, 'label': (0, 1, 2), 'score': (0, 0.5, 1), 'label_names': None}, { ...
kylemvz/magichour-old
StringKernel/kernel_kmeans.py
Python
apache-2.0
4,707
0.002337
"""Kernel K-means""" # Author: Mathieu Blondel <mathieu@mblondel.org> # License: BSD 3 clause import logging import numpy as np from sklearn.base import BaseEstimator, ClusterMixin from sklearn.metrics.pairwise import pairwise_kernels from sklearn.utils import check_random_state logger = logging.getLogger(__name__)...
Yuqiang Guan, Brian Kulis. KDD 2004. """ def __init__(self, n_clusters=3, max_iter=50, tol=1e-3, random_state=None, kernel="linear", gamma=None, degree=3, coef0=1, kernel_params=None, verbose=0, nystroem=-1): self.n_clusters = n_clusters self.max_iter = max...
lf.coef0 = coef0 self.kernel_params = kernel_params self.verbose = verbose self.nystroem = nystroem @property def _pairwise(self): return self.kernel == "precomputed" def _get_kernel_approx(self, X, Y=None): n = Nystroem(kernel=self.kernel, n_components=self...
networks-lab/metaknowledge
metaknowledge/proquest/recordProQuest.py
Python
gpl-2.0
4,491
0.006903
import collections import io import itertools from ..mkExceptions import BadProQuestRecord, RecordsNotCompatible from ..mkRecord import ExtendedRecord from .tagProcessing.specialFunctions import proQuestSpecialTagToFunc from .tagProcessing.tagFunctions import proQuestTagToFunc class ProQuestRecord(ExtendedRecord): ...
oQu
estRecordParser(inRecord, recNum) elif isinstance(inRecord, io.IOBase): fieldDict = proQuestRecordParser(enumerate(inRecord), recNum) elif isinstance(inRecord, str): #Probaly a better way to do this but it isn't going to be used much, so no need to improve it ...
netzulo/qacode
tests/001_functionals/suite_004_navbase.py
Python
gpl-3.0
16,880
0
# -*- coding: utf-8 -*- """Package for suites and tests related to bots.modules package""" import pytest from qacode.core.bots.modules.nav_base import NavBase from qacode.core.exceptions.core_exception import CoreException from qacode.core.testing.asserts import Assert from qacode.core.t
esting.test_info import TestInfoBotUnique from qacode.utils import settings from selenium.webdriver.remote.webelement import WebElement ASSERT = Assert() SETTINGS = settings(file_path="qacode/configs/") SKIP_NAVS = SETTINGS['tests']['skip']['bot_navigations'] SKIP_NAVS
_MSG = 'bot_navigations DISABLED by config file' class TestNavBase(TestInfoBotUnique): """Test Suite for class NavBase""" app = None page = None @classmethod def setup_class(cls, **kwargs): """Setup class (suite) to be executed""" super(TestNavBase, cls).setup_class( ...
edineicolli/daruma-exemplo-python
scripts/fiscal/ui_fiscal_icnfefetuarpagamento.py
Python
gpl-2.0
5,558
0.0036
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui_fiscal_icnfefetuarpagamento.ui' # # Created: Mon Nov 24 22:25:57 2014 # by: pyside-uic 0.2.15 running on PySide 1.2.2 # # WARNING! All changes made in this file will be lost! from PySide import QtCore, QtGui from pydaruma.pydaruma i...
r = QtGui.QPushButton(ui_FISCAL_iCNFEfetuarPagamento) self.pushButtonEnv
iar.setObjectName("pushButtonEnviar") self.horizontalLayout.addWidget(self.pushButtonEnviar) self.pushButtonCancelar = QtGui.QPushButton(ui_FISCAL_iCNFEfetuarPagamento) self.pushButtonCancelar.setObjectName("pushButtonCancelar") self.horizontalLayout.addWidget(self.pushButtonCancelar) ...
twstrike/le_for_patching
acme/acme/client.py
Python
apache-2.0
23,969
0.000167
"""ACME client API.""" import collections import datetime import heapq import logging import time import six from six.moves import http_client # pylint: disable=import-error import OpenSSL import requests import sys import werkzeug from acme import errors from acme import jose from acme import jws from acme import ...
w_cert_uri=new_cert_uri) if authzr.body.identifier != identifier: raise errors.UnexpectedUpdate(authzr) return authzr def request_challenges(self, identifier, new_authzr_uri): """Request challenges. :param identifier: Identifie
r to be challenged. :type identifier: `.messages.Identifier` :param str new_authzr_uri: new-authorization URI :returns: Authorization Resource. :rtype: `.AuthorizationResource` """ new_authz = messages.NewAuthorization(identifier=identifier) response = self.net...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.3/Lib/plat-mac/lib-scriptpackages/Netscape/WorldWideWeb_suite.py
Python
mit
16,104
0.005899
"""Suite WorldWideWeb suite, as defined in Spyglass spec.: Level 1, version 1 Generated from /Volumes/Sap/Applications (Mac OS 9)/Netscape Communicator\xe2\x84\xa2 Folder/Netscape Communicator\xe2\x84\xa2 AETE/AEUT resource version 1/0, language 0, script 0 """ import aetools import MacOS _code = 'WWW!' class Worl...
_arguments['----'] = _object _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) if _arguments.get('errn', 0): raise aetools.Error, aetools.decodeerror(_arguments) # XXXX Optionally decode result if _arguments.has_key('----...
you can call FindURL to find out the URL used to download the file. Required argument: File spec Keyword argument _attributes: AppleEvent attribute dictionary Returns: The URL """ _code = 'WWW!' _subcode = 'FURL' if _arguments: raise TypeError, 'No optional args ...
acaldero/moon
app-mon.py
Python
gpl-3.0
5,026
0.015519
#!/usr/bin/python -u # # Application Monitoring (version 1.5) # Alejandro Calderon @ ARCOS.INF.UC3M.ES # GPL 3.0 # import math import time import psutil import threading import multiprocessing import subprocess import os import sys import getopt import json def print_record ( format, data ): try: ...
= getopt.getopt(argv,"h:f:r:d:p:",["format=","rate=","delta=","pid="]) except getopt.GetoptError: print 'app-mon.py -f <format> -r <rate> -d <delta> -p <pid>' sys.exit(2) for opt, arg in opts: if opt == '-h':
print 'app-mon.py -f <format> -r <rate> -d <delta> -p <pid>' sys.exit() elif opt in ("-f", "--format"): format = str(arg) elif opt in ("-p", "--pid"): p_id = int(arg) elif opt in ("-r", "--rate"): rrate = float(arg) ...
gmr/queries
tests/utils_tests.py
Python
bsd-3-clause
4,097
0
""" Tests for functionality in the utils module """ import platform import unittest import mock import queries from queries import utils class GetCurrentU
serTests(unittest.TestCase):
@mock.patch('pwd.getpwuid') def test_get_current_user(self, getpwuid): """get_current_user returns value from pwd.getpwuid""" getpwuid.return_value = ['mocky'] self.assertEqual(utils.get_current_user(), 'mocky') class PYPYDetectionTests(unittest.TestCase): def test_pypy_flag(sel...
explosiveduck/ed2d
ed2d/debug.py
Python
bsd-2-clause
203
0.004926
from _
_future__ import print_function from ed2d.cmdargs import CmdArgs debugEnabled = CmdArgs.add_arg('debug', bool, 'Enable debug output.') def debug(*args): if debugEnabled:
print(*args)
mstoppert/adventofcode
23/answer.py
Python
mit
728
0.005495
file = open('input.txt') instructions = [] for line in file.readlines(): instructions.append(line.replace(',', '').strip
().split(' ')) regs = { 'a': 0, 'b': 0 } ptr = 0 while True: if ptr not in range(len(instructions)): break instr = instructions[ptr] inst, r = instr[0], instr[1] di = 1 if inst == 'inc': regs[r] += 1 elif inst == 'tpl': regs[r] *= 3 elif inst == 'hlf'...
1: di = int(offset) elif inst == 'jmp': di = int(r) ptr += di print regs
psywolf/cardfight
cardfight.py
Python
gpl-3.0
6,620
0.033384
#!/usr/bin/python3 import random import copy import enum import jsonpickle import pickle import argparse from sharedlib import Attr, Card, Config import json class Die: def __init__(self, attack, defense, magic, mundane, numSides=12): self.attack = attack self.defense = defense self.magic = magic self.mundane...
return attacker if damage > defender.currentLife(): damage = defender.currentLife() if Attr.lifedrain in attacker.attrs and Attr.construct not in defender.attrs: attacker.wounds = max(0, attacker.wounds - damage) defender.wounds += damage if defender.currentLife() <= 0: return attacker ...
rrentLife() <= 0: return defender return None def is_odd(x): return x % 2 != 0 def getStats(attacker, defender, numFights, maxTurns, scriptable): outcomes = dict() for w in Winner: outcomes[w] = [] for i in range(0,numFights): a = copy.copy(attacker) d = copy.copy(defender) winner, turns = fightToT...
mpirnat/adventofcode
day04/test.py
Python
mit
521
0.005758
#!/usr/bin/env python import unittest from day04 import find_integer class Test(unittest.TestCase): cases = ( ('abc
def', 609043), ('pqrstuv', 1048970), ) def test_gets_integer(self): for (key, expected) in self.cases: result = find_integer(key, zeroes=5) self.assertEqual(result, expected,
"Expected {key} to yield {expected}, but got {result}".\ format(**locals())) if __name__ == '__main__': unittest.main()
google-research/google-research
gfsa/model/edge_supervision_models_test.py
Python
apache-2.0
8,558
0.00187
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
expected_block_count) for block in params.values(): # Each block contains 4 sublayers. self.assertLen(block, 4) # Gradients should work. outs, vjpfun = jax.vjp( functools.partial( edge_supervision_models.transformer_steps.call, n
ode_embeddings=jnp.zeros((5, 3), jnp.float32), edge_embeddings=jnp.zeros((5, 5, 4), jnp.float32), neighbor_mask=jnp.zeros((5, 5), jnp.float32), num_real_nodes_per_graph=4), params, ) vjpfun(outs) def test_transformer_steps_masking(self): """Transformer should m...
pvsousalima/marolo
models/20_validators.py
Python
mit
6,559
0
# coding: utf-8 from smarthumb import SMARTHUMB from gluon.contrib.imageutils import RESIZE # Noticias db.noticias.titulo.requires = [ IS_NOT_EMPTY(error_message=T('Este campo não pode ficar vazio!')), IS_NOT_IN_DB(db, db.noticias.titulo, error_message=T('Título deve ser único.')), IS_LENG...
ENGTH(256, error_message=T('Tamanho máximo de 256 caracteres.')) ] db.carousel.imagem.requires = [ IS_EMPTY_OR( IS_IMAGE(error_message=T('Arquivo enviado deve ser uma imagem.')) ), IS_LENGTH(100 * 1024, # 100kb error_message=T('Arquiv
o muito grande!' 'Tamanho máximo permitido é 100kb')), IS_EMPTY_OR(RESIZE(1200, 400)) ] db.carousel.url.requires = [ IS_NOT_EMPTY( error_message=T('Este campo não pode ficar vazio!')), IS_LENGTH(256, error_message=T('Tamanho máximo de 256 caracteres.')), IS_URL() ] ...
alexgorban/models
research/object_detection/core/box_list_ops.py
Python
apache-2.0
43,889
0.004124
# Copyright 2017 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...
(x_min, win_x_max), tf.less_equal(y_max, win_y_min), tf.less_equal(x_max, win_x_min) ], 1) valid_indices = tf.reshape( tf.where(tf.logical_not(tf.reduce_any(coordinate_violations, 1))), [-1]) return gather(boxlist, valid_indices), valid_indices def intersection(boxlist1, boxlist2, scope=No...
rgs: boxlist1: BoxList holding N boxes boxlist2: BoxList holding M boxes scope: name scope. Returns: a tensor with shape [N, M] representing pairwise intersections """ with tf.name_scope(scope, 'Intersection'): y_min1, x_min1, y_max1, x_max1 = tf.split( value=boxlist1.get(), num_or_si...
hrashk/sympy
sympy/concrete/tests/test_gosper.py
Python
bsd-3-clause
7,307
0.002053
"""Tests for Gosper's algorithm for hypergeometric summation. """ from sympy import binomial, factorial, gamma, Poly, S, simplify, sqrt, exp, log, Symbol from sympy.abc import a, b, j, k, m, n, r, x from sympy.concrete.gosper import gosper_normal, gosper_sum, gosper_term def test_gosper_normal(): assert gosper_n...
2, m + n)/(m*(1 + 2*m)) def test_gosper_sum_algebraic(): assert gosper_sum( n**2 + sqrt(2), (n, 0,
m)) == (m + 1)*(2*m**2 + m + 6*sqrt(2))/6 def test_gosper_sum_iterated(): f1 = binomial(2*k, k)/4**k f2 = (1 + 2*n)*binomial(2*n, n)/4**n f3 = (1 + 2*n)*(3 + 2*n)*binomial(2*n, n)/(3*4**n) f4 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*binomial(2*n, n)/(15*4**n) f5 = (1 + 2*n)*(3 + 2*n)*(5 + 2*n)*(7 + 2*n)*bi...
ygol/odoo
addons/purchase_stock/tests/test_fifo_price.py
Python
agpl-3.0
16,403
0.002744
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from .common import PurchaseTestCommon from odoo.addons.stock_account.tests.common import StockAccountTestCommon from odoo.tests import Form class TestFifoPrice(PurchaseTestCommon, StockAccountTestCommon): ...
'product_id': product_cable_management_box.id, 'product_qty': 30, 'product_uom': self.env.ref('uom.product_uom_kgm').id,
'price_unit': 0.150, 'date_planned': time.strftime('%Y-%m-%d')}), (0, 0, { 'name': product_cable_management_box.name, 'product_id': product_cable_management_box.id, 'product_qty': 10.0, 'product_...
MisanthropicBit/colorise
src/colorise/win/win32_functions.py
Python
bsd-3-clause
10,715
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """Windows API functions.""" import ctypes import os import sys from ctypes import WinError, wintypes from colorise.win.winhandle import WinHandle # Create a separate WinDLL instance since the one from ctypes.windll.kernel32 # can be manipulated by other code that also ...
dle.validate(target): # We create a new handle each time since the old handle may have been # invalidated by a redirection return create_std_handle(target) raise ValueError("Invalid handle identifier '{0}'".format(target)) def get_windows_clut(): """Query and return the internal Windo...
look-up table.""" # On Windows Vista and beyond you can query the current colors in the # color table. On older platforms, use the default color table csbiex = CONSOLE_SCREEN_BUFFER_INFOEX() csbiex.cbSize = ctypes.sizeof(CONSOLE_SCREEN_BUFFER_INFOEX) retval = kernel32.GetConsoleScreenBufferInfoEx( ...
iZonex/aioactor
examples/accounts/app.py
Python
apache-2.0
1,531
0
import asyncio import uvloop from aioactor.transports import NatsTransport from aioactor.service import Service from aioactor.broker import ServiceBroker asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) # TODO ADD possible actions list! # TODO ADD abstractions to Message Handler! # MessageHandler must be able t...
'handler': NatsTransport } } broker = ServiceBroker(io_loop=loop, **settings) services = [UsersService] registe
r_services(broker, services) print(broker.available_services()) await broker.start() if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.run_forever() loop.close()
qtumproject/qtum
test/functional/wallet_hd.py
Python
mit
7,811
0.005121
#!/usr/bin/env python3 # Copyright (c) 2016-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test Hierarchical Deterministic wallet function.""" import os import shutil from test_framework.test_...
d_add_2) assert_equal(hd_info_2["hdkeypath"], "m/88'/0'/"+str(i)+"'") assert_equal(hd_info_2["hdseedid"], masterkeyid) assert_equal(hd_add, hd_add_2) connect_nodes(self.nodes[0], 1) self.sync_all() # Needs rescan self.stop_nod
e(1) self.start_node(1, extra_args=self.extra_args[1] + ['-rescan']) assert_equal(self.nodes[1].getbalance(), NUM_HD_ADDS + 1) # Try a RPC based rescan self.stop_node(1) shutil.rmtree(os.path.join(self.nodes[1].datadir, self.chain, "blocks")) shutil.rmtree(os.path.join(s...
phildini/logtacts
contacts/tests/test_models.py
Python
mit
9,784
0.000511
from django.test import TestCase from django.core.urlresolvers import reverse from common.factories import UserFactory import contacts as contact_constants from contacts import factories from contacts import models class ContactModelTests(TestCase): def setUp(self): self.book = factories.BookFactory.crea...
lf.assertFalse(self.contact.can_be_viewed_by(user)) def test_contact_cant_be_edited_by_bad(self): user = UserFactory.create(username='asheesh') self.assertFalse(self.contact.can_be_edited_by(user)) def test_get_contacts_for_user(self): bookowner = factories.BookOwnerFactory.create(book...
def test_get_contacts_for_user_bad_user(self): user = UserFactory.create(username="nicholle") self.assertFalse( list(models.Contact.objects.get_contacts_for_user(user)), ) def test_preferred_address_with_preferred(self): field = factories.ContactFieldFactory( ...
GenericStudent/home-assistant
tests/components/logbook/test_init.py
Python
apache-2.0
61,935
0.001405
"""The tests for the logbook component.""" # pylint: disable=protected-access,invalid-name import collections from datetime import datetime, timedelta import json import unittest import pytest import voluptuous as vol from homeassistant.components import logbook, recorder from homeassistant.components.alexa.smart_hom...
logbook.humanify(self.hass, (eventA, eventB, eventC), entity_attr_cache, {}) ) assert len(entries) == 2 self.assert_entry(entries[0], pointB, "bla", entity_id=entity_id) self.assert_entry(entries[1], pointC, "bla", entity_id=entity_id)
def test_home_assistant_start_stop_grouped(self): """Test if HA start and stop events are grouped. Events that are occurring in the same minute. """ entity_attr_cache = logbook.EntityAttributeCache(self.hass) entries = list( logbook.humanify( self....