prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.internet._sigchld}, an alternate, superior SIGCHLD monitoring API. """ import os, signal, errno from twisted.python.log import msg from twisted.trial.unittest import TestCase from twisted.internet.fdesc import setNonBlock...
IG_DFL) else: self.signalModuleHandler = None self.oldFD = self.installHandler(-1) if self.signalModuleHandler is not None and self.oldFD != -1: msg("SIGCHLD setup issue: %r %r" % (self
.signalModuleHandler, self.oldFD)) raise RuntimeError("You used some signal APIs wrong! Try again.") def tearDown(self): """ Restore whatever signal handler was present when setUp ran. """ # If tests set up any kind of handlers, clear them out. self.installHand...
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
type of fuel self.fuelCost = fuelCost #: The type of fossil fuel, such as coal, oil, or gas. Values are: "oil", "coal", "lignite", "gas" self.fossilFuelTyp
e = fossilFuelType #: The active power output level of the unit at which the given type of fuel is switched off. This fuel (e.g., oil) is sometimes used to stabilize the base fuel (e.g., coal) at low active power output levels. self.lowBreakpointP = lowBreakpointP #: The cost of fuel used for ...
# A Test Program for pipeTestService.py # # Install and start the Pipe Test service, then run this test # either from the same machine, or from another using the "-s" param. # # Eg: pipeTestServiceClient.py -s server_name Hi There # Should work. from win32pipe import * from win32file import * from win32event import * ...
ait for all threads to finish. WaitForMultipleObjects(thread_waits, 1, INFINITE) def main(): import sys, getopt server = "." thread_count = 0 msg_count = 500 try: opts, args = getopt.getopt(sys.argv[1:], 's:t:m:vl') for o,a in
opts: if o=='-s': server = a if o=='-m': msg_count = int(a) if o=='-t': thread_count = int(a) if o=='-v': global verbose verbose = 1 if o=='-l': testLargeMessage(s...
class Config: # specific (for this development instance) # SERVER_NAME = 'localhost:5000' SQLALCHEMY_DATABASE_URI = "sqlite:///data.db" ANTIVIRUS_CHECK_REQUIRED = False SECRET_KEY = "toto" # develop settings DEBUG = True ASSETS_DEBUG = True DEBUG_TB_ENABLED = True # TEMPLATE_DEB...
_PREFETCH_MULTIPLIER = 1
CELERY_ALWAYS_EAGER = False # True: run tasks locally, no async CELERY_EAGER_PROPAGATES_EXCEPTIONS = True # uncomment if you don't want to use system timezone # CELERY_TIMEZONE = 'Europe/Paris'
olic booleans as variadic positional arguments. """ if len(args) > 0 and isinstance(args[0], (list, tuple)): raise Exception("Tuple or list passed to add_constraints!") if o.TRACK_CONSTRAINTS in self.options and len(args) > 0: if o.SIMPLIFY_CONSTRAINTS in self.options: ...
ugins: self.se.downsize() # # State branching operations # def step(self, **kwargs): """ Perform a step of symbolic execution using this state. Any arguments to `AngrObjectFactory.successors` can be passed to this. :return: A SimSuccessors object categorizi...
he basic block at this state's instruction pointer. Any arguments to `AngrObjectFactory.block` can ba passed to this. :return: A Block object describing the basic block of code at this point. """ if not args and 'addr' not in kwargs: kwargs['addr'] = self.addr return...
########## recombination.py parameters class Recombination_Parameters(object): # Change these two values to the folders you prefer - use an absolute path e.g. /Users/Harry/fastq-data and # /Users/Harry/csv-data or a path relative to the tools directory. # You may use the same folder for input and output. ...
ontains the # actual signatures, separated by a comma (each serotype can have multiple signatures) signatures = { "AAV1": [ "AGTGCTTCAACGGGGGCCAG", "GGGCGTGAATCCATCATCAACCCTGG", "CCGGAGCTTCAAACACTGCATTGGACAAT" ], "AAV2": [ "AGGCAACAGACAAGCA...
TTCATC" ], "AAV7": [ "AGTGAAACTGCAGGTAGTACC" ], "AAV8": [ "GCAAAACACGGCTCCTCAAAT", "CAGCAAGCGCTGGAACCCCGAGATCCAGTA", "AAATACCATCTGAATGGAAGAAATTCATTG", "CGTGGCAGATAACTTGCAGC", "ATCCTCCGACCACCTTCAACC" ], ...
output_shape = ((2, 2048, 1, 1) if data_format == 'channels_first' else (2, 1, 1, 2048)) self.assertEqual(output_shape, output.shape) if data_format == 'channels_first': block_shapes = { 'block0': (2, 64, 112, 112), 'block0mp': (2, 64, 55, 55), 'block1'...
ata_format) apply_gradients(model, optimizer, compute_gradients(model, images, labels)) self.assertEqual(320, len(model.variables)) context.async_wait() events = events_fr
om_logdir(logdir) self.assertEqual(len(events), 2) self.assertEqual(events[1].summary.value[0].tag, 'loss') @test_util.disable_tfrt('Flaky test. b/157103729') def test_train(self): self._test_train() @test_util.disable_tfrt('TFE_ContextGetExecutorForThread missing b/156188669') def test_train_asyn...
#!/usr/bin/env python3 # 574A_bear.py - Codeforces.com/problemset/problem/574/A Bear program by Sergey 2015 import unittest import sys ############################################################################### # Bear Class ############################################################################### class Be...
#################################### class unitTests(unittest.TestCase): def test_single_test(self): """ Bear class testing """ # Constructor test test = "5\n5 1 11 2 8" d = Bear(test) self.assertEqual(d.n, 5) self.assertEqual(d.nums, [5, 1, 11, 2, 8]) # ...
mple test test = "4\n1 8 8 8" self.assertEqual(Bear(test).calculate(), "6") # Sample test test = "2\n7 6" self.assertEqual(Bear(test).calculate(), "0") # My tests test = "4\n0 1 1 1" self.assertEqual(Bear(test).calculate(), "2") # Time limit tes...
#!/usr/bin/python -O # # /usr/sbin/webapp-config # Python script for managing the deployment of web-based # applications # # Originally written for the Gentoo Linux distribution # # Copyright (c) 1999-2007 Authors # Released under v2 of the GNU GPL # # Author(s) Stuart Herbert # ...
ED_DIR' : None, 'VHOST_PERMS_VIRTUALOWNED_FILE': None, 'VHOST_PERMS_INSTALLDIR' : None, 'ROOT'
: self.__root, 'PN' : None, 'PVR': None} result = {} for i in list(export_map.keys()): value = export_map[i] if not value: value = self.get_config(i.lower()) os.putenv(i, str(value)) ...
kld = GPSI.compute_fe_terms(xi, xo, xm, sample_count=10) vfe = np.mean(nll) + np.mean(kld) str1 = " va_nll_bound : {}".format(vfe) str2 = " va_nll_term : {}".format(np.mean(nll)) str3 = " va_kld_q2p : {}".format(np.mean(kld)) joint_str = "\n".join(...
rng=rng) ############
#################################################### # Apply some updates, to check that they aren't totally broken # ################################################################ log_name = "{}_FINAL_RESULTS_NEW.txt".format(result_tag) out_file = open(log_name, 'wb') Xva = row_shuffle(Xva) ...
# -*- coding: utf-8 -*- # Gene
rated by Django 1.10.1 on 2016-12-09 01:29 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("hordak", "0007_auto_20161209_0111")] operations = [ migrations.RenameField("Account", "has_statements", "is_bank_account"
) ]
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 this program. If not, see <http://www.gnu.org/licenses/>. ''' __version__ = "0....
, '43': ('360x640', 'webm'), '44': ('480x854', 'webm'), '45': ('720x1280', 'webm'), '46': ('1080x1920', 'webm'),
'82': ('640x360-3D', 'mp4'), '84': ('1280x720-3D', 'mp4'), '100': ('640x360-3D', 'webm'), '102': ('1280x720-3D', 'webm')} def __init__(self, streammap, opener, title="ytvid"): if not streammap.get("sig", ""): streammap['sig'] = [_decrypt_signature(streammap['s'][0])] ...
""" Markup class allows the use of easy-to-write characters to style the text instead of using escape codes. ==text== --> reverse video '''text''' --> bold ~~text~~ --> strikethrough Copyright (c) 2015 makos <https://github.com/makos>, chibi <http://neetco.de/chibi> under GNU GPL v3, see LICENSE for details """ impo...
input_text = input_text.replace('\033', '\\033') return input_text def demarkify(self, input_text): """Prints out a marked-up piece of text.""" output_text = self.esc(input_text) # strikethrough output_text = re.sub( '~~(?P<substring>.*?)~~', '\033[0;9m\g<substr...
tput_text) # bold output_text = re.sub( '\'\'\'(?P<substring>.*?)\'\'\'', '\033[0;1m\g<substring>\033[0m', output_text) # rv output_text = re.sub( '==(?P<substring>.*?)==', '\033[0;7m\g<substring>\033[0m', output_text) return outpu...
turn attr() return attr def get_feed(self, extra_params=None): if extra_params: try: obj = self.get_object(extra_params.split('/')) except (AttributeError, LookupError): raise LookupError('Feed does not exist') else: obj =...
ler, data): handler.startElement(u'source', {}) if data.get('id'): handler.addQuickElement(u'id', data['id']) if data.get('title'): self.write_text_construct(handler, u'title', data['title']
) if data.get('subtitle'): self.write_text_construct(handler, u'subtitle', data['subtitle']) if data.get('icon'): handler.addQuickElement(u'icon', data['icon']) if data.get('logo'): handler.addQuickElement(u'logo', data['logo']) if data.get('updated'):...
# Copyright (C) 2016 # Jakub Krajniak (jkrajniak at gmail.com) # # This file is part of ChemLab # # ESPResSo++ 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 # (...
.join(os.path.dirname(__file__), '..'))) import chemlab.gromacs_topology class TestTopologyReader(unittest.TestCase): @classmethod def setUpClass(cls): cls.topol_file = 'topol.top' cls.gt = chemlab.gromacs_topology.GromacsTopology(cls.topol_file, generate_exclusions=True) cls.gt.read()...
expected_nr_atoms = 0 for mol_name, nmols in self.gt.gt.molecules: mol_atoms = len(self.gt.gt.molecules_data[mol_name]['atoms']) expected_nr_atoms += nmols * mol_atoms self.assertEqual(total_nr_atoms, expected_nr_atoms) total_nr_bonds = len(self.gt.bonds)...
has a good docstring. # - Add methods for regex find and replace. # - guess_content_type() method? # - Perhaps support arguments to touch(). import sys, warnings, os, fnmatch, glob, shutil, codecs, hashlib __version__ = '2.2' __all__ = ['path'] # Platform-specific support for path.owner if os.name == 'nt': ...
): r""" Return a list of the path components in this path. The first item in the list will be a path. Its value will be either os.curdir
, os.pardir, empty, or the root directory of this path (for example, '/' or 'C:\\'). The other items in the list will be strings. path.path.joinpath(*result) will yield the original path. """ parts = [] loc = self while loc != os.curdir and loc != os.pardir: ...
# Copyright 2014-2015 Rumma & Ko Ltd # # License: GNU Affero General Public License v3 (see file COPYING for details) """Defines "parency links" between two "persons", and a user interface to manage them. This module is probably useful in combination with :mod:`lino_xl.lib.households`. .. autosummary:: :toctree: ...
o the model which represents a human in your application. Default value is ``'contacts.Person'`` (referring to :class:`lino_xl.lib.contacts.Person`). """ def on_site_startup(self, site): self.person_model = site.models.resolve(self.person_model) super(Plugin, self).on_site_startup(...
, site, user_type, m): # mg = site.plugins.contacts mg = site.plugins[self.person_model._meta.app_label] m = m.add_menu(mg.app_label, mg.verbose_name) m.add_action('humanlinks.Links') m.add_action('humanlinks.LinkTypes')
from
investor_lifespan_model.investor import Investor from investor_lifespan_model.market import Market from investor_lifespan_model.insurer import Insurer from investor_lifespan_model.lifespan_model import LifespanModel f
rom investor_lifespan_model.mortality_data import π, G, tf
RegObj.dll is an ActiveX server--and, hence, has an automation interface--that is available with documentation in the distribution file kno
wn as RegObji.exe, from the following page: http://msdn.microsoft.com/vbasic/downloads/addins.asp To provide early binding for RegObj use >>> from win32com.client import gencache >>> gencache.EnsureModule('{DE10C540-810E-11CF-BBE7-444553540000}', 0, 1, 0) or the MakePy ut
ility within PythonWin, referring to "Regstration Manipulation Classes (1.0)" (Please notice the spelling error.) Sample use, to determine what command is associated with a Python file: >>> from win32com.client import Dispatch, gencache >>> from win32con import HKEY_CLASSES_ROOT >>> gencache.EnsureModule('{DE10C540...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2010-2012 ChriCar Beteiligungs- und Beratungs- GmbH (<http://www.camptocamp.at>) # # Thi...
Foundation, either version 3 of the # License, or (at your option) any later ver
sion. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU A...
from django.core.management.base import BaseCommand, CommandError from geography.models import Place class Command(BaseCommand): help = u"""Add new places""" usage_str = 'USAGE: ./manage.py add_places map_name STATE|CITY|RIVER|LAKE|... [difficulty]' def handle(self, *args, **options): if len(args...
.usage_str) place_type = self.Place.PLACE_TYPE_SLUGS[args[1]] map_name = args[0] state_file = open(map_name.lower() + ".txt") states = state_file.read() ss = states.split("\n") for s in ss: place = s.split("\t") if(len(place) == 2): ...
lace_type) p.save() self.stdout.write(name + " added")
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('django_nyt', '0006_auto_20141229_1630'), ('wiki', '0001_initial'), ] operations = [ migrations.CreateModel( name
='ArticleSubscription', fields=[ ('articleplugin_ptr', models.OneToOneField(auto_created=True, to='wiki.ArticlePlugin', primary_key=True, parent_link=True, serialize=False, on_delete=models.CASCADE)), ('subscription', models.OneToOneField(to='django_nyt.Subscription', on_del
ete=models.CASCADE)), ], options={ }, bases=('wiki.articleplugin',), ), migrations.AlterUniqueTogether( name='articlesubscription', unique_together=set([('subscription', 'articleplugin_ptr')]), ), ]
""" Support for Vera cover - curtains, rollershutters etc. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/cover.vera/ """ import logging from homeassistant.components.cover import CoverDevice from homeassistant.components.vera import ( VeraDevice, V...
else: return True def open_cover(self, **kwargs): """Open the cover.""" self.vera_device.open(
) def close_cover(self, **kwargs): """Close the cover.""" self.vera_device.close() def stop_cover(self, **kwargs): """Stop the cover.""" self.vera_device.stop()
# -*- coding: utf-8 -*- """ @file costMemory.py @author Jakob Erdmann @author Michael Behrisch @date 2012-03-14 @version $Id: costMemory.py 22608 2017-01-17 06:28:54Z behrisch $ Perform smoothing of edge costs across successive iterations of duaIterate SUMO, Simulation of Urban MObility; see http://sumo.dlr.d...
# decay costs of unseen edges self.num_decayed = 0 for edges in self.intervals.values(): for id, edgeMemory in edges.items(): if not edgeMemory.seen: edgeMemory.update( self.traveltime_free[id], self.memory_weight, self.new_weig...
# if id == "4.3to4.4": # with open('debuglog', 'a') as f: # print(self.memory_factor, 'decay', edgeMemory.cost, file=f) # figure out the interval length if len(self.intervals.keys()) > 1: sorted_begin_times = sorted(self.intervals.key...
#<ImportSpecificModules> import ShareYourSystem as SYS #
</ImportSpecificModules> #print(SYS.SumClass().insert('Parameter').hdfview().HdformatedConsoleStr) #print(SYS.SumClass().insert('Result').hdfview().HdformatedConsoleStr) #print(SYS.Sum.attest_insert()) #
print(SYS.Sum.attest_retrieve()) #print(SYS.Sum.attest_find()) #print(SYS.Sum.attest_recover()) #print(SYS.Sum.attest_scan())
dtv_test2, \t.platdata_size\t= sizeof(dtv_test2), \t.parent_idx\t= -1, }; /* Node /test3 index 2 */ static struct dtd_test3 dtv_test3 = { \t.reg\t\t\t= {0x1234567890123456, 0x9876543210987654, 0x2, 0x3}, }; U_BOOT_DEVICE(test3) = { \t.name\t\t= "test3", \t.platdata\t= &dtv_test3, \t.platdata_size\t= sizeof(dtv_test3),...
of na + ns = 1 + 1)", str(e.exception)) def test_add_prop(self): """Test that a subequent node can
add a new property to a struct""" dtb_file = get_dtb_file('dtoc_test_add_prop.dts') output = tools.GetOutputFilename('output') self.run_test(['struct'], dtb_file, output) with open(output) as infile: data = infile.read() self._CheckStrings(HEADER + ''' struct dtd_san...
import codecs import mock import os import tempfile import unittest from time import strftime import six from kinto import config from kinto import __version__ class ConfigTest(unittest.TestCase): def test_transpose_parameters_into_template(self): self.maxDiff = None template = "kinto.tpl" ...
config.init('kinto.ini', 'memory') args, kwargs = list(mocked_render_template.call_args) self.assertEquals(args, ('kinto.tp
l', 'kinto.ini')) self.assertDictEqual(kwargs, { 'secret': kwargs['secret'], 'storage_backend': 'kinto.core.storage.memory', 'cache_backend': 'kinto.core.cache.memory', 'permission_backend': 'kinto.core.permission.memory', 'storage_url': '', ...
def max_rectangle(heights): res = 0 heights.append(0) stack = [0] for i in range(1, len(heights)): while stack and heights[i] < heights[stack[-1]]: h = heights[stack.pop()] w = i if not stack else i - stack[-1] - 1 res = max(res, h * w) stack.append(i...
heights[j]
= 0 if matrix[i][j] == '0' else heights[j] + 1 ans = max(ans, max_rectangle(heights)) return ans if __name__ == "__main__": sol = Solution() M = [['1', '0', '1', '0', '0'], ['1', '0', '1', '1', '1'], ['1', '1', '1', '1', '1'], ['1', '0', '0', '1', '0']] print...
#!/usr/bin/env python # -*- co
ding: utf-8 -*- # Copyright (c) 2015-2017: # Frederic Mohier, frederic.mohier@alignak.net # """ Alignak - C
hecks pack for NRPE monitored Linux hosts/services """
', 'yeux_enfonces', 'soif', 'pli_cutane', 'fievre_presence', 'fievre_presence_duree', 'fievre_presence_longue', 'tdr', 'urines_foncees', 'saignements_anormaux', 'raideur_nuque', 'ictere', 'choc', 'eruption_cutanee', 'ecoulement_nasal', 'yeux_rouge', 'ecoulement_oculaire',...
from custom.tdh.models import TDHEnrollChildFluff return [k for k in TDHEnrollChildFluff().__dict__['_obj'].keys() if k not in UNNECESSARY_FIELDS] class InfantTreatment(BaseSqlData): table_name = "fluff_TDHInfantTreatmentFluff" slug = 'infant_treatment' title = 'Infant Treatment' @propert...
[] @property def group_by(self): return ['case_id', 'infection_grave_treat_0', 'infection_grave_treat_1', 'infection_grave_treat_2', 'infection_grave_no_ref_treat_0', 'infection_grave_no_ref_treat_1', 'infection_grave_no_ref_treat_2', 'infection_grave_no_ref_treat_5', 'i...
import numpy as np import copy import datetime as dt import QSTK.qstkutil.qsdateutil as du import QSTK.qstkutil.DataAccess as da import QSTK.qstkstudy.EventProfiler as ep from bollinger import Bollinger """ Accepts a list of symbols along with start and end date Returns the Ev
ent Matrix which is a pandas Datamatrix Event matrix has the following structure : |IBM |GOOG|XOM |MSFT| GS | JP | (d1)|nan |nan | 1 |nan |nan | 1 | (d2)|nan | 1 |nan |nan |nan |nan | (d3)| 1 |nan | 1 |nan | 1 |nan | (d4)|nan | 1 |nan | 1 |nan |nan | .........
.......................... ................................... Also, d1 = start date nan = no information about any event. 1 = status bit(positively confirms the event occurence) """ def find_events(ls_symbols, d_data): df_close = d_data['close'] ts_market = df_close['SPY'] print "Finding Events" # ...
# This file is part of pybliographer # # Copyright (C) 1998-2004 Frederic GOBRY # Email : gobry@pybliographer.org # # 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 t...
s] = key skeys.append (s) return table, skeys def standard_date (entry, coding): (text, month, day) = entry.format (coding) if month: text = "%s/%s" % (month, text) if day : text = "%s/%s" % (day, text) return text def last_first_full_authors (entry, coding): return autho...
try, coding, 0, 1) def first_last_full_authors (entry, coding): return author_desc (entry, coding, 0, -1) def full_authors (entry, coding): return author_desc (entry, coding, 0, 0) def initials_authors (entry, coding): return author_desc (entry, coding, 1, 0) def first_last_initials_authors (entry, cod...
] = QtWidgets.QDockWidget('Plotting-' + str(count)) dock['Plotting-' + str(count)].setWidget(self.plottingWidget) self.addDockWidget(QtCore.Qt.TopDockWidgetArea, dock['Plotting-' + str(count)]) self.tabifyDockWidget(dock['Welcome'], dock['Plotting-' + str(count)]) ...
' + str(count)].setVisible(True) dock['Plotting-' + str(count)].setFocus() dock['Plotting-' + str(count)].raise_() temp = self.obj_appconfig.current_project['ProjectName'] if temp: self.obj_appconfig.dock_dict[temp].a
ppend( dock['Plotting-' + str(count)] ) count = count + 1 def ngspiceEditor(self, projDir): """ This function creates widget for Ngspice window.""" self.projDir = projDir self.projName = os.path.basename(self.projDir) self.ngspiceNetlist = os.path...
ry() for in_feat_b in union_b.getFeatures(request): count += 1 at_map_b = in_feat_b.attributes() tmp_geom = geometry_checker(in_feat_b.geometry()) if engine.intersects(tmp_geom.constGet()): int_geom = geometry_checker(geo...
QgsWkbTypes.GeometryCollection: # Intersection produced different geometry types temp_list = int_geom.as
GeometryCollection() for i in temp_list: if i.type() == geom.type(): int_geom = QgsGeometry(geometry_checker(i)) try: _write_feature( ...
import os import glob import subprocess def expand_path(path): return os.path.abspath(os.path.expandvars(os.path.expanduser(path))) def is_file(path): if not path: return False if not os.path.isfile(path): return False return True def arg_is_file(path): try: if not is_file(path): raise ...
help = ('Input sequence file(s) name ')) parser.add_argument('-o', '--out-format', type = str, choices = ['nex', 'fasta', 'phy'], help = ('The format of the output sequence file(s). Valid options ')) parser.add_argument('-j', '--path-to-jModelTest', type = str, help=('The full path to the jModelTest execut...
-substitution-models', type = str, choices = ['3','5','7','11'] default = ['3'] help = ('Number of substitution schemes to test. Default is all GTR models "-s 3".')) parser.add_argument('-g', '--gamma', type = str, default = ['4'] help = ('Include models with rate variation among sites and number of cate...
# coding=utf-8 import random lista = [] for x in range(10): numero = random.randint(1, 100)
if x == 0: maior, menor = numero, numero elif numero > maior: maior = numero elif numero < menor: menor = numero lista.append(numero) lista.sort() print(lista) print("Maior: %d" % maior) prin
t("Menor: %d" % menor)
# -*- coding: utf-8 -*- # Gen
erated by Django 1.10.8 on 2018-04-26 12:20 from __fut
ure__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('codenerix_products', '0011_auto_20180202_0826'), ] operations = [ migrations.AddField( model_name='productunique', name='caducity', ...
be returned with instances where there is a significant performance difference """ regression_table_data = list() improvement_table_data = list() full_comparison_str = str() for workload_scale_key, workload in grouped.items(): for query_name, file_formats in workload.items(): for file_format, resu...
format = first_query_result[QUERY][TEST_VECTOR][FILE_FORMAT] compression_codec = first_query_result[QUERY][TEST_VECTOR][COMPRESSION_CODEC] compression_type = first_query_result[QUERY][TEST_VECTOR][COMPRESSION_TYPE] avg_time = results[AVG] stddev = results[STDDEV] num_clients = results[NUM_CLIENTS] ...
TIONS] runtime_profile = first_query_result[RUNTIME_PROFILE] file_type_id = data_store.get_file_format_id( file_format, compression_codec, compression_type) if file_type_id is None: print 'Skipping unkown file type: %s / %s' % (file_format, compression) continue workload_id = data_...
# 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...
])) self.assertEqual(34.0, result.numpy()) def testNetworkAsAGraph(self): self.skipTest("TODO(ashankar,josh11b): FIX THIS") # Verify that we're using ResourceVariables def testNetwor
kVariablesDoNotInterfere(self): self.skipTest("TODO: FIX THIS") net1 = MyNetwork() net2 = MyNetwork() one = constant_op.constant([[1.]]) print(type(net1(one))) net2(one) net1.trainable_weights[0].assign(constant_op.constant([[1.]])) net2.trainable_weights[0].assign(constant_op.constan...
from datetime import timedelta from requests.auth import HTTPBasicAuth from django.core.exceptions import ValidationError from django.utils import timezone from django.core.cache import cache from ..settings import ( WFRS_GATEWAY_COMPANY_ID, WFRS_GATEWAY_ENTITY_ID, WFRS_GATEWAY_API_HOST, WFRS_GATEWAY_CO...
) headers = { "request-id": request_id, "gateway-company-id": self.company_id, "gateway-e
ntity-id": self.entity_id, } if client_request_id is not None: headers["client-request-id"] = str(client_request_id) # Send request logger.info( "Sending WFRS Gateway API request. URL=[%s], RequestID=[%s]", url, request_id, ) ...
import pandas as pd from pandas import Dat
aFrame from matplotlib import pyplot as plt from matplotlib import style style.use('ggplot') df = pd.read_csv('sp500_ohlc.csv', index_col = 'Date', parse_dates=True) #print df.head() df['STD'] = pd.rolling_std(df['Close'], 25, min_periods=1) ax1 = plt.subplot(2, 1, 1) df['Close'].plot() plt.ylabel('Close') # do...
TD'].plot() plt.ylabel('Standard Deviation') plt.show()
# -*- coding: utf-8 -*- """ *************************************
************************************** ProcessingPlugin.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * ...
m is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * ...
fro
m django.contrib import admin import models # Register your models here. admin.site.register(models.UserProfile) admin.site
.register(models.Event)
#!/usr/bin/python import sys import pyxbackup as pxb import pytest def test__parse_port_param(): assert(pxb._parse_port_param('27017,27019')) == True assert(pxb.xb_opt_remote_nc_port_min) == 27017 assert(pxb.xb_opt_remote_nc_port_max) == 27019 a
ssert(pxb._parse_port_param('27017, 27019')) == True assert(pxb._parse_port_param('abcde, 27019')) == False assert(pxb._parse_port_param('abcde, ')) == False assert(pxb._parse_port_param('9999, ')) == False assert(pxb._parse_port_param('9999 ')) == False assert(pxb._parse_port_param('9999')) == True...
2, 13] assert(pxb._xb_version(verstr = '2.2.13', tof = True)) == 2.2
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
, "ceph-a") osddir = os.path.join(self.tempdir, "osd", "ceph-0") os.makedirs(mondir) os.makedirs(osddir) _, version = self._exec(["ceph", "--version"], stdout=True) version = version.decode("ascii").split()[2] version = pkg_resources.parse_version(version) if ve...
ailsafe_full_ratio = 1 """ else: extra = """ mon_allow_pool_delete = true """ # FIXME(sileht): check availible space on /dev/shm # if os.path.exists("/dev/shm") and os.access('/dev/shm', os.W_OK): # journal_path = "/dev/shm/$cluster-$id-journal" # else: j...
#!/usr/bin/env python3 # ReText # Copyright 2011-2012 Dmitry Shachnev # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. ...
ut 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 this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, # MA 02110-1301, USA. import sys import signal from ReText import * from ReText.window import ReTextWindow def main(): app = QApplication(sys.argv) app.setOrganizationName("ReText project") app.setApplicationName("ReText") RtTranslator = QTranslator() for path in datadirs: if RtTr...
THis function ... :param ski: :param component: :return: """ # Get title title = component.parameters.title # Set the deprojection geometry ski.set_stellar_component_geometry(title, component.deprojection) # ----------------------------------------------------------------- def se...
xes are implemented at this moment") # Check whether the title is defined if title is None: log.warning("The title for the '" + name + "' dust component is not specified") # Set dust component properties properties = dict() properties["geometry"] = geometry properties["geometry_type"] = geomet...
properties["mix_type"] = mix_type properties["mix_properties"] = mix_properties properties["normalization_type"] = normalization_type properties["normalization_properties"] = normalization_properties properties["mix"] = mix properties["mass"] = mass proper
st) log.debug('Token request validation ok for %r.', request) except errors.OAuth2Error as e: log.debug('Client error during validation of %r. %r.', request, e) return headers, e.json, e.status_code token = token_handler.create_token(request, refresh_token=True) ...
equest.client_id, request.code, request) return headers, json.dumps(token), 200 def validate_authorization_request(self, reque
st): """Check the authorization request for normal and fatal errors. A normal error could be a missing response_type parameter or the client attempting to access scope it is not allowed to ask authorization for. Normal errors can safely be included in the redirection URI and sen...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on Wed Jul 24 11:30:24 2013 @author: Sat Kumar Tomer @email: satkumartomer@gmail.com @website: www.ambhas.com """ import numpy as np import h5py import os import datetime as dt def extract_smc(h5_file, lat, lon): """ Extract Soil Moisture Content fro...
lat = 12 lat = [10,15] lon: longitude, either a single value or min,max limits eg. as for lat
""" res = 0.1 ######### convert lat, lon into indices ############## # min max are given min_max = type(lat) is list if min_max: lat_min = lat[0] lat_max = lat[1] i_lat_min = int(np.floor((90-lat_min)/res)) i_lat_max = int(np.floor((90-lat_max)/res)) lo...
# Copyright 2016, IBM US, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
e_command(" ".join(cmd_parms)) if rc != 0: logging.warning("%s::ipmi query failed with output %s", _method_, stderr) raise exceptions.DeviceException("ipmi query failed with output %s" % stderr) for line in stdout: if "Firmware Revision" in line: self....
ude_name=["self"]) def get_architecture(self): return None @entry_exit(exclude_index=[0, 1], exclude_name=["self", "new_password"]) def change_device_password(self, new_password): """Update the password of the ipmi default user on the BMC of the openpower server. """ _method...
import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) TEST_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT), "tests") SINGLE_ORCA_RUN_FILE = os.path.join(PROJECT_ROOT, "code", "single_core_run_orca.py") SINGLE_RUN_MOB_KMC_FILE = os.path.joi
n( PROJECT_ROOT, "code", "single_core_run_mob_KMC.py" ) SINGLE_RUN_DEVICE_KMC_FILE = os
.path.join( PROJECT_ROOT, "code", "single_core_run_device_KMC.py" )
obj.stance), "orientation": packets.Container(yaw=b_obj.yaw, pitch=b_obj.pitch), "grounded": packets.Container(grounded=b_obj.on_ground)}) def send_action(self, b_obj): """ sneaking, not sneaking, leave bed, start sprinting, stop sprinting """ if b_obj.action...
obj.velocities.y) < 0.005: # minecraft value b_obj.velocities.y = 0 if abs(b_obj.velocities.z) < 0.005: # minecraft value b_obj.velocities.z = 0 def clip_ladder_velocities(self, b_obj): if self.is_on_ladder(b_obj): if b_obj.velocities.y < -0.15: ...
b_obj.velocities.x = math.copysign(0.15, b_obj.velocities.x) if abs(b_obj.velocities.z) > 0.15: b_obj.velocities.z = math.copysign(0.15, b_obj.velocities.z) if self.is_sneaking(b_obj) and b_obj.velocities.y < 0: b_obj.velocities.y = 0 def handle_water_movement(se...
import Deci
mal_pb2 import Log_pb2 import uRPC_pb2 import client import s
erver
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. """ Test cases for the TAAR Hybrid recommender """ from taar.recommenders.hybrid_recommender import CuratedRecommender ...
r.can_recommend({"installed_addons": []}) @mock_s3 def test_curated_recommendations(test_ctx): ctx = install_mo
ck_curated_data(test_ctx) r = CuratedRecommender(ctx) # CuratedRecommender will always recommend something no matter # what for LIMIT in range(1, 5): guid_list = r.recommend({"client_id": "000000"}, limit=LIMIT) # The curated recommendations should always return with some kind ...
import unittest import os from flow.benchmarks.baselines.bottleneck0 import bottleneck0_baseline from flow.benchmarks.baselines.bottleneck1 import bottleneck1_baseline
from flow.benchmarks.baselines.bottleneck2 import bottleneck2_baseline from flow.benchmarks.baselines.figureeight012 import figure_eight_baseline from flow.benchmarks.baselines.grid0 import grid0_baseline from flow.benchmarks.baselines.grid1 import grid1_baseline
from flow.benchmarks.baselines.merge012 import merge_baseline os.environ["TEST_FLAG"] = "True" class TestBaselines(unittest.TestCase): """ Tests that the baselines in the benchmarks folder are running and returning expected values (i.e. values that match those in the CoRL paper reported on the websit...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('api', '0009_dummyprovider'), ] o...
ls.DateTimeField(auto_now=True)), ('name', models.CharField(max_length=1024)), ('template_name', models.CharField(max_length=1024)), ], options={ 'abstract': False, }, ),
migrations.CreateModel( name='ExternalJobPortalFormGroup', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('modified_at', models...
#Equals and hash class Eq(object): def __init__(self, data): self.data = data def __eq__(self, other): return self.data == other.data class Ne(object): def __init__(self, data): self.data = data def __ne__(self, other): return self.data != other.data class Hash(obj...
.data = data def __hash__(self): re
turn hash(self.data) class Unhashable1(object): __hash__ = None class EqOK1(Unhashable1): def __eq__(self, other): return False def __ne__(self, other): return True class Unhashable2(object): #Not the idiomatic way of doing it, but not uncommon either ...
# -*- coding: utf-8 -*- # # # # ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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; ei...
ndler=LogRecordStreamHandler, traceback_frames=1): SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler) self.timeout = 1 self.traceback_frames = traceback_frames def terminal_size(): h, w, hp,
wp = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0))) return w, h def print_linesep(): print terminal_size()[0] * u'\N{BOX DRAWINGS LIGHT HORIZONTAL}' def indent(msg, level=4): indentation = level * ' ' return indentation + msg.replace('\n', '\n' + indentati...
res. EXC_PATCH = "pyvtk580_tryexcept_and_pyexceptions.diff" # fixes attributes in vtkproperty for shader use in python VTKPRPRTY_PATCH = "vtkProperty_PyShaderVar.diff" # recent segfault with vtk 5.6.1 and wxPython 2.8.11.0 # see here for more info: # http://vtk.1045678.n5.nabble.com/wx-python-scripts-segfault-td12344...
VTKPRPRTY_PATCH) self.wxvtkrwi_displayid_segfault_patch_filename = os.path.join( config.patches_dir, WXVTKRWI_DISPLAYID_SEGFAULT_PATCH) config.VTK_LIB = os.path.join(self.inst_dir, 'lib') # whatever the case may be...
config.VTK_SODIR = os.path.join(self.inst_dir, 'bin') # inst/VTK/lib/site-packages the VTK python package config.VTK_PYTHON = os.path.join( config.VTK_LIB, 'site-packages') else: # on *ix, inst/VTK/lib contains DLLs config.VTK_SODIR =...
# Copyright 2015, 2018 IBM Corp. # # 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 require...
, None, None) self.assertRaises(exception.InvalidDevicePath, mgmt.remove_block_dev, link) # stat was called once; exec was not called self.assertEqual(1, mock_stat.call_count) self.assertEqual(0, mock_writefile.call_count) # Delete special file not foun...
mock_stat.side_effect = (None, OSError(), None) self.assertRaises(exception.InvalidDevicePath, mgmt.remove_block_dev, link) # stat was called twice; exec was not called self.assertEqual(2, mock_stat.call_count) self.assertEqual(0, mock_writefile.call_cou...
# This file is formatted with black. # https://github.com/psf/black import os import json import subprocess import sys import simplekml ALT_MODE = simplekml.AltitudeMode.absolute # Absolute altitude means from sea floor # Current commit if os.environ.get("TRAVIS"): COMMIT = os.environ["TRAVIS_COMMIT"] else: ...
esc += f"IPv4: {node.get('ipv4')}<br>" desc += f"IPv6: {node.get('ipv6')}<br>" desc += f"Mode: {node.get('mode')}<br>" if node["type"] != "router": desc += f"Connected Router: {node.get('router')}<br>" # Antenna specific keys if node["type"] == "antenna": desc += f"SSID: {node.get('...
+= f"Antenna Type: {node.get('antennaType')}<br>" desc += f"Antenna Cone: {node.get('antennaCone')}<br>" desc += f"Antenna Direction: {node.get('antennaDirection')}<br>" desc += f"Antenna Distance: {node.get('antennaDistance')}<br>" desc += f"Antenna Protocol: {node.get('antennaProtocol...
#! /usr/bin/python import sys, localconfig, platform, time #OS Runtime comments if platform.system() == "Windows": sys.path.append(localconfig.winpath) print "You
are running the AnkitBot UAA Module for Windows. Sponsored by DQ. :)" else: sys.path.append(localconfig.linuxpath) print "You are running the AnkitBot UAA Module for Linux. Sponsored by DQ. :)" import wikipedia import globalfunc as globe override = False if not globe.startAllowed(override): pri...
from unittest import TestCase from django.template import Context
, Template, VariableNode from django.test import override_settings class NodelistTest(TestCase): def test_for(self): template = Template('{% for i in 1 %}{{ a }}{% endfor %}') vars = template.nodelist.get_nodes_by_type(VariableNode)
self.assertEqual(len(vars), 1) def test_if(self): template = Template('{% if x %}{{ a }}{% endif %}') vars = template.nodelist.get_nodes_by_type(VariableNode) self.assertEqual(len(vars), 1) def test_ifequal(self): template = Template('{% ifequal x y %}{{ a }}{% endifequal %...
"""Test cases for STEREO Map subclasses. This particular test file pertains to CORMap. @Author: Pritish C. (VaticanCameos) """ import os import glob from sunpy.map.sources.stereo import CORMap from sunpy.map import Map import sunpy.data.test path = sunpy.data.test.rootdir fitspath = glob.glob(os.path.join(path, "cor...
Map(fitspath) # COR Tests def test_fitstoEIT(): """Tests the creation of CORMap using FITS.""" assert isinstance(cor, CORMap) def test_is_datasource_for(): """Test the is_datasource_for method of CORMap. Note that header data to be provided as an argument can be a MapMeta object.""" assert cor...
or.data, cor.meta) def test_measurement(): """Tests the measurement property of the CORMap object.""" assert cor.measurement == "white-light" def test_observatory(): """Tests the observatory property of the CORMap object.""" assert cor.observatory == "STEREO A"
g'): match = re.match(r'\\g<(\S+)>', arg).group(1) groups.append(match) elif arg.startswith('\\'): match = int(re.match(r'\\(\d+)', arg).group(1)) groups.append(match) else: raise errors.AnsibleFilterError('Unknown argument') flags = 0 ...
tionary") rc = item.get('rc', 0) failed = item.get('failed', False) if rc != 0 or failed: return True else: return False def success(*a, **kw): ''' Test if task result yields success ''' return not failed(*a, **kw) def changed(*a, **kw): ''' Test if task result yields chang...
ot isinstance(item, MutableMapping): raise errors.AnsibleFilterError("|changed expects a dictionary") if not 'changed' in item: changed = False if ('results' in item # some modules return a 'results' key and isinstance(item['results'], MutableSequence) and ...
from sa_tools.base.magic import MagicMixin from sa_tools.inbox import Inbox from sa_tools.session import SASession from sa_tools.index import Index import os import pickle import sys def py_ver() -> str: return str(sys.version_info.major) class APSession(object): def __init__(self, username: str, passwd: s...
s): self.
username = username self.passwd = passwd self._session_bak = \ '.' + username.replace(' ', '_') + py_ver() + '.bak' self.session = self._get_session(save_session=save_session) del passwd del self.passwd def _get_session(self, save_session: bool=True) -> SASessio...
# Authors: Aaron Qiu <zqiu@ulg.ac.be>, # Antonio Sutera <a.sutera@ulg.ac.be>, # Arnaud Joly <a.joly@ulg.ac.be>, # Gilles Louppe <g.louppe@ulg.ac.be>, # Vincent Francois <v.francois@ulg.ac.be> # # License: BSD 3 clause from __future__ import division, print_function, absolute_import ...
from utils import scale def _partition_X(X, n_jobs): """Private function used to partition X between jobs.""" n_nodes = X.shape[1] # Compute the number of jobs
n_jobs = min(cpu_count() if n_jobs == -1 else n_jobs, n_nodes) # Partition estimators between jobs n_node_per_job = (n_nodes // n_jobs) * np.ones(n_jobs, dtype=np.int) n_node_per_job[:n_nodes % n_jobs] += 1 starts = np.cumsum(n_node_per_job) return n_jobs, [0] + starts.tolist() def _parallel_...
# Copyright 2011 Kyriakos Zarifis # Copyright 2008 (C) Nicira, Inc. # # This file is part of POX. # # POX 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) ...
fid) else:
# We know the outport, set up a flow log.info('installing flow for ' + str(packet)) match = ofcommand.extractMatch(packet) actions = [ofcommand.Output(prt[0])] ofcommand.addFlowEntry(con, inport, match, actions, bufid) # Separate bufid, make addFlowEntry() only ADD the entry ...
import _plotly_utils.basevalidators class DeltaValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="delta", parent_name="indicator", **kwargs): super(DeltaValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, ...
default, it is set to the current value. relative Show relative change valueformat Sets the value formatting rule using d3 formatting mini-language whi
ch is similar to those of Python. See https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format """, ), **kwargs )
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2018-11-06 11:00 from __future__ import unicode_literals from django.db import migrations, models class Mig
ration(migrations.Migration): dependencies = [ ('rdrf', '0081_clinicaldata_active'),
] operations = [ migrations.AlterField( model_name='surveyrequest', name='survey_name', field=models.CharField(max_length=80), ), ]
import os import chardet from humanfriendly import format_size import pygments import pygments.lexers import pygments.lexers.special import pygments.formatters from pygments.util import ClassNotFound from mako.lookup import TemplateLookup from mfr.core import extension from mfr.extensions.codepygments import settings...
encoding = detected_encoding.get('encoding', None) if encoding is None: raise exceptions.FileDecodingError(
message='Unable to detect encoding of source file.', extension=ext, category='undetectable_encoding', code=400, ) try: content = data.decode(encoding) except UnicodeDecodeError as err: ...
impo
rt sys from math import ceil def main(): AREA = 1.76 w = float(input()) h = float(input()) print(ceil(w * h / AREA)) if __name__ == "__main__": sys.exit(int(main()
or 0))
#!/usr/bin/env python import json import sys import argparse from clingo import Control, Number class App: def __init__(self, args): self.control = Control() self.args = args self.horizon = 0 self.objects = 0 self.end = None def show(self, model): if not s...
> 1: self.control = Cont
rol() for source in self.args.file: self.control.load(source) for i in range(0, self.objects): parts.append(("object", [Number(i + 1, count)])) for i in range(0, self.horizon): parts.append(("horizon", [Number(i + 1, count)])) if self.args.scratch or count == 1: ...
# -*- coding: utf-8 -*- # # This file is part of INSPIRE. # Copyright (C) 2014-2017 CERN. # # INSPIRE 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 ...
ANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public Lic
ense for more details. # # You should have received a copy of the GNU General Public License # along with INSPIRE. If not, see <http://www.gnu.org/licenses/>. # # In applying this license, CERN does not waive the privileges and immunities # granted to it by virtue of its status as an Intergovernmental Organization # or...
""" Django settings for detest project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) imp...
b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', }, 'detest': { 'handlers': ['console'], 'level': 'DEBUG',
}, 'detest_ui': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } LOGGING = {}
from application import CONFIG, app from .models import * from flask import current_app, session from flask.ext.login import login_user, logout_user, current_user from flask.ext.principal import Principal, Identity, AnonymousIdentity, identity_changed, identity_loaded, RoleNeed import bcrypt import re import sendgrid i...
y, None) identity_changed.send(current_app._get_current_object(), identity = AnonymousIdentity()) def tokenize_email(email): return ts.dumps(email, salt = CONFIG["EMAIL_TOKENIZER_SALT"]) def detokenize_email(token): return ts.loads(token, salt = CONFIG["EMAIL_TOKENIZER_SALT"], max_age = 86400) def send_recover...
message.set_from("noreply@hackbca.com") message.set_subject("hackBCA III - Account Recovery") message.set_html("<p></p>") message.add_filter("templates", "enable", "1") message.add_filter("templates", "template_id", CONFIG["SENDGRID_ACCOUNT_RECOVERY_TEMPLATE"]) message.add_substitution("prefix", "staff") ...
from django.apps import AppConfig class UserregistrationConfig(AppConfig): nam
e = 'userregistration'
import utils from flask import render_template, redirect, request, session, url_for, json, jsonify from . import murmurbp from .User import User # User Views @murmurbp.route("/users", methods = ['GET']) def get_all_users(): u = User() ul = utils.obj_to_dict(u.get_all()) data = [{'UserId': k, 'UserName': v...
nel() cl = utils.obj_to_dict(c.get_all()) data = [ v for k, v in cl.iteritems()] resp = jsonify(channels=data) return resp, 20
0 @murmurbp.route("/channels", methods = ['POST']) def add_channel(): c = Channel() name = request.form['channelName'] parent = request.form['parent'] new_channel = c.add_channel(name, parent) data = utils.obj_to_dict(new_channel) resp = jsonify(data) return resp, 200 @murmurbp.route("/cha...
# # This file is part of TSmells # # TSmells is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # TSmells is distributed in the hope ...
ss.ui import Dockable class TDockable(JPanel, Dockable): # # Implementation of Dockable interface # def mouseEnterEdge(self, edge): pass def mouseLeaveNode(self, node): pass def mouseLeaveEdge(self, edge): pass def getPreferredSize(self): return Dimensio...
): ''' prefer vertical orientation ''' return 2 # vertical, see com.hp.hpl.guess.ui.MainUIWindow.java def opening(self, state): self.visible = state def attaching(self, state): pass def getTitle(self): return("") def getWindow(self): return self.myPare...
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PyWrapt(PythonPackage): """Module for decorators, wrappers and monkey patching.""" homepage = "https://
github.com/GrahamDumpleton/wrapt" url = "https://pypi.io/packages/source/w/wrapt/wrapt-1.10.10.tar.gz" version('1.10.10', '97365e906afa8b431f266866ec4e2e18')
#encoding: utf-8 from __future__ import unicode_literals TITLE_TO_SLUG = { 'איגוד הביטקוין': 'bitcoin-org-il', 'אליאב': 'eliav', '* בדיקות פרודקשיין *': 'production-test', 'בי״ס עמית': 'amit', 'הבר קיימא': 'barkayma', 'הסדנא לידע ציבורי': 'hasadna', 'הפורום לממשל פתוח': 'open-government', 'התנועה לאיכות השל
טון': 'mqg', 'מעיין ברוך': 'maayan-baruch', 'מרצ': 'meretz', 'נטף': 'nataf',
'נען': 'naan', 'קהילה פתוחה': 'open-community', }
#!/usr/bin/env python2.7 import numpy as np import matplotlib.pyplot as plt Freq=np.array([30,40,45,50,53,55,60,65,70,80,90,95,98,100,110,120]) Db=np.a
rray([70.5,78.6,83.2,88.4,87.5,86.7,85.2,83.9,85.1,88,95.7,100.4,100.4,99.2,94.7,94.9]) plt.xlabel('Frecuencia') plt.ylabel('Decibel') plt.title('DecibelvsFreq a 0.1volts') #for i in range(len(Freq)): # plt.text(Freq[i],Db[i], r'$Freq=%f, \ Db=%f$' % (Freq[i], Db[i])) plt.axis([0, 330, 50, 130]) plt.plot(Freq,Db,'bo',...
k') plt.grid(True) plt.show()
#import os import pickle import glob #import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt #from data_control_no_images.read import R
ead listing = glob.glob('F:/Project_Cars_Data/1lap-fullspeed/Watkins Glen International - Short Circuit' + '/*.pkl') x = [] y = [] throttle = [] raw_throttle = [] brake = [] raw_brake = [] steering = [] raw_steering = [] xy = [] for filen
ame in tqdm(listing): with open(filename, 'rb') as file_data: project_cars_state = pickle.load(file_data) controller_state = pickle.load(file_data) #remove none flying lap data if project_cars_state.mParticipantInfo[0].mCurrentLapDistance == 0.0: continue p...
is #* scikit-beam - data analysis tools for X-ray science # - https://github.com/scikit-beam/scikit-beam #* xray-vision - plotting helper functions for X-ray science # - https://github.com/Nikea/xray-vision import xray_vision import matplotlib.cm as mcm import copy import xray_vision.mpl_plotting as mpl_plot...
ey', 'seagreen', 'silver', 'darkmagenta', 'darkslategrey', 'darkgoldenrod', 'rosybrown', 'goldenrod', 'darkturquoise', 'plum', 'purple', 'olive', 'gold','powderblue', 'peachpuff','violet', 'lime', 'greenyellow', 'tan', 'skyblue', 'magenta', 'blac...
markers ) import matplotlib as mpl # Custom colormaps ################################################################################ # ROYGBVR but with Cyan-Blue instead of Blue color_list_cyclic_spectrum = [ [ 1.0, 0.0, 0.0 ], [ 1.0, 165.0/255.0, 0.0 ], [ 1.0, 1.0, 0.0 ], [ 0.0, ...
#!/usr/bin/env python import sys,re,time,argparse def main(args): # print >>sys.stdout, "Start analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S") convert(args.input,args.output) # print >>sys.stdout, "Finish analysis: " + time.strftime("%a,%d %b %Y %H:%M:%S") def extract_exon_length_from_cigar(cigar): cigar_m = ["...
ent 7. MAPQ 8. Number of nucleotides that are softly-clipped by aligner; left_right 9. exon count 10. exon start set 11. exon end set''' parser = argparse.ArgumentParser(description="Function: convert sam to gpd.",formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i','--in
put',type=argparse.FileType('r'),required=True,help="Input: sam file") parser.add_argument('-o','--output',type=argparse.FileType('w'),required=True,help="Output: gpd file") args = parser.parse_args() return args if __name__=="__main__": args = do_inputs() main(args)
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # """ Methods to calculate ECP values (Endogenous Competition Potential) """ ######################################################## #~ Import libraries. ######################################################## from cellery i...
d]) #-------------------------- #~ Run in parallel. aECPVlsAVlsB = zeros((l
enaMrnVlsDtA,lenaMrnVlsDtB),dtype=float32) aECPVlsAVlsB.fill(nan)#fill all ECP with nan to start qInJobs = Queue() qOutRslts = Queue() cntVlABPrs=0 for intrvlA,intrvB in product(intrvlsMrnVlsA,intrvlsMrnVlsB): qInJobs.put((intrvlA,intrvB)) cntVlABPrs += 1 for t in xrange(nThrds): Process(target = mltECPcl...
#!/usr/bin/env python """ Copyright (c) 2019 Alex Forencich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
_ts_step, output_pps=output_pps ) @always(delay(3200)) def clkgen(): clk.next = not clk input_clk.next = not input_clk outpu
t_clk_hp = Signal(int(3200)) @instance def clkgen_output(): while True: yield delay(int(output_clk_hp)) output_clk.next = not output_clk @always(delay(5000)) def clkgen_sample(): sample_clk.next = not sample_clk @instance def check(): yield dela...
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-01-19 06:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('condensed_urls', '0001_initial'), ] operations =
[ migrations.AddField(
model_name='condensedurl', name='visited_count', field=models.IntegerField(default=0), ), ]
# Copyright 2017 Huawei Technologies Co.,LTD. # 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 # # Unl...
ities to a list of formal objects.""" objs = [] for db_obj in db_objs: objs.append(cls._from_db_object(cls(context), db_obj)) retu
rn objs class CyborgObjectSerializer(object_base.VersionedObjectSerializer): # Base class to use for object hydration OBJ_BASE_CLASS = CyborgObject CyborgObjectDictCompat = object_base.VersionedObjectDictCompat class CyborgPersistentObject(object): """Mixin class for Persistent objects. This adds...
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2010 Nick Hall # # 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; e
ither version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # #...
; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Tag editing module for Gramps. """ #------------------------------------------------------------------------- # # GNOME modules # #-----------------------------------------------------------------...
00) s = pd.Series(arr) df = tm.makeDataFrame() class TestTopper(TestCase): def __init__(self, *args, **kwargs): TestCase.__init__(self, *args, **kwargs) def runTest(self): pass def setUp(self): pass def test_topn_largest(self): # get the n largest bn_res = to...
.assert_almost_equal(bn_res, arg_res) # get the nsmallest bn_res = topper.bn_topn(arr, -10) bn_args = topper.bn_topargn(arr, -10) arg_res = arr[bn_args] tm.assert_almost_equal(bn_res, arg_res) # get the nsmallest bn_res = topper.bn_topn(arr, -10,
ascending=False) bn_args = topper.bn_topargn(arr, -10, ascending=False) arg_res = arr[bn_args] tm.assert_almost_equal(bn_res, arg_res) def test_nans(self): """ bottleneck.partsort doesn't handle nans. We need to correct for them. the arg version is trickiers since w...
from flask import render_template, redirect, request, url_for, flash from flask_login import login_user, logout_user, login_required, \ current_user from . import auth from .. import db from ..models import User from ..email import send_email from .forms import LoginForm, RegistrationForm, ChangePasswordForm,\ ...
'A confirmation email has been sent to you by email.') return redirect(url_for('auth.login')) return render_template('auth/register.html', form=form) @auth.route('/confirm/<token>') @login_required def confirm(token): if current_user.confirmed: return redirect(url_for('main.index')) if cur...
on link is invalid or has expired.') return redirect(url_for('main.index')) @auth.route('/confirm') @login_required def resend_confirmation(): token = current_user.generate_confirmation_token() send_email(current_user.email, 'Confirm Your Account', 'auth/email/confirm', user=current_user, t...
#!/usr/bin/python import sys from LAPS.MsgBus.Bus import Bus # Create queue with a unique name # insert message # receive msg # delete queue if __name__ == "__main__": # If invoked directly, parse command line arguments for logger information #
and pass the rest to the run() method defined above # -------------------------------------------------------------------------- try: unique_queue_name = sys.argv[1] except: print "Not enough command line arguments: this test needs a unique queue name" exit(1) #msgbus = Bus...
, address=unique_queue_name) #parset = """ #key=value #""" #msgbus.send(parset,"Observation123456")
ion = option[:-1] value = getattr(self, option) print indent + "%s = %s" % (option, value) def run (self): """A command's raison d'etre: carry out the action it exists to perform, controlled by the options initialized in 'initialize_options()', customized by other c...
lf._ensure_stringlike(option,
what, default) if val is not None and not tester(val): raise DistutilsOptionError, \ ("error in '%s' option: " + error_fmt) % (option, val) def ensure_filename (self, option): """Ensure that 'option' is the name of an existing file.""" self._ensure_tested_stri...
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2005-2010 (ita) """ ConfigSet: a special dict The values put in :py:class:`ConfigSet` must be lists """ import copy, re, os from waflib import Logs, Utils re_imp = re.compile('^(#)*?([^#=]*?)\ =\ (.*?)$', re.M) class ConfigSet(object): """ A dict that honor ...
:: from waflib.ConfigSet import ConfigSet env = ConfigSet() env.a
ppend_value('CFLAGS', ['-O2']) child = env.derive() child.CFLAGS.append('test') # warning! this will modify 'env' child.CFLAGS = ['-O3'] # new list, ok child.append_value('CFLAGS', ['-O3']) # ok Use :py:func:`ConfigSet.detach` to detach the child from the parent. """ newenv = ConfigSet() newenv.par...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry import test from measurements import smoothness import page_sets @test.Disabled('linux') # crbug.com/368767 class SchedulerToughSchedulingC...
ness page_set = page_sets.ToughSchedulingCasesPageSet # Pepper plugin is not supported on android. @test.Disabled('android', 'win') # crbug.com/384733 class SchedulerToughPepperCases(test.Test): """Measures rendering statistics while interacting with pages that have pepper plugins""" test = smoothness.Smooth...
_set = page_sets.ToughPepperCasesPageSet def CustomizeBrowserOptions(self, options): # This is needed for testing pepper plugin. options.AppendExtraBrowserArgs('--enable-pepper-testing')
import numpy as np import pylab as pl import sys sys.path.append('../../lablib') import ourgui def smoothList(list,strippedXs=False,degree=10): if strippedXs==True: return Xs[0:-(len(list)-(len(list)-degree+1))] smoothed=[0]*(len(list)-degree+
1) for i in range(len(smoothed)): smoothed[i]=sum(list[i:i+degree])/float(degree) return smoothed def smoothListGaussian(list,strippedXs=False,degree=5): window=degree*2-1 weight=np.array([1
.0]*window) weightGauss=[] for i in range(window): i=i-degree+1 frac=i/float(window) gauss=1/(np.exp((4*(frac))**2)) weightGauss.append(gauss) weight=np.array(weightGauss)*weight smoothed=[0.0]*(len(list)-window) for i in range(len(smoothed)): smooth...
reating a new hash. Typically this option is not needed, as the default (``"2a"``) is usually the correct choice. If specified, it must be one of the following: * ``"2"`` - the first revision of BCrypt, which suffers from a minor security flaw and is generally not used anymore. * ``"2a"...
if ident == IDENT_2Y: ident = IDENT_2A else: assert ident != IDENT_2X config = u("%s%02d$%s") % (ident, self.rounds, self.salt) return uascii_to_str(config) #=================================================================== # specialized salt generation...
======= @classmethod def _bind_needs_update(cls, **settings): return cls._needs_update @classmethod def _needs_update(cls, hash, secret): if isinstance(hash, bytes): hash = hash.decode("ascii") # check for incorrect padding bits (passlib issue 25) if hash.st...
import collections import jinja2 import requests from flask import ( current_app, Blueprint, render_template, request, jsonify, abort ) frontend = Blueprint('frontend', __name__, template_folder='templates') headers = {"Content-type": "application/json"} @jinja2.contextfilter @frontend.app_t...
quest.args.get('query', '') page = request.args.get('page', 0) premises_url = current_app.config['PREMISES_REGISTER'] url = "%s/search?_query=%s&_page=%s&_representation=json" % (premises_url, query, page) resp = requests.get(url, headers=headers) if resp.sta
tus_code != 200: abort(resp.status_code) current_app.logger.info(resp.json()) return jsonify(resp.json()) @frontend.route('/premises/<int:id>') def premises(id): premises_register = current_app.config['PREMISES_REGISTER'] poao_premises_register = current_app.config['POAO_PREMISES_REGISTER'] ...
from math import log10, floor # N = 12 N = 101 # N = 1000001 def n_squares(n): return [i**2 for i in range(2, n)] # print(n_squares(11)) # print(n_squares(100)) ##### This block from stackoverflow: # https://stackoverflow.com/questions/37023774/all-ways-to-partition-a-string import itertools memo = {} def mu...
3, 4]])) # print(list_sum([[1], [2], [3], [4]])) def is_s_num(num): sqrt = num**0.5 for part in allPartitions([int(i) for i in str(num)]): if sqrt == list_sum(part): return True return False # print(81, is_s_num(81)) # print(64, is_s_num(64)) # print(8281, is_s_num(8281)) # print(9801,...
N): squares = n_squares(N) sum = 0 for n in squares: if is_s_num(n): print(n, "is true") sum += n return sum print(T(N))