prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# This script calculates how many error reports are in each subdirectory # and how many error reports are in total. # Edit in_dir and out_file parameters as you need. import os in_dir = "D:/Projects/CrashRpt/valid_reports" out_file = "stats.txt" f = open(out_file, "w") def get_txt_file_count(dirname): count = 0...
walk(dirname, True): for file in files: if file[-4:] != ".txt": continue; count += 1 break; return count multimap = dict() for root, dirs, files in os.walk(in_dir): for dir in dirs: dir_name = os.path.join(root, dir) report_count_in_dir = get_txt_file_count(dir_n...
: multimap[report_count_in_dir].append(dir) else: multimap[report_count_in_dir] = [dir] ordered_list = list(multimap.keys()) ordered_list.sort() ordered_list.reverse() total_count = 0 total_groups = 0 for count in ordered_list: total_groups += len(multimap[count]); total_count += count * l...
#!/usr/bin/env python2 # References: # https://fedoraproject.org/wiki/Koji/ServerHowTo # https://github.com/sbadakhc/kojak/blob/master/scripts/install/install import util.cfg as cfg import util.pkg as pkg import util.cred as cred from util.log import log # # Setup # log.info("General update") pkg.clean() pkg.update...
("Configure Koji Builder") with cfg.mod_ini("/etc/kojid/kojid.conf") as i: i.kojid.sleeptime = 2 i.kojid.maxjobs = 20 i.kojid.server = koji_url["hub"] i.kojid.topurl = koji_url["top"] # i.kojid.cert is set at runtime i.kojid.ca = cred.ca_crt i.kojid.serverca = cred.ca_crt i.kojid.smtphost ...
ibuilder>" # # Koji CLI # log.info("Configure Koji CLI") with cfg.mod_ini("/etc/koji.conf") as i: i.koji.server = koji_url["hub"] i.koji.weburl = koji_url["web"] i.koji.topurl = koji_url["top"] i.koji.topdir = "/mnt/koji" i.koji.cert = cred.user["kojiadmin"].pem i.koji.ca = cred.ca_crt i.k...
from .simpl
e import SIMPLE_ADJACENCIES from .combo import ComboAdjacency, LearnedComboAdjacency def construct_adjacency(matrix, **kwargs): if isinstance(matrix, (list,)): if kwargs.get('learned_tradeoff', False): return LearnedComboAdjacency(adj_list=matrix, **kwargs) return ComboAdjacency(adj
_list=matrix, **kwargs) return SIMPLE_ADJACENCIES[matrix](**kwargs)
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
urce name availability. :param message: Error Message. :type message: str :param name_available: Indicates whether the resource name is available. :type name_available: bool :param reason: Reason for name bei
ng unavailable. :type reason: str """ _attribute_map = { 'message': {'key': 'message', 'type': 'str'}, 'name_available': {'key': 'nameAvailable', 'type': 'bool'}, 'reason': {'key': 'reason', 'type': 'str'}, } def __init__(self, message=None, name_available=None, reason=None...
# Name: Examples for using conditioning number finders for curves and surfaces # Description: Contains some ex
amples with descriptions of how to use the functions # Created: 2016-08-18 # Author: Janis Lazovskis # Navigate to the conditioning directory # Run Python 2 # Example (curve) execfile('curves.py') x = variety() x0,x1,x2 = sp.var('x0,x1,x2') x.varlist = [x0,x1,x2] x.func = x0*x0 + x1*x2 - x1*x0 x.points = [[1,1,0], [2...
y list saying the last point isn't in P^2 cnumcurve(x) # Non-example (curve) # Use the above, but instead, put: x.points = [[1,1,0], [2,1,-2], [1,1,1]] # Then cnumcurve will return an empty list saying the last point isn't on the curve cnumcurve(x) # Example surface execfile('surfaces.py') x = variety() x0,x1,x2,x3 ...
) # Call ntools.assert_raises(SCIONPathPolicyViolated, inst.check_filters, pcb) def test_property_ranges(self): inst, pcb = self._setup(reasons="reasons") ntools.assert_raises(SCIONPathPolicyViolated, inst.check_filters, pcb) class TestPathPolicyCheckPropertyRanges(object): ""...
pcb") get_time.return_value = 100 pcb = create_mock(["copy", "get_hops_hash", "get_timestamp", "get_expiration_time"]) inst.id = pcb.get_hops_hash.return_value pcb.get_timestamp.return_value = 95 # Call inst.update(pcb) # Tests p...
rt_called_once_with() ntools.eq_(inst.delay_time, 5) ntools.eq_(inst.last_seen_time, 100) ntools.eq_(inst.expiration_time, pcb.get_expiration_time.return_value) class TestPathStoreRecordUpdateFidelity(object): """ Unit tests for lib.path_store.PathStoreRecord.update_fidelity """ ...
# -*- coding: utf-8 -*- MDL_BYTE = 1 MDL_UNSIGNED_
BYTE = 2 MDL_SHORT = 3 MDL_UNSIGNED_SHORT = 4 MDL_HALF = 5 MDL_INT = 6 MDL_UNSIGNED_INT = 7 MDL_FLOAT = 8 MDL
_DOUBLE = 9 MDL_FILE = 1 MDL_NODE = 2 MDL_MESH = 3 MDL_BONE = 4 MDL_VERTEXARRAY = 5 MDL_INDICEARRAY = 6 MDL_PROPERTIES = 7 MDL_ANIMATIONKEYS = 8 MDL_AABB = 9 MDL_SURFACE = 10 MDL_NEWTONCOLLISIONTREE = 11 MDL_POSITION = 1 MDL_NORMAL = 2 MDL_TEXTURE_COORD = 3 MDL_COLOR = 4 MDL_TANGENT = 5 MDL_BINORMAL = 6 MDL_BONEINDIC...
import sys, os class FastaTarget: def __init__(self): self.tid = '' self.len = '' self.offset = -1 self.blen = -1 self.llen = -1 class FastaIndex: def __init__(self, fname=''): self.f = open(fname, 'r') self.ft = {} for line in self.f.readlines(...
return seq def getChromosomes(faFile = ''): faiFile = "%s.fai" % (faFile) if not os.path.exists(faiFile): raise NameError("Cannot find fai file for %s" % faFile) faidx = FastaIndex(faiFile) fachr = faidx.ft.keys()
chromosomes = [] autosomal = ["%d" % c for c in range(1,23)] autosomal.extend(['X','Y']) for chrom in autosomal: if chrom in fachr: chromosomes.append(chrom) chromosomes.extend( list (set(fachr) - set(autosomal))) return chromosomes
# encoding: utf-8 # Copyright (c) 2001-2014, Canal TP and/or its affiliates. All rights reserved. # # This file is part of Navitia, # the software to build cool stuff with public transport. # # Hope you'll enjoy and contribute to this project, # powered by Canal TP (www.canaltp.fr). # Help us simplify mobility...
except sqlalchemy.exc.SQLAlchemyError as e: logger.exception('error durring transaction') if not hasattr(e, 'connection_invalidated') \
or not e.connection_invalidated: transaction.rollback() raise TechnicalError('problem with databases: ' + str(e)) except: logger.exception('error durring transaction') try: transaction.rollback() except: ...
# Copyright 2013 Google Inc. 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 applicable law or ...
L_APPLICATION_ID_PREFIX = 'dev~' # String. Prefix used to detect if a server is running locally. _LOCAL_SERVER_PREFIX = 'localhost' # String. Prefix App Engine uses for application ids in production. _REMOTE_APPLICATION_ID_PREFIX = 's~' # String. Email address used unless os.environ['USER_EMAIL'] is set in tests. _TEST...
TEST_SERVER_SOFTWARE = 'Test' class Error(Exception): """Base error type.""" class EnvironmentAuthenticationError(Error): """Raised when establishing an environment fails due to bad credentials.""" class Environment(object): """Sets up the execution environment to use remote_api for RPCs. As wit...
from __future__ import print_function from lector import * from lpSolv import * import sys import math def generarRestriccionesTipo(matriz, tipo): numeroRestricciones = (n* (n-1)) / 2 if tipo == 0 or tipo == 1: for j in range(0, n): restriccionCanecaI = [] for k in range(0, i * ...
sumaPesos = 0 sumaVolumenes = 0 for i in range(len(items)): sumaPesos += items[i].getPeso() for i in range(len(items)): sumaVolumenes += items[i].getVolumen() pesos = math.ceil(sumaPesos / float(caneca
.getPeso())) volumenes = math.ceil(sumaVolumenes / float(caneca.getVolumen())) if(pesos >= volumenes): return pesos else: return volumenes param = (sys.argv[1] if len(sys.argv) > 1 else -1) o = leerArchivo(param) caneca = o[0] items = o[1] numeroProblema = o[2] + "_2.lp" n = int(hallarN()) ...
f not v: v = Visit(user_id1=self.id, user_id2=u.id) v.visit_date = datetime.now(tz=None) if new_v: DBSession.add(v) # @classproperty # def __mapper_args__(cls): # return dict( # order_by='mba_users.name', # polymorphic_identity=c...
.id==others_requests.c.user_b_id, secondaryjoin=MbaUser.id==others_requests.c.user_a_id, viewonly=True) class Participate(Base): __tablename__ = 'participate' user_id = Column(Integer, ForeignKey('mba_users.id'), primary_key=True) act_id = Column(Integer, ...
mary_key=True) creation_date = Column(DateTime(), nullable=False, default=datetime.now) #用户参加活动之后可进行评分 rating = Column(Integer()) user = relationship("MbaUser", backref=backref("partin", cascade="all, delete-orphan") ) meetup = relationship("Act") class ...
from pyrates.utility import grid_search_annarchy, plot_timeseries from ANNarchy import Projection, Population, TimedArray
, setup, Network, Monitor, Uniform, Normal, \ EIF_cond_exp_isfa_ista from pyrates.utility import pyrates_from_annarchy import matplotlib.pyplot as plt import numpy as np # parameters ############ T = 1000.0 # simulation time (ms) dt = 1e-2 # integration step-size (ms) Ne = 100 ...
y neurons c_min = 0.1 c_max = 1.0 # network definition #################### setup(method='explicit', dt=dt) # Neuron definition neuron = EIF_cond_exp_isfa_ista() neuron.equations = """ I = g_exc * (e_rev_E - v) + g_inh * (e_rev_I - v) + i_offset * Normal(0.2, 1.0) tau_m * dv/dt = (v_rest - v + delta_T ...
#python3 ''' ''' import sys while 1: try: h1,m1,s1,h2,m2,s2=map(int,input().split()) except EOFError: break '''<- this is /* in c/c++ m1=input() s1=input() h2=input() m2=input() s2=inp
ut() ''' s1=s
2+60-s1 s2=s1%60 s1=s1/60 m1=m2+60-1-m1+s1 m2=m1%60 m1=m1/60 h2=h2-h1-1+m1 #print("d d d"%(h,m,s)) <- wrong format print('%d'%h2,'%d'%m2,'%d'%s2)
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
-m p
ip install google-cloud-aiplatform # [START aiplatform_generated_aiplatform_v1beta1_VizierService_SuggestTrials_sync] from google.cloud import aiplatform_v1beta1 def sample_suggest_trials(): # Create a client client = aiplatform_v1beta1.VizierServiceClient() # Initialize request argument(s) request...
from django.short
cuts import render, render_to_response, RequestContext from .forms import SignUpForm # Create your views here. def home(request): form = SignUpForm(request.POST or None) if form.is_valid(): save_it = form.save(commit=False) save_it.save() return render_to_response("sign
up.html", locals(), context_instance=RequestContext(request))
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-05-12 08:41 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('cases',...
name='office', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, t
o='offices.Office'), ), ]
tup_conf(config=config, pre_config=PRE_CONFIG) result = self.check_pad(email) self.check_report(
result, 1, ['TEST_RULE']) def test_check_for_faraway_charset_in_headers_not_match(self): config = "header TEST_RULE eval:check_for_faraway_charset_in_headers()" email = "Subject: This is a test subject" self.setup_conf(config=config, pre_config=PRE_CONFIG) result = self.check_pad...
self.check_report(result, 0, []) def test_check_for_faraway_charset_in_headers_with_all_locales(self): config = ("header TEST_RULE eval:check_for_faraway_charset_in_headers()\n" "ok_locales all") email = "Subject: This is a test subject" self.setup_conf(config=confi...
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <lkcl@lkcl.net> # # 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/...
ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyjamas import DOM from pyjamas import Factory from pyjamas.ui.CellPanel import CellPanel from pyjamas.ui import HasHorizontalAlignment from pyjamas.ui import HasVerticalAlig...
lPanel(CellPanel): def insert(self, widget, beforeIndex): widget.removeFromParent() tr = DOM.createTR() td = DOM.createTD() DOM.insertChild(self.getBody(), tr, beforeIndex) DOM.appendChild(tr, td) CellPanel.insert(self, widget, td, beforeIndex) self.setCe...
for editor in self.editors: if editor.filename == filename: current_file_editor = editor if current_file_editor is None and len(self.editors) > 0: current_file_editor = self.editors[0] if current_file_editor is not None: self._ma...
ect('notify::filename', self.on_editor_notify_filename) editor.connect('notify::modified', self.on_editor_notify_modified)
editor.connect('notify::state', self.on_editor_notify_state) self._update_editor_title(editor) self._update_editor_state(editor) self._update_open_files() def _close_editor(self, editor): if not editor.confirm_discard(): return if editor == self.current_...
tracks_file = os.path.join(self.opensfm_project_path, 'tracks.csv') reconstruction_file = os.path.join(self.opensfm_project_path, 'reconstruction.json') if not io.file_exists(tracks_file) or rerun: self.run('create_tracks') else: log.ODM_WARNING('Found a valid O...
p.get_gps_dop() else: dop = args.gps_accuracy # default value if p.latitude is not None and p.longitude is not None: exif_overrides[p.filename] = { 'gps': { 'latitude
': p.latitude, 'longitude': p.longitude, 'altitude': p.altitude if p.altitude is not None else 0, 'dop': dop, } } with open(os.path.join(self.opensfm_project_path, "exif_overrides...
sample_time, notes, barcode]) if len(survey_ids) > 0: sql = """INSERT INTO ag.source_barcodes_surveys (survey_id, barcode) VALUES (%s, %s)""" ...
speaking the ag_login_id isn't needed but it makes it really hard to hack the function
when you would need to know someone else's login id (a GUID) to delete something maliciously. If the barcode has never been scanned, assume a mis-log and wipe it so barcode can be logged again. If barcode has been scanned, that means we have recieved it and must withdraw it to delete it...
m Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in complian...
start_cmd = self.which(ffname) if start_cmd is not None: break else: # couldn't find firefox on the system path raise RuntimeError
("Could not find firefox in your system PATH." + " Please specify the firefox binary location or install firefox") return start_cmd def _default_windows_location(self): program_files = [os.getenv("PROGRAMFILES", r"C:\Program Files"), os.getenv("PROGRAMF...
import math class Point(object): X = 0 Y = 0 def __init__(self, x, y): self.X = x self.Y = y def getX(self): return self.X def getY(self): return self.Y def __str__(self): return "Point(%s,%s)" % (self.X, self.Y) def __eq__(self, other): ...
class Trail(object): def __init__(self): self.trail = [] def extend(self, point): self.trail.append(point) print "Added : " + str(point) def getHousesCountVisitedOnce(self): uniquePoints = [] for point1 in self.trail: found = False for poi...
if found == False: uniquePoints.append(point1) return len(uniquePoints) def main(): # # Entry point # origin = Point(0,0) # Where Santa starts it's run. trail = Trail() # The gifts delivery trail. trail.extend(origin) with open('data.txt') as f: for c in...
""" WSGI config for proxy project. It exposes the WSGI call
able as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proxy.settings") application = get_wsgi_applic
ation()
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (c) 2016 Gramps Development Team # # 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 ...
""" return getattr(self.db, attr) def clear_cache(self, handle=None): """ Clears all caches if handle is None, or specific entry.
""" if handle: del self.cache_handle[handle] else: self.cache_handle = LRU(100000) def get_person_from_handle(self, handle): """ Gets item from cache if it exists. Converts handles to string, for uniformity. """ if isinstance(h...
''' Created on Sep 10, 2014 @author: moloyc ''' import os import logging from jinja2 import Environment, PackageLoader from netaddr import IPNetwork import util from model import Pod from dao import Dao from writer import DhcpConfWriter moduleName = 'ztp' logging.basicConfig() logger = logging.getLogger(moduleName)...
p) elif util.isPlatformCentos(): dhcpTemplate = self.templateEnv.get_template('dhcp.conf.centos') ztp = self.populateDhcpDeviceSpecificSetting(podName, ztp) con
f = dhcpTemplate.render(ztp = ztp) logger.debug('dhcpd.conf\n%s' % (conf)) return conf def populateDhcpGlobalSettings(self): ztp = {} ztpGlobalSettings = util.loadClosDefinition()['ztp'] subnet = ztpGlobalSettings['dhcpSubnet'] dhcpBlock = IPNetwork(subn...
#!/usr/bin/env python3 # 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 # "L...
append(exception_str) if tracebacks: print(""" ERROR: There were some import errors """,
file=sys.stderr) for trace in tracebacks: print("----------------------------------------", file=sys.stderr) print(trace, file=sys.stderr) print("----------------------------------------", file=sys.stderr) sys.exit(1) else: return imported_classes if __...
de': 'fallback_mode', 'fullPath': 'full_path', 'loadBalancingMode': 'load_balancing_mode', 'manualResume': 'manual_resume', 'maxAnswersReturned'
: 'max_answers_returned', 'qosHitRatio': 'qos_hit_ratio', 'qosHops': 'qos_hops', 'qosKilobytesSecond': 'qos_kilobytes_second', 'qosLcs': 'qos_lcs', 'qosPacketRate
': 'qos_packet_rate', 'qosRtt': 'qos_rtt', 'qosTopology': 'qos_topology', 'qosVsCapacity': 'qos_vs_capacity', 'qosVsScore': 'qos_vs_score', 'verifyMemberAvailability': 'verify_member_availability', 'membersReference': 'members' } returnables = [ 'alternat...
import tkinter as tk import tkinter.ttk as ttk def NewFlight(): from Controller import LoadNewFlightPage LoadNewFlightPage(mainPage) def LogBook():
from Controll
er import LoadLogBookPage LoadLogBookPage(mainPage) def CreateMainPage(): global mainPage mainPage = tk.Tk() mainPage.configure(background="midnight blue") mainPage.title("RAF Flying Logbook v1") """mainPage.geometry('%dx%d+0+0' % (mainPage.winfo_screenwidth(),mainPage.winfo_screenh...
""" Definition of model
s. """ from django.db import models from django import forms; # Create your models here. class Artist(models.Model): name = models.CharField(max_length=50); year_formed = models.PositiveIntegerField(); class ArtistForm(forms.ModelForm): class Meta: model = Artist; fields = ['name', 'year_...
els.CharField(max_length=50); artist = models.ForeignKey(Artist);
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('flood_mapper', '0003_data_migration_20141201_0218'),
] operations = [ migrations.AlterField( model_name='floodstatus', name='notes', field=models.TextField(null=True, blank=True), preserve_default=True, ), migrations.AlterField( model_name='vi
llage', name='slug', field=models.SlugField(unique=True, max_length=100), preserve_default=True, ), ]
volume_name" field in the input example, ' 'volume_path points to HDF5 volumes containing int64 ' 'label data, and `dataset` is the name of the dataset ' 'from which data will be read.') flags.DEFINE_string('model_name', None, 'Name of the ...
m(pred_bg & true_mask) self.tn += np.sum(pred_bg & true_bg) self.num_patches += 1 predicted = expit(predicted) self.images_xy.append(self.slice_image(labels, predicted, weights, 0)) self.images_xz.append(self.slice_image(labels, predicted, weights, 1)) self.images_yz.append(self.slice_image(lab...
.""" if not self.total_voxels: return [] precision = self.tp / max(self.tp + self.fp, 1) recall = self.tp / max(self.tp + self.fn, 1) for images in self.images_xy, self.images_xz, self.images_yz: for i, summary in enumerate(images): summary.tag += '/%d' % i summaries = ( ...
import numpy a
s np def P_vector(model, nodal_load): """Return the load vector """ P = np.zeros(model.nt) for n, p in noda
l_load.items(): if n not in model.CON: raise Exception('Not a valid DOF for the applied load!') for i, d in enumerate(model.DOF[n]): P[d] = p[i] return P
#!/usr/bin/env python """ Test code for blackjack game. Tests can be run with py.test or nosetests """ from __future__ import print_function from unittest import TestCase from card_games import blackjack from card_games.blackjack import BlackJack print(blackjack.__file__) class TestRule(TestCase): def setUp(se...
pass def test_init(self): mygame = BlackJack() self.assertEqual(len(mygame.player_hand), 2) # Initial hand for Player self.assertEqual(len(mygame.dealer_hand), 2) # Initial hand for Dealer def test_player_bust(self): mygame = BlackJack() for cnt in range(10): # Dr...
e.game_result(), 'bust') # Definitely a bust
# coding=utf-8 # --------------------------------
------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsof
t (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class AddDataLakeStoreParameters(Model): """The parameters used to add a new Dat...
-------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2019, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: yo...
eriod=1000): """ :param n: Number of units :type n: int :param k: The activity of the top k units will be allowed to remain, the rest are set to zero :type k: int :param kInferenceFactor:
During inference (training=False) we increase k by this factor. :type kInferenceFactor: float :param boostStrength: boost strength (0.0 implies no boosting). :type boostStrength: float :param boostStrengthFactor: Boost strength factor to use [0..1] :type boostStrengthFactor: float ...
# Portions Copyright (c) Facebook, Inc. and its affiliates. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2. # highlight.py - highlight extension implementation file # # Copyright 2007-2009 Adam Hupp <adam@hupp.org> and others # # This software may be...
ename TextLexer = pygments.lexers.TextLexer HtmlFormatter = pygments.formatters.HtmlFormatter SYNTAX_CSS = '\n<link rel="stylesheet" href="{url}highlightcss" ' 'type="text/css" />' def pygmentize(field, fctx, style, tmp
l, guessfilenameonly=False): # append a <link ...> to the syntax highlighting css old_header = tmpl.load("header") if SYNTAX_CSS not in old_header: new_header = old_header + SYNTAX_CSS tmpl.cache["header"] = new_header text = fctx.data() if util.binary(text): return # ...
intang_assets: NUMBER(20,4) 无形资产 r_and_d_costs: NUMBER(20,4) 开发支出 goodwill: NUMBER(20,4) 商誉 long_term_deferred_exp: NUMBER(20,4) 长期待摊费用 deferred_tax_assets: NUMBER(20,4) 递延所得税资产 loans_and_adv_granted: NUMBER(20,4) 发放贷款及垫款 ...
) 应付票据 acct_payable: NUMBER(20,4) 应付账款 adv_from_cust: NUMBER(20,4) 预收款项 fund_sales_fin_assets_rp: NUMBER(20,4) 卖出回购金融资产款 handling_charges_comm_payable: NUMBER(20,4) 应付手续费及佣金 empl_ben_payable: NUMBER(20,4)
应付职工薪酬 taxes_surcharges_payable: NUMBER(20,4) 应交税费 int_payable: NUMBER(20,4) 应付利息 dvd_payable: NUMBER(20,4) 应付股利 oth_payable: NUMBER(20,4) 其他应付款 acc_exp: NUMBER(20,4) 预提费用 deferred_inc: NUMBER(20,4) 递延收益 st_bonds_pa...
fro
m .tornadoconnection import TornadoLDAPConnectio
n
from docutils import nodes, utils from docutils.parsers.rst.roles import set_classes # I cant figure out how the hell to import this so I'm just gonna forget it for now def apigen_role(name, rawtext, text, lineno, inliner, options={}, content=[]): """Link to API Docs page. Returns 2 part tuple containing lis...
:param lineno: The line numbe
r where rawtext appears in the input. :param inliner: The inliner instance that called us. :param options: Directive options for customization. :param content: The directive content for customization. """ try: class_name = text.replace('\\', '.') if text[0:1] == '.': clas...
""" Copyright (c) 2016-2017, Kir Chou https://github.com/note35/sinon/blob/master/LICENSE A set of functions for handling known error """ def _
_exception_helper(msg, exception=Exception): #pylint: disable=missing-docstring raise exception(msg) def mock_type_error(obj): #pylint: disable=missing-docstring error_msg = "[{}] is an invalid module/class".format(str(obj)) return __exception_helper(error_msg) def prop_type_error(prop): #pylint: disable=...
(obj, prop): #pylint: disable=missing-docstring name = obj.__name__ if hasattr(obj, "__name__") else obj error_msg = "[{}] is an invalid property, it should be a method in [{}]".format(prop, name) return __exception_helper(error_msg) def prop_in_obj_error(obj, prop): #pylint: disable=missing-docstring ...
import sys, os import math, numpy as np import matplotlib.pyplot as pp import roslib; roslib.load_manifest('sandbox_tapo_darpa_m3') import hrl_lib.util as ut import hrl_lib.matplotlib_util as mpu import scipy.optimize as scp # Params area = 0.0 # For one push and pull: def force_one_push_pull(d): ft_l = d['ft'...
c, ft, marker='o', color=color, label=nm.split('/')[-1].split('.')[0], s=50) pp.xlabel('ADC bias - ADC') pp.ylabel('FT_z') pp.legend() pp.grid('on') def residuals(p, y, x, area): coeff_1, coeff_2, coeff_3, coeff_4 = p err = y-(coeff_1*area*(x)**3 + coeff_2*area*(x)**2 + coeff_3*...
ing on 4-cm data d = ut.load_pickle(pkl_list[2]) x,y_meas = force_one_push_pull(d) area = math.sqrt(d['contact_area']) coeff_1 = 5. coeff_2 = 5. coeff_3 = 5. coeff_4 = 5. p0 = np.array([coeff_1, coeff_2, coeff_3, coeff_4]) p_lsq = scp.leastsq(residuals, p0, args=(y_meas, x, area)) ...
from ex25 import * print "Let's practice everything." print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.' poem = """ \tThe lovely world with logic so firmly planted cannot discern \n the needs of love nor comprehend passion from intuition and requires an explantion \n\t\twhere there is...
five = 10 - 2 + 2 - 5 print "This should be five: %s" % five def secret_formula(started): jelly_beans = started * 500 jars = jelly_beans / 1000 crates = jars / 100 return jelly_beans, jars, crates start_point = 10000 beans, jars, crates = secret_formula(start_point) print "With a starting point of...
d %d crates." % (beans, jars, crates) start_point = start_point / 10 print "We can also do that this way:" print "We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point) sentence = "All good things come to those who wait." words = break_words(sentence) sorted_words = sort_words(words) print_fir...
import numpy as np import pytest from sklearn.preprocessing import StandardScaler from sklearn.utils import check_random_state import fri from fri import genLupiData from fri.parameter_searcher import find_best_model @pytest.fixture(scope="session") def randomstate(): return check_random_state(1337) @pytest.ma...
("problem", fri.LUPI_MODELS) def test_baseline_lupi(problem, n_weak, randomst
ate): n_samples = 300 template = problem.value[0]().get_initmodel_template params = problem.value[0]().get_all_parameters() data = genLupiData( problem, n_strel=1, n_weakrel=n_weak, n_samples=n_samples, n_irrel=1, n_repeated=0, random_state=random...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class M
igration(migrations.Migration): dependencies = [ ('libreosteoweb', '0021_therapeutsettings_siret'), ] operations = [ migrations.AddField( model_name='therapeutsettings', name='invoice_footer', field=models.TextField(null=True, verbose_name='Invoice foote...
preserve_default=True, ), ]
e for these cases. language = 'en' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match fil...
ls. # # latex_appendices = [] # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master...
# If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinf...
# coding:utf-8 # # The MIT License (MIT) # # Copyright (c) 2016-2021 yutiansut/QUANTAXIS # # 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 th...
self.conn.commit() self.conn.close() def _create(self,
cache_file): """Create the tables needed to store the information.""" conn = sqlite3.connect(cache_file) cur = conn.cursor() cur.execute("PRAGMA foreign_keys = ON") cur.execute(''' CREATE TABLE jobs( hash TEXT NOT NULL UNIQUE PRIMARY KEY, description ...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyKiwisolver(PythonPackage): """A fast implementation of the Cassowary constraint solver""...
1f3bf01fbc8b9c990a7889e9bb4400c4d0ff9155aa0bdd19cce24a9') version('1.2.0', sha256='247800260cd38160c362d211dcaf4ed0f7816afb5efe56544748b21d6ad6d17f') version('1.1.0', sha256='53eaed412477c836e1b9522c19858a8557d6e595077830146182225613b11a75') version('1.0.1', sha256='ce3be5d520b4d2c3e5eeb4cd2ef62b9b9ab8a
c6b6fedbaa0e39cdb6f50644278') depends_on('python@2.7:2.8,3.4:', type=('build', 'run')) depends_on('python@3.5:', type=('build', 'run'), when='@1.2.0:') depends_on('python@3.6:', type=('build', 'run'), when='@1.3.0:') depends_on('python@3.7:', type=('build', 'run'), when='@1.3.2:') depends_on('py-s...
# Lint as: python3 """A torque based stance controller framework.""" from __future__ import absolute_import from __future__ import division #from __future__ import google_type_annotations from __future__ import print_function import os import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspec...
= 0.45, body_mass: float = 220 / 9.8, body_inertia: Tuple[float, float, float, float, float, float, float, float, float] = (0.07335, 0, 0, 0, 0.25068, 0, 0, 0, 0.25447), num_legs: int = 4, friction_coeffs: Sequence[float
] = (0.45, 0.45, 0.45, 0.45), qp_solver = convex_mpc.QPOASES ): """Initializes the class. Tracks the desired position/velocity of the robot by computing proper joint torques using MPC module. Args: robot: A robot instance. gait_generator: Used to query the locomotion phase and leg ...
fileObject = open(filepath, 'a+') fileObject.writelines(transList) fileObject.flush() return fileObject def shelveNetwork(graph = {},filepath = "defaultFilePath"): """ Stores via the Graph at the filepath location e.g '/apath/file.xay' Preconditions: Takes a graph Postconditions: Ret...
d', 'e', 'f']} nothernetwork = {'a': [1,2,3], 'b' : [4,5,6], 1 : ['d', 'e', 'f'], 4: ['e', 'f', 'g'], 'x': [9, 10,11], 11: [12, 13, 14]} loopnetwork = {'a': [1,2,3], 'b' : [4,5,6], 1 : ['d', 'e', 'f'], 4: ['e', 'f', 'g'], 12: [13], 13: [12]} #DATASETS FOR MUTUAL INFORMATION ...
,'c'], 'b': ['a', 'b', 'c'], 'c': ['a','b','c']} noselfcon = {'a':['b','c'], 'b': ['a', 'c'], 'c': ['a','b']} cycle3 = {'a':['b'], 'b':['c'], 'c':['a']} cycle4 = {'a':['b'], 'b':['c'], 'c':['d'], 'd...
#!
/usr/bin/env python from PyMiniQbt import getVersion, getName, QasmAsyncInterpreter import sys def main(arguments): if(not len(arguments) == 2): print("which file?") sys.exit(-1) print("Using", getName(), "version:", getVersion()) with open(arguments[1]) as dat: src = dat.read() ...
s:") for register in interpreter.getRegisters(): print(register,":",interpreter.readClassicResult(register).dataToString()) if __name__ == "__main__": main(sys.argv)
import logging from sleekxmpp import ClientXMPP log = logging.getLogger(__name__) class HipshareXMPP(ClientXMPP): def __init__(self, jid, password): ClientXMPP.__init__(self, jid, password) self.add_event_handler("session_start", self.session_start, threaded=True) def session_start(self, eve...
fig self.xmpp = HipshareXMPP(config.strategy['jid'], config.strategy['password']) for plugin in config.opt
ions['plugins']: self.xmpp.register_plugin(plugin) def connect(self, *args, **kwargs): return self.xmpp.connect(*args, **kwargs) def disconnect(self, *args, **kwargs): return self.xmpp.disconnect(*args, **kwargs) def get_plugin(self, plugin): return self.xmpp.plugin[pl...
ging.WARNING) class TestRepoUtils(object): @classmethod def setup_class(cls): cls.temp_path = tempfile.mkdtemp(prefix='test_repo-') cls.dest_path = cls.temp_path + '/empty_dest' cls.src_path = cls.temp_path + '/empty_src' if 'TEST_ONLINE' in os.environ: cls.repo_u...
ee(cls.temp_path) def setup_method(self, method): assert not os.path.exists(self.dest_path) proc = subprocess.Popen( ('git', 'init', self.src_path), stdout=subprocess.PIPE, ) assert proc.wait() == 0 proc = subprocess.Popen
( ('git', 'config', 'user.email', 'test@ceph.com'), cwd=self.src_path, stdout=subprocess.PIPE, ) assert proc.wait() == 0 proc = subprocess.Popen( ('git', 'config', 'user.name', 'Test User'), cwd=self.src_path, stdout=subproc...
#!/usr/bin/env python import os import django # Base paths DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__)) SITE_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) # Debugging DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS =...
USER': 'hacktyler_crime', 'PASSWORD': 'qw8ndyHprt', } } # Localization TIME_ZONE = 'America/Chicago' LANGUAGE_CODE = 'en-us' USE_I18N = True USE_L10N = True # Media STATIC_ROOT = os.path.join(SITE_ROOT, 'media') STATIC_URL = '/site_media/' ADMIN_MEDIA_PREFIX = '/site_media/ad
min/' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ) # Uploads MEDIA_ROOT = '/tmp/sirens' # Make this unique, and don't share it with anybody. SECRET_KEY = '+ei7-2)76sh$$dy...
# This is an example of popping a packet from the Emotiv class's packet queue # and printing the gyro x and y values to the console. from emokit.emotiv import Emotiv import platform if platform.system() == "Windows": import socket # Needed to prevent gevent crashing on Windows. (surfly / gevent issue #459) impor...
set_ydata(np.ma.array(x, mask=True)) return line, def animate(rb): print "Animation!" print rb
line.set_ydata(rb) return line, def counter(): i = 0 while is_running: yield i i = i + 1 ani = animation.FuncAnimation(fig, animate, evt_wrapper(), init_func=init, interval=20, blit=True) plt.show() # gevent.Greenlet.spawn(evt_main, test_buf) while True: gevent.sleep(0)
import pybedtools a = pybedtools.example_bed
tool('a.bed') b = pybedtools.example_bedtool('b.bed') print "cat a.bed\n" + str(a) print "cat b.bed\n"
+ str(b) print a.intersect(b)
# # Copyright (C) 2013-2014 Emerson Max de Medeiros Silva # # This file is part of ippl. # # i
ppl 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 v
ersion. # # ippl is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # alon...
""" Tests for the InstructorService """ import json from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory from courseware.models import StudentModule from instructor.services import InstructorService from instructor.tests.test_tools import ...
self.course.id, 'robot-some-other_problem-urlname' ) self.problem_urlname = unicode(self.problem_location)
self.other_problem_urlname = unicode(self.other_problem_location) self.service = InstructorService() self.module_to_reset = StudentModule.objects.create( student=self.student, course_id=self.course.id, module_state_key=self.problem_location, state=j...
# Copyright (c) 2014 Yubico AB # All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program...
General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Additional permission under GNU GPL version 3 section 7 # # If you modify this program, or any covered work, by linking or # combining it with the OpenSSL project's OpenSSL library (or a # modified version of that library...
grant you additional # permission to convey the resulting work. Corresponding Source for a # non-source form of such a combination shall include the source code # for the parts of OpenSSL used as well as that of the covered work. from __future__ import print_function from .utils import time_challenge, parse_full, fo...
import Fast5File def run(parser, args): if args.read: for i, fast5 in enumerate(Fast5File.Fast5FileSet(args.files)): for metadata_dict in fast5.read_metadata: if i == 0: header = metadata_dict.keys() print "\t".join(["filename"] + header) print "\t".join([fast5.filename] + [str( metadata_dict[...
5 in Fast5File.Fast5FileSet(args.files): asic_temp = fast5.get_asic_temp() asic_id = fast5.get_asic_id() heatsink_temp = fast5.get_heatsink_temp() pr
int "%s\t%s\t%s" % (asic_id, asic_temp, heatsink_temp) fast5.close()
# -*- coding: utf-8 -*- import time import requests from datetime import datetime from logging import getLogger from typing import Optional from typing import Dict from typing import Iterable from funcy import compose from funcy import partial from pandas import DataFrame from pandas import to_datetime from pandas imp...
ow get USD_BTC history btc_price_hist = coin_history('bitcoin') # and write that history to DB, btc_rows = marshall(btc_price_hist) # NOTE since latest fetch time? # recent_btc = btc_rows[btc_rows['time'] > latest_fetch_time] # [inserter(row) for _, row in recent_btc.iterrows()] [inserter(ro...
_public() # and a method for grabbing historical prices grab_historical_prices = partial(historical_prices_of, polo, btc_price_hist) # for each market, for market in polo.return_ticker(): # fetch all the chart data since last fetch generator = grab_historical_prices( market, ...
#!/usr/bin/python from ABE_ADCDACPi import ADCDACPi import time import math """ ================================================ ABElectronics ADCDAC Pi 2-Channel ADC, 2-Channel DAC | DAC sine wave generator demo Version 1.0 Created 17/05/2014 Version 1.1 16/11/2014 updated code and functions to PEP8 format run with...
2, 3565, 35
48, 3531, 3514, 3496, 3478, 3460, 3442, 3423, 3405, 3386, 3367, 3347, 3328, 3308, 3288, 3268, 3248, 3227, 3207, 3186, 3165, 3144, 3122, 3101, 3079, 3057, 3036, 3013, 2991, 2969, 2946, 2924, 2901, 2878, 2855, 2832, 2808, 2785, 2762, 2738, 2714, 2690, 2667, 2643, 2618, 2594, 2570, 2546, 2521...
# PRNG (Pseudo-Random Number Generator) Test # PRNG info: # http://en.wikipedia.org/wiki/Pseudorandom_number_generator # FB - 201012046 # Compares output distribution of any given PRNG # w/ an hypothetical True-Random Number Generator (TRNG) import math import time global x x = time.clock() # seed for the PRNG # PRNG ...
if b == 0: ctr += 1 # print num # increase bit count in the array cnk[ctr] += 1 print 'Number of bits in each pseudo-random number (n) =', n print print 'Comparison of "0" count distributions:' print print ' k', ' c(n,k)', ' actual', '%dif' difSum = 0 for k in range(n + 1): cnk_ = c(n, k) ...
e percentage between the distributions:' print 100 * difSum / (2 ** n)
"""Tests for the unused-variable message in assignment expressions""" def typed_assignment_in_function_default( # [unused-variable] param: str = (typed_default := "walrus"), # [unused-variable] ) -> None: """An unused annotated assignment expression in a defau
lt parameter should emit""" return param def assignment_in_function_default( # [unused-variable] param=(default := "walrus"), # [unused-variable] ) -> None: """An unused assignment expression in a default parameter should emit""" return param def assignment_used_in_function_scope( # [unused-variabl...
) -> None: """An used assignment expression in a default parameter should not emit""" print(function_default) return param def assignment_used_in_global_scope( # [unused-variable] param=(global_default := "walrus"), ) -> None: """An used assignment expression in a default parameter should not emit...
#!/usr/bin/env python from iris_sdk.mode
ls.maps.base
_map import BaseMap class SubscriptionsMap(BaseMap): subscription = None
log.info('Registering data type "{}".'.format(tag)) @abstractproperty def skeleton(self): """ Reserved for future use """ pass @abstractproperty def tag(self): """ A str which uniquely identifies this type and serves as its key in the Registry.typemap dict ...
= DataframeJSON() def __init__(self, data): super(Dataframe, self).__init__() self.value = data self.validate() @classmethod def fromDataset(cls, value, metadata=None): df = cls._create_dataframe(value) return cls(df) @classmethod def _create_datafra...
= json.loads(six.text_type(value), object_pairs_hook=collections.OrderedDict) #Pandas does not maintain the order of dicts, so we must break the dict #up and put it into the dataframe manually to maintain the order. cols = list(ordered_jo.keys()) if len(cols) == 0: ...
""" Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ from __future__ import unicode_literals import json import os from osbs.api import OSBS from osbs.conf import Configuration from atomic_re...
OpenShift. """ key = "import_image" can_fail = False def __init__(self, tasker, workflow, url, verify_ssl=True, use_auth=True): """ constructor :param tasker: DockerTasker instance :param workflow: DockerBuildWorkflow instance :param url: str, URL to OSv3 inst...
""" # call parent constructor super(ImportImagePlugin, self).__init__(tasker, workflow) self.url = url self.verify_ssl = verify_ssl self.use_auth = use_auth def run(self): try: build_json = json.loads(os.environ["BUILD"]) except KeyError: ...
s import frappe from frappe import _ from frappe.utils import fmt_money, formatdate, format_time, now_datetime, \ get_url_to_form, get_url_to_list, flt from datetime import timedelta from dateutil.relativedelta import relativedelta from frappe.core.doctype.user.user import STANDARD_USERS import frappe.desk.notificatio...
ef get_payables(self): return self.get_type_balance('payables', 'Payable') def get_invoiced_amount(self): return self.get_type_balance('invoiced_amount', 'Receivable') def get_expenses_booked(self): expense, past_expense = self.get_period_amounts(self.get_root_type_accounts("expense")) return { "label":...
(self, accounts): """Get amounts for current and past periods""" balance = past_balance = 0.0 for account in accounts: balance += (get_balance_on(account, date = self.future_to_date) - get_balance_on(account, date = self.future_from_date)) past_balance += (get_balance_on(account, date = self.past_to_da...
# -*- coding: utf-8 -*- import attr from navmazing import NavigateToAttribute from widgetastic.widget import NoSuchElementException from widgetastic.widget import Text from widgetastic.widget import View from widgetastic_patternfly import BootstrapNav from widgetastic_patternfly import BreadCrumb from widgetastic_patte...
_entities = View.include(BaseEntitiesView, use_parent=True) @property def is_displayed(self): return ( self.in_object and self.title.text == 'Cloud Object S
tore Objects') @View.nested class my_filters(Accordion): # noqa ACCORDION_NAME = "My Filters" navigation = BootstrapNav('.//div/ul') tree = ManageIQTree() class ObjectStoreObjectDetailsView(ObjectStoreObjectView): """The detail Object Store Object page""" @property def i...
##### __all__ = [ 'Domain', 'ProductDomain', 'RealDomain', 'IntegerDomain', 'MultinomialDomain' ] ## FUNCTIONS ################################################################# ## ABSTRACT CLASSES AND MIXINS ############################################### class Domain(with_metaclass(abc.ABCMeta,...
array`` of type `dtype`. :type: ``np.ndarray`` """ return self._example_point @property def values(self): """ Returns an `np.array` of type `dtype` containing some values from the domain. For domains where `is_finite` is ``True``, all elements
of the domain will be yielded exactly once. :rtype: `np.ndarray` """ separate_values = [domain.values for domain in self._domains] return np.concatenate([ join_struct_arrays(list(map(np.array, value))) for value in product(*separate_values) ]) ...
#
-*- coding: utf-8 -*- from __future__ import unicode_literals if __name__ == '__main__': from command_manager import Manager manager = Manager(["commands"]) manager.ru
n()
# -*- coding: utf-8 -*- slenderParameters = {'notPlate': {'beam': {'M': {'BF': '2*bf', 'tfCriteria': True, 'TF': ('2*tf', ''), 'D': 'd', 'twCriteria': True, 'TW': ('(D-2*TF)/(d-2(tf+r))*tw', '')}, 'H': {'BF': '2*bf', 'tfCriteria': True, 'TF': ('2*0.55*tf/.6', ''), 'D': 'd', ...
'tw*(D-2*TF)/(d-2*(tf+r))')}, 'H': {'BF': 'c+bf+2*tf', 'tfCriteria': 't1<(B1*tf)/(bf)', 'TF': ('(BF*t1)/(B1)', '(BF*tf)/bf'), 'D': 'd+2*t1', 'twCriteria': 't2<(d*tw)/(d-2(tf+r))', 'TW': ('t2*(D-2*TF)/d', 'tw*(D-2*TF)/(d-2*(tf+r))')}}}} if __name__...
ility = 'M' parameters = slenderParameters[comositeSection][sectionPos][ductility] BF = parameters['BF'] tfCriteria = parameters['tfCriteria'] TF1 = parameters['TF'][0] TF2 = parameters['TF'][1] D = parameters['D'] twCriteria = parameters['twCriteria'] TW1 = parameters['TW'][0] TW2 =...
defaul
t_app_config = 'hs_tr
acking.apps.HSTrackingAppConfig'
"""The vimdoc parser.""" from vimdoc import codeline from vimdoc import docline from vimdoc import error from vimdoc import regex def IsComment(line): return regex.comment_leader.match(line) def IsContinuation(line): return regex.line_continuation.match(line) def StripContinuator(line): assert regex.line_c...
lank_code_line.match(line): return codeline.Blank() fmatch = regex.function_line.match(line) if fmatch: namespace, name, args = fmatch.groups() return codeline.Function(name, namespace, regex.function_arg.findall(args)) cmatch = regex.command_line.match(line) if cmatch: args, name = cmatch.group...
'register': '-register' in args, 'buffer': '-buffer' in args, 'bar': '-bar' in args, } return codeline.Command(name, **flags) smatch = regex.setting_line.match(line) if smatch: name, = smatch.groups() return codeline.Setting('g:' + name) flagmatch = regex.flag_line.match(line) ...
#!/usr/bin/python #coding=utf-8 ''' @author: sheng @license: ''' import unittest from meridian.acupoints import zhima
i44 class TestZhimai44Functions(unittest.TestCase): def setUp(self): pass def test_xxx(self): pass if __name__ == '__main__': un
ittest.main()
utoff of the same type already exists with this cut-off date !' )] def cutoff_date_onchange( self, cr, uid, ids, type, cutoff_date, move_label): res = {'value': {}} if type and cutoff_date: context = {'type': type, 'cutoff_date': cutoff_date} res['value']...
'ir.actions.act_window', 'nodestroy': False, 'target': 'current', } return action class account_cutoff_line(orm.Model): _name = 'account.cutoff.line' _description = 'Account Cut-off Line' _columns = { 'parent_id': fields.many2one( 'account.c...
_id': fields.related( 'parent_id', 'company_currency_id', type='many2one', relation='res.currency', string="Company Currency", readonly=True), 'partner_id': fields.many2one('res.partner', 'Partner', readonly=True), 'account_id': fields.many2one( 'account.account', 'Ac...
""" Tests for job management """ import unittest from unittest import mock import biokbase.narrative.jobs.jobmanager from biokbase.narrative.jobs.job import Job from .util import TestConfig import os from IPython.display import HTML from .narrative_mock.mockclients import get_mock_client, get_failing_mock_client from b...
f test_single_job_status_fetch(self): # new_job = phony_job() # self.jm.register_new_job(new_job) # self.jm._handle_comm_message(create_jm_message("job_status", new_job.job_id)) # msg = self.jm._comm.last_message # self.assertEqual(msg['data']['msg_type'], "job_status") # ...
_message_cache() # Should "fail" based on sent message. # def test_job_message_bad_id(self): # self.jm._handle_comm_message(create_jm_message("foo", job_id="not_a_real_job")) # msg = self.jm._comm.last_message # self.assertEqual(msg['data']['msg_type'], 'job_does_not_exist') def te...
if not self.isPause: # se o jogador nao 'pausou' o jogo if self.gameOver: # se fim de jogo if self.goAlpha == 0: pygame.mixer.music.stop() self.gameOverSound.play() self.goAlpha += 2 if self.goAlpha > 200 and (self.inp...
t para ser atualisado def updateGameObject(self, gameObject): gameObject.previousPosition = gameObject.position.copy()
gameObject.update() # aplica os modificadores da fase no gameObject # param: gameObject - um GameObject para ser aplicado as mudancas da fase # retorna se o gameObject saiu do mapa def updateStageModifiers(self, gameObject): self.applyGravity(gameObject) self.applyCollision(gameO...
test_framework.test_framework import OpenBazaarTestFramework, TestFailure class CompleteDirectOnlineTest(OpenBazaarTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 def run_test(self): alice = self.nodes[0] bob = self.nodes[1] # generate some...
ed") # check the sale saved correctly api_url = alice["gateway_url"] + "ob/order/" + orderId r = requests.get(api_url) if r.status_code != 200: raise TestFailure("CompleteDirectOnlineTest - FAIL: Couldn't load order from Alice") resp = json.loads(r.text) if r...
True: raise TestFailure("CompleteDirectOnlineTest - FAIL: Alice incorrectly saved as funded") # fund order spend = { "address": payment_address, "amount": payment_amount, "feeLevel": "NORMAL" } api_url = bob["gateway_url"] + "wallet/spend...
#!/usr/bin/python3 def vogal(v): lista = ['a','e','i','o','u','A'
,'E
','I','O','U'] if v in lista: return True else: return False
.selected[0].objkey) elif menuitem.returnkey == 'popupMissionSet': self.set_mission(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.returnkey == 'popupMissionRemove': self.remove_mission(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.r...
t(obj.selected[0].objkey, obj.selected[0].extra_info) elif menuitem.returnkey == 'showPosition': self.show_position() def map_callback(self, obj): '''called when an event happens on the slipmap''' from MAVProxy.modules.mavproxy_map import mp_slipmap if isinstance(obj, m...
eturn if not isinstance(obj, mp_slipmap.SlipMouseEvent): return if obj.event.m_leftDown and self.moving_rally is not None: self.click_position = obj.latlon self.click_time = time.time() self.mpstate.functions.process_stdin("rally move %u" % self.moving_ral...
from algorithms.structures.disjoint_set import DisjointSet def test_disjoint_set(): a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ds = Disjo
intSet(a) assert ds.find_set(1) != ds.find_set(2)
ds.union(1, 2) assert ds.find_set(1) == ds.find_set(2) assert ds.find_set(1) != ds.find_set(3) ds.union(2, 3) assert ds.find_set(1) == ds.find_set(2) assert ds.find_set(2) == ds.find_set(3)
import re from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-ShellcodeMSIL', 'Author': ['@mattifestation'], 'Description': ('Execute shellcode within the context of the running PowerShell ' ...
nts': [ 'http://www.exploit-monday.com', 'https://github.com/mattifestation/PowerSploit/blob/master/CodeExecution/Invoke-ShellcodeMSIL.ps1' ] } # any options needed by the module, settable during runtime self.options = { # format: ...
, default_value} 'Agent' : { 'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Shellcode' : { 'Description' : 'Shellcode to inject, 0x00,0x0a,... format.', ...
14, 'mov m,e': 115, 'mov m,h': 116, 'mov m,l': 117, 'hlt': 118, 'mov m,a': 119, 'mov a,b': 120, 'mov a,c': 121, 'mov a,d': 122, 'mov a,e': 123, 'mov a,h': 124, 'mov a,l': 125, 'mov a,m': 126, 'mov a,a': 127, 'add b': 128, 'add c': 129, 'add d': 130, 'a...
elif scLine.split(' ')[1] == 'equ': # Check if it's a variable declaration if int(scLine.split(' ')[2]) >= 2 ** 8: # Number is out of bounds for Intel 8080 print(Fore.RED + 'Variable too large: ' + ...
str(i + 1)) raise SyntaxError variableMap[scLine.split(' ')[0]] = unHex(scLine.split( ' ')[2].ljust(4, '0')) # It is, save it to a dictionary print('Updating variables') continue else: ...
from twi
sted.trial import unittest from twistedchecke
r.checkers.docstring import DocstringChecker class DocstringTestCase(unittest.TestCase): """ Test for twistedchecker.checkers.docstring """ def test_getLineIndent(self): """ Test of twistedchecker.checkers.docstring._getLineIndent. """ checker = DocstringChecker() ...
import os.path for root, dirs, files in os.walk(os.path.dirname(os.path.realpath(__file__))): for file in files : if file.endswith('.prog') : os.chdir(root) f1 = open(file, 'r') output = file.split(".") f2 = open(output[0]+'.py', 'w') indent = 0 ...
= tag.replace("{", ":\n") a = a.replace("CIKLUS", "for") a = a.replace("ELAGAZAS", "if") if "\n" in a:
t = a.split("\n") for t1 in t: for i in range(indent): t1 = pad + t1 if "for" in t1 or "if" in t1: indent += 1 if "}" in t1: ...
png except ImportError: png = False import pygtk pygtk.require('2.0') import gtk import gtk.gtkgl import gtk.gtkgl.apputils from OpenGL.GL import * from OpenGL.GLU import * import openglutils class MatrixWidget(gtk.DrawingArea, gtk.gtkgl.Widget): """OpenGL widget drawing the view of the matrices of the worl...
events for the manipulation of the view self.set_events(gtk.gdk.ALL_EVENTS_MASK) self.connect('scroll-event', self.__on_scroll) self.connect('motion-notify-event', self.__on_motion_notify) self.connect('button-press-event', self.__on_butt
on_press) self.connect('button-release-event', self.__on_button_release) def get_pointsize(self): """ Returns the size of a cell, in pixels.""" return self.__pointsize def set_pointsize(self,pointsize): """ Sets the size of a cell, in pixels. Requests a redraw.""" ...
# -*- coding: utf-8 -*- from django import forms from cms_content.settings import EDITOR from cms_content.models import CMSArticle from cms_content import widgets WIDGET = getattr(widgets, EDITOR) class CMSArticleAdminForm(forms.ModelForm): content = forms.CharField(widget=WIDGET) class Meta: m...
s = 'error' required_css_class = 'required' content = forms.CharField(
widget=WIDGET) class Meta: model = CMSArticle fields = ('title', 'slug', 'content', 'category',)
import os import os.path import sys import pygame from buffalo import utils from buffalo.scene import Scene from buffalo.label import Label from buffalo.button import Button from buffalo.input import Input from buffalo.tray import Tray from camera import Camera from mapManager import MapManager from pluginManager im...
= (int(self.fPos[0]), int(self.fPos[1])) class EditMapTestScene(Scene): def on_escape(self): sys.exit() def blit(self): Camera.blitView() def update(self
): super(EditMapTestScene, self).update() keys = pygame.key.get_pressed() self.camera_controller.update(keys) Camera.update() MapManager.soft_load_writer() def __init__(self): Scene.__init__(self) self.BACKGROUND_COLOR = (0, 0, 0, 255) PluginManager.l...
# Copyright 2015 Antiun Ingenieria S.L. - Javier Iniesta # Copyright 2016 Tecnativa S.L. - Vicent Cubells # Copyright 2016 Tecnativa S.L. - Pedro M. Baeza # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). from odoo.exceptions import UserError, ValidationError from odoo.tests import common class T...
cannot create recursive industries." self.assertEqual(e.exception.args[0], error_message) def test_name(s
elf): self.assertEqual(self.industry_child.display_name, "Test / Test child")
#!/usr/bin/env python # # Generate report in Excel format (from xml input) # import sys,os,shelve import re,dfxml,fiwalk from bc_utils import filename_from_path from openpyxl.workbook import Workbook from openpyxl.writer.excel import ExcelWriter from openpyxl.cell import get_column_letter def bc_generate_feature_x...
e filename = "Unknown" feature = "Unknown" position = "Unknown" # Some lines in the annotated_xxx.txt have less than three # columns where filename or
feature may be missing. if len(row) > 3: filename = row[3] else: filename = "Unknown" if len(row) > 1: feature = row[1] else: feature = "Unknown" position = row[0] # If it is a special file, check if the ...
import numpy as np import cvxopt as co def load_mnist_dataset(): import torchvision.datasets as datasets mnist_train = datasets.MNIST(root='../data/mnist', train=True, download=True, transform=None) mnist_test = datasets.MNIST(root='../data/mnist', train=False, download=True, transform=None) test_labe...
_len-lens)-3 > min_block_len: break block_len = min( [block_len, block_len - (block_start+block_len-lens)-3] ) lbls[block_start:block_start+block_len-1] = 1 marker = 1 for d in range(dims): seqs[d,block_start:block_start+block_len-1] = np.random.randn(1,block...
comb_block_len, anom_prob=1.0, num_blocks=1): seqs = co.matrix(0.0, (1, lens)) lbls = co.matrix(0, (1, lens)) marker = 0 # generate first state sequence, gaussian noise 0=mean, 1=variance seqs = np.zeros((1, lens)) lbls = np.zeros((1, lens)) bak = seqs.copy() prob = np.random.uniform()...
3765\">B: Bring me the golden mane of Kerunos</a><br>", "<a action=\"bypass -h Quest 335_TheSongOfTheHunter 3766\">A: Bring back 20 skulls of undead executed criminals</a><br>", "<a action=\"bypass -h Quest 335_TheSongOfTheHunter 3767\">A: Recover the stolen bust of the late King Travis</a><br>", "<a actio...
if Rnd.get(100) < 20 : if pins < 4 and pins : reply_0 = Rnd.get(6) + 12 reply_2 = Rnd.get(6)
reply_3 = Rnd.get(6) + 6 elif pins >= 4 : reply_0 = Rnd.get(6) + 6 if not Rnd.get(20) : reply_1 = Rnd.get(2) + 18 reply_2 = Rnd.get(6) reply_3 = Rnd.get(6) + 6 ...
import uuid from unithelper import DBTestCase from unithelper import mocker from unithelper import requestor from unithelper import hashable_dict from bc import database from bc import metrics from bc_wapi import wapi_metrics class Test(DBTestCase): def test_metric_get(self): """Check getting metric with metri...
'ok')) self.a
ssertEquals(wapi_metrics.metricGet({'id':''}), requestor({'message': 'Metric not found' }, 'error')) with mocker([('bc.metrics.get', mocker.exception), ('bc_wapi.wapi_metrics.LOG.error', mocker.passs)]): self.assertEquals(wapi_metrics.metricGet({'id':''}), requestor({'message': 'Unable to obtain metr...
#! /usr/bin/env python # -*- coding:
utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under
the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is dist...
# -*- coding: utf-8 -*- """ Created on Mon Apr 24 10:55:03 2017 @author: rstreet """ from django.core.management.base import BaseCommand from django.contrib.auth.models import User from events.models import Field, ObsRequest from sys import exit from scripts import query_db class Command(BaseCommand): help = ''...
_for_field(self,*args, **options): field_name = options['field'][0] field_id = Field.objects.get(name=field_name).id print '\nActive obs for '+field_name+':\n' active_obs = query_db.get_acti
ve_obs() for obs in active_obs: print obs.grp_id, obs.timestamp, obs.time_expire def handle(self,*args, **options): self._fetch_obs_for_field(*args,**options)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2017 Julien Girard # # Licensed under the GNU GENERAL PUBLIC LICENSE, Version 3 ; # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://http://www.gnu.org/licenses/gpl-3.0.htm...
is_open = is_open_port(p + 1) else: print(e) except OverflowError as e: # If port is overflow, we get a random open port is_open = get_open_port() return is_open def get_fw_port(port): if ":" in port: fw_port = is_open_port(port.split(":...
se sometimes you don\'t need a full stack') parser.add_argument( '-b', '--boot', help='Boot option. Can be hdd, cdrom or network.', dest='boot' ) parser.add_argument( '-c', '--cores', help='Number of cores for the virtual machine.', dest='cores' ) par...
_("calendar|Islamic"), _("calendar|Swedish") ) _ = locale.translation.lexgettext self.hebrew = ( "", # TRANSLATORS: see # http://gramps-project.org/wiki/index.php?title=Translating_Gramps#Translating_dates # to learn how to s...
ovided in _grampslocale). E.g., for French:: LANG=fr_FR.utf8 LC_ALL=fr_FR.utf8 GRAMPS_RESOURCES=$PWD python -m gramps.gen
.datehandler._datestrings Then merge the output into your language's .po file, and further modify the strings as needed. Then remove the strings from your language's :class:`DateParserXX` and :class:`DateHandlerXX` classes. """ if __name__ == '__main__': import sys from ..utils.grampslocale import GrampsLocal...
""" Tests for the lms_result_processor """ import six import pytest from lms.djangoapps.courseware.tests.factories import UserFactory from lms.lib.courseware_search.lms_result_processor import LmsSearchResultProcessor from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tes...
ItemFactory.create( parent=self.section, category='sequential', display_name='Test Subsection', ) self.vertical = ItemFactory.create( parent=self.subsection, category='vertical', display_name='Test Unit', ) self.html...
vertical, category='html', display_name='Test Html control', ) self.ghost_subsection = ItemFactory.create( parent=self.section, category='sequential', display_name=None, ) self.ghost_vertical = ItemFactory.create( pa...