prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from io import StringIO from pathlib import Path from cwltool.main import main fr
om .util import get_data def test_empty_input(tmp_path: Path) -> None: """Affirm that an empty input works.""" empty_json = "{}" empty_input = StringIO(empty_json) params = [ "--outdir", str(tmp_path), get_data("tests/wf/no-parameters-echo.cwl"), "-", ] try: ...
Exit as err: assert err.code == 0
""" Extend suppliers table with new fields (to be initially populated from declaration data) Revision ID: 940 Revises: 930 Create Date: 2017-08-16 16:39:00.000000 """ # revision identifiers, used by Alembic. revision = '940' down_revision = '930' from alembic import op import sqlalchemy as sa def upgrade(): o...
op.add_column(u'suppliers', sa.Column('other_company_registration_number', sa.String(), nullable=True)) op.add_column(u'suppliers', sa
.Column('registration_date', sa.DateTime(), nullable=True)) op.add_column(u'suppliers', sa.Column('vat_number', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('organisation_size', sa.String(), nullable=True)) op.add_column(u'suppliers', sa.Column('trading_status', sa.String(), nullable=T...
r.add_argument("--fc_step", type=float, default=CONFIG_34, help="the value by which the force constant is increased each time (for force_constant_adjustable mode)") parser.add_argument("--distance_tolerance", type=float, default=CONFIG_35, help="max distance allowed between center of data cloud and potential center (fo...
(layer_types) force.set_data_type_in_input_layer(args.data_type_in_input_layer) force.set_list_of_index_of_atoms_forming_dihedrals_from_index_of_backbone_atoms(index_of_backbone_atoms) force.set_index_of_backbone_atoms(index_of_backbone_atoms) if args.data_type_in_input_l...
force.set_list_of_pair_index_for_distances(CONFIG_80) force.set_num_of_nodes(num_of_nodes) force.set_potential_center(potential_center) force.set_force_constant(float(force_constant)) unit_scaling = 1.0 # TODO: check unit scaling force.set_scaling_fa...
import socket, re, sys from codecs import encode, decode from . import shared def get_whois_raw(domain, server="", previous=None, rfc3490=True, never_cut=False, with_server_list=False, server_list=None): previous = previous or [] server_list = server_list or [] # Sometimes IANA simply won't give us the right root W...
if target_server == "whois.jprs.jp": request_domain = "%s/e" % domain # Suppress Japanese output elif domain.endswith(".de") and ( target_server == "whois.denic.de" or target_server == "de.whois-servers.net
" ): request_domain = "-T dn,ace %s" % domain # regional specific stuff elif target_server == "whois.verisign-grs.com": request_domain = "=%s" % domain # Avoid partial matches else: request_domain = domain response = whois_request(request_domain, target_server) if never_cut: # If the caller has requested to...
of the ## License, or (at your option) any later version. ## ## Invenio 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 ...
t_external_results_overview, perform_external_collection_search from invenio.access_control_admin import acc_get_action_id from invenio.access_control_config import VIEWRESTRCOLL, \ CFG_ACC_GRANT_AUTHOR_RIGHTS_TO_EMAILS_IN_TAGS, \ CFG_ACC_GRANT_VIEWER_RIGHTS_TO_EMAILS_IN_TAGS from invenio.websearchadminlib impo...
nio.dbquery import DatabaseError, deserialize_via_marshal, InvenioDbQueryWildcardLimitError from invenio.access_control_engine import acc_authorize_action from invenio.errorlib import register_exception from invenio.textutils import encode_for_xml, wash_for_utf8, strip_accents from invenio.htmlutils import get_mathjax_...
############################################################################## # 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...
RANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free S...
######################### """ This module contains external, potentially separately licensed, packages that are included in spack. So far: argparse: We include our own version to be Python 2.6 compatible. distro: Provides a more stable linux distribution detection. functools: Used for implement...
ngo.utils.translation import ugettext_lazy from memoized import memoized from corehq import privileges from corehq.apps.accounting.models import BillingAccount from corehq.apps.accounting.utils import domain_has_privilege from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader from corehq.apps.r...
UserFilter', 'corehq.apps.reports.filters.dates.DatespanFilter', 'corehq.apps.reports.filters.users.ChangeActionFilter', 'corehq.apps.reports.filters.users.User
PropertyFilter', 'corehq.apps.reports.filters.users.UserUploadRecordFilter', ] description = ugettext_lazy("History of user updates") ajax_pagination = True default_sort = {'changed_at': 'desc'} @classmethod def get_primary_properties(cls, domain): """ Get slugs and hum...
.key.project, key2.project) self.assertEqual(ds_api.lookup.call_count, 2) read_options = datastore_pb2.ReadOptions() ds_api.lookup.assert_any_call( self.PROJECT, [key2_pb], read_options=read_options ) ds_api.lookup.assert_any_call( self.PROJECT, [key1_pb,...
ef test_get_multi_hit_multiple_keys_different_project(self): from google.cloud.datastore.key import Key PROJECT1 = "PROJECT" PROJECT2 = "PROJECT-ALT" # Make sure our IDs are actually diffe
rent. self.assertNotEqual(PROJECT1, PROJECT2) key1 = Key("KIND", 1234, project=PROJECT1) key2 = Key("KIND", 1234, project=PROJECT2) creds = _make_credentials() client = self._make_one(credentials=creds) with self.assertRaises(ValueError): client.get_multi([...
#!/usr/bin/env python import pickle import argparse f
rom pprint import pprint description = """ print out run status from pickled Location object """ parser = argparse.ArgumentParser(description=description) parser.add_argument('pickle', type=argparse.FileType('r'), help='path to location pickle') args = parser.parse_args() l = pickle.load(args.pi
ckle) pprint(l)
# Copyright (c) 2013 Red Hat Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
KIND, either express or # implied. # See the License for the specific l
anguage governing permissions and # limitations under the License. import uuid import mock import six from sahara.service.validations.edp import job_executor as je from sahara.tests.unit.service.validation import utils as u from sahara.utils import edp def wrap_it(data): je.check_job_executor(data, 0) class ...
# ####################### BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All ...
nts.eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLa
stChar[1] = aBuf[0] self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get...
from django.conf.urls import url from . import views app_name = 'r
evisions' urlpatterns = [ url(r'^revision/$', views.RevisionView.as_view(), name = 'revision'), url(r'^mail/$', views.MailView.as_view(), name = '
mail'), ]
[src['vertno']], nn=src['nn'][src['vertno']], nuse=src['nuse'], coord_frame=src['coord_frame'], vertno=np.arange(src['nuse']), type='discrete') return SourceSpaces([src]) def _fit_eval(rd, B, B2, fwd_svd=None, fwd_data=None, whitener=None, lwork=None): """Calculate ...
] conf = {key: conf[:, ki] for ki, key in enumerate(keys)} khi2 = np.array([r[5] for r in res]) nfree = np.array([r[6] for r in res]) residual_noproj = np.array([r[7] for r in res]).T return pos, amp, ori, gof, conf,
khi2, nfree, residual_noproj '''Simplex code in case we ever want/need it for testing def _make_tetra_simplex(): """Make the initial tetrahedron""" # # For this definition of a regular tetrahedron, see # # http://mathworld.wolfram.com/Tetrahedron.html # x = np.sqrt(3.0) / 3.0 r = np....
# -*- coding: utf-8 -*- # # Copyright (c) 2012-2018, CRS4 # # 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...
OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARIS...
import parse_message def query(host, port): msg = \ 'MSH|^~\&|REC APP|REC FAC|SEND APP|SEND FAC|20110708163513||QBP^Q22^QBP_Q21|111069|D|2.5|||||ITA||EN\r' \ 'QPD|IHE PDQ Query|111069|@PID.5.2^SMITH||||\r' \ 'RCP|I|' # establish the connection sock = socket.socket(socket.AF_INET, ...
""" if not self.op.no_remember: self.cfg.MarkInstanceUp(self.instance.uuid) if self.primary_offline: assert self.op.ignore_offline_nodes self.LogInfo("Primary node offline, marked instance as started") else: StartInstanceDisks(self, self.instance, self.op.force) result = ...
ance_shutdown( self.instance.primary_node, self.instance, self.op.timeout, self.op.reason) msg = resul
t.fail_msg if msg: self.LogWarning("Could not shutdown instance: %s", msg) ShutdownInstanceDisks(self, self.instance) class LUInstanceReinstall(LogicalUnit): """Reinstall an instance. """ HPATH = "instance-reinstall" HTYPE = constants.HTYPE_INSTANCE REQ_BGL = False def ExpandNames(s...
__all__
= ['ttypes'
, 'constants', 'PlayerStrategy']
############################################################################## # # Immobilier it's an application # designed to manage the core business of property management, buildings, # rental agreement and so on. # # Copyright (C) 2016-2018 Verpoorten Leïla # # This program is free software: you can...
r self.cleaned_data.get("loyer_percu") == 0) and \ (self.cleaned_data.get("charges_percu") is None or self.cleaned_data.get("charges_percu") == 0): msg = u"L'état ne peut pas être à 'PAYE' si aucun montant n'est introduit pour les loyer/charge percue(s)" self._errors["etat_suivi"...
a.get("date_paiement_reel") if date_paiement_reel and date_paiement and date_paiement_reel < date_paiement: msg = u"La date réelle de paiement doit être supérieure ou égale à la date supposée du paiement" self._errors["date_paiement_reel"] = self.error_class([msg])
he given strftime format. html_last_updated_fmt = '%%b %%d, %%Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that shou...
mmonly, this is either ".txt" or ".rst". Only files with this suffix are considered documents.''' do_prompt(d, 'suffix',
'Source file suffix', '.rst', suffix) print ''' One document is special in that it is considere
.2.2 255.255.255.0 secondary") configuring_interface_vlan(t, "4000", do="ip address 3.2.2.2 255.255.255.0 secondary") configuring_interface_vlan(t, "4000", do="ip address 3.2.2.2 255.255.255.128") assert_interface_configuration(t, "Vlan4000", [ "interface Vlan4000", " ip...
4.2.2.2 255.255.255.0 secondary", " ip address 3.2.2.2 255.255.255.128", "end"]) configuring(t, do="no interface vlan 40
00") @with_protocol def test_overlapping_ips(self, t): enable(t) create_vlan(t, "1000") create_interface_vlan(t, "1000") create_vlan(t, "2000") create_interface_vlan(t, "2000") configuring_interface_vlan(t, "1000", do="ip address 2.2.2.2 255.255.255.0") ...
# -*- coding: utf-8 -*- import sys import pytest
py3 = sys.version_info[0] >= 3 class DummyCollector(pytest.collect.File): def collect(self):
return [] def pytest_pycollect_makemodule(path, parent): bn = path.basename if "py3" in bn and not py3 or ("py2" in bn and py3): return DummyCollector(path, parent=parent)
he specific language governing permissions and # limitations under the License. # ============================================================================== """Configuration and utilities for receiving inputs at serving time.""" from __future__ import absolute_import from __future__ import division from __future_...
ict during iteration is OK in this case. receiver_tensors_alternatives[alternative_name]
= ( receiver_tensors_alt) for name, tensor in receiver_tensors_alt.items(): if not isinstance(name, six.string_types): raise ValueError( 'receiver_tensors keys must be strings: {}.'.format(name)) if not (isinstance(tensor, ops.Tensor) ...
__author__ = 'thor' import ut as ms import pandas as pd import ut.pcoll.order_conserving from functools import reduce class SquareMatrix(object): def __init__(self, df, index_vars=None, sort=False): if isinstance(df, SquareMatrix): self = df.copy() elif isinstance(df, pd.DataFrame): ...
reduce_fun[k] = lambda x: reduce(v, x) elif not isinstance(reduce_fun, dict) and broadcast_functions: reduce_fun = dict(list(zip(self.value_vars, [reduce_fun] * len(self.value_vars)))) df = df.groupby(self.index_vars).agg(reduce_fun).reset_index(drop=False) return SquareMatrix(...
def reverse_indices(self): return [self.index_vars[1], self.index_vars[0]] def sort(self, **kwargs): kwargs = dict({'columns': self.index_vars}, **kwargs) sm = self.copy() sm.df = sm.df.sort(**kwargs) return sm def __str__(self): return self.df.__str__() ...
from datetime import date, timedelta INITIAL_OFFSET = timedelta(days=5) class IntervalException(Exception): """ Exception to be raises when interval is behaving weirdly - as not an interval """ def get_dates_for_timedelta(interval_delta, start=None, stop=None, skip_weeke...
ta: interval_delta instance :type interval_delta: datetime.timedelta :param start: starting point of the interval :type start: date :param st
op: when to stop :param skip_weekend: don't place dates at weekends :return: [datetime objects] """ if start is None: start = date.today() if stop is None: stop = start + timedelta(days=365) dates = [start] while dates[-1] + interval_delta <= stop: increased_date =...
# -*- coding: utf-8 -*- from __future__ import absolute_import import base64 import hashlib import warnings from io import BytesIO from django.core.files.base import ContentFile from django.utils import six from easy_thumbnails import fields as easy_thumbnails_fields from easy_thumbnails import files as easy_thumbnai...
StorageFileField(easy_thumbnails_fields.ThumbnailerField): attr_class = MultiStorageFieldFile def __init__(self, verbose_name=None, name=None,
storages=None, thumbnail_storages=None, thumbnail_options=None, **kwargs): if 'upload_to' in kwargs: # pragma: no cover upload_to = kwargs.pop("upload_to") if upload_to != generate_filename_multistorage: warnings.warn("MultiStorageFileField can handle only File objects...
import
string from random import choice from django.contrib.auth.models import User def get_random_id(): valid_id = False test_name = 'EMPTY' while valid_id is False: s1 = ''.join([choice(string.ascii_uppercase) for i in range(2)]) s2 = ''.join([choice(string.digits) for i in range(8)]) t...
'user_id': fields.many2one('res.users', 'Responsible', track_visibility='always'), 'day_to_action_next': fields.integer('Days to next action'), 'action_next': fields.char('Next Action'), 'days_to_date_deadline': fields.char('Date to deadline'), } _defaults = { 'day_next_...
aim type."), } """def _find_object_id(self, cr, uid, context=None): context = context o
r {} object_id = context.get('object_id', False) ids = self.pool.get('ir.model').search(cr, uid, ['|', ('id', '=', object_id), ('model', '=', context.get('object_name', False))]) return ids and ids[0] or False _defaults = { 'object_id': _find_object_id }""" class claim_from_invo...
############################################################################## # Copyright (c) 2017, Los Alamos National Security, LLC # Produced at the Los Alamos National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, ...
run_env.set('F77', join_path(self.spec.prefix.bin, 'flang'))
run_env.set('F90', join_path(self.spec.prefix.bin, 'flang'))
ons:: [wsgi_fs] call = brim.wsgi_fs.WSGIFS # path = <path> # The request path to match and serve; any paths that do not begin # with this value will be passed on to the next WSGI app in the # chain. Default: / # serve_path = <path> # The local file path containing files to serve...
ime(itempath) body += ( ' <tr class="item %s">\n' ' <td class="colname"><a href="%s">%s</a></td>\n' ' <td class="colsize">' '<script type="text/javascript">' 'document.write(new Number(%s).toLocal...
' <td class="coldate">' '<script type="text/javascript">' 'document.write(new Date(%s * 1000).toLocaleString());' '</script></td>\n' ' </tr>\n' % ('ext' + ext, http.quote(item), escape(item), size, mtime)) ...
instance, requested_networks=None): """Deallocates all network structures related to instance.""" # NOTE(vish): We can't do the floating ip deallocation here because # this is called from compute.manager which shouldn't # have db ac...
elf, context, instance): """Returns all network info related to an instance.""" flavor = flavors.extract_flavor(instance) args = {'instance_id': instance['uuid'], 'rxtx_factor': flavor['rxt
x_factor'], 'host': instance['host'], 'project_id': instance['project_id']} nw_info = self.network_rpcapi.get_instance_nw_info(context, **args) return network_model.NetworkInfo.hydrate(nw_info) @wrap_check_policy def validate_networks(self, context, requested_ne...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the L...
n EventObject a
nd send it through analysis.""" # This event requires an URL attribute. url_attribute = getattr(event_object, 'url', None) if not url_attribute: return # Check if we are dealing with a web history event. source, _ = eventdata.EventFormatterManager.GetSourceStrings(event_object) if sourc...
sort_values>`_. :param int|None limit: Either a positive integer for the number of rows to take or ``None`` to take all. :param bool ascending: Sort ascending vs descending. :param dict sql_kwargs: A dictionary of keyword arguments passed into `pandas.read_sql <http://pandas.pydata.org/pandas-d...
seaborn.distplot.html>`_ on ``distplot`` for more information. Note that this requires Seaborn in order to function.
:param int|None bins: The number of bins to use. If unspecified, the `Freedman-Diaconis rule <https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule>`_ will be used to determine the number of bins. :param dict kwargs: A dictionary of options to pass on to `seaborn.distplot <http://stanford.edu/~...
import re from calendar import monthrange import datetime class Card(object): """ A credit card that may be valid or invalid. """ # A regexp for matching non-digit values non_digit_regexp = re.compile(r'\D') # A mapping from common credit card brands to their number regexps BRAND_VISA = '...
given month and year, as well as the raw month and year values. """ # Attach month and year self.month = month self.year = year # Get the month's day count weekday, day_count = monthrange(year, month) # Attach the last possible datetime for the provided...
t, 23, 59, 59, 999999 ) def __repr__(self): """ Returns a typical repr with a simple representation of the exp date. """ return u'<ExpDate expired_after={d}>'.format( d=self.expired_after.strftime('%m/%Y') )...
# 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...
le law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ========
====================================================================== """Tests for parser module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import textwrap from tensorflow.contrib.autograph.pyct import parser from tensorflow.python.platform impor...
#!usr/bin/python #Gmail Brute Forcer #To use this script you need ClientCookie and Client Form. #http://wwwsearch.sourceforge.net/ClientCookie/src/ClientCookie-1.0.3.tar.gz #http://wwwsearch.sourceforge.net/ClientForm/src/ClientForm-0.1.17.tar.gz #To install the package, run the following command: #python setup.py buil...
t "Usage: ./gmailbrute.py <user> <wordlist>" sys.exit(1) try: words = open(sys.argv[2], "r").readlines() except(IOError): print "Error: Check your wordlist path\n" sys.exit(1) print "\n\t d3hydr8[at]gmail[dot]com GmailBruteForcer v1.0" print "\t--------------------------------------------------\n" print ...
+] User:",sys.argv[1] print "[+] Words Loaded:",len(words),"\n" wordlist = copy(words) def reloader(): for word in wordlist: words.append(word) def getword(): lock = threading.Lock() lock.acquire() if len(words) != 0: value = random.sample(words, 1) words.remove(value[0]) else: print "Reloading Word...
#Aditya Joshi #Enumerating Oriented Gene Ordering from itertools import permutations,product from math import fabs n = int(raw_input()) def make_set(n): set = [] for x in range(1,n+1): set += [x] return set def plusAndMinusPermut
ations(items): for p in permutations(items,len(items)): for signs in product([-1,1], repeat=len(items))
: yield [a*sign for a,sign in zip(p,signs)] def array_to_string(list): string = "" string += str(list[0]) + " " + str(list[1]) return string count = 0 for x in plusAndMinusPermutations(make_set(n)): print array_to_string(x) count += 1 print count
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # #
Michael A.G. Aivazis # California Institute of
Technology # (C) 1998-2005 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # from SI import meter, second gal = 0.01*meter/second**2 # version __id__ = "$Id: force.py,v 1.1.1.1 2005/03/08 16:13:41 aivazis Exp $" #...
from .base import * import dj_database_url if os.environ.get('DEBUG') == 'False': DEBUG = False else: DEBUG = True try: from .local import * except ImportError: pass ALLOWED_HOSTS = ['*'] DATABASES = {'default': dj_database_url.config()} SOCIAL_AUTH_YAMMER_KEY = os.environ.get('SOCIAL_AUTH_YAMMER...
TATICFILES_STORAGE = 'core.storage.S3PipelineManifestStorage' STATIC_URL = 'http://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME AWS_QUERYSTRING_AUTH = False AWS_S3_FILE_OVERWRITE = True PIPELINE_JS_COMPRESSOR = 'pipeline.compressors.yuglify.YuglifyCompressor' PIPELINE_CSS_COMPRESSOR = 'pipeline.compressors.yuglify...
lify'
import datetime import logging from functools import reduce from flask_babelpkg import lazy_gettext from .filters import Filters log = logging.getLogger(__name__) class BaseInterface(object): """ Base class for all data model interfaces. Sub class it to implement your own interface for some data ...
The list of columns to include """ for item in lst: retdict = {} for col in list_columns: retdict[col] = self._get_attr_value(item, col) yield retdict def get_values_json(self, lst, list_columns): """ Converts list of
objects from query to JSON """ result = [] for item in self.get_values(lst, list_columns): for key, value in list(item.items()): if isinstance(value, datetime.datetime) or isinstance(value, datetime.date): value = value.isoformat() ...
""" @file sumoConfigGen.py @author Craig Rafter @date 29/01/2016 Code to generate a config file for a SUMO model. """ def sumoConfigGen(modelname='simpleT', configFile='./models/simpleT.sumocfg', exportPath='../', AVratio=0, stepSize=0.01, run=0, port=8813): configXML ...
"/> </processing> <report> <no-step-log value="true"/> <error-log value="logfile.txt"/> </report> <traci_server> <remote-port value="{SUMOport}"/> </traci_server>""".format(model=modelname, expPath=exportPath, AVR=int(AVratio*100), stepSz=stepSiz...
Nrun=run, SUMOport=port) print >> configXML, "</configuration>" configXML.close()
from __future__ import absolute_import from base64 import b64encode from ..packages.six import b ACCEPT_ENCODING = 'gzip,deflate' def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None): """ Shortcuts for generatin...
b64encode(b(basic_auth)).decode('utf-8') if proxy_basic_auth:
headers['proxy-authorization'] = 'Basic ' + \ b64encode(b(proxy_basic_auth)).decode('utf-8') if disable_cache: headers['cache-control'] = 'no-cache' return headers
''' Problem 2 @author: Kevin Ji ''' def sum_even_fibonacci( max_value ): # Initial two elements prev_term = 1 cur_term = 2 temp_sum = 2
while cur_term < max_value: next_term = prev_term + cur_term prev_term = cur_term cur_term = next_term if cur_term % 2 == 0: temp_sum += cur_term return temp_sum print( sum_even_
fibonacci( 4000000 ) )
mport pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.setup import async_setup_component from tests.async_mock import AsyncMock, patch from tests.common import MockConfigEntry @pytest.fixture def mock_bridge_setup(): """Mock bridge setup.""" with p...
ait async_setup_component(hass, hue.DOMAIN, {}) is True assert len(mock_bridge_setup.mock_calls) == 1 mock_bridge_setup.async_reset = AsyncMock(return_value=True) assert await hue.async_unload_entry(hass, entry) assert len(mock_bridge_setup.async_reset.mock_calls) == 1 assert hass.data[hue.DOMAIN] ...
et yet.""" entry = MockConfigEntry(domain=hue.DOMAIN, data={"host": "0.0.0.0"}) entry.add_to_hass(hass) assert await async_setup_component(hass, hue.DOMAIN, {}) is True assert entry.unique_id == "mock-id" async def test_fixing_unique_id_no_other(hass, mock_bridge_setup): """Test we set unique ID i...
from django.views.generic.detail import DetailView from django.shortcuts import render, redirect from django.http import Htt
p404 from aspc.folio.models import Page class AttachedPageMixin(object): def get_page(self): try: return Page.objects.get(slug=self.page_slug) except Page.DoesNotExist: return None def get_context_data(self, **kwargs): context = super(AttachedPageMixin, self...
g_path): '''slug_path: ^(?P<slug_path>(?:[\w\-\d]+/)+)$ ''' slug_parts = slug_path.rstrip('/').split('/') pages = Page.objects.exclude(managed=True) for part in slug_parts: try: new_page = pages.get(slug=part) except Page.DoesNotExist: raise Http404 else: ...
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
CONF.neutron_default_tenant_id ctx = nova_context.RequestContext(user_id=None, project_id=project_id) networks = {} for n in self.network_api.get_all(ctx): networks[n['id']] = n['label'] return [{'id': k, 'label': v} for k, v
in networks.iteritems()] @extensions.expected_errors(()) def index(self, req): context = req.environ['nova.context'] authorize(context) networks = list(self.network_api.get_all(context)) if not self._default_networks: self._refresh_default_networks() networks...
# Copyright 2020 The TensorFlow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
port-not-at-top from tensorflow_graphics.util.doc i
mport _import_tfg_docs if _import_tfg_docs(): from tensorflow_graphics.geometry import convolution from tensorflow_graphics.geometry import deformation_energy from tensorflow_graphics.geometry import representation from tensorflow_graphics.geometry import transformation from tensorflow_graphics.util import ex...
#!/bin/python2 # Script that replies to username mentions. import time import os import cPickle im
port sys import traceback import numpy import sys from PIL import Image from urlparse import urlparse import gabenizer IMG = "http://i.4cdn.org/r9k/1463377581531.jpg" def main(): image = gabenizer.process_image(sys.argv[1], './plugins/gabenize
r/gabenface.png') image.save("./plugins/gabenizer/whatfuck.png") if __name__ == "__main__": main()
nputs] shapes = [sp_input.dense_shape for sp_input in sp_inputs] if expand_nonconcat_dim: max_shape = math_ops.reduce_max( array_ops.concat( [array_ops.reshape(shape, [
1, -1]) for shape in shapes], 0), 0) shapes = [ array_ops.concat([ max_sha
pe[:axis], shape[-1:] if axis == -1 else shape[axis:axis + 1], [] if axis == -1 else max_shape[axis + 1:] ], 0) for shape in shapes ] output_ind, output_val, output_shape = ( gen_sparse_ops.sparse_concat(inds, vals, shapes, axis, name=name)) return sparse_tensor.SparseTen...
# Change environ to automatically call putenv() if it exists try: # This will fail if there's no putenv putenv except NameError: pass else: import UserDict # Fake unsetenv() for Windows # not sure about os2 here but # I'm guessing they are the same. if name in ('os2', 'nt'): ...
while
1: wpid, sts = waitpid(pid, 0) if WIFSTOPPED(sts): continue elif WIFSIGNALED(sts): return -WTERMSIG(sts) elif WIFEXITED(sts): return WEXITSTATUS(sts) else: rais...
# Copyright 2014 Red Hat, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
mport exception from nova import objects from nova.objects import
base from nova.objects import fields class Agent(base.NovaPersistentObject, base.NovaObject): VERSION = '1.0' fields = { 'id': fields.IntegerField(read_only=True), 'hypervisor': fields.StringField(), 'os': fields.StringField(), 'architecture': fields.StringField(), 'v...
"""Describe the language syntax.""" import re class Symbol: """Describes the language symbols.""" # General pattern of formulas pattern = '([a-z0-9&\-\|><\(\)]*)' accepted_chars = '([a-z0-9&\-\|><\(\)]*)' def __init__(self, value): """Init a propositional symbol.""" self.value =...
"""Base class for language operators.""" class Associativity: """Possible operators associativity.""" LEFT
= 1 RIGHT = 0 def subformulas(self): """Get the formula subformulas.""" raise NotImplementedError def evaluate(self, symbol_values): """Evaluate an operator with given values.""" raise NotImplementedError def __str__(self): """Return the string representati...
# -*- coding: utf-8 -*- ''' Created on Apr 27, 2016 @author: Aaron Ponti ''' from ch.systemsx.cisd.openbis.dss.etl.dto.api.impl import MaximumIntensityProjectionGenerationAlgorithm class GenericTIFFSeriesMaximumIntensityProjectionGenerationAlgorithm(MaximumIntensityProjectionGenerationAlgorithm): ''' Cust
om MaximumIntensityProjectionGenerati
onAlgorithm for Generic TIFF Series that makes sure that the first timepoint in a series is registered for creation of the representative thumbnail. ''' def __init__(self, datasetTypeCode, width, height, filename): """ Constructor """ # Call the parent base constructo...
''' Created on 17/2/2015
@author: PC0
6 Primer cambio en el proyecto ''' from include import app if __name__ == '__main__': app.run("127.0.0.1", 9000, debug=True)
e on repeated requests. _accepted = {} # Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9. accept_language_re = re.compile(r''' ([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\*) # "en", "en-au", "x-y-z", "*" (?:;q=(0(?:\.\d{,3})?|1(?:.0{,3})?))? # Optional "q=1.00", "q=0.8" ...
self.django_output_charset = 'utf-8' self.__language = '??' def merge(self, other): self._catalog.update(other._catalog) def set_language(self, language): self.__language = language def language(self): return self.__language def __repr__(self): r...
n23(DjangoTranslation): """ Compatibility class that is only used with Python 2.3. Python 2.3 doesn't support set_output_charset on translation objects and needs this wrapper class to make sure input charsets from translation files are correctly translated to output charsets. With a full...
def get_file_e
xtension(filename): return filename.split(".
")[-1]
# Copyright 2012 Managed I.T. # # Author: Kiall Mac Innes <kiall@managedit.ie> # # 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 r...
a['type'] == 'array': subinstance = instance.get(name, None) filtered[name] = self._filter_array(subinstance, subschema) elif 'type' in subschema and subschema['type'] == 'object': subinstance = instance.get(name, None) properties = subschema['...
perties) else: filtered[name] = instance.get(name, None) return filtered def _filter_array(self, instance, schema): if 'items' in schema and isinstance(schema['items'], list): # NOTE(kiall): We currently don't make use of this.. raise NotImplemen...
all available for all models. The default is ptype='deviance', which uses squared-error for Gaussian models (a.k.a ptype='mse' there), deviance for logistic and Poisson regression, and partial-likelihood for the Cox model (Note that CV for cox model is not implemented yet). ...
lambda_1se largest value of lambda such that error is within 1 standard error of the minimum. class Type of regression - internal usage. fit_preval if keep=true, this is the array of prevalidated fits. Some entries can be NA, if that and subsequent values of lambda ar...
then the remainder to compute the fit with each of the folds omitted. The error is accumulated, and the average error and standard deviation over the folds is computed. Note that cvglmnet does NOT search for values for alpha. A specific value should be supplied, else alpha=1 is assumed by default. ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] ta...
PriorityContainer, Logger from sara_flexbe_states.sara_set_head_angle import SaraSetHeadAngle from sara_flexbe_states.run_trajectory import RunTrajectory from sara_flexbe_states.set_gripper_state import SetGripperState # Additional imports can be added inside the following tags # [MANUAL_IMPORT] # [/MANUAL_IMPORT] ...
class Init_SequenceSM(Behavior): ''' Initialisation Sequence ''' def __init__(self): super(Init_SequenceSM, self).__init__() self.name = 'Init_Sequence' # parameters of this behavior # references to used behaviors # Additional initialization code can be added inside the following tags # [MANUAL_INI...
import numpy as np import matplotlib.pyplot as plt from math import exp size = 9 dt = 50.0 # ms dt_2 = 550.0 # Vectors to fit x_fit = np.zeros(size) V_max_fit = np.zeros(size) V0_fit = np.zeros(size) # Paramters of the model tau_rec = 1000.0 # ms tau_mem = 32.0 # ms tau_in = 1.8 # ms A = 144.0 u = 0.26 # First ...
alpha_fit[k] * tau_in - V0_fit[k] * tau_diff) #print 'aux', aux2 aux = alpha_fit[i] * tau_mem / aux2 V_max_fit[k] = alpha_fit[k] * (aux ** (tau_mem / tau_diff)) # The final values ex1 = np.exp(-dt_2 / tau_in) ex2 = np.exp(-dt_2 / tau_mem) print 'ex1 ex2', ex1, ex2 problem = ex1 - ex2 problem = ex1 - ex2 t...
* tau_in - V0_fit[-1] * tau_diff) V_max_fit[-1] = alpha_fit[-1] * (aux ** (tau_mem / tau_diff)) amp_fit = V_max_fit - V0_fit # Finally we plot plt.subplot(1, 2, 1) plt.plot(x_fit, '*-', label='x_fit') plt.legend() plt.subplot(1, 2, 2) plt.plot(V_max_fit, '*-', label='Vmax_fit') plt.hold(True) plt.plot(V0_fit...
try: from tornado.websocket import WebSocketHandler import tornado.ioloop tornadoAvailable = True except ImportError: class WebSocketHandler(object): pass tornadoAvailable = False from json import loads as fromJS, dumps as toJS from threading import Thread from Log import console import Settings from utils impor...
hannel].remove(self) if len(channels[channel]) == 0: del channels[channel] handlers.remove(self) console('websocket', "Closed") verbs = { 'status': "Status set", 'name': "Renamed", 'goal': "Goal set", 'assigned': "Reassigned", 'hours': "Hours updated", } from Event import EventHandler, addEventHandler...
skUpdate(self, handler, task, field, value): if field == 'assigned': # Convert set of Users to list of usernames value = [user.username for user in value] elif field == 'goal': # Convert Goal to goal ID value = value.id if value else 0 description = ("%s by %s" % (verbs[field], task.creator)) if field in ve...
0 Else dont", "If a = 10 Then doit 10, 20, 30 Else dont 5, 10, 15", "If a = 10 Then Exit Function", "If a = 10 Then Exit Function Else DoIt", "If a = 10 Then Exit Function Else DoIt=1", "If a = 10 Then Exit Function Else DoIt 1, 2, 3", "If a = 10 Then DoIt Else Exit Funct...
Thing.Object, c) As Object.Obj a=10 n=20 Exit Function c="hello" End Function """) # simple sub with scope tests.append(""" Private Function MySub(x, y As Variant, z, a As Boolena, b, c As Long) As Variant a=10 n=20 c="hello" End Function Public Function MySub(x, y, z, a, b, c) As String a=10 n=20 c="hello
" End Function """) # function returning an array tests.append(""" Function fn(x As Single, y, z As Boolean, a, b As Variant, c) As Single() a=10 n=20 c="hello" End Function """) # << Parsing tests >> (45 of 61) # simple sub tests.append(""" Function fn(x As Single, y, z As Boolean, a, Optional b As Variant, c) As Sin...
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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. # # This program is distrib...
, loc, scale, r
ot, angle, rotA) matrixes = Matrix_listing(matrixes_) Ma.sv_set(matrixes) def register(): bpy.utils.register_class(MatrixGenNode) def unregister(): bpy.utils.unregister_class(MatrixGenNode) if __name__ == '__main__': register()
import html import inflect import titlecase from flask import url_for from shared.pd_exception import DoesNotExistException from .. import APP, importing from ..data import match from ..view impo
rt View @APP.route('/match/<int:match_id>/') def show_match(match_id: int) -> str: view = Match(match.get_match(match_id)) return view.page() # pylint
: disable=no-self-use,too-many-instance-attributes class Match(View): def __init__(self, viewed_match: match.Match) -> None: super().__init__() if not viewed_match: raise DoesNotExistException() self.match = viewed_match self.id = viewed_match.id self.comment = vi...
# -*- coding: utf-8 -* PROVINCE_CHOICES = ( ('AG', 'Agrigento'), ('AL', 'Alessandria'), ('AN', 'Ancona'), ('AO', 'Aosta'), ('AR', 'Arezzo'), ('AP', 'Ascoli Piceno'), ('AT', 'Asti'), ('AV', 'Avellino'), ('BA', 'Bari'), # ('BT', 'Barletta-Andria-Trani'), # active starting from 2009...
# ('MB', 'Monza e Brianza'), # active starting
from 2009 ('NA', 'Napoli'), ('NO', 'Novara'), ('NU', 'Nuoro'), ('OG', 'Ogliastra'), ('OT', 'Olbia-Tempio'), ('OR', 'Oristano'), ('PD', 'Padova'), ('PA', 'Palermo'), ('PR', 'Parma'), ('PV', 'Pavia'), ('PG', 'Perugia'), ('PU', 'Pesaro e Urbino'), ('PE', 'Pescara'), ...
) ] def __init__(self, name, json_snippet, stack): super(Instance, self).__init__(name, json_snippet, stack) self._href = None self._dbinstance = None @property def dbinstance(self): """Get the trove dbinstance.""" if not self._dbinstance and self.resour...
tus, status_reason=self.TROVE_STATUS_REASON.get(instance.status, _("Unknown"))) if updates: if instance.status != self.ACTIVE: dmsg = ("Instance is in status %(now)s. Waiting on status"
" %(stat)s") LOG.debug(dmsg % {"now": instance.status, "stat": self.ACTIVE}) return False try: return ( self._update_name(instance, updates.get(self.NAME)) and self._update_flavo...
#!/usr/bin/python import re import csv import os import json def read_csv(fn): results = {} with open(fn, 'rb') as csvfile: rows = csv.reader(csvfile, delimiter=',') for row in rows: m = re.search('Total Transactions', row[1]) if len(row) == 7 and m: tem...
results[row[0]] = {row[1]: float(
row[2]) + temp.get(row[1]), row[3]: float(row[4]) + temp.get(row[3])} results[row[0]]['Throughput'] = results[row[0]][row[1]] / results[row[0]][row[3]] return results def traverse_all_csvs(path_to_dir): files = [] for (dirpath, dirnames, filenames) in...
# Copyright (C) 2017,2019, Yu Sheng Lin, johnjohnlys@media.ee.ntu.edu.tw # This file is part of Nicotb. # Nicotb 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...
t it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Nicotb. If not, see <http://www.gnu.org/...
= ""): if event_released: n = event_released.pop() else: n = len(waiting_coro) waiting_coro.append(list()) if COSIM and hier: BindEvent(n, (TOP_PREFIX+hier).encode()) return n def CreateEvents(descs: list): return [CreateEvent(event) for event in descs] def GetEvent(ev): return ev if isinstance(ev, int)...
# # This file is part of CasADi. # # CasADi -- A symbolic framework for dynamic optimization. # Copyright (C) 2010 by Joel Andersson, Moritz Diehl, K.U.Leuven. All rights reserved. # # CasADi is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Pub...
n("exact_jacobian",True) #integrator.setOption("linear_multistep_method","bdf") # adams or bdf #i
ntegrator.setOption("nonlinear_solver_iteration","newton") # newton or functional integrator.setOption("number_of_fwd_dir",4) integrator.setOption("number_of_adj_dir",0) integrator.setOption("fsens_err_con",True) integrator.setOption("quad_err_con",True) integrator.setOption("abstol",1e-8) integrator.setOption("reltol"...
"""empty message Revision ID: 4fe34588268f Revises: 26dba2ff3e74 Create Date: 2014-12-09 01:41:2
4.333058 """ # revision identifiers, used by Alembic. revision = '4fe34588268f' down_revision = '26dba2ff3e74' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### pass ### end Alembic commands ### def downgrade
(): ### commands auto generated by Alembic - please adjust! ### pass ### end Alembic commands ###
import os
from g import config_dir, templates_dir, DEFAULT_GID, DEFAULT_UID from utils.misc import prepare_dir from utils.jinja import render_jinja registryctl_config_dir = os.path.join(config_dir, "registryctl") registryctl_config_template_path = os.path.join(templates_dir, "registryctl", "config.yml.jinja") registryctl_conf =...
dir, "registryctl", "config.yml") registryctl_env_template_path = os.path.join(templates_dir, "registryctl", "env.jinja") registryctl_conf_env = os.path.join(config_dir, "registryctl", "env") levels_map = { 'debug': 'debug', 'info': 'info', 'warning': 'warn', 'error': 'error', 'fatal': 'fatal' } d...
import time import test_rnd as rnd import random import pysos # initialize the data N = 1234 it
ems = [(rnd.utf8(20), rnd.utf8(200))
for i in range(N)] start = time.time() db = pysos.Dict('temp/sos_dict') #import shelve #db = shelve.open('temp.shelve') print("%.2fs: %d items loaded" % (time.time() - start, len(db))) # add all items for key,val in items: db[key] = val print("%.2fs: %d items added" % (time.time() - start, len(items))) # re...
import sys import argparse import pickle def read_index(pickleFile): pickleFile = open(pickleFile, 'rb') index = pickle.load(pickleFile) return index def main(args): wordIndex = read_index('indice.pickle') docIndex = read_index('indice_doc.pickle') wordList =
args.palabras for word in wordList: print wordIndex[word] # print docIndex if __name__ == '__main__': parser = argparse.ArgumentParser(description='Busca palabras') parser.add_argument('palabras', metavar='N', type=str, nargs='+', help='Palabras a buscar en el indice') args = parser.
parse_args() main(args)
""" A component which allows you to send data to Dweet.io. For more details about this component, please refer to the documentation at https://home-assistant.io/components/dweet/ """ import logging from datetime import timedelta import voluptuous as vol from homeassistant.const import EVENT_STATE_CHANGED, STATE_UNKNO...
e = event.data.get('new_state') if state is None or state.state in (STATE_UNKNOWN, '') \ or state.entity_id not in whitelist: return try: _state = state_helper.state_as_number(state) except ValueErro
r: _state = state.state json_body[state.attributes.get('friendly_name')] = _state send_data(name, json_body) hass.bus.listen(EVENT_STATE_CHANGED, dweet_event_listener) return True @Throttle(MIN_TIME_BETWEEN_UPDATES) def send_data(name, msg): """Send the collected data to Dw...
# Copyright (c) 2013 Che-Liang Chiou import os import re from SCons.Script import Dir class Label(object): VALID_NAME = re.compile(r'^[A-Za-z0-9_.\-/]+$') @classmethod def make_label(cls, label_str): package_str = None target_str = None if not isinstance(label_str, str): ...
assert isinstance(target_name, str) Label.check_name(target_na
me) self.target_name = target_name def __str__(self): return self.target_name def __repr__(self): return 'TargetName("%s")' % self.target_name def __eq__(self, other): return (self.__class__ is other.__class__ and self.target_name == other.target_name) ...
ssert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false assert re(roo...
t_eq(reduced(f, G, polys=True), (Q, r)) assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r)) H = groebner(G, polys=True) assert _strict_eq(H.reduce(f), (Q, r)) f = 2*x**3 + y**3 + 3*y G = groebner([x**2 + y**2 - 1,
x*y - 2]) Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + 3*y/4] r = 0 assert reduced(f, G) == (Q, r) assert G.reduce(f) == (Q, r) assert reduced(f, G, auto=False)[1] != 0 assert G.reduce(f, auto=False)[1] != 0 assert G.contains(f) is True assert G.contai...
mbers reported by each reporting interval, and the summary latency numbers printed at the end of the run in "General Statistics" -> "Response Time". Example Sysbench output: sysbench 0.5: multi-threaded system evaluation benchmark <... lots of output we don't care here ...> Threads started! [ 2s] th...
[token] = float(re.findall(search_string, line)[0]) tps_line = ', '.join(map(str, all_tps)) # Print all tps data points in the log for reference. And report # percentiles of these tps data in the final result set. logging.info('All TPS numbers: \n %s', tps_line) tps_percentile = sample.PercentileCalculator(...
%s' % str(percentile) logging.info('%s tps %f', percentile_string, tps_percentile[percentile_string]) metric_name = ('%s %s') % (SYSBENCH_RESULT_NAME_TPS, percentile_string) results.append(sample.Sample( metric_name, tps_percentile[percentile_string], NA_UNIT, ...
port Toolkit, Robot, Rectangle from javax.imageio import ImageIO from java.io import File elif sys.platform == 'cli': import clr clr.AddReference('System.Windows.Forms') clr.AddReference('System.Drawing') from System.Drawing import Bitmap, Graphics, Imaging from System.Windows.Forms import S...
R} | # System temp | """ self._given_screenshot_dir = self._norm_path(screenshot_directory) self._screenshot_taker = ScreenshotTaker() def _norm_path(self, path): if not path: return path return os.path.normpath(path.replace('/', os.sep)) @property ...
lf): return self._given_screenshot_dir or self._log_dir @property def _log_dir(self): variables = BuiltIn().get_variables() outdir = variables['${OUTPUTDIR}'] log = variables['${LOGFILE}'] log = os.path.dirname(log) if log != 'NONE' else '.' return self._norm_pat...
#!/usr/bin/python from mininet.net import Mininet from mininet.node import Controller, RemoteController from mininet.cli import CLI from mininet.log import setLogLevel, info import time import os import subprocess import csv import StringIO import iptc HOSTS = 3 p1_log = open('logs-example/log.p1.txt', 'w') p2_log...
name__ == '__main__': setLogLevel( 'info' ) p1 = subprocess.Popen(['pox/pox.py', "master66"],stdin=subprocess.PIPE, stdout=p1_log,stderr=p1_log,preexec_fn=os.
setpgrp) print 'c1 runs, master' print 'wait for 3 seconds...' time.sleep(3) myNet() print 'close pox logs..' p1_log.close() p2_log.close() print 'bye' # t.process.terminate()
) self.leds = Leds(self) self.audio = Audio(self) # head self.head = Head(self) # arms self.hands = Hands(self) self.wrists = Wrists(self, self.hands) self.elbows = Elbows(self, self.wrists, self.hands) self.arms = Arms(self, self.elbo...
=.5): self.log("goToPosture=%s|speed=%s" % ("Sit", speed)) self.env.robotPosture.post.goToPosture("Sit", speed) self.env.motion.waitUntilMoveIsFinished(); return self; ################################### # stiffness ################################### def stiff(self): ...
pNames, pStiffnessLists, pTimeLists) return self; def rest(self): self.env.motion.rest() return self; def relax(self): pNames = self.joints.Chains.Body pStiffnessLists = 0 pTimeLists = 1.0 self.env.motion.stiffnessInterpolation(pNames, pStiffnessLists, p...
import binascii import os import random from django.db import models from django.utils.encoding import force_text, python_2_unicode_compatible from aesfield.field import AESField from olympia.amo.fields import PositiveAutoField from olympia.amo.models import ModelBase from olympia.users.models import UserProfile #...
.format(prefix, random.randint(0, 999)) if cls.object
s.filter(key=key).exists(): return cls.get_unique_key(prefix, try_count=try_count + 1, max_tries=max_tries) return key @staticmethod def generate_secret(byte_length): """ Return a true random ascii string containing byte_length of random...
from tests.base_test import BaseTest from tests import config from core import modules from core.sessions import SessionURL from testfixtures import log_capture from core import messages import logging import os import subprocess class FileBzip(BaseTest): # Create and bzip2 binary files for the test binstring...
\x00\\x00' > "$BASE_FOLDER/binfile1" bzip2 "$BASE_FOLDER/binfile0" bzip2 "$BASE_FOLDER/binfile1" chown www-data: -R "$BASE_FOLDER/"
""".format( config = config ), shell=True) self.run_argv = modules.loaded['file_bzip2'].run_argv def test_compress_decompress(self): # Decompress and check test file self.assertTrue(self.run_argv(["--decompress", self.compressed[0]])); self.assertEqual( ...
# Copyright 2010-2017, The University of Melbourne # Copyright 2010-2017, Brian May # # This file is part of Karaage. # # Karaage 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...
me): if django.VERSION < (1, 7): for app in settings.INSTALLED_APPS: try: module_name = app + "." + name module = importlib.import_module(module_name) yield module except ImportError: pass else: from django.a...
me + "." + name module = importlib.import_module(module_name) yield module def get_urls(name): for module in get_app_modules("urls"): urls = getattr(module, name, None) if urls is not None: yield urls
g_bag.get_dag('child_dag_1').get_dagrun(execution_date=day_2, session=session) assert dagrun_0_1.state == State.QUEUED assert dagrun_0_2.state == State.QUEUED assert dagrun_1_1.state == State.QUEUED assert dagrun_1_2.state == State.SUCCESS def test_external_task_marker_future(dag_bag_ext): """ ...
nge(25): task = ExternalTaskMarker( task_id=f"{daily_task.task_id}_{i}", external_dag_id=daily_dag.dag_id, external_task_id=daily_task.task_id, execution_date="{{ macros.ds_add(ds, -1 * %s) }}" % i, dag=agg_dag, ) start >> task yie...
marker(dag_bag_multiple): """ Test clearing a dag that has multiple ExternalTaskMarker. sqlite3 parser stack size is 100 lexical items by default so this puts a hard limit on the level of nesting in the sql. This test is intentionally skipped in sqlite. """ agg_dag = dag_bag_multiple.get_dag("a...
# -*- coding: utf-8 -*- from ccxt.async.base.exchange import Exchange import hashlib class bit2c (Exchange): def describe(self): return self.deep_extend(super(bit2c, self).describe(), { 'id': 'bit2c', 'name': 'Bit2C', 'countries': 'IL', # Israel 'rateLimi...
': self.market_id(symbol), } if type == 'market': method += 'MarketPrice' + self.capitalize(side) else: order['Price'] = price order['Total'] = amount * price order['IsBid'] = (side == 'buy') result = await getattr(self, method)(self.extend...
info': result, 'id': result['NewOrder']['id'], } async def cancel_order(self, id, symbol=None, params={}): return await self.privatePostOrderCancelOrder({'id': id}) def sign(self, path, api='public', method='GET', params={}, headers=None, body=None): url = self.urls['api'] ...
import numpy as np from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.tf.misc import normc_initializer from ray.rllib.models.tf.tf_modelv2 import TFModelV2 from ray.rllib.models.torch.misc import SlimFC, normc_initializer as \ torch_normc_initializer from ray.rllib.models.torch.torch_modelv2 import...
self._logits = SlimFC( in_size=prev_layer_size, out_size=self.num_outputs, initializer=torch_normc_initializer(0.01),
activation_fn=None) self._value_branch = SlimFC( in_size=prev_layer_size, out_size=1, initializer=torch_normc_initializer(1.0), activation_fn=None) self._hidden_layers = nn.Sequential(*layers) self._hidden_out = None @override(Mo...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2020 Satpy developers # # This file is part of satpy. # # satpy 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...
ere import CO2Cor
rector # noqa: F401 from .atmosphere import PSPAtmosphericalCorrection # noqa: F401 from .atmosphere import PSPRayleighReflectance # noqa: F401 from .geometry import EffectiveSolarPathLengthCorrector # noqa: F401 from .geometry import SunZenithCorrector # noqa: F401 from .spectral import NIREmissivePartFromReflect...
#!/usr/bin/env python # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2016 # Leandro Toledo de Souza <devs@python-telegram-bot.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by #...
ins the classes that represent Telegram InlineQueryResultCachedVideo""" from telegram import InlineQueryResult, InlineKeyboardMarkup, InputMessageContent class InlineQueryResultCachedVideo(InlineQueryResult): def __init__(self, id, video_file_id, title, ...
super(InlineQueryResultCachedVideo, self).__init__('video', id) self.video_file_id = video_file_id self.title = title # Optionals if description: self.description = description if caption: self.caption = caption if reply_markup: ...
ns an authorization server page # in default web browser. # The new credentials are also stored in the Storage object, # which updates the credentials file. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() if flags: credentials = tools.run_flow(flow, storage, flags) print ...
The event's title. Description The event's description. Where The location where the event takes place. Starts ej August 23, 2011 at 10:00PM Ends ej: August 23, 2011 at 11:00PM ''' # so dirty gcal_description = "#{city} {tags} {title} {shortURL}({human_date}{pl...
human dates (spanish, quick and dirty) Args: date_time (datetime object) abbr (boolean) abreviate month names? default False Returns: str """ tmp = date_time.strftime('%d de //%m//, %H:%M hs') tmp_month_number = tmp.split("//")[1].split("//")[0] month = "" ...
#!/usr/bin/python """nrvr.util.ipaddress - Utilities regarding IP addresses Class provided by this module is IPAddress. Works in Linux and Windows. Idea and first implementation - Leo Baschy <srguiwiz12 AT nrvr DOT com>
Contributor - Nora Baschy Public repository - https://github.com/srguiwiz/nrvr-commander Copyright (c) Nirvana Research 2006-2015. Simplified BSD License""" import re class IPAddress(object): """Methods for multiple machi
nes on one subnet. As implemented only supports IPv4.""" octetsRegex = re.compile(r"^\s*([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\s*$") @classmethod def asList(cls, ipaddress, rangeCheck=False): """For ipaddress="10.123.45.67" return mutable [10, 123, 45, 67]. ...
from flask import Flask, url_for, redirect, render_template, request from flask.ext.sqlalchemy import SQLAlchemy from flask.ext import superadmin, login, wtf from flask.ext.superadmin.contrib import sqlamodel from wtforms.fields import TextField, PasswordField from wtforms.validators import Required, ValidationError ...
er = User() form.populate_obj(user)
db.session.add(user) db.session.commit() login.login_user(user) return redirect(url_for('index')) return render_template('form.html', form=form) @app.route('/logout/') def logout_view(): login.logout_user() return redirect(url_for('index')) if __name__ == '__main__': ...
# -*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, url from django.utils.translation import ugettext_lazy as _ from wiki.core.plugins import registry from wiki.core.plugins.base import BasePlugin from wiki.plugins.attachments import views from wiki.plugins.attachments import models from wiki.plugi...
ugins.notifications import ARTICLE_EDIT class AttachmentPlugin(BasePlugin): #settings_form = 'wiki.plugins.notifications.forms.SubscriptionForm' slug = settings.SLUG urlpatterns = patterns('', url(r'^$', views.AttachmentView.as_view(), name='attachments_index'), url(r'^search/$', ...
e='attachments_search'), url(r'^add/(?P<attachment_id>\d+)/$', views.AttachmentAddView.as_view(), name='attachments_add'), url(r'^replace/(?P<attachment_id>\d+)/$', views.AttachmentReplaceView.as_view(), name='attachments_replace'), url(r'^history/(?P<attachment_id>\d+)/$', views.AttachmentHisto...
from __future__ import absolute_import, unicode_literals from case import Mock, patch from amqp.five import text_t from amqp.utils import (NullHandler, bytes_to_str, coro, get_errno, get_logger, str_to_bytes) class test_get_errno: def test_has_attr(self): exc = KeyError('foo') ...
t not get_errno(exc) def test_no_args(self): assert not get_errno(object()) class test_coro: def test_advances(self): @coro def x(): yield 1 yield 2 it = x() assert next(it) == 2 class test_str_to_bytes: de
f test_from_unicode(self): assert isinstance(str_to_bytes(u'foo'), bytes) def test_from_bytes(self): assert isinstance(str_to_bytes(b'foo'), bytes) def test_supports_surrogates(self): bytes_with_surrogates = '\ud83d\ude4f'.encode('utf-8', 'surrogatepass') assert str_to_bytes(u'...
_cached_fetch(lambda message_id: to_dict_cache_key_id(message_id, apply_markdown), Message.get_raw_db_rows, message_ids, id_fetcher=id_fetcher, ...
le this specially, inferring the domain from the # e-mail address, because the recipient may not existing in Zulip # and we may need to make a stub MIT user on the fly. try: validators.validate_email(email) except ValidationError: return False domain = resolve_email_to_domain(email)...
l address is an IRC user in the # same realm as user_profile, i.e. if the domain were example.com, # the IRC user would need to be username@irc.example.com try: validators.validate_email(email) except ValidationError: return False domain = resolve_email_to_domain(email) return ...
import pygame from pygame.colordict import T
HECOLORS import data class Platform(pygame.sprite.Sprite): def __init__(self, width, height): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([width, height]) self.image.fill(THECOLORS["green"]) self.rect = self.image.get_rect() class Trampoline(pygame.sprite.S...
ng") self.rect = self.image.get_rect()
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino <jespinog@gmail.com> # Copyright (C) 2014 David Barragán <bameda@dbarragan.com> # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the F...
e(sender, instance, **kwargs): """ Creating new membership with associated user. If the user is the project owner we don't do anything because that info will be shown in created project timeline entry @param sender: Membership model @param instance: Membership object """ # We shown in crea...
and instance.user and instance.user != instance.project.owner: created_datetime = instance.created_at _push_to_timelines(instance.project, instance.user, instance, "create", created_datetime) # Updating existing membership elif instance.pk: try: prev_instance = sender.object...
main"], force) run_as_root(["apt-get", "update"]) run_as_root(["apt-get", "install", "clang-4.0"], force) return gcc or clang def check_gstreamer_lib(): return subprocess.call(["pkg-config", "gstreamer-1.0 >= 1.12"], stdout=PIPE, stderr=PIPE) == 0 def run_as_root(...
pkgs = pkgs_fedora for p in pkgs: command = ['dnf', 'install'] if "|{}".format(p) not in installed_pkgs: install = True break if install: if
force: command.append('-y') print("Installing missing dependencies...") run_as_root(command + pkgs) return True return False def install_salt_dependencies(context, force): pkgs_apt = ['build-essential', 'libssl-dev', 'libffi-dev', 'python-dev'] pkgs_dnf = ['gcc', 'libf...
from django import forms from django.test import TestCase from django.core.exceptions import NON_FIELD_ERRORS from modeltests.validation import ValidationTestCase from modeltests.validation.models import Author, Article, ModelToValidate # Import other tests for this package. from modeltests.validation.validators impor...
l_clean, 'url', [u'This URL appears to be a broken link.']) def test_correct_url_value_passes(self): mtv = ModelToValidate(number=10, name='Some Name', url='http://www.djangoproject.com/') self.assertEqual(None, mtv.full_clean()) # This will fail if there's no Internet connection def test_corr...
ionWithMessage(mtv.full_clean, 'url', [u'This URL appears to be a broken link.']) def test_correct_ftp_url_but_nonexisting(self): mtv = ModelToValidate(number=10, name='Some Name', url='ftp://ftp.google.com/we-love-microsoft.html') self.assertFieldFailsValidationWithMessage(mtv.full_clean, 'url', [...
import os import sys as sys os.system("python bot/bot.py engage") import bot_response as bot import bot_learn as learner def hasUserSwore(message): if "fuck" in message: return True elif "bitch" in message: return True elif "Fuck" in message: re...
.bot") #os.remove("responses.bot") os.remove("bot_response.py") writeCommand("Hello", "Hi") print "Cleared commands" elif(messageToBot == "learn"): learner.learn(db_supp
ort=False) elif(messageToBot == "--get-commands"): commandsList = open("commands.list","r") print commandsList.read() bot.getResponse(messageToBot) toBot() def writeCommand(command, response): file = open("bot_response.p...
__aut
hor__
= 'thuy'
# Copyright 2012 Jose Blanca,
Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of ngs_crumbs. # ngs_crumbs 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...
t 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 ngs_crumbs. If not, see <http://www.gnu.org/licenses/>. from __future__ import division from ...
from django.conf.urls import url from fundraiser_app import views urlpatterns = [ url(r'^$', views.FMItemListView.as_view(), name='fmitem_list'), url(r'^about/$', views.AboutView.as_view(), name='about'), url(r'^fmitem/(?P<pk>\d+)$', views.FMItemDetailView.as_view(), name='fmitem_detail'), url(r'^fmite...
m/(?P<pk>\d+)/edit$', views.FMItemUpdateView.as_view(), name='fmitem_edit'), url(r'^fmitem/(?P<pk>\d+)/remove$', views.FMItemDeleteView.as_view(), name='f
mitem_remove'), url(r'^fmitem/(?P<pk>\d+)/publish/$', views.fmitem_publish, name='fmitem_publish'), ]