prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
smaller or equal to StopIdx if startIdx is not None and stopIdx is not None and startIdx > stopIdx: raise Exception("Error. startIdx {} is larger than stopIdx {}".inputFormat(startIdx, stopIdx)) if not ext: ext = DEFAULT_EXTENSIONS.get(inputFormat.lower(), None) if inpu...
pecifying the number of pixels or splits per dimension. Indirectly controls the number of Spark partitions, with one partition per block. blockSizeUnits: string, either "pixels" or "splits", default "pixels"
Units for interpreting a tuple passed as blockSize when shuffle=True. startIdx: nonnegative int, optional, default = None Convenience parameters to read only a subset of input files. Uses python slice conventions (zero-based indexing with exclusive final position). These parameters g...
# -*- coding: utf-8 -*- # Copyright 2017, 2021 ProjectQ-Framework (www.projectq.ch) # # 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....
OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for projectq.cengines._main.py.""" import sys import weakref import pytest from projectq.backends import Simulator from projectq.cengines import Ba...
DummyEngine() ceng2 = DummyEngine() test_backend = DummyEngine() engine_list = [ceng1, ceng2] eng = _main.MainEngine(backend=test_backend, engine_list=engine_list) assert id(eng.next_engine) == id(ceng1) assert id(eng.main_engine) == id(eng) assert not eng.is_last_engine assert id(ceng1...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 Agile Business Group sagl (<http://www.agilebg.com>) # # This program is f
ree software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # ...
lic License for more 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 openerp import models, fields class Company(mo...
'''Module containing a DensityFunc abstract class, with common probability densities @since: Jan 10, 2013 @author: kroon ''' from __future__ import division import numpy as np class Gaussian(object): ''' Class for representing a multi-dimensional Gaussian distribution of dimension d, given mean and c...
''' return np.exp(self.logf(x)) def logf(self, x): ''' Calculate the log-density at x
Parameters ---------- x : (d,) ndarray Evaluate the log-normal distribution at a single d-dimensional sample x Returns ------- val : scalar The value of the log of the normal distribution at x. ''' #x = x[...
""" A pair of numbers is considered to be cool if their product is divisible by their sum. More formally, a pair (i, j) is cool if and only i
f (i * j) % (i + j) = 0. Given two lists a and b, find cool pairs with the first number in the pair fro
m a, and the second one from b. Return the number of different sums of elements in such pairs. Example For a = [4, 5, 6, 7, 8] and b = [8, 9, 10, 11, 12], the output should be coolPairs(a, b) = 2. There are three cool pairs that can be formed from these arrays: (4, 12), (6, 12) and (8, 8). Their respective ...
return res def update(self, value): """ search order for local (i.e., @variable) variables: scope, key_variable [('locals', 'local_name'), ('globals', 'local_name'), ('locals', 'key'), ('globals', 'key')] """ key = self.name ...
except AttributeError: if is_list_like(x): try: return ~y.isin(x) except AttributeError: pass return x not in y _cmp_ops_syms = '>', '<', '>=', '<=', '==', '!=', 'in', 'not in' _cmp_ops_funcs = op.gt, op.lt, op.ge, op.le, op.eq, op.ne, _in, _no...
ct(zip(_cmp_ops_syms, _cmp_ops_funcs)) _bool_ops_syms = '&', '|', 'and', 'or' _bool_ops_funcs = op.and_, op.or_, op.and_, op.or_ _bool_ops_dict = dict(zip(_bool_ops_syms, _bool_ops_funcs)) _arith_ops_syms = '+', '-', '*', '/', '**', '//', '%' _arith_ops_funcs = (op.add, op.sub, op.mul, op.truediv if PY3 else op.div, ...
import sys, os, math import time import numpy as np from pandas.io.parsers import read_csv from sklearn.decomposition import PCA from sklearn.cross_validation import StratifiedShuffleSplit from sklearn import metrics import sklearn.svm as svm from sklearn.naive_bayes import MultinomialNB from sklearn.naive_bayes impo...
b.pyplot as plt cut_pt = 1 print ("Reading the file...") input_res = read_csv(os.path.expanduser("input/t
rain.csv"), nrows=3000) # load pandas dataframe input_res = input_res.as_matrix() shape = input_res.shape number_of_rows = shape[0] number_of_columns = shape[1] number_of_fv = number_of_columns - cut_pt print ("Number of rows: %d (document)" % number_of_rows) print ("Number of columns: %d (feature vector(preprocessed)...
from .connection import Connection from .group i
mport Gro
up, SerialGroup, ThreadingGroup from .tasks import task
""" UNFINISHED Fixer for turning multiple lines like these: from __future__ import division from __future__ import absolute_import from __future__ import print_function into a single line like this: from __future__ import (absolute_import, division, print_function) This helps wit
h testing of ``futurize``. """ from lib2to3 import fixer_base from libfuturize.fixer_util import future_import class FixOrderFutureImports(fixer_base.BaseFix): BM_compatible = True PATTERN = "file_input" run_order = 10 # def match(self, node): # """ # Match only once per file # ...
# if hasattr(node, 'type') and node.type == syms.file_input: # return True # return False def transform(self, node, results): # TODO # write me pass
impo
rt axi2s_c import sys
uut = axi2s_c.axi2s_c() uut.read(sys.argv[1])
#!/usr/bin/env python2 # -*- coding: utf-8 -*- import utils import xml_utils from parser_exception import ParserException class Event(object): def __init__(self, node): """ Constructor Keyword arguments: node -- XML node defining this event """ self.node = node self.name = node.get('name') uti...
te demand can only be issued for the same events, one decla
red in the super-class and the other in the sub-class. The assert statement checks this, nothing else needs to be done. """ assert id(self) == id(other) def __cmp__(self, other): return cmp(self.id, other.id) or cmp(self.name, other.name) def __str__(self): if self.type is None: type = None e...
n tests. """ import numpy as np b = np.arange(100*100).reshape(100, 100) c = b i = 1 rc = sys.getrefcount(i) for j in range(15): d = op(b, c) assert_(sys.getrefcount(i) >= rc) del d # for pyflakes def assert_allclose(actual, desired, rtol=1e-7, atol=0, equal_nan=False, ...
o not have the same shape: %s - %s" % (x.shape, y.shape)) def _diff(rx, ry, vdt): diff = np.array(rx-ry, dtype=vdt) return np.abs(diff) rx = integer_repr(x) ry = integer_repr(y) return _diff(rx, ry, t) def _integer_repr(x, vdt, comp): # Reinterpret binary ...
tation of the float as sign-magnitude: # take into account two-complement representation # See also # http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm rx = x.view(vdt) if not (rx.size == 1): rx[rx < 0] = comp - rx[rx < 0] else: if rx < 0: rx =...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('blogg', '0001_initial'), ] operations = [ migrations.CreateModel( name='Comment', fields=[ ...
o_created=True, primary_key=True)), ('content', models.TextField(max_length=1000L)), ('author', models.CharField(default=b'Anonymous', max_length=100, blank=True)), ('ip_address', models.GenericIPAddressField(null=True, blank=True)), ('user_agent', models....
('modified', models.DateTimeField(auto_now=True, auto_now_add=True)), ('post', models.ForeignKey(related_name='comments', to='blogg.Post')), ], options={ 'ordering': ['-created'], }, bases=(models.Model,), ), ]
letely removed in 2.0 args, varargs, varkw, defaults = inspect.getargspec(member) if varargs is not None: args.append(varargs) if varkw is not None: args.append(varkw) func = build_function(getattr(member, '__name__', None) or localname, args, defaults, member._...
s as guessed. """ # astroid from living objects ############################################### def __init__(self): self._done = {} self._module = None def inspect_build(self, module, modname=None, path=None): """build astroid from a living module (i.e. using inspect) ...
used when there is no python source code available (either because it's a built-in module or because the .py is not available) """ self._module = module if modname is None: modname = module.__name__ try: node = build_module(modname, module.__doc__) ...
# coding: utf-8 """ HDL Testing Platform REST API for HDL TP # noqa: E501 OpenAPI spec version: 1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_client from swagger_cl
ient.models.task impo
rt Task # noqa: E501 from swagger_client.rest import ApiException class TestTask(unittest.TestCase): """Task unit test stubs""" def setUp(self): pass def tearDown(self): pass def testTask(self): """Test Task""" # FIXME: construct object with mandatory attributes wit...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): depe
ndencies = [ ('discussions', '0004_auto_20150430_1641'), ] operations = [ migrations.AlterField( model_name='disc
ussion', name='original_post', field=models.OneToOneField(null=True, to='discussions.Post', related_name='OP'), ), ]
''' File: input.py Author: Tristan van Vaalen Handles user input ''' import signal import sys import verbose v = verbose.Verbose() class InputHandler(): def __init__(self): v.debug('Initializing input handler').indent() self.running = True self.signal_level = 0 v.debug('Regist...
sys.exit(0) def output_options(self): v.write( 'Available options:\n' + ' - help: prints this message\n' +
' - exit: exit program' ' - test: magic' ) def get(self): v.debug('Entering input loop') v.write('AUDIOLYZE v0.01\nPress ctrl+D to exit') while self.running: try: self._parse_input(raw_input('>>> ')) except EOFError: ...
import networkx as nx import itertools import matplotlib.pyplot as plt fig = plt.figure() fig.subplots_adjust(left=0.2, wspace=0.6) G = nx.Graph() G.add_edges_from([(1,2,{'w': 6}), (2,3,{'w': 3}), (3,1,{'w': 4}), (3,4,{'w': 12}), (4,5,{'w': 13})...
()] )) #plt.show() for t in triangles: weights = {} for v in t: k = (G.get_edge_data(*v)['w']) weights[k]=v l = weights.keys() if len(l) != 1:
l.sort() l.reverse() pprint.pprint(l) quitar = l.pop() G.remove_edge(*weights[quitar]) graph2 = fig.add_subplot(122) graph2.plot(nx.draw(G, pos=pos, node_size = [G.degree(n) for n in G.nodes()], width = [G.get_edge_data(*e)['w'] for e in G.edges()]...
#!/usr/bin/env python import glob, os, sys import sipconfig from PyQt4 import pyqtconfig def get_diana_version(): depends = filter(lambda line: line.startswith("Depends:"), open("debian/control").readlines()) for line in depends: pieces = line.split() for piece in pi...
os.path.join(diana_inc_dir, "PaintGL"), metlibs_inc_dir, qt_pkg_dir+"/include" ] makefile.extra_lib_dirs += [diana_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += ["-Wl,-rpath="+diana_lib_dir, "-Wl,-fPIC"]...
if module == "metlibs": makefile.extra_include_dirs.append(diana_inc_dir) makefile.extra_include_dirs.append("/usr/include/metlibs") makefile.extra_lib_dirs += [diana_lib_dir, "/usr/lib", metlibs_lib_dir, qt_pkg_dir+"/lib"] makefile.extra_lflags += [...
impo
rt unittest from flip_bit_to_win import flip_bit class TestFlipBit(unittest.TestCase): def test_flip_bit(self): self.assertEquals(flip_bit(0b1011100101), 4) self.assertEquals(flip_bit(1775), 8) if __name__ == '__main__': unittest.main(
)
# # rtlsdr_scan # # http://eartoearoak.com/software/rtlsdr-scanner # # Copyright 2012 - 2015 Al Brown # # A frequency scanning GUI for the OsmoSDR rtl-sdr library at # http://sdr.osmocom.org/trac/wiki/rtl-sdr # # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gene...
ir() if os.path.isdir(os.path.join(scriptDir, 'res')): resDir = os.path.join(scriptDir, 'res') else: resDir = os.path.join(scriptDir, '..', 'res') return resDir def get_resource_path(resource): return os.path.join(get_resdir(), resource) def limit(value, minimum, maximum): retur...
mum) def level_to_db(level): return 10 * math.log10(level) def db_to_level(dB): return math.pow(10, dB / 10.0) def next_2_to_pow(val): val -= 1 val |= val >> 1 val |= val >> 2 val |= val >> 4 val |= val >> 8 val |= val >> 16 return val + 1 def calc_samples(dwell): samples...
""" Testing python specific API for Minimizer related classes. """ import sys import os import unittest import bornagain as ba class TestMinimizerHelper: def __init__(self): self.m_ncalls = 0 self.m_pars = None def objective_function(self, pars): self.m_ncalls += 1 self.m_pars...
.0 self.assertEqual(par.value, 42.0) def test_ParametersSetIterator(self): """ Testing of python iterator over defined fit parameters. """ pars = ba.Parameters() self.assertEqual(pars.size(), 0) pars.add(ba.Parameter("par0", 1.0, ba.AttLimits.limitless())) ...
, p in enumerate(pars): self.assertEqual(p.name(), expected_names[index]) def test_ParametersAdd(self): """ Testing Parameters::add method """ params = ba.Parameters() params.add("par0", 0.0) params.add("par1", 1.0, min=1.0) params.add("par2", 2....
.disable() base.LEVEL_TAGS = self.old_level_tags class BaseTests: storage_class = default_storage levels = { 'debug': constants.DEBUG, 'info': constants.INFO, 'success': constants.SUCCESS, 'warning': constants.WARNING, 'error': constants.ERROR, } def se...
storage() response = self.get_response() storage.add(constants.INFO, 'Test message 3') list(storage) # Simulates a read storage.update(response) stor
ing = self.stored_messages_count(storage, response) self.assertEqual(storing, 0) def test_existing_read_add_update(self): storage = self.get_existing_storage() response = self.get_response() list(storage) # Simulates a read storage.add(constants.INFO, 'Test message 3') ...
, os.sep) dst_dir = os.path.join(staging_dir, config.get(section, option)) dst_dir = dst_dir.replace('\\', os.sep) src_paths = glob.glob(os.path.join(src_dir, src_subdir)) if src_paths and not os.path.exists(dst_dir): os.makedirs(dst_dir) for src_path in src_paths: dst_path = os.path.joi...
e ones in the staging dir will never be edited, and we want # to have the build be triggered when the thing-that-was-copied-there # changes. def PathFixup(path): """Fixes path for depfile format: backslash to forward slash, and backslash escaping for spaces.""" return path.replace('\\', '...
ure that g_archive_inputs is complete (i.e. # that there's not file copies that got missed). staging_contents = [] for root, files in os.walk(os.path.join(staging_dir, UPDATER_DIR)): for filename in files: staging_contents.append(PathFixup(os.path.join(root, filename))) # Make sure there'...
et """ from lib import base_app, build, http, image, config from lib.misc import app_expose, ctime from lib.base_app import init_app import cherrypy from cherrypy import TimeoutError import os.path import shutil import time class app(base_app): """ template demo app """ title = "Meaningful Scales Detection: ...
and input_id.y input_id = kwargs.key
s()[0].split('.')[0] assert input_id == kwargs.keys()[1].split('.')[0] # get the images input_dict = config.file_dict(self.input_dir) fnames = input_dict[input_id]['files'].split() for i in range(len(fnames)): shutil.copy(self.input_dir + fnames[i], ...
im
port json import
os import datetime for i in range(9): try: os.chdir('../call_record/') with open('callsSortedperson_'+str(i)+'.json','r') as f: data=json.load(f) print 'User: ',i #print len(data) friends=[] for j in range(len(data)): #print data[j][0] friends.append(data[j][0]) friends=list...
H scriptPath = os.path.realpath(os.path.dirname(sys.argv[0])) os.chdir(scriptPath) # APPEND FOLDER OF REQUIRED LIBRARY sys.path.append("Adafruit/Adafruit_PWM_Servo_Driver") # FINALLY LOAD THE LIBRARY from Adafruit_PWM_Servo_Driver import PWM LED_PIN_0 = 0 LED_PIN_1 = 2 LED_PIN_2 = 4 LED_PIN_3 = 6 LED_PIN_4 = 8 LED_PIN...
, BRIGHT_7 ] position[33] = [ BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_0, BRIGHT_1, BRIGHT_2, BRIGHT_3, BRIGHT_4, BRIGHT_5, BRIGHT_6, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7 ] position[34] = [ BRIGHT_7, BRIGHT_7, BRIGHT_0, BRIGHT_1, BRIGHT_2, BRIGHT_3, BRIGHT_4, BRIGHT_5, BRIGHT_6, BRIGHT_7, BRIGHT_7, BR...
HT_7, BRIGHT_7, BRIGHT_7 ] position[35] = [ BRIGHT_7, BRIGHT_0, BRIGHT_1, BRIGHT_2, BRIGHT_3, BRIGHT_4, BRIGHT_5, BRIGHT_6, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7, BRIGHT_7 ] position[36] = [ BRIGHT_0, BRIGHT_1, BRIGHT_2, BRIGHT_3, BRIGHT_4, BRIGHT_5, BRIGHT_6, BRIGHT_7, BRIGHT_7, BRIGHT_7...
callback_classes = [ ['ns3::ObjectBase *', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['...
'unsigned short', 'ns3::LteUePhy::State', 'ns3::LteUePhy::State', 'ns
3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'unsigned short', 'unsigned short', 'double', 'double', 'unsigned char', 'ns3::empty', 'ns3::empty', 'ns3::empty', 'ns3::empty'], ['void', 'unsigned short', 'unsigned short', 'double', 'double', 'bool', 'unsigned char', 'ns3::empty', '...
from django.sho
rtcuts import render from django.utils.translation import activate def index(request): # latest_question_list = Question.objects.order_by('-pub_date')[:5] # context = {'latest_question_list': latest_question_
list} # activate('pt-br') # print(request.LANGUAGE_CODE) context = {} return render(request, 'index.html', context)
#
####################################################################### # MCU Gear(R) system Sample Code # Auther:y.kou. # web site: http://www.milletool.com/ # Date : 8/OCT/2016 # ######################################################################## #Revisi
on Information # ######################################################################## #!/usr/bin/python from milpy import mil from milpy import milMod from milpy import wiringdata from milpy import Moisuture import time wiringdata.initIO() modA = milMod.milMod(Moisuture.getInfo(0)) if __name__=='__main__': try...
* (attempts - 1)) return time_to_sleep def create_exponential_delay_function(base, growth_factor): """Create an exponential delay function based on the attempts. This is used so that you only have to pass it the attempts parameter to calculate the delay. """ return functools.partial( ...
key]) if retry_exception is not None: retryable_exceptions.extend(retry_exception) if len(checkers) == 1: # Don't need to use a MultiChecker return MaxAttemptsDecora
tor(checkers[0], max_attempts=max_attempts) else: multi_checker = MultiChecker(checkers) return MaxAttemptsDecorator( multi_checker, max_attempts=max_attempts, retryable_exceptions=tuple(retryable_exceptions)) def _create_single_checker(config): if 'response' in config[...
from __future__ import print_function import zlib import numpy as np from . import ncStream_pb2 as stream # noqa MAGIC_HEADER = b'\xad\xec\xce\xda' MAGIC_DATA = b'\xab\xec\xce\xba' MAGIC_VDATA = b'\xab\xef\xfe\xba' MAGIC_VEND = b'\xed\xef\xfe\xda' MAGIC_ERR = b'\xab\xad\xba\xda' def read_ncstream_messages(fobj): ...
buf = zlib.decompress(buf) assert len(buf) == data_header.uncompressedSize elif data_header.c
ompress != stream.NONE: raise NotImplementedError('Compression type %d not implemented!' % data_header.compress) return np.frombuffer(bytearray(buf), dtype=dt).reshape(*shape) # STRUCTURE = 8; # SEQUENCE = 9; _dtypeLookup = {stream.CHAR: 'b', stream.BYTE: 'b', stream.SHOR...
#!/usr/bin/env python """ runtests.py [OPTIONS] [-- ARGS] Run tests, building the project first. Examples:: $ python runtests.py $ python runtests.py -t {SAMPLE_TEST} """ from __future__ import division, print_function PROJECT_MODULE = "msmbuilder" PROJECT_ROOT_FILES = ['msmbuilder', 'LICENSE', 'setup.py'] ...
test") try: shutil.rmtree(test_dir) except OSError: pass try: os.makedirs(test_dir) except OSError: pass cwd = os.getcwd() try: os.chdir(test_dir) result = subprocess.call(commands) finally: os.chdir(cwd) sys.exit(result) de
f build_project(args): """ Build a dev version of the project. Returns ------- site_dir site-packages directory where it was installed """ root_ok = [os.path.exists(os.path.join(ROOT_DIR, fn)) for fn in PROJECT_ROOT_FILES] if not all(root_ok): print("To ...
der(provider): provider.refresh_provider_relationships(wait=600) return True @pytest.fixture(params=['instances', 'images']) def tag_mapping_items(request, appliance, provider): entity_type = request.param collection = getattr(appliance.collections, 'cloud_{}'.format(entity_type)) collection.filte...
if entity_type == 'images' else provider.mgmt.get_vm(name) ) except ImageNotFoundError: msg = 'Failed looking up template [{}] from CFME on provider: {}'.format(name, provider) logger.exception(msg) pytest
.skip(msg) return collection.instantiate(name=name, provider=provider), mgmt_item, entity_type def tag_components(): # Return tuple with random tag_label and tag_value return ( fauxfactory.gen_alphanumeric(15, start="tag_label_"), fauxfactory.gen_alphanumeric(15, start="tag_value_") ) ...
"""Helpers for testing Met Office DataPoint.""" from homeassistant.components.metoffice.const import DOMAIN from homeassistant.const import CONF_API_KEY, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME TEST_DATETIME_STRING = "2020-04-25T12:00:00+00:00" TEST_API_KEY = "test-metoffice-api-key" TEST_LATITUDE_WAVERTREE = 53.3...
ls_like_temperature", "13"), "uv": ("uv_index", "6"), "precipitation": ("
probability_of_precipitation", "0"), "wind_direction": ("wind_direction", "E"), "wind_gust": ("wind_gust", "7"), "wind_speed": ("wind_speed", "2"), "humidity": ("humidity", "60"), } WAVERTREE_SENSOR_RESULTS = { "weather": ("weather", "sunny"), "visibility": ("visibility", "Good"), "visibili...
from sys import stdin def readLine(): return stdin.readline().strip() def readInt(): return int(readLine()) def readInts():
return list(map(int, readLine().split())) def main(): T = readInt() for i in range(T): pages = [{'url': None, 'v': 0} for j in range(10)] for j in range(10): pages[j]['url'], pages[j]['v'] = readLine().split() pages[j]['v'] = int(pages[j]['v']) maxVal = max(pages, key=lambda x: x['v'])['v'] page...
= '__main__': main()
import sys import numpy as np from copy import copy, deepcopy import multiprocessing as mp from numpy.random import shuffle, random, normal from math import log, sqrt, exp, pi import itertools as it from scipy.stats import gaussian_kde, pearsonr from scipy.stats import ttest_1samp from itertools import product try: ...
j = geneindex(g2, genes) # to if (i > -1 and j > -1): x = map(float,dats[i]) #from y = map(float,d
ats[j]) # to x = np.array(x); x = (x-x.mean())/max(1,(x-x.mean()).max()) y = np.array(y); y = (y-y.mean())/max(1,(y-y.mean()).max()) return((x,y)) else: return( ([],[]) ) def corEdges(exprfile, genefile, fileout, reps, cpus, g1, g2): genes = open(genefile,'r').read().strip().s...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings import django.core.validators class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ] operations = [...
, ), migrations.CreateModel( name='Album', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False,
auto_created=True, primary_key=True)), ('title', models.CharField(max_length=20)), ('description', models.CharField(max_length=140)), ('date_uploaded', models.DateField(auto_now_add=True)), ('date_modified', models.DateField(auto_now=True)), ...
from argh import dispatch_commands from argh.decorators import named, arg from geobricks_raste
r_correlation.core.raster_correlation_core import get_correlation @named('corr') @arg('--bins', default=150, help='Bins')
def cli_get_correlation(file1, file2, **kwargs): corr = get_correlation(file1, file2, kwargs['bins']) print "Series: ", corr['series'] print "Stats: ", corr['stats'] def main(): dispatch_commands([cli_get_correlation]) if __name__ == '__main__': main()
from django.utils.translation import ugettext_lazy as _ import horizon from openstack_dashboard.dashboards.groups import dashboard class Instances(horizon.Panel): name = _("Groups")
slug = "instances" das
hboard.Groups.register(Instances)
import striga class
CustomConte
xt(striga.context): pass
# This file is part of h5py, a Python interface to the HDF5 library. # # http://www.h5py.org # # Copyright 2008-2013 Andrew Collette and contributors # # License: Standard 3-clause BSD; see "license.txt" for full license terms # and contributor agreement. from __future__ import absolute_import import tempf...
ual(descriptor, 0)
os.fsync(descriptor) finally: shutil.rmtree(dn_tmp) class TestCacheConfig(TestCase): def test_simple_gets(self): dn_tmp = tempfile.mkdtemp('h5py.lowtest.test_h5f.TestFileID.TestCacheConfig.test_simple_gets') fn_h5 = os.path.join(dn_tmp, 'test.h5') try: ...
emoved']['install'] = 1 expectations['compute']['removed']['uninstall'] = 1 self.deployment_assertions(expectations) def test_compute_scale_in_compute_ignore_failure_true(self): expectations = self.deploy_app('scale_ignore_failure') expectations['compute']['new']['install'] = 3 ...
ute']['existing']['install'] = 0 expectations['db']['existing']['install'] = 1 expectations['db']['existing']['rel_install'] = 0 expectations['db']['existing']['scale_rel_install'] = 2 self.deployment_assertions(expectations) expectations = self.scale(parameters={ 's...
'delta': -1}) expectations['compute']['new']['install'] = 0 expectations['compute']['existing']['install'] = 0 expectations['compute']['removed']['install'] = 1 expectations['compute']['removed']['uninstall'] = 1 expectations['db']['existing']['install'] = 1 expecta...
# Copyright 2009 Daniel Woodhouse # #This file is part of mtp-lastfm. # #mtp-lastfm 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. # #mtp...
a list""" tree = ET.parse(doc) iter = tree.getiterator() tags = [] for child in iter: if child.tag == tag: tags.append(child.text) return tags def create_api_sig(self, dict): """dict is a dicti
onary of param_name : value sorted into the correct order""" data = "" items = dict.items() items.sort() for i in items: for j in i: data += j data += self.api_2 api_sig = hashlib.md5(data.encode('UTF-8')).hexdigest() return api_sig ...
for i in [40,80, 160, 200, 211, 250, 375, 512, 550]: start = self.gen.randrange(2 ** (i-2)) stop = self.gen.randrange(2 ** i) if stop <= start: continue self.assertTrue(start <= self.gen.randrange(start, stop) < stop) def test_rangelimits(sel...
is, so # I am opting for using a generator as the middle argument of setstate # wh
ich attempts to cast a NaN to integer. state_values = self.gen.getstate()[1] state_values = list(state_values) state_values[-1] = float('nan') state = (int(x) for x in state_values) self.assertRaises(TypeError, self.gen.setstate, (2, state, None)) def test_referenceImplement...
from django.forms.widgets import TextInput from django.core.urlresolvers import reverse from django.conf import settings from django.utils.safestring import mark_safe class TagAutocompleteTagIt(TextInput): def __init__(self, max_tags, *args, **kwargs): self.max_tags = ( max_tags if...
on = ( "true" if getattr(settings, "TAGGING_AUTOCOMPLETE_REMOVE_CONFIRMATION", True) else "false" ) animate = ( "true" if getattr(settings, "TA
GGING_AUTOCOMPLETE_ANIMATE", True) else "false" ) list_view = reverse("ac_tagging-list") html = super(TagAutocompleteTagIt, self).render(name, value, attrs) # Subclass this field in case you need to add some custom behaviour like custom callbacks # js = u"""<script t...
from django import forms from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from apps.grid.fields import TitleField, UserModelChoiceField from apps.grid.widgets import CommentInput from .base_form import BaseForm class DealActionCommentForm(BaseForm): exclude_i...
a(cls, activity, group=None, prefix=""): data = super().get_data(activity, group, prefix) # Remove action comment, due to an old bug it seems to exist as an attribute too if "tg_action_comment" in data: del data["tg_action_comm
ent"] # Get action comment data["tg_action_comment"] = activity.comment or "" return data
ed header replaces the size field, # we need to recalculate the offset where the next # header starts. offset = next.offset_data if next.isreg() or next.type not in SUPPORTED_TYPES: offset += next._block(next.size) tarfi...
' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fi
leobj's mode. `fileobj' is not closed, when TarFile is closed. """ if len(mode) > 1 or mode not in "raw": raise ValueError("mode must be 'r', 'a' or 'w'") self.mode = mode self._mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] if not fileobj: if...
s # to the test configuration class TestConfig: # Create a simple second order system to use for testing sys = ct.tf([10], [1, 2, 1]) def test_set_defaults(self): ct.config.set_defaults('config', test1=1, test2=2, test3=None) assert ct.config.defa...
'config.oldkey'] == 4 assert ct.config.defaults['config.newkey'] == 4 ct.config.defaults.update({'config.newkey': 5}) with pytest.warns(FutureWarning, match=msgpattern): ct.config.defaults.update({'config.oldkey': 6}) with pytest.warns(FutureWarning, mat
ch=msgpattern): assert ct.config.defaults.get('config.oldkey') == 6 with pytest.raises(KeyError): with pytest.warns(FutureWarning, match=msgpattern): ct.config.defaults['config.oldmiss'] with pytest.raises(KeyError): ct.config.defaults['config.neverde...
# Generated by Django 2.2.4 on 2019-08-26 18:34 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('helpdesk', '0027_auto_20190826_0700'), ] operations = [ migrations.AlterFi...
), migrations.AlterField( model_name='ticket', name='assigned_to', field=models.ForeignKey(blank=True, null=True, on_delete=django.
db.models.deletion.CASCADE, related_name='assigned_to', to=settings.AUTH_USER_MODEL, verbose_name='Assigned to'), ), migrations.AlterField( model_name='ticketcc', name='user', field=models.ForeignKey(blank=True, help_text='User who wishes to receive updates for this t...
tablename = module + "_" + resourcename table = db.define_table(tablename, timestamp, Field("name", notnull=True), Field("description", "text"), Field("active", "boolean", default=True), migrate=migrate) ...
= IS_IN_DB(db, "delphi_group.id", "%(name)s") table.group_id.represent = lambda id: (id and [db(db.delphi_group.id == id).select(limitby=(0, 1)).first().name] or ["None"])[0] # C
RUD Strings ADD_PROBLEM = T("Add Problem") LIST_PROBLEMS = T("List Problems") s3.crud_strings[tablename] = Storage( title_create = ADD_PROBLEM, title_display = T("Problem Details"), title_list = LIST_PROBLEMS, title_update = T("Edit Problem"), title_search = T("Search...
# -*- coding: utf-8 -*- import logging from wakatime.compat import u try: import mock except ImportError: import unittest.mock as mock try: # Python 2.6 import unittest2 as unittest except ImportError: # Python >= 2.7 import unittest class TestCase(unittest.TestCase): patch_these = [] ...
)) and len(patch_this) > 0: retval = patch_this[1] if callable(retval): retval = retval() mocked.return_value = retval def tearDown(self): mock.patch.stopall() def normalize_list(self, items): return sorted([u(...
lf, first_list, second_list): self.assertEquals(self.normalize_list(first_list), self.normalize_list(second_list))
# CIS 410/510pm # Homework 5 beta 0.0.1 # Cameron Palk # May 2016 # # Special thanks to Daniel Lowd for the skeletor code import sys import tokenize from functools import reduce global_card = [] num_vars = 0 ''' Calc Strides ''' def calcStrides( scope ): rev_scope = list( reversed( scope ) ) res = [ 1 ] + [ 0 ] *...
ul__, factors ) z = sum( f.vals ) return z # ''' Main ''' def main(): # Read file factors = read_model() # Computer partition function z = computePartitionFunction( factors ) # Print results prin
t( "Z =", z ) return # Run main if this module is being run directly if __name__ == '__main__': main()
to BGR, they are already! So all we need to do is to normalize # by 255 if we want to convert to BGR255 format, or flip the channels # if we want it to be in RGB in [0-1] range. if cfg.INPUT.TO_BGR255: to_bgr_transform = T.Lambda(lambda x: x * 255) else: to_bgr_tr...
ce) for o in predictions] # always single image is passed at a time prediction = predictions[0] # reshap
e prediction (a BoxList) into the original image size height, width = original_image.shape[:-1] prediction = prediction.resize((width, height)) if prediction.has_field("mask"): # if we have masks, paste the masks in the right position # in the image, as defined by the bo...
from ...utils.code_utils import deprecate_mo
dule deprecate_module("EMUtils", "waveform_utils", "0.16.0", error=True) from .waveform_
utils import *
class Breakpoint(): def __i
nit__(self, breakpo
intNumber): self.breakpointNumber = breakpointNumber class BreakpointPPUByTime(Breakpoint): def __init__(self, breakpointNumber, scanline, tick): Breakpoint.__init__(self, breakpointNumber) self._scanline = scanline self._tick = tick def toString(self): retu...
#!/usr/bin/env python from flask import Flask, jsonify, request, abort, render_template app = Flask(__name__) @app.route("
/",methods=['GET']) def index(): if request.method == 'GET': return render_template('index.html') else: abort(400) @app.route("/devices",methods=['GET']) def devices(): if request.method == 'GET': r
eturn render_template('devices.html') else: abort(400) if __name__ == "__main__": app.debug = True app.run(host='0.0.0.0')
that param type conversion happens. """ def test_int(self): lr = LogisticRegression(maxIter=5.0) self.assertEqual(lr.getMaxIter(), 5) self.assertTrue(type(lr.getMaxIter()) == int) self.assertRaises(TypeError, lambda: LogisticRegression(maxIter="notAnInt")) self.assertRa...
ord_only def setParams(self, seed=None): """ setParams(self, seed=None) Sets params for this test. """ kwargs = self._input_kwargs return self._set(**kwargs) c
lass HasThrowableProperty(Params): def __init__(self): super(HasThrowableProperty, self).__init__() self.p = Param(self, "none", "empty param") @property def test_property(self): raise RuntimeError("Test property to raise error when invoked") class ParamTests(SparkSessionTestCase...
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
iron.get('LOCA
L_KAFKA_JAR'), "LOCAL_KAFKA_JAR environment var is not provided.") class CrossLanguageKafkaIOTest(unittest.TestCase): def get_open_port(self): s = None try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except: # pylint: disable=bare-except # Above call will fail for nodes that on...
from bibliopixel.animation.circle import Circle from bibliopixel.colors import palettes class Swirl(Circle): COLOR_DEFAULTS = ('palet
te', palettes.get('three_sixty')), def __init__(self, layout, angle=12, **kwds): super().__init__(layout, **kwds) self.angle = angle def pre_run(self): self._step = 0 def step(self, amt=1): for a in range(0, 360, self.angle): c = self.palette(self._s...
self._step += amt
from task_manager.tag_manager.tag_manager import TaggingModel from task_manager.models import Task import numpy as np import json enabled_tagger_ids = [tagger.pk for tagger in Task.objects.filter(task_type='train_tagger').filter(status='completed')] enabled_taggers = {} # Load Tagger models for _id in enabled_tagger...
ate(results_transposed): positive_tag_ids = np.nonzero(tagger_ids) positive_tags = [tagger_descriptions[positive_tag_id] for positive_tag_id in positive_tag_ids[0]] texta_facts = [] if positive_tags: if 'texta_...
documents[i]['texta_facts'] = [] for tag in positive_tags: new_fact = {'fact': 'TEXTA_TAG', 'str_val': tag, 'doc_path': input_feature, 'spans': json.dumps([[0,len(texts[i])]])} texta_facts.append(new_fact) ...
#!/usr/bin/env python3 # -*- coding : utf-8 -*- from collections import Iterable from collections import Iterator isinstance([], Iterable) isinstance({}, Iterable) isinstance((), Iterable) isinstance('abc', Iterabl
e) isinstance((x for x in range(10)), Iterable) isinstance(100, Iterable) # Iterable but not Iterator isinstance([], Iterator) isinstance({}, Iterator) isinstance((), Iterator) isinstance('abc', Iterator) isinstance((x for x in range(10)), Iterator) isinstance(100, Iterator) # use iter() to migrate iterable to i
terator # iterator is a data stream and donnot have a fixed length and is a lazy-calculated object # if you could use 'for loop' , then it's a Iterable # if you could use 'next()' , then it's a Iterator for x in [1, 2, 3, 4, 5]: pass # Equals to it = iter([1, 2, 3, 4, 5]) while True: try: x = next(i...
# Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json import requests from django.conf import settings def get_contact(school): if not settings.ZOHO_CREDENTIALS: return list_url = 'https://invoic...
st_name": "", "last_name": "", "email": school.primary_email, "phone": "", "mobile": "", "is_primary_contact": True }], "default_templates": { "invoice_template_id": "", "estimate_template_id": "", "creditnote_template_id": "", ...
plate_id": "", "creditnote_email_template_id": "" }, "notes": "" }
break if status != "creating" and status != "deleting" : #予期しないステータス raise IaasException("EPROCESS-000112", [volumeId, status,]) return volume; def createVolume(self, instanceNo, volumeNo) : tableAWSVOL = self.conn.getTable("AWS_VOLUME")...
stanceNo, volumeNo) : tableAWSVOL = self.conn.getTable("AWS_VOLUME") awsVolume = self.conn.selectOne(tableAWSVOL.select(tableAWSVOL.c.VOLUME_NO==volumeNo)) volumeId = awsVolume["VOLUME_ID"] # ボリュームの作成待ち volume = None try : volume = self.waitVolume(volumeId) ...
#ボリューム作成失敗時 raise IaasException("EPROCESS-000113", [volumeId, volume.status,]) # ログ出力 self.logger.info(None, "IPROCESS-100122", [volumeId,]) except Exception: self.logger.error(traceback.format_exc()) # ボリューム作成失敗時 awsVol...
# Copyright 2012 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditi...
moved. Can you avoid introducing the\n' '#include? See relevant DEPS file(s) for details and contacts.', warning_descriptions)) return results def _CommonChecks(input_api, output_api): """Checks common to both upload and commit.""" results = [] results.extend(input_api.canned_checks.CheckOwner...
results.extend(_V8PresubmitChecks(input_api, output_api)) results.extend(_CheckUnwantedDependencies(input_api, output_api)) return results def _SkipTreeCheck(input_api, output_api): """Check the env var whether we want to skip tree check. Only skip if src/version.cc has been updated.""" src_version = 'sr...
""" CacheItem interface: '_id': string, 'url': string, 'response_url': string, 'body': string, 'head': string, 'response_code': int, 'cookies': None,#grab.response.cookies, """ from hashlib import sha1 import zlib import logging import marshal import time from grab.response import Response from grab.cookie import Cook...
BLES WHERE TABLE_TYPE = 'BASE TABLE' AND table_schema NOT IN ('pg_catalog', 'information_schema')""" ) found = False for row in self.cursor: if row[0] == 'cache': found = True break
if not found: self.create_cache_table() def create_cache_table(self): self.cursor.execute('BEGIN') self.cursor.execute(''' CREATE TABLE cache ( id BYTEA NOT NULL CONSTRAINT primary_key PRIMARY KEY, timestamp INT NOT NULL, d...
import websocket import package import thread import time import run import random import config import dht import logging logging.basicConfig() def on_message(ws, message): #d = package.LoadPackage(message) #res = run.PackageParser(d) #ws.send(package.DumpPackage(res)) print message def on_error(ws...
int("### closed ###") def on_open(ws): deviceConfig = config.DeviceConfig() deviceConfig.Update("device.conf") HSPackage = package.GenSH(deviceConfig) #print HSPackage,123 ws.send(HSPackage) def SendRandomData(*args): while True: humdi, temp = dht.GetData() if ...
or temp == -1): continue dump = package.SensorDump(0, temp) dump1 = package.SensorDump(1, humdi) ws.send(dump) ws.send(dump1) time.sleep(1) thread.start_new_thread(SendRandomData, ()) if __name__ == "__main__": ws = websocket.WebSocke...
dict values containing a protocol string and a list of port range strings. This is a substructure of the firewall rule dictionaries, which additionally contain a 'source' field. Raises: ValueError: If any of the input strings are malformed. """ def _AddToPortSpecs(protocol, port_string, ...
rt_string, port_specs) _AddToPortSpecs(socket.getprotobyname('udp'), port_string, port_specs) return port_specs.values() def __init__(self, allowed, allowed_ip_sources): self.port_specs = FirewallRules.ParsePortSpecs(allowed) self.source_ranges = allowed_ip_sources self.source_tags = [] ...
ags = sorted(set(source_tags)) self.target_tags = sorted(set(target_tags)) def AddToFirewall(self, firewall): if self.source_ranges: firewall['sourceRanges'] = self.source_ranges if self.source_tags: firewall['sourceTags'] = self.source_tags if self.target_tags: firewall['targetTags...
import os import os.path from freight.constants import PROJECT_ROOT from freight.exceptions import CommandError class UnknownRevision(CommandError): pass class Vcs(object): ssh_connect_path = os.path.join(PROJECT_ROOT, "bin", "ssh-connect") def __init__(self, workspace, url, username=None): se...
y, value) env.setdefault("FREIGHT_SSH_REPO", self.url) kwargs["env"] = env if capture: handler = workspace.capture else: handler = workspace.run rv = handler(command, *args, **kwargs) if isinstance(rv, bytes): rv = rv.decode("utf8")
if isinstance(rv, str): return rv.strip() return rv def exists(self, workspace=None): if workspace is None: workspace = self.workspace return os.path.exists(workspace.path) def clone_or_update(self): if self.exists(): self.update() ...
"""Top level site urls.""" from django.conf.urls import patterns, include, url from quiz2 import views from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', url(r'^$', views.home, name='home'), url(r'^register/$', views.register, name='register'), url(r'^login/$', views.u...
ser/password/reset/$', 'django.contrib.auth.views.password_reset', {'post_reset_redirect' : '/user/password/reset/done/'}, name="password_reset"), (r'^user/password/reset/done/$', 'django.contrib.auth.views.password_reset_done'), (r'^user/password/reset/(?P<uidb36>[0-9A-Za-z]+)-(...
'django.contrib.auth.views.password_reset_complete'), )
def get_weekday(current_weekday, days_ahead): """ (int, int) -> int Return which day of the week it will be days_ahead days from current_weekday. current_weekday is the current day of the week and is in the range 1-7, indicating whether today is Sunday (1), Monday (2), ..., Saturday (7). days...
_weekday(6, 116, 3) 5 """ days_diff = days_difference(current_day, birth
day_day) return get_weekday(current_weekday, days_diff)
from .base import * # noqa INTERNAL_IPS = INTERNAL_IPS + ('', ) ALLOWED_HOSTS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app_kdl_liv', 'USER': 'app_kdl', 'PASSWORD': '', 'HOST': '' }, } # ------------------------------...
y: import django_extensions # noqa INSTALLED_APPS = INSTALLED_APPS + ('django_extensions',) except ImportError:
pass # ----------------------------------------------------------------------------- # Local settings # ----------------------------------------------------------------------------- try: from .local import * # noqa except ImportError: pass
# -*- coding: utf-8 -*- from django.conf.urls import url from projects import views urlpatterns = [ url(r'^$', views.MainPageView.as_view(), name='main'), # Inlist url(r'^inlist/$', views.InlistView.as_view(), name='inlist'), url(r'^inlist/(?P<pk>[0-9]+)/delete/$', views.InlistItemDelete.as_view(), ...
s.ProjectView.as_view(), name='project'), url(r'^project/create/$', views.CreateProjectView.as_view(), name='create_project'), url(r'project/(?P<pk>[0-9]+)/edit/$', views.EditProjectView.as_view(), name='edit_project'), url(r'project/(?P<
pk>[0-9]+)/delete/$', views.DeleteProjectView.as_view(), name='delete'), url(r'sort/actions/$', views.ActionlistSortView.as_view(), name='sort_actions'), ]
from pydevin import * import math # ball parameters definitions BALL_POS_Y_MAX = 115 BALL_POS_Y_MIN = 5 BALL_POS_Y_CENTER = (BALL_POS_Y_MAX + BALL_POS
_Y_MIN) / 2.0 BALL_POS_X_MAX = 125 BALL_POS_X_MIN = 20 BALL_POS_X_CENTER = (BALL_POS_X_MAX + BALL_POS_X_MIN) / 2.0 A_X = -1.0/(BALL_POS_X_MAX - BALL_POS_X_CENTER) B_X = -(A_X)*BALL_POS_X_CENTER A_Y = -1.0/(BALL_POS_Y_MIN - BALL_POS_Y_CENTER) B_Y = -(A_Y)*BALL_POS_Y_CENTER # ball tracking x_buffer = [ 0 for i in ra...
# end of ball parameters pos_computed = 0 # motor params alpha_x = 1 # l=1500, h=2500 beta_x = 0 alpha_y = 1 # l=1500, h=2500 beta_y = 0 pdev = PyDevin() pdev.init() def norm(x, y): return math.sqrt(x*x + y*y) def r_range(v, l, h): if(v < l): return l elif(v > h): return h return v # ball tracki...
# -*- coding: utf-8 -*- # © 2016 Cyril Gaudin (Camptocamp) # License AGPL-3.0
or later (http://www.gnu.org/licenses/agpl). from opene
rp import api, fields, models class MrpConfigSettings(models.TransientModel): """ Add settings for dismantling BOM. """ _inherit = 'mrp.config.settings' dismantling_product_choice = fields.Selection([ (0, "Main BOM product will be set randomly"), (1, "User have to choose which compone...
''' 9.5 First, you have to resolve assignment9_3. This is slightly different. This program records the domain name (instead of the address) where the message was sent from instead of who the mail came from (i.e., the whole email address). At the end of the program,
print out the contents of your dictionary. Sample: python assignment9_5_dictionary.py {'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7, 'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8} ''' dDomain = dict() try: flHand = open("mbox-short.txt") except: print('There is no "mbox-short.txt" file in the...
e lWords = sLine.split() lEmailDomain = lWords[1].split('@') dDomain[lEmailDomain[1]] = dDomain.get(lEmailDomain[1], 0) + 1 print (dDomain)
# -*- 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 'Reference_Domain.external_id' db.add_column(u'django_reference_data_reference_domain', 'exte...
db.models.fields.CharField',
[], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'admin_code2': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'admin_code3': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), ...
if os.path.isfile(image): dockerfile = image else: dockerfile = "{:s}/Dockerfile".format(image) with open(dockerfile, "r") as std: _from = "" for line in std.readlines(): if line.startswith("FROM"): _from = line return _from def change_Docke...
casa --nologger --log2term --nologfile -c", tf.name]) # log taskname.last task_last = '%s.last' % taskname if os.path.exists(task_last): with opEn(task_last, 'r') as last: print('%s.last is: \n %s' % (taskname, last.read())) # remove temp directory. This also gets rid of the casa l...
""" Stack a list of fits files along a given axiis. fitslist: list of fits file to combine outname: output file name axis: axis along which to combine the files fits: If True will axis FITS ordering axes ctype: Axis label in the fits header (if given, axis will be ignored) ...
from django.contrib import admin from achievs.models import Achievement # from achievs.models import Gold # from achievs.models import Silver # from achievs.models import Bronze # from achievs.models import Platinum from achievs.models import Level # class PlatinumInline(admin.StackedInline): # model=Platinum # cla...
odelAdmin): fieldsets = [ (None, {'fields': ['name']}), ('Date information', {'fields': ['pub_date']}), ] #inlines=[GoldInline, SilverInline, BronzeInline, PlatinumInline] inlines=[LevelInline] list_display = ('name', 'pub_date') list_filter=['pub_date'] search_fields=['name']
date_hierarchy='pub_date' # admin.site.register(Gold) # admin.site.register(Silver) # admin.site.register(Bronze) # admin.site.register(Platinum) admin.site.register(Level) admin.site.register(Achievement, AchievementAdmin)
# ============================================================================ # # Copyright (c) 2007-2010 Integral Technology Solutions Pty Ltd, # All Rights Reserved. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL...
tores is None or len(fileStores)==0: log.info('Persistent Store is not specified, skipping.') else:
fileStoreList=fileStores.split(',') for fileStore in fileStoreList: __createFileStore(fileStore, resourcesProperties, domainProperties) #======================================================================================= # Configure filestore #=====================================...
d = {} for i in range(100000
): d[i] = i JS_CODE = ''' var d = {}; for (var i = 0; i < 100000; i++) {
d[i] = i; } '''
from __future__ import
unicode_literals from django.apps import AppConfig class PaypalConfi
g(AppConfig): name = 'paypal'
import matplotlib matplotlib.use('WXAgg') from matplotlib import cm import matplotlib.pyplot as plt import numpy as np import CoolProp from mpl_toolkits.mplot3d import Axes3D fig = plt.figure(figsize=(2, 2)) ax = fig.add_subplot(111, projection='3d') NT = 1000 NR = 1000 rho, t = np.logspace(np.log10(2e-3), np.log10(1...
NR) Tsat = np.linspace(273.17, 647.0, 100) psat = CoolProp.CoolProp.PropsSI('P', 'Q', 0, 'T', Tsat, 'Water') rhoL = CoolProp.CoolProp.PropsSI('D', 'Q', 0, 'T', Tsat, 'Water') rhoV = CoolProp.CoolProp.PropsSI('D', 'Q', 1, 'T', Tsat, 'Water') ax.plot_surface(np.log(RHO), T, np.log(P), cmap=cm.jet, edgecolor='none') ax...
plot(np.log(rhoV), Tsat, np.log(psat), color='k', lw=2) ax.text(0.3, 800, 22, "CoolProp", size=12) ax.set_frame_on(False) ax.set_axis_off() ax.view_init(22, -136) ax.set_xlabel(r'$\ln\rho$ ') ax.set_ylabel('$T$') ax.set_zlabel('$p$') plt.tight_layout() plt.savefig('_static/PVTCP.png', transparent=True) plt.savefig('_s...
#!/usr/bin/env python from __future__ import absolute_import import os import shutil import tempfile from distutils.core import setup from .Dependencies import cythonize, extended_iglob from ..Utils import is_package_dir from ..Compiler import Options try: import multiprocessing parallel_compiles = int(mult...
}, help='set a cythonize option') parser.add_option('-3', dest='python3_mode', action='store_true', help='use Python 3 syntax mode by default') parser.add_option('-x', '--exclude', metava
r='PATTERN', dest='excludes', action='append', default=[], help='exclude certain file patterns from the compilation') parser.add_option('-b', '--build', dest='build', action='store_true', help='build extension modules using distutils') parser.ad...
# -*- coding: utf-8 -*- """ Running the Gibbs sampler on flowcymetry data http://www.physics.orst.edu/~rubin/nacphy/lapack/linear.html matlab time: Elapsed time is 1.563538 seconds. improve sample_mu: python: 0.544 0.005 0.664 cython_admi: 0.469 0.005 0.493 moved_index_in_cyt...
mix.data[mix.x==k,1],'o') plt.figure() for k in range(mix.K): plt.plot(mus[:,(2*k):(2*(k+1))]) plt.show() print("mixture took %.4f sec"%(t1-t0)) mix2 = GMM.mixture(
data,K) mus = np.zeros((sim,4)) t0 = time.time() for i in range(sim): mix2.sample() t1 = time.time() print("Python mixture took %.4f sec"%(t1-t0)) if 0: import pstats, cProfile import pyximport pyximport.install() import bayesianmixture.distr...
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2017-02-12 06:08 from
__future__ import unicode_literals from django.db import migrations import fossevents.users.models class Migration(migrations.Migration): dependencies = [ ('users', '0004_user_is_moderator'), ] operations = [ migrations.AlterModelManagers(
name='user', managers=[ ('objects', fossevents.users.models.CustomUserManager()), ], ), ]
# -*- coding: utf-8 -*- """The app module, containing the app factory function.""" from flask import Flask, render_template, Markup from . import public, admin from .extensions import * from .config import Config #extensions def getPackage(num): packages = { "0": "No Package", "1": "Basic Package"...
letter in value: if _js_escapes.has_key(letter): retval.
append(_js_escapes[letter]) else: retval.append(letter) return Markup("".join(retval)) #creates and returna a flask app instance def create_app(config_object=Config): app = Flask(__name__) app.config.from_object(config_object) register_extensions(app) re...
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Tests for the module module, which contains Module and related classes.""" import os import unittest from tvcm import fake_fs from...
der.LoadModule(module_name='src.my_module')
assert False, 'Expected an exception' except module.DepsException, e: exc = e self.assertEquals( ['src.my_module', 'tvcm.foo'], exc.context) def testGetAllDependentFilenamesRecursive(self): fs = fake_fs.FakeFS() fs.AddFile('/x/y/z/foo.html', """ <!DOCTYPE html> <lin...
if not self.company_id.transfer_account_id.id: raise UserError(_('Transfer account not defined on the company.')) self.destination_account_id = self.company_id.transfer_account_id.id elif self.partner_id: if self.partner_type == 'customer': self.d...
ment_type == 'outbound': sequence_code = 'account.payment.supplier.invoice' rec.name = self.env['ir.sequence'].with_context(ir_sequence_date=rec.payment_date).next_by_
code(sequence_code) if not rec.name and self.payment_type != 'transfer': raise UserError(_("You have to define a sequence for %s in your company.") % (sequence_code,)) # Create the journal entry amount = rec.amount * (rec.payment_type in ('outbound', 'transfer') and ...
""" JSONField automatically serializes most Python terms to JSON data. Creates a TEXT field with a default value of "{}". See test_json.py for more information. from django.db import models from django_extensions.db.fields import json class LOL(models.Model): extra = json.JSONField() """ from __future__ impo...
ONList(res) return res else: return value def get_db_prep_save(self, value, connection, **kwargs): """Convert our JSON object to a string before we save""" if value is None and self.null: return None # default values come in as strings; only non-s...
ing_types): value = dumps(value) return super(JSONField, self).get_db_prep_save(value, connection=connection, **kwargs) def south_field_triple(self): """Returns a suitable description of this field for South.""" # We'll just introspect the _actual_ field. from south.mode...
#!/usr/bin/env python # -*- coding: utf8 -*- """setup (C) Franck Barbenoire <fbarbenoire@yahoo.fr> License : GPL v3""" from distutils.core import setup from setuptools import find_packages setup(name = "django-openzoom", version = "0.1.1", description = "Django application for displaying very high resolution...
m", packages = find_packages(), include_package_data = True, zip_safe = False, classifiers = ['Development Status :: 3 - Alpha', 'License :: OSI Approved :: GNU General Public License (GPL)',
'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Framework :: Django', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content'] )
from __future__ import print_function def validate_book(body): ''' This does not only accept/refuse a book. It also returns an ENHANCED version of body, with (mostly fts-related) additional fields. This function is idempotent. ''' if '_language' not in body: raise ValueError('language...
return self._search({'quer
y': {'multi_match': {'query': query, 'fields': '_text_*'} }}) def get_books_by_title(self, title): return self._search(self._get_search_field('title', title)) def get_books_by_actor(self, authorname): return self._se...
# -*- coding: UTF-8 -*- ############################################################################## # # OERPLib # Copyright (C) 2012-2013 Sébastien Alix. # # 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 # ...
onnection_class( host, port, key_file, cert_file, strict, timeout)) self.key_file = key_file self.cert_file = cert_file class TimeoutSafeTransportPy26(xmlrpclib.SafeTransport): def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *args, **k...
host, extra_headers, x509 = self.get_host_info(host) conn = TimeoutHTTPSPy26(host, timeout=self.timeout) return conn # Define the TimeTransport and TimeSafeTransport class version to use TimeoutTransport = TimeoutTransportPy26 TimeoutSafeTransport = TimeoutSafeTransportPy26 else: ...
ing the inputs unchanged. def f_oneway(*args): """Performs a 1-way ANOVA. The one-way ANOVA tests the null hypothesis that 2 or more groups have the same population mean. The test is applied to samples from two or more groups, possibly with differing sizes. Read more in the :ref:`User Guide <univa...
nal optimizations. """ f_obs = np.asarray(f_obs, dtype=np.float64) k = len(f_obs) # Reuse f_obs for chi-squared statistics chisq = f_obs chisq -= f_exp chisq **= 2 chisq /= f_exp chisq = chisq.sum(axis=0) return chisq, special.chdtrc(k - 1, chisq) def chi2(X, y): """Co...
and class. This score can be used to select the n_features features with the highest values for the test chi-squared statistic from X, which must contain only non-negative features such as booleans or frequencies (e.g., term counts in document classification), relative to the classes. Recall that ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from os.path import join, isfile from os import walk import io import os import sys from shutil import rmtree from setuptools import find_packages, setup, Command def read_file(filename): with open(filename) as fp: return fp.read().strip() def read_requirem...
guage :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: Imp
lementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy' ], package_data={ '': package_files([ 'gerapy/server/static', 'gerapy/server/core/templates', 'gerapy/templates', ]) }, # $ setup.py publish support. cmdcla...
t_messages_sent": "300", "ports": "3", "flow_datapath_id": "55120148545607", "switch_port_counters": [{ "bytes_received": "0", "bytes_sent": "512", "duration": "200", "packets_internal_received": "444", "...
'controller': 'OpenDaylight_V2', 'port_number_on_switch': 3, 'switch': '55120148545607' }, ADMIN_ID), (9800, '55120148545607:2', { 'controller': 'OpenDaylight_V2', 'port_number_on_switch': 2, 'neutron_port_id': POR...
(100, '55120148545607:1', { 'controller': 'OpenDaylight_V2', 'port_number_on_switch': 1, 'neutron_port_id': PORT_1_ID, 'switch': '55120148545607' }, ADMIN_ID), ] self._test_for_meter('switch.port.receive.bytes', expected_da...
zone = self.driver.list_zones()[0] Route53MockHttp.type = 'ZONE_DOES_NOT_EXIST' try: self.driver.list_records(zone=zone) except ZoneDoesNotExistError as e: self.assertEqual(e.zone_id, zone.id) else: self.fail('Exception was not thrown') de...
es_not_exist(self): Route53MockHttp.type = 'RECORD_DOES_NOT_EXIST' rid = 'CNAME:doesnotexist.t.com' try: self.driver.get_record(zone_id='47234', record_id=rid
) except RecordDoesNotExistError: pass else: self.fail('Exception was not thrown') def test_create_zone(self): zone = self.driver.create_zone(domain='t.com', type='master', ttl=None, extra=None) self.assertEqual(zone.id,...
def s
um_args(*args): return sum(ar
gs)
# i18n markers def N_(msg): ''' Si
ngle translatable string marker. Does nothing, just a marker for \\*.pot file compilers. Usage:: n = N_('translate me') translated = env.gettext(n) ''' return msg class M_(object): ''' Marker for translatable string with plural form. Does not make a translation, just inca...
d: a key used to format Usage:: message = M_(u'max length is %(max)d symbol', u'max length is %(max)d symbols', count_field="max") m = message % {'max': 10} trans = env.ngettext(m.single, m.plural, ...
port types import warnings warnings.warn("the imp module is deprecated in favour of importlib; " "see the module's documentation for alternative uses", PendingDeprecationWarning, stacklevel=2) # DEPRECATED SEARCH_ERROR = 0 PY_SOURCE = 1 PY_COMPILED = 2 C_EXTENSION = 3 PY_RESOURCE = 4 PKG_D...
hould be returning bytes, but # SourceLoader.get_code() just passed what is returned to # compile() which can handle str. And converting to bytes would # require figuring out
the encoding to decode to and # tokenize.detect_encoding() only accepts bytes. return file.read() else: return super().get_data(path) class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader): """Compatibility support for implementing load_sou...