prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
rank treeview columns=[ {'name':_("id"), 'visible':False}, {'name':_("Rank"), 'visible':True}, {'name':_("Date"), 'xalign':1.0}, {'name':_("Distance"), 'xalign':1.0, 'format_float':'%.2f', 'quantity':'distance'}, ...
ing.debug(">>") self.waypoint = waypoint if not getattr(self, 'mapviewer', None): self.mapviewer = MapViewer(self.data_path, pytrainer_main=self.parent, box=self.map_vbox) self.mapviewer_fs = MapViewer(self.data_path, pytrainer_main=self.parent, box=self.map_vbox_old) log...
(self,listSport): logging.debug(">>") liststore = self.sportlist.get_model() if self.sportlist.get_active() is not 0: self.sportlist.set_active(0) #Set first item active if it isnt firstEntry = self.sportlist.get_active_text() liststore.clear() #Delete all items ...
import logging from ftmstore import get_dataset log = logging.getLogger(__name__) MODEL_ORIGIN = "m
odel" def get_aggregator_name(collection): return "collection_%s" % collection.id def get_aggregator(collection, origin="aleph"): """Connect to a followthemoney dataset.""" dataset = get_aggregator_name(collection) return get_dataset(dataset, origin=or
igin)
import RPi.GPIO as GPIO import time import sys #on renseigne le pin sur lequel est branché le cable de commande du servo moteur superieur (haut-bas) servo_pin = 12 #recuperation de la valeur du mouvement a envoyer au servo duty_cycle = float(sys.argv[1]) GPIO.setmode(GPIO.BOARD) GPIO.setup(servo_pin, GPIO.OUT) # ...
exit() except KeyboardInterrupt: print("CTRL-C: Terminating program.") # si le progr
amme est utilise seul, cela permet de l'eteindre en cas d'urgence
#!/usr/bin/env python from __future__ import division, print_function, absolute_import def configuration(parent_name='special', top_path=None): from numpy.distutils.misc_uti
l import Configuration config = Configuration('_precompute', parent_name, top_path) return config if __name__ == '__main__': from numpy.distuti
ls.core import setup setup(**configuration().todict())
# 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 compli
ance 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, softwa
re # 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. # =====================================================================...
# -*- coding: utf-8 -*- __author__ = 'k' import re import scrapy from bs4 import BeautifulSoup import logging from thepaper.items import NewsItem import json logger = logging.getLogger("NbdSpider") from thepaper.settings import * from thepaper.util import judge_news_crawl import time class DonewsSpider(scrapy.spiders...
ww.donews.com/net/", "http://www.donews.com/original/", ] def parse(self,response): origin_url = response.url topic_url = origin_url[:-1] self.fl
ag.setdefault(topic_url,0) yield scrapy.Request(origin_url,callback=self.parse_topic) def parse_topic(self,response): origin_url = response.url temp = origin_url.rsplit("/",1) topic_url = temp[0] if temp[1] == "": pageindex = 1 else: pageindex...
eclass, mc._baseclass) assert_equal(mc_pickled._mask, mc._mask) assert_equal(mc_pickled._data, mc._data) def test_pickling_wstructured(self): # Tests pickling w/ structured array a = array([(1, 1.), (2, 2.)], mask=[(0, 0), (0, 1)], dtype=[('a', int), ('b', float)])...
def test_fancy_printoptions(self): # Test printing a masked array w/ fancy dtype. fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])]) test = array([(1, (2, 3.0)), (4, (5, 6.0))], mask=[(1, (0, 1)), (0, (1, 0))], dtype=fancydtype) ...
d_array on arrays # On ndarray ndtype = [('a', int), ('b', float)] a = np.array([(1, 1), (2, 2)], dtype=ndtype) test = flatten_structured_array(a) control = np.array([[1., 1.], [2., 2.]], dtype=np.float) assert_equal(test, control) assert_equal(test.dtype, control...
from typing import cast, List, TypeVar, Any, Type, Optional from uuid import UUID from graphscale import check from graphscale.pent import ( create_pent, delete_pent, update_pent, Pent, PentContext, PentMutationData, PentMutationPayload, ) T = TypeVar('T') def typed_or_none(obj: Any, cl...
name) payload_cls = context.cls_from_name(payload_cls_name) deleted_id = await delete_pent(context, pent_cls, obj_id) return cast(PentMutationPayload, payload_cls(deleted_id)) async def gen_create_pent_dynamic( context: PentContext, pent_cls_name: str, data_cls_name: str, payload_cls_name:...
ionPayload: data_cls = context.cls_from_name(data_cls_name) check.isinst(data, data_cls) pent_cls = context.cls_from_name(pent_cls_name) payload_cls = context.cls_from_name(payload_cls_name) out_pent = await create_pent(context, pent_cls, data) return cast(PentMutationPayload, payload_cls(out...
import pytz from datetime import datetime, timedelta def is_dst(zonename, date): local_tz = pytz.timezone(zonename) localized_time = local_tz.localize(date) return localized_time.dst() != timedelta(0) def get_offset(zonename, date): local_tz = pytz.timezone(zonename) if zonename == 'UTC': ...
int(l
ocal_timestamp) + int(time_item * 60) timesteps.append(new_time) return timesteps def convert_ISO_to_epoch(datetime_string, date_format): """ Takes a datetime string and returns an epoch time in seconds Only works when datetime_string is in UTC """ datetime_object = datetime.strptime(...
import time from unittest import TestCase from unittest import mock from elasticsearch_raven import utils class RetryLoopTest(TestCase): @mock.patch('time.sleep') def test_delay(self, sleep): retry_g
enerator = utils.retry_loop(1) for i in range(4): retr
y = next(retry_generator) retry(Exception('test')) self.assertEqual([mock.call(1), mock.call(1), mock.call(1)], sleep.mock_calls) @mock.patch('time.sleep') def test_back_off(self, sleep): retry_generator = utils.retry_loop(1, max_delay=4, back_off=2) ...
# encoding: utf-8 from PyQt4.QtCore import * from PyQt4.QtGui import * class ExceptionDialog(QMessageBox): def __init__(self,parent,exc,t1=None,t2=None): QMessageBox.__init__(self,parent) if t1==None: t1=(exc.args[0] if len(exc.args)>0 else None) self.setText(u'<b>'+exc.__class__.__name__+...
eptionDialog(parent,exc).show() # import traceback # QMessageBox.critical(parent,exc.__class__.__name__,'<b>'+exc.__class__._
_name__+':</b><br>'+exc.args[0]+'+<br><small><pre>'+Qt.convertFromPlainText((traceback.format_exc()))+'</pre></small>') if __name__=='__main__': import sys qapp=QApplication(sys.argv) e=ValueError('123, 234, 345','asdsd') showExceptionDialog(None,e)
from __future__ import absolute_import from django.contrib import admin from django.contrib.admin.models import DELETION from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import Permission from django.core.urlresolvers import reverse from django.utils.html import escape from admin.common...
fields = [f.name for f in OSFLogEntry._meta.get_fields()] list_filter = [ 'user', 'action_flag' ] search_fields = [ 'object_repr', 'change_message' ] list_display = [ 'action_time',
'user', 'object_link', 'object_id', 'message', ] def has_add_permission(self, request): return False def has_change_permission(self, request, obj=None): return request.user.is_superuser and request.method != 'POST' def has_delete_permission(self, request...
# -*- coding: utf-8 -*- import oauth2 # XXX pumazi: factor this out from webob.multidict import MultiDict, NestedMultiDict from webob.request import Request as WebObRequest __all__ = ['Request'] class Request(WebObRequest): """The OAuth version of the WebOb Request. Provides an easier way to obtain O...
def _checks_positive_for_oauth(self, params_var): """Simple check for the presence of OAuth parameters.""" checks = [ p.find('oauth_') >= 0 for p in params_var ] return True in checks @property def str_oauth_header(self): extracted = {} # Check for OAuth in the...
auth_header = self.headers['authorization'] # Check that the authorization header is OAuth. if auth_header[:6] == 'OAuth ': auth_header = auth_header.lstrip('OAuth ') try: # Extract the parameters from the header. ex...
"""Geometry functions and utilities.""" from enum import Enum from typing import Sequence, Union import numpy as np # type: ignore from pybotics.errors import PyboticsError class OrientationConvention(Enum): """Orientation of a body with respect to a fixed coordinate system.""" EULER_XYX = "xyx" EULER...
oat() cast when numpy is supported in mypy result = float((
angle + np.pi) % (2 * np.pi) - np.pi) return result def rotation_matrix_x(angle: float) -> np.ndarray: """Generate a basic 4x4 rotation matrix about the X axis.""" s = np.sin(angle) c = np.cos(angle) matrix = np.array([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]).reshape((4, 4)) return ...
"Change Manager for literal values (supporting ==)" from __future__ import annotations from .bitmap import bitmap from .index_update import IndexUpdate from .changemanager_base import BaseChangeManager from typing import ( Any, TYPE_CHECKING, ) if TYPE_CHECKING: from .slot import Slot class LiteralChan...
l = False, buffer_deleted: bool = True, buffer_exposed: bool = False, buffer_masked: bool = False, ) -> None: super(LiteralChangeManager, se
lf).__init__( slot, buffer_created, buffer_updated, buffer_deleted, buffer_exposed, buffer_masked, ) self._last_value: Any = None def reset(self, mid: str) -> None: super(LiteralChangeManager, self).reset(mid) s...
from guize
ro import App app = App() app.info("Info", "This is a guizero app") app.error("Error", "Try and keep these out your code...") app.warn
("Warning", "These are helpful to alert users") app.display()
# -*- coding: utf-8 -*- # Copyright (c) 2017, Softbank Robotics Europe # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, t...
se type is changed through assignment To avoid funct
ions being called with bad arguments, you can use Python's `typing module <https://docs.python.org/3/library/typing.html>`_) (however only with Python3). To check if a variable is not incorrectly used, you can install and run `mypy module <http://mypy.readthedocs.io/en/latest/>`_). But if the latest is great for stati...
''' Copyright 2016, EMC, Inc. Author(s): George Paulos ''' import fit_path # NOQA: unused import import os import sys import subprocess import fit_common from nose.plugins.attrib import attr @attr(all=True, regression=True, smoke=True) class rackhd20_api_config(fit_common.unittest.TestCase): def test_api_20_co...
orEnable": True} api_data = fit_common.rackhdapi("/api/2.0/config", action="patch", payload=data_payload) self.assertEqual(api_data['status'], 200, "Was expecting code 200. Got " + str(api_data['status'])) for item in api_data['json']: self.assertNotEqual(item, '', 'Empty JSON Field:...
ogColorEnable'] is True): self.assertEqual(api_data['json']['logColorEnable'], False, "Incorrect value for 'logColorEnable', should be False") else: self.assertEqual(api_data['json']['logColorEnable'], True, "Incorrect value 'logColorEnable', should be True") api_data = fit_commo...
import numpy as np import matplotlib.p
yplot as plt N=10000 np.random.seed(34) lognormal_values = np.random.lognormal(size=N) _, bins, _ = plt.hist(lognormal_values, np.sqrt(N), normed=True, lw=1, label="Histogram") sigma = 1 mu = 0 x = np.linspace(min(bins), max(bins), len(bins)) pdf = np.exp(-(np.log(x) - mu)**2 / (2 * sigma**2))/ (x * sigma * np.sqrt(2 ...
') plt.show()
# -*- coding: utf-8 -*- import pytest import numpy as np from pandas import Series, Timestamp from pandas.compat import range, lmap import pandas.core.common as com import pandas.util.testing as tm def test_mut_exclusive(): msg = "mutually exclusive arguments: '[ab]' and '[ab]'" with tm.assert_raises_regex...
State(10).uniform()) # check with no arg random state assert com._random_state()
is np.random # Error for floats or strings with pytest.raises(ValueError): com._random_state('test') with pytest.raises(ValueError): com._random_state(5.5) def test_maybe_match_name(): matched = com._maybe_match_name( Series([1], name='x'), Series( [2], name='x')...
#!/usr/bin/python # # Copyright 2008-2010 WebDriver committers # Copyright 2008-2010 Google 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...
assert 12345 == profile.default_preferences["sample.int.preference"] def test_that_boolean_prefs_are_written_in_the_correct_format(self): # The setup gave us a browser but we dont need it self.driver.quit() profile = webdriver.FirefoxProfile() profile.set_preference("sample.bool.pr...
assert True == profile.default_preferences["sample.bool.preference"] def test_that_we_delete_the_profile(self): path = self.driver.firefox_profile.path self.driver.quit() assert not os.path.exists(path) def test_profiles_do_not_share_preferences(self): self.profile1 = webdrive...
#!/usr/bin/env python import argparse import gzip import logging import os import shutil import subprocess browser_specific_args = { "firefox": ["--install-browser"] } def tests_affected(commit_range): output = subprocess.check_output([ "python", "./wpt", "tests-affected", "--null", commit_range ...
wptreport: gzip_file(wptreport) if __name__ == "__main__": parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument("--commit-range", action="store", help="""Git commit range. If specified, this will be supplied to the `wpt tes...
parser.add_argument("product", action="store", help="Browser to run tests in") parser.add_argument("wpt_args", nargs="*", help="Arguments to forward to `wpt run` command") main(**vars(parser.parse_args()))
#!/
usr/bin/env py
thon from subprocess import call call(["bickle", "builds", "stpettersens/Packager", "-n", "5"])
"""Module provides provides a convinient class :class:`Attachment` to access (Create, Read, Delete) document attachments.""" import base64, logging from os.path import basename from copy import deepcopy from mimetypes import guess_type from httperror import *...
content_type = h.get( 'Content-Type', None ) return (d.getvalue(), content_type) @classmethod def putattachm
ent( cls, db, doc, filepath, data, content_type=None, hthdrs={}, **query ) : """Upload the supplied content (data) as attachment to the specified document (doc). `filepath` provided must be a URL encoded string. If `doc` is document-id, then `rev` keyword parameter should ...
from __future__ import absolute_import, print_function, division from six.moves import xrange def render_string(string, sub): """ string: a string, containing formatting instructions sub: a dictionary containing keys and values to substitute for them. returns: string % sub The only diffe...
tion as E: # If unable to render the string, render longer and longer # initial substrings until we find the minimal initial substr
ing # that causes an error i = 0 while i <= len(string): try: finalCode = string[0:i] % sub except Exception as F: if str(F) == str(E): raise Exception( string[0:i] + "<<<< caused exception " + st...
self._option_string_actions = {} # groups self._action_groups = [] self._mutually_exclusive_groups = [] # defaults storage self._defaults = {} # determines whether an "option" looks like a negative number self._negative_number_matcher = _re....
.) add_argument(option_string, option_string, ..., name=value, ...) """ # if no positional args are supplied or only one is supplied and # it doesn't look like an option string, parse a positional # argument chars = self.prefix_chars if not args or len(ar...
kwargs = self._get_optional_kwargs(*args, **kwargs) # if no default was supplied, use the parser-level default if 'default' not in kwargs: dest = kwargs['dest'] if dest in self._defaults: kwargs['default'] = self._defaults[dest] elif self.a...
#### NOTICE: THIS FILE IS AUTOGEN
ERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object imp
ort * def create(kernel): result = Creature() result.template = "object/mobile/shared_dressed_diax.iff" result.attribute_template_id = 9 result.stfName("npc_name","diax") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
# -*- coding: utf-8 -*- """ Created on Thu Feb 25 10:21:20 2016 @author: suraj """ import pickle import numpy as np X = pickle.load(open('x_att.p')) y = pickle.load(open('y_att.p')) batchX = [] batchy = [] def convertPointsToBatch(day_of_week,data1,data2): for i in range(5)
: batchX.extend(data1[((i*672)+((day_of_week)*96)):((i*672)+((day_of_week)*96))+96]) batchy.extend(data2[((i*672)+((day_of_week)*96)):((i*672)+((day_of_week)*96))+96]) pass for i in range(7): conve
rtPointsToBatch(i,X,y) batchX = np.array(batchX) batchy = np.array(batchy) print batchX.shape print batchy.shape print batchX[0] print batchy[0] pickle.dump(batchX,open('batch_x_att.p','wb')) pickle.dump(batchy,open('batch_y_att.p','wb'))
import webapp2 import models class PrefsPage(webapp2.RequestHandler): def post(self): userprefs = models.get_userprefs() try: tz_offset = int(self.request.get('tz_offset')) userprefs.tz_offset = tz_offset userprefs.put()
except ValueError: # User entered a value that wasn't an integer. Ignore for now. pass self.redirect('/') application = webapp2.WSGIApplication([('/prefs', PrefsPage)],
debug=True)
# pywws - Python software for USB Wireless Weather Stations # http://github.com/jim-easterbrook/pywws # Copyright (C) 2008-15 Jim Easterbrook jim@jim-easterbrook.me.uk # 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 F...
dtext en" import platform import usb class USBDevice(object): def __init__(self, idVendor, idProduct): """Low level USB device access via PyUSB library. :param idVendor: the USB "vendor ID" number, for example 0x1941. :type idVendor: int :param idProduct: the USB "product ID" nu...
_device(idVendor, idProduct) if not dev: raise IOError("Weather station device not found") self.devh = dev.open() if not self.devh: raise IOError("Open device failed") self.devh.reset() ## if platform.system() is 'Windows': ## self.devh.setConfig...
""
" Generates a list of [b, N, n] where N is the amount of b-bit primes and n is the amount of b-bit safe primes. """ import gmpy import json for b in xrange(1,33): N = 0 n = 0 p = gmp
y.mpz(2**b) while True: p = gmpy.next_prime(p) if p > 2**(b+1): break if gmpy.is_prime(2*p + 1): n += 1 N += 1 d = n/float(N) print json.dumps([b, N, n])
# pylint: skip-file # vim: expandtab:tabstop=4:shiftwidth=4 #pylint: disable=too-many-branches def main(): ''' ansible module for gcloud iam service-account keys''' module = AnsibleModule( argument_spec=dict( # credentials state=dict(default='present', type='str', choices=['pres...
results=api_rval['results'], state="list") ######## # Delete ######## if state == 'absent': if module.check_mode: module.exit_json(changed=False, msg='Would have performed a delete.') api_rval = gcloud.delete_service_account_key(module.params['key_id']) if api_rva...
ule.fail_json(msg=api_rval) module.exit_json(changed=True, results=api_rval, state="absent") if state == 'present': ######## # Create ######## if module.check_mode: module.exit_json(changed=False, msg='Would have performed a create.') # Create it here ...
#!/usr/bin/env python2 # encoding=utf-8 from __future__ import division, print_function from math import ceil, floor, log10, pi from sys import argv, stdout from xml.dom import minidom import bz2 import csv # local imports from my_helper_functions_bare import * def pretty_mean_std(data): return uncertain_number_...
if len(data["packings"]) == 0 or packing != data["packings"][-1] \ or n_atoms != data["n_atoms"][-1]: data["packings"].append(packing) data["n_atoms"].append(n_atoms) data["collisions"
].append(int(xmldoc.getElementsByTagName( 'Duration')[0].attributes['TwoParticleEvents'].value)) for parameter in varying_parameters: data[parameter].append([]) data["times"][-1].append(float( xmldoc.getElementsByTagName('Duration')[0].attributes['Time'].value)) data...
else: return NotImplemented def __lt__(self, other): """Implementation of less than operator WARNING: The exact behavior of this isn't yet well-defined enough to be used for consensus-critical applications. """ if isinstance(other, TimeAttestation): ...
HeaderAttestation.TAG: r = opentimestamps.core.dubious.notary.EthereumBlockHeaderAttestation.deserialize(payload_ctx) else: return UnknownAttestation(tag, serialized_attestation) # If attestations want to have unspecified fields for future # upgradability they should do ...
lass UnknownAttestation(TimeAttestation): """Placeholder for attestations that don't support""" def __init__(self, tag, payload): if tag.__class__ != bytes: raise TypeError("tag must be bytes instance; got %r" % tag.__class__) elif len(tag) != self.TAG_SIZE: raise ValueE...
# encoding: utf-8 def _unicode_truncate(ustr, length, encoding="UTF-8"): "Truncate @ustr to specific encoded byte length" bstr = ustr.encode(encoding)[:length] return bstr.decode(encoding, 'ignore') def extract_title_body(text, maxtitlelen=60): """Prepare @text: Return a (title, body) tuple @text...
ne, rest if rest.strip(): return firstline, text else: return text, "" if __name__ =
= '__main__': import doctest doctest.testmod()
re_pair_divide_list[:20], features.feature_pair_sub_mul_list[:20]) labels = toLabels(train_y) gbc = GradientBoostingClassifier(n_estimators=3000, max_depth=8) gbc.fit(sub_x_Train, labels) return gbc # use svm to predict the loss, based on the result of gbm classifier def gbc_svr_predict...
tures.feature_pair_divide_list, features.feature_pair_sub_mul_list, features.feature_pair_sub_list_sf, features.feature_pair_plus_list2) return svr_preds # invoke the function gbc_gbr_predict_part def gbc_gbr_predict(gbc, train_x, train_y, ...
r_plus_list, features.feature_pair_mul_list, features.feature_pair_divide_list, features.feature_pair_sub_mul_list, features.feature_pair_sub_list2) return gbr_preds # the main function
# -*- coding: utf-8 -*- """ /*************************************************************************** Name : lookup value selector Description : Enables the selection of lookup values from a lookup entity. Date : 09/February/2017 copyright :...
self.lookup_entity = self._profile.entity_by_name( '{}_{}'.format(self._profile.prefix, lookup_entity_name) ) self.notice = NotificationBar(self.notice_bar) self._view_model = QStandardItemModel() self.value_list_box.setModel(self._view_mode
l) header_item = QStandardItem(lookup_entity_name) self._view_model.setHorizontalHeaderItem(0, header_item) self.populate_value_list_view() self.selected_code = None self.selected_value_code = None self.value_list_box.clicked.connect(self.validate_selected_code) de...
# vim: set encoding=utf-8 # Copyright (c) 2016 Intel Corporation  # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #       http://www.apache.org/licenses/LICENSE-2.0 # # Unless require...
===================================== [0] 7.71320643267 2.81913279907 [1] 0.207519493594 -1.25365381375 [2] 6.33648234926 2.46673638752 [3] 7.48803882539 2.7
6469126003 [4] 4.98507012303 2.06401101556 """ self._scala.boxCox(column_name, lambda_value, self._tc.jutils.convert.to_scala_option(box_cox_column_name))
def
test_local_variable(): x =
1 x = 2
"""IETF usage guidelines plugin See RFC 8407 """ import optparse import sys import re from pyang import plugin from pyang import statements from pyang import error from pyang.error import err_add from pyang.plugins import lint def pyang_plugin_init(): plugin.register_plugin(IETFPlugin()) class IETFPlugin(lint.L...
's description statement must contain the following text: Copyright (c) <year> IETF
Trust and the persons identified as authors of the code. All rights reserved. Redistribution and use in source and binary forms, with or without modification, is permitted pursuant to, and subject to the license terms contained in, the Revised BSD License set forth in Section 4.c of the IETF ...
# Copyright (C) 2015 The Android Open Source Project # # Licensed unde
r 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 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. archs_list = ['ARM', 'ARM64', 'MIPS', 'MIPS64', 'X86', 'X86_64'...
d_ots_key(xmss, addr_state, start=0): for i in range(start, 2 ** xmss.height): if not addr_state.ots_key_reuse(i): xmss.set_ots_index(i) return True return False def valid_payment_permission(public_stub, master_address_state, payment_xmss, json_slave_txn): access_type = mas...
raise Exception('Transaction Submission Failed, Response Code: %s', response.error_code) response = {'tx_hash': bin2hstr(tx.txhash)} return response app.add_url_rule('/json_rpc', 'api', api.as_view(), methods=['POST']) def parse_arguments(): parser = argparse.ArgumentParser(description='QRL node') ...
gument('--network-type', dest='network_type', choices=['mainnet', 'testnet'], default='mainnet', required=False, help="Runs QRL Testnet Node") return parser.parse_args() def main(): args = parse_arguments() qrl_dir_post_fix = '' copy_files = [] if args.network_type == 'tes...
ikit-learn style wrapper for statsmodels.api.GLM. The purpose of this class is to make generalized linear models compatible with scikit-learn's Pipeline objects. family : instance of subclass of statsmodels.genmod.families.family.Family The family argument determines the distribution family to us...
predict(self, X, offset = None, exposure = None): ''' Predict the response based on the input data X. Parameters ---------- X : array-like, shape = [m, n] where m is the number of samples and n is the number of features The training predictors. The...
can be a numpy array, a pandas DataFrame, or a patsy DesignMatrix. ''' #Format the data X, offset, exposure = self._scrub_x(X, offset, exposure) #Linear transformation eta = self.transform(X, offset, exposure) #Nonlinear transformation ...
#Prueba para mostrar los nodos conectados a la red from base_datos import db import time from datetime import t
imedelta, datetime,date dir_base="/media/CasaL/st/Documentos/proyectoXbee/WSN_XBee/basesTest/xbee_db02.db" d=timedelta(minutes=-10) #now=datetime.now() #calculo=now+d #print(calculo.strftime("%H:%M:%S")) #hoy=datetime.now() #miFecha=date(hoy.year,7,13) #miHoraFecha=datetime(2017,7,13,20,13) #print(miFecha.strftime("%Y...
' base=db(dir_base) ultimoRegistro=base.consultaSimp(conFechaHora)[0][0] aux1=ultimoRegistro.split(" ") horaReg=aux1[0].split(":") fechaReg=aux1[1].split("/") aux_ini=datetime(int(fechaReg[2]),int(fechaReg[1]),int(fechaReg[0]),int(horaReg[0]),int(horaReg[1]),int(horaReg[2])) aux_final=aux_ini+d hora_inicio=aux_ini.strf...
#!/bin/python # -*- coding: utf-8 -*- # #################################################################### # gofed-ng - Golang system # Copyright (C) 2016 Fridolin Pokorny, fpokorny@redhat.com # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public Lice...
t your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the...
# #################################################################### import sys from threading import Lock from service import Service class StorageService(Service): @classmethod def on_startup(cls, config, system_json): # TODO: config is not accessible when local cls._system = None # We ...
def I(x, y, z): return y ^ (x | (~z)) def XX(func, a, b, c, d, x, s, ac): """Wrapper for call distribution to functions F, G, H and I. This replaces functions FF, GG, HH and II from "Appl. Crypto." Rotation is separate from addition to prevent recomputation (now summed-up in one function). "...
p[ 7], S23, r_uint(0x676F02D9L)) # 31 b = XX(G, b, c, d, a, inp[12], S24, r_uint(0x8D2A4C8AL)) # 32 # Round 3. S31, S32, S33, S34 = 4, 11, 16, 23 a = XX(H, a, b, c, d, inp[ 5], S31, r_uint(0xFFFA3942L)) # 33 d = X
X(H, d, a, b, c, inp[ 8], S32, r_uint(0x8771F681L)) # 34 c = XX(H, c, d, a, b, inp[11], S33, r_uint(0x6D9D6122L)) # 35 b = XX(H, b, c, d, a, inp[14], S34, r_uint(0xFDE5380CL)) # 36 a = XX(H, a, b, c, d, inp[ 1], S31, r_uint(0xA4BEEA44L)) # 37 d = XX(H, d, a, b, c, inp[ 4], S32, r_uin...
import sqlite3 import directORM class Proveedor: def __init__(self): self.idProveedor = -1 self.nombre = '' self.email = '' self.tlf_fijo = '' self.tlf_movil = '' self.tlf_fijo2 = '' self.tlf_movil2 = '' self.banco = '' self.cuenta_bancaria ...
t nombre = ?, email = ?, tlf_fijo = ?, tlf_movil = ?, tlf_fijo2 = ?, tlf_movil2 = ?, banco = ?, cuenta_bancaria = ?, direccion = ?, foto_logo = ? where idProveedor = ? ''' def __init__(self): self.gestorDB = d...
ETE self.gestorDB.ejecutarSQL(sql, (proveedor.idProveedor)) def get_proveedor(self, idProveedor=None): sql = self.SELECT + " where idProveedor=" + str(idProveedor) +";" fila = self.gestorDB.consultaUnicaSQL(sql) if fila is None: return None else: o =...
def hsd_inc_beh(rxd, txd): '''| | Specify the be
havior, describe data process
ing; there is no notion | of clock. Access the in/out interfaces via get() and append() | methods. The "hsd_inc_beh" function does not return values. |________''' if rxd.hasPacket(): data = rxd.get() + 1 txd.append(data)
ec,"XXX",bd) replace(fnameh,"ZZZ",tc) replace(fnameh,"YYY",tf) replace(fnameh,"XXX",bd) run_in_shell("gcc -O3 -std=c99 -c "+fnamec) replace("arch.h","@WL@","64") print("Elliptic Curves") print("1. ED25519") print("2. C25519") print("3. NIST256") print("4. BRAINPOOL") print("5. ANSSI") print("6. HIFIVE") pr...
6. NUMS512E") print("17. SECP256K1\n") print("Pairing-Friendly Elliptic Curves") print("18. BN254") print("19. BN254CX") print("20. BLS383") print("21. BLS381") print("22. FP256BN") print("23. FP512BN") print("24. BLS461\n") print("25. BLS24") print("26. BLS48\n") print("RSA") print("27. RSA2048") print("28. RSA3072"...
curve_selected=False rsa_selected=False while ptr<max: x=int(input("Choose a Scheme to support - 0 to finish: ")) if x == 0: break # print("Choice= ",x) already=False for i in range(0,ptr): if x==selection[i]: already=True break if already: continue selection.append(x) ptr=ptr+1 # curveset(big,fie...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Btc plugin for Varas Author: Neon & A Sad Loner Last modified: November 2016 """ import urllib2 from plugin import Plugin name = 'Bitcoin' class Bitcoin(Plugin)
: def __init__(self): Plugin.__init__(self,"bitcoin","<wallet> Return current balance from a Bitcoin wallet","A Sad Loners",1.0) def run(self,address): #1btc = 100000000satoshi print "https://blockchain.info/it/q/addressbalance/"+address try: api = urllib2.urlopen("https://b...
satoshi = float(resp) btc = satoshi/100000000 return "Balance: " + str(btc)
from logging import getLogger from vms.models import Dc, DummyDc logger = getLogger(__name__) class DcMiddleware(object): """ Attach dc attribute to each request. """ # noinspection PyMethodMayBeStatic def process_request(self,
request): dc = getattr(request, 'dc', None) if not dc or dc.is_dummy: if request.path.startswith('/api/'): return # Managed by ExpireTokenAuthentication and request_data decorator if request.user.is_authenticated(): # Set requ
est.dc for logged in user request.dc = Dc.objects.get_by_id(request.user.current_dc_id) # Whenever we set a DC we have to set request.dc_user_permissions right after request.dc is available request.dc_user_permissions = request.dc.get_user_permissions(request.user) ...
""" Example of using cwFitter to generate a HH model for EGL-19 Ca2+ ion channel Based on experimental data from doi:10.1083/jcb.200203055 """ import os.path import sys import time import numpy as np import matplotlib.pyplot as plt sys.path.append('../../..') from channelworm.fitter import * if __name__ == '__main__...
uator.iv_cost(popt) print 'IV cost:' print IV_fit_cost if 'VClamp' in sampleData: VClamp_fit_cost = myEvaluator.vclamp_cost(popt) print 'VClamp cost:' print VClamp_fit_cost ...
= np.arange(-0.040, 0.080, 0.001) Iopt = mySimulator.iv_act(vData,*popt) plt.plot([x*1 for x in bestSim['V_ss']],bestSim['I_ss'], label = 'Initial parameters', color='y') plt.plot([x*1 for x in sampleData['IV']['V']],sampleData['IV']['I'], '--ko', label = 'sa...
# -*- coding: utf-8 -*- # 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 ...
nder 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. import six from tempest_lib import exceptions as lib_exc from tempest.api.bare...
ls from tempest import test class TestChassis(base.BaseBaremetalTest): """Tests for chassis.""" @classmethod def resource_setup(cls): super(TestChassis, cls).resource_setup() _, cls.chassis = cls.create_chassis() def _assertExpected(self, expected, actual): # Check if not exp...
"" @property def username(self): netloc = self.netloc if "@" in netloc: userinfo = netloc.rsplit("@", 1)[0] if ":" in userinfo: userinfo = userinfo.split(":", 1)[0] return userinfo return None @property def password(self): ...
rse_cache[key] = v return v for c in url[:i]: if c not in scheme_chars: break else: try: # make sure "url" is not actually a port number (in which case # "scheme" is really part of t
he path _testportnum = int(url[i+1:]) except ValueError: scheme, url = url[:i].lower(), url[i+1:] if url[:2] == '//': netloc, url = _splitnetloc(url, 2) if (('[' in netloc and ']' not in netloc) or (']' in netloc and '[' not in netloc)): ...
# plugins module for amsn2 """ Plugins with amsn2 will be a subclass of the a
MSNPlugin() class. When this module is initially imported it should load the plugins from the last session. Done in the init() proc. Then the GUI should call plugins.loadPlugin(name) or plugins.unLoadPlugin(name) in order to deal with plugins. """ # init() # Called when the plugins module is imported (only for the fir...
e a list ready for getPlugins(). # Should also auto-update all plugins. def init(): pass # loadPlugin(plugin_name) # Called (by the GUI or from init()) to load a plugin. plugin_name as set in plugin's XML (or from getPlugins()). # This loads the module for the plugin. The module is then responsible for calling plugins...
# # gPrime - A web-based genealogy program # # Copyright (C) 2008 Brian G. Matherly # # 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 ) any later ...
Option from ._string import StringOption from ._color import ColorOption from ._number import NumberOption from ._text import TextOption from ._boolean import BooleanOption from ._enumeratedlist import EnumeratedListOption from ._f
ilter import FilterOption from ._person import PersonOption from ._family import FamilyOption from ._note import NoteOption from ._media import MediaOption from ._personlist import PersonListOption from ._placelist import PlaceListOption from ._surnamecolor import SurnameColorOption from ._destination import Destinatio...
# Copyright (c) Mathias Kaerlev 2012. # This file is part of Anaconda. # Anaconda 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. # ...
ceived a copy of the GNU General Public License # along with Anaconda. If not, see <http://www.gnu.org/li
censes/>. from mmfparser.data.chunkloaders.actions.names import *
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ """Wordcount exercise Google's Python class The main() below is already defined and comp...
word = word.lower() if word in word_dict: value = word_dict.get(word) word_dict[word] = value+1 else: word_dict[wo
rd] = 1 file.close() return word_dict def print_words(filename): word_dict = parse_file(filename) keys = sorted(word_dict.keys()) for key in keys: print key,word_dict[key] def print_top(filename): word_dict = parse_file(filename) top_list = sorted(word_dict.items(),key=value_sort,r...
elf.x95m_iptn = {} self.x97m_ptn = [] self.x97m_iptn = {} self.w95m_ptn = [] self.w95m_iptn = {} self.w97m_ptn = [] self.w97m_iptn = {} self.__signum__ = 0 self.__date__ = 0 self.__time__ = 0 ...
data) : ret = None try :
mac_data = ExtractMacroData_W95M(data) if mac_data == None : raise SystemError for data in mac_data : hash_data = GetMD5_Macro(data, W95M) ret = self.__ScanVirus_Macro_ExpendDB__(hash_data, W95M) if ret != None : return ret except : ...
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this fil
e. import os #Functions for manipulating datetime objects #CCYY-MM-DDThh:mm:ssZ def parseDateClass(s): year, month, day = s.split("-") day, tail = day[:2], day[2:] hour, minute, second = t
ail[1:].split(":") second = second[:2] year, month, day = int(year), int(month), int(day) hour, minute, second = int(hour), int(minute), int(second) return createDateClass(year, month, day, hour, minute, second) if os.name != "java": from datetime import datetime, timedelta #Helper ...
#!/usr/bin/env python #-*- coding: UTF-8 -*- from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import subprocess, time last_ch = 0 class TvServerHandler(BaseHTTPRequestHandler): def do_GET(self): global last_ch cmd = self.path.split('/') if 'favicon.ico' in cmd: return ...
e(301) self.send_header("Location", "http://<your ip>:8484?t=%f" % time.time()) self.end_headers() return def do_POST(self): pass return def main(): try: server = HTTPServer(('',8485),TvServerHandler) print 'server started' server.serve_forever() except K...
n()
import kivy kivy.require('1.9.1') from kivy.uix.label import Label from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.uix.scatter import Scatter from kivy.app import Builder from kivy.metrics import dp from kivy.graphics import Color, Line from autosportlabs.racecapture.geo.geopoint i...
__init__(self, **kwargs): super(RaceTrackView, self).__init__(**kwargs) def loadTrack(self, track): self.initMap(track) def initMap(self, track): self.ids.trackmap.setTrackPoints(track.map_points) def remove_reference_mark(self, key): self.ids.trackmap.remove_marker(key) ...
def add_reference_mark(self, key, color): trackmap = self.ids.trackmap if trackmap.get_marker(key) is None: trackmap.add_marker(key, color) def update_reference_mark(self, key, geo_point): self.ids.trackmap.update_marker(key, geo_point) def add_map_path(self, key, path, ...
import unittest from sikuli import * from java.awt.event import KeyEvent from javax.swing import JFrame not_pressed = True WAIT_TIME = 4 def pressed(event): global not_pressed not_pressed = False print "hot
key pressed! %d %d" %(event.modifiers,event.keyCode) class TestHotkey(unittest.TestCase): def testAddHotkey(self): self.assertTrue(Env.addHotkey(Key.F6, 0, pressed)) def testAddHotkeyReal(self): #f = JFrame("hello") global not_pressed Env.addHotkey(Key.F6, 0, pressed)
self.assertTrue(not_pressed) count = 0 while not_pressed and count < WAIT_TIME: count += 1 wait(1) keyDown(Key.F6) keyUp(Key.F6) self.assertFalse(not_pressed) #f.dispose() def testRemoveHotkey(self): self.assertFalse(Env.removeHotkey(Key.F7, 0)) ...
from jsonrpc import ServiceProxy import sys import string # ===== BEGIN USER SETTINGS ===== # if you do not set these you will be prompted for a password for every command rpcuser = "" rpcpass = "" # ====== END USER SETTINGS ====== if rpcpass == "": access = ServiceProxy("http://127.0.0.1:22713") else: access = Se...
mount:") comment = raw_input("Comment (optional): ") commentto = raw_input("Comment-to (optional): ") try: print access.sendtoaddress(to,amt,comment,commentto) except: print access.sendtoaddress(to,amt) except: print "\n---An error occurred---\n
" elif cmd == "setaccount": try: addr = raw_input("Address: ") acct = raw_input("Account:") print access.setaccount(addr,acct) except: print "\n---An error occurred---\n" elif cmd == "setgenerate": try: gen= raw_input("Generate? (true/false): ") cpus = raw_input("Max processors/cores (-1 for unlimited,...
# -*- coding: utf-8 -*- import os """ Illustration d'un exercice de TD visant à montrer l'évolution temporelle de la densité de probabilité pour la superposition équiprobable d'un état n=1 et d'un état n quelconque (à fixer) pour le puits quantique infini. Par souci de simplicité, on se débrouille pour que E_1/hbar...
nimation # Pour l'animation progressive # Second état n observer (à fixer) n = 2 # On met tous les paramètres à 1 (ou presque) t0 = 0 dt = 0.1 L = 1 hbar = 1 h = hbar * 2 * np.pi m = (2 * np.pi)**2 E1 = h**2 / (8 * m * L**2) En = n * E1 x = np.linspace(0, L, 1000) def psi1(x, t): return np.sin(np.pi * x / L) ...
bar) def psin(x, t): return np.sin(n * np.pi * x / L) * np.exp(1j * En * t / hbar) def psi(x, t): return 1 / L**0.5 * (psi1(x, t) + psin(x, t)) fig = plt.figure() line, = plt.plot(x, abs(psi(x, t0))**2) plt.title('$t={}$'.format(t0)) plt.ylabel('$|\psi(x,t)|^2$') plt.xlabel('$x$') plt.plot(x, abs(psi1(x, t...
from __future__ import unicode_literals, division, absolute_import import re from argparse import ArgumentParser, ArgumentTypeError from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from flexget import options from flexget.event import event from flexget.terminal import TerminalTable, Te...
[regexp.regexp or ''] table_data.append(regexp_row) try: table = TerminalTable(options.table_type, table_data) console(table.output) except TerminalTableError as e: console('ERROR: %s' % str(e)) def action_add(options): with Session() as session: regexp_list = d...
nd regexp list with name {}, creating'.format(options.list_name)) regexp_list = db.create_list(options.list_name, session=session) regexp = db.get_regexp(list_id=regexp_list.id, regexp=options.regexp, session=session) if not regexp: console("Adding regexp {} to list {}".format(o...
# -*- coding: utf-8 -*- from __future__ import unicode_lite
rals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('flyerapp', '0007_auto_20150629_1135'), ] operations = [ migrations.AddField( model_name='schedule', name='l
ogic_delete', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='flight', name='pub_date', field=models.DateTimeField(default=datetime.datetime(2015, 6, 30, 18, 59, 57, 180047), null=True, verbose_name=b'date published'), ...
from __future__ import unicode_literals from django.apps import AppConfig class ApplicationsConfig(AppConfig): name = 'applications' def ready(self): super(ApplicationsConfig, self).ready() from applications.signals import create_draft_application, clean_dra
ft_application, \ auto_delete_file_on_change, auto_delete_file_on_delete create_draft_application clean_draft_application auto_delete_file_on_change auto_delete_file_on_d
elete
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publi...
g_modifiers(effect): if effect.modifiers: msg = 'drone self skillreq dmg effect has modifiers, overwriting them' logger.warning(msg) effect.modifiers = make_drone_dmg_modifiers() effect.build_status = EffectBuildStatus.custom EffectFactory.register_instance_by_id( add_missile_rof_modif...
stance_by_id( add_missile_dmg_modifiers_therm, EffectId.missile_therm_dmg_bonus) EffectFactory.register_instance_by_id( add_missile_dmg_modifiers_kin, EffectId.missile_kin_dmg_bonus2) EffectFactory.register_instance_by_id( add_missile_dmg_modifiers_expl, EffectId.missile_expl_dmg_bonus) EffectFa...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Tuxemon # Copyright (C) 2014, William Edwards <shadowapex@gmail.com>, # Benjamin Bean <superman2k5@gmail.com> # # This file is part of Tuxemon. # # Tuxemon 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. # # Tuxemon is distributed in the hope that
it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Tuxemon. If not, see <http://www.gnu.org...
from django.db import models from django.core.urlresolvers import reverse from jsonfield import JSONField impo
rt collections # Create your models here. class YelpvisState(models.Model): title=models.CharField(max_length=255) slug=models.SlugField(unique=True,max_length=255) description = models.CharField(max_length=255) content=models.TextField() published=models.BooleanField(default=True) created=models.DateTimeField(...
ng = ['-created'] def __unicode__(self): return u'%s' % self.title def get_absolute_url(self): return reverse('blog:post', args=[self.slug]) class YelpvisCommentState(models.Model): content=models.TextField() pub_date = models.DateTimeField(auto_now_add=True) vis_state = JSONField() class Meta...
# coding=UTF-8 # Author: Dennis Lutter <lad1337@gmail.com> # # This file is part of Medusa. # # Medusa 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...
self).setUp()
self.db = test.db.DBConnection() def select(self): """Select from the database.""" self.db.select("SELECT * FROM tv_episodes WHERE showid = ? AND location != ''", [0000]) def test_threaded(self): """Test multi-threaded selection from the database.""" for _ in range(4): ...
# Copyright 2014 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
BUFFER = BytesIO() BUFFER.write(
BYTES_TO_SIGN) BUFFER.seek(0) SIGNED_CONTENT = self._call_fut(BUFFER) self.assertEqual(SIGNED_CONTENT, b'kBiQqOnIz21aGlQrIp/r/w==') def test_it_with_stubs(self): import mock class _Buffer(object): def __init__(self, return_vals): self.return_va...
#!/usr/bin/env p
ython3 # -*- coding: utf-8 -*- # @Date : 2017/10/18 17:13 # @Author : xxc727xxc (xxc727xxc@foxmail.com) # @Version
: 1.0.0 if __name__ == '__main__': pass
s.PROTECT', 'to': u"orm['physical.DiskOffering']"}), 'endpoint': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'endpoint_dns': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'engi...
lated.ForeignKey', [], {'related_name': "u'engines'", 'on_delete': 'models.PROTECT', 'to': u"orm['physical.EngineType']"}), 'engine_upgrade_option': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "u'backwards_engine'",
'null': 'True', 'on_delete': 'models.SET_NULL', 'to': u"orm['physical.Engine']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'path': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'template_name': (...
from pymacaron.log
import pymlogger import multiprocessing from math import ceil from pymacaron.config import get_config log = pymlogger(__name__) # Calculate resources available on this container hardware. # Used by pymacaron-async, pymacaron-gcp and pymacaron-docker def get_gunicorn_worker_count(cpu_count=None): """Return the...
t * 2 + 1 return multiprocessing.cpu_count() * 2 + 1 def get_celery_worker_count(cpu_count=None): """Return the number of celery workers to run on this container hardware""" conf = get_config() if hasattr(conf, 'worker_count'): # Start worker_count parrallel celery workers return conf....
# # This file is part of Plinth. # # 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 Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distribute...
return TemplateResponse( request, 'help_manual.html', {'title': _('{box_na
me} Manual').format(box_name=_(cfg.box_name)), 'content': content}) def status_log(request): """Serve the last 100 lines of plinth's status log""" num_lines = 100 with open(cfg.status_log_file, 'r') as log_file: data = log_file.readlines() data = ''.join(data[-num_lines:]) contex...
an 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 distributed in the hope that it will be useful, # but...
ist, or one list more than once def __add__(self, other): raise NotImpleme
ntedError def __radd__(self, other): raise NotImplementedError def __imul__(self,other): raise NotImplementedError def __mul__(self, other): raise NotImplementedError def __rmul__(self,other): raise NotImplementedError # only works if other is not also a Container ...
# View more python tutorial on my Youtube and Youku channel!!! # Youtube video tutorial: https://www.youtube.com/channel/UCd
yjiB5H8Pu7aDTNVXTTpcg # Youku video tutorial: http://i.youku.com/pythontutorial """ Please note, this code is only for python 3+. If you are using python 2+
, please modify the code accordingly. """ from __future__ import print_function import tensorflow as tf import numpy as np # create data x_data = np.random.rand(100).astype(np.float32) y_data = x_data*0.1 + 0.3 ### create tensorflow structure start ### ### create tensorflow structure end ### # Very importa...
nd(os.path.abspath("../")) import utils template_png='algorithms/inputFields/template.png' amount_input_png='algorithms/inputFields/amount_template.png' date_input_png='algorithms/inputFields/date_template.png' def searchTemplateCenterPointIn(check, template, searchMap, step=1, threshold=-9999999): fromIndex = ...
[1] - template.shape[1] / 2)] radios = [int(template.shape[0] / 2), int(template.shape[1] / 2)] maxConv = threshold maxCenterConv = [0, 0] for centerConvX in range(fromIndex[0], toIndex[0]): for centerConvY in range(fromIndex[1], toIndex[1]): if searchMap[centerConvX, centerConvY]...
%2, centerConvY - radios[1]:centerConvY + radios[1] + template.shape[1]%2] \ * template conv = np.sum(convMatrix) if maxConv < conv: maxConv = conv maxCenterConv = [centerConvX, centerConvY]...
import sys import os.path import re import time from docutils import io, nodes, statemachine, utils try: from docutils.utils.error_reporting import ErrorString # the new way except ImportError: from docutils.error_reporting import ErrorString # the old way from docutils.parsers.rst import Directive, con...
lines = ['<div class="ipynotebook">'] lines.append(header) lines.append(body) lines.append('</div>') text = '\n'.join(lines) # add dependency self.state.document.settings.record_dependencies.add(nb_path) attributes['source'
] = nb_path # create notebook node nb_node = notebook('', text, **attributes) (nb_node.source, nb_node.line) = \ self.state_machine.get_source_and_line(self.lineno) return [nb_node] class notebook(nodes.raw): pass def visit_notebook_node(self, node): self.visit_...
# Problem 28 # Starting with the number 1 and moving to the right in a clockwise direction a 5 by 5 spiral is formed as follows: # # 21 22 23 24 25 # 20 7 8 9 10 # 19 6 1 2 11 # 18 5 4 3 12 # 17 16 15 14 13 # # It can be verified that the sum of the numbers on the diagonals is 101. # # What is the sum of the n...
r all iterations # start the offsets off with a minimal value row_offset = 0 col_offset = 0 # working variables, these will be used to keep track of the current positione candidate_col = starting_point candidate_row = starting_point my_
grid[candidate_row][candidate_col] = grid_value grid_value += 1 # this seeds the center of our spiral while not grid_filled: try: if current_direction == fill_directions.right and my_grid[candidate_row][candidate_col + 1] == 0: candidate_col += 1 # offset by one column if my_g...
guage import Tools.Notifications class png2yuvTask(Task): def __init__(self, job, inputfile, outputfile): Task.__init__(self, job, "Creating menu video") self.setTool("png2yuv") self.args += ["-n1", "-Ip", "-f25", "-j", inputfile] self.dumpFile = outputfile self.weighting = 15 def run(self, callback): ...
rncodePostcondition in this case because for right now we're just gonna ignore the fact that mplex fails with a buffer underrun error on some streams (this always at the very end) def prepare(self): self.error = None if self.demux_task: self.args += s
elf.demux_task.mplex_streamfiles def processOutputLine(self, line): print("[MplexTask] ", line[:-1]) if line.startswith("**ERROR:"): if line.find("Frame data under-runs detected") != -1: self.error = self.ERROR_UNDERRUN else: self.error = self.ERROR_UNKNOWN class RemoveESFiles(Task): def __init__...
# Copyright 2022 The Magenta Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
lags.config_from_flags() pipeline_insta
nce = improv_rnn_pipeline.get_pipeline( config, FLAGS.eval_ratio) FLAGS.input = os.path.expanduser(FLAGS.input) FLAGS.output_dir = os.path.expanduser(FLAGS.output_dir) pipeline.run_pipeline_serial( pipeline_instance, pipeline.tf_record_iterator(FLAGS.input, pipeline_instance.input_type), ...
'''This allows running a bit of code on couchdb docs. code should take a json python object, modify it and hand back to the code Not quite that slick yet, need way to pass in code or make this a decorator ''' import importlib from harvester.collection_registry_client import Collection from harvester.couchdb_init import...
_type'] else: doc['s
ourceResource']['collection'] = doc['originalRecord']['collection'] return doc
#!python from __future__ import with_statement from __future__ import division from __future__ import absolute_import from __future__ import print_function import pandas as pd import wordbatch.batcher def decorator_apply(func, batcher=None, cache=None, vectorize=None): def wrapper_func(*args, **kwargs): return Appl...
input_split, merge_output, minibatch_size, bat
cher) def transform(self, data, input_split=False, merge_output=True, minibatch_size=None, batcher=None): if batcher is None: batcher = self.batcher return batcher.process_batches(batch_transform, data, [self.function] + self.args + self.kwargs + self.cache + self.vectorize, ...
import os #os.system("python D:\prog\python_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l -s --type pdf D:\m_\\ecPro\pacal\\trunk\pacal\\examples\\functions.py") #os.system("python D:\prog\python_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l -s --type pdf D:\m_\\ecPro\pacal\\trunk\pacal\\examples\\how_to_...
.3.4c\pyreport\pyreport.py -e -l --type pdf D:\\m_\\ecPro\\pacal\\trunk\\pacal\\examples\\springer_book\\Chapter4_products.py") #os.system("D:\\prog\\Python27\\python D:\prog\python_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l --type pdf D:\\m_\\ecPro\\pacal\\trunk\\pacal\\examples\\springer_book\\Chapter5_func...
yreport\pyreport.py -e -l --type pdf D:\\m_\\ecPro\\pacal\\trunk\\pacal\\examples\\springer_book\\Chapters678.py") #os.system("D:\\prog\\Python27\\python D:\prog\python_packages\pyreport-0.3.4c\pyreport\pyreport.py -e -l --type pdf D:\\m_\\ecPro\\pacal\\trunk\\pacal\\examples\\springer_book\\Chapter9_applications.py")...
e # 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. # ======================================================================...
_shape, use_explicit_padding=False, use_keras=False) self.check_extract_features_returns_correct_shape( 2, image_height, image_width, depth_multiplier, pad_to_multiple, expected_feature_map_shape, use_explicit_padding=True, use_keras=False) def test_extract_features_with_dynamic_i...
(2, 8, 8, 256), (2, 4, 4, 256), (2, 2, 2, 256)] self.check_extract_features_returns_correct_shapes_with_dynamic_inputs( 2, image_height, image_width, depth_multiplier, pad_to_multiple, expected_feature_map_shape, use_explicit_padding=Fa...
# -*
- coding: utf-8 -*- """ rio.blueprints.api_1 ~~~~~~~~~~~~~~~~~~~~~ """ from flask import Blueprint bp = Blueprint('api_1',
__name__)
from .base impor
t * DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' try: from .local import * except ImportError: pass MIDDLEWARE_CLASSES += [ 'debug_toolba
r.middleware.DebugToolbarMiddleware', ]
# -*- coding: utf-8 -*- ############################################################################### # # Base64Encode # Returns the specified text or file as a Base64 encoded string. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License");...
he URL input for this Choreo. ((conditional, string) A URL to a hosted file that should be Base64 encoded. Required unless providing a value for the Text input.) """ super(Base64EncodeInputSet, self)._set_input('URL', value) class Base64EncodeResultSet(ResultSet): """ A ResultSet with methods t...
o execution. """ def getJSONFromString(self, str): return json.loads(str) def get_Base64EncodedText(self): """ Retrieve the value for the "Base64EncodedText" output from this Choreo execution. ((string) The Base64 encoded text.) """ return self._output.get('Base64En...
"""Define statements for retrieving the data for each of the types.""" CONSTRAINTS = """ select o.owner, o.constraint_name, o.constraint_type, o.table_name, o.search_condition, o.r_owner, o.r_constraint_name, o.delete_rule, ...
der by o.owner, o.library_name""" LOBS = """ select o.owner, o.column_name, o.table_name, o.segment_name, o.in_row from %(p_ViewPrefix)s_lobs o %(p_WhereClause)s order by o.column_name""" ROLES = """ select o.role, ...
o.sequence_owner, o.sequence_name, to_char(min_value), to_char(max_value), to_char(increment_by), cycle_flag, order_flag, to_char(cache_size), to_char(last_number) from %(p_ViewPrefix)s_sequences o %(p_WhereClause)s ...
#!/usr/bin/python # -*- coding: utf-8 -*- class A: #classic class """this is class A""" pass __slots__=('x','y') def test(self):
# classic class test """this is A.test()""" print "A class" class B(object): #new class """this is class B""" __slots__=('x','y') pass def test(self): # new class test """this is B.test()""" print "B class" if __name__ == '__main__': ...
lp(a) #help(b)
"""Classes required to create a Bluetooth Peripheral.""" # python-bluezero imports from bluezero import adapter from bluezero import advertisement from bluezero import async_tools from bluezero import localGATT from bluezero import GATT from bluezero import tools logger = tools.create_module_logger(__name__) class...
y_services.append(uuid) def add_characteristic(self, srv_id, chr_id, uuid, value, notifying
, flags, read_callback=None, write_callback=None, notify_callback=None): """ Add information for characteristic. :param srv_id: integer of parent service that was added :param chr_id: integer between 0 & 9999 as unique reference ...
from django import forms from apps.clientes.models import Cliente from apps.clientes.choices import SEXO_CHOICES import re class ClienteForm(forms.ModelForm): """ Se declaran los campos y atributos que se mostraran en el formulario """ sexo = forms.ChoiceField(choices=SEXO_CHOICES, required=...
dationError("El Email ya esta dado de alta") if not(re.match('^[(a-z0-9\_\-\.)]+@[(a-z0-9\_\-\.)]+\.[(a-z)]{2,15}$', email.lower())): raise forms.ValidationError("No es un email correc
to") return email def clean_direccion(self): """ Valida que la dirección no sea menor a 5 caracteres """ direccion = self.cleaned_data['direccion'] if len(direccion) < 5: raise forms.ValidationError( "Debe de tener un mínimo de...
#!/bin/python3 import sys import os import tempfile import pprint import logging from logging import debug, info, warning, error def process_info(line): line = line.strip() arr = line.split(':') if len(arr) < 2: return None, None key = arr[0] val = None if key == "freq": val = "...
: ssid : {}".format("*" if "associated" in info else " ", bss, info["SSID"])) print(" signal : {}".format(info["signal"])) print(" ...
print(" security : {}".format( "WPA2" if info.get("RSN", False) else "WPA" if info.get("WPA", False) else "WEP" if info.get("Privacy", False) else "None")) def main(): wifi_if = "wlp8s0" if len(sys.argv) == 2: wifi_if = sys.argv[...
"OBJECT_INHERIT": "OI", "CONTAINER_INHERIT": "CI", "NO_PROPAGATE_INHERIT": "NP", "I
NHERIT_ONLY": "IO", "INHERITED": "ID", "SUCCESSFUL_ACCESS": "SA", "FAILED_ACCESS": "FA", } return short_names[self.name] class AC
EType(IntEnum): """ Type of the ACE. """ ACCESS_ALLOWED = 0 ACCESS_DENIED = 1 SYSTEM_AUDIT = 2 SYSTEM_ALARM = 3 ACCESS_ALLOWED_COMPOUND = 4 ACCESS_ALLOWED_OBJECT = 5 ACCESS_DENIED_OBJECT = 6 SYSTEM_AUDIT_OBJECT = 7 SYSTEM_ALARM_OBJECT = 8 ACCESS_ALLOWED_CALLBACK = 9 ACCE...
tr = {} self.dev_type = {} self.pcid = {} self._parser = expat.ParserCreate() self._parser.buffer_size = 102400 self._parser.StartElementHandler = self.start_handler self._parser.CharacterDataHandler = self.data_handler self._parser.EndElementHandler = self.end_...
= "memory" and self.attr["class"] == "memory":
memory = Memory(self.description, self.product, self.vendor, self.version, \ self.slot, self.size) self.dev_type.setdefault((3, "memory"), []).append(memory) elif self.attr["id"].split(":")[0] == "bank" and self.attr["class"] == "memory": bank = Bank(self.description, ...
#!/usr/bin/env python # Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''Unit tests for writers.android_policy_writer''' import os import sys if __name__ == '__main__': sys.path.append(os.path.join(o...
WriterUnitt
estCommon): '''Unit tests to test assumptions in Android Policy Writer''' def testPolicyWithoutItems(self): # Test an example policy without items. policy = { 'name': '_policy_name', 'caption': '_policy_caption', 'desc': 'This is a long policy caption. More than one sentence ' ...
#!/usr/bin/env python # reads data from wind direction thingy (see README) # labe
ls follow those set out in the Wunderground PWS API: # http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol # # SOURCES: # RETURNS: two objects for humidity and temperature # CREATED: 2017-08-02 # ORIGINAL SOURCE: https://github.com/dirtchild/weatherPi [please do not remove this line] # MODIFIED: see https://gi...
from config import * def getReading(): # Choose a gain of 1 for reading voltages from 0 to 4.09V. # Or pick a different gain to change the range of voltages that are read: # - 2/3 = +/-6.144V # - 1 = +/-4.096V # - 2 = +/-2.048V # - 4 = +/-1.024V # - 8 = +/-0.512V # - 16 = +/-0.256V # See table...