prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
""" Django settings for hello project. Generated by 'django-admin startproject' using Django 1.9.5. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os # B...
lates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_process...
}, ] WSGI_APPLICATION = 'example.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangopr...
""" """ from .register import get_registered_layers #custom layer import begins import axpy import flatten import argmax import reshape import roipooling import priorbox import permute import detection_out import normalize import select import crop import reduction #custom layer import ends custom_layers = get_regi...
kwargs[arg_name
] = params[arg_name] if node is not None and len(node.metadata): kwargs.update(node.metadata) return arg_list, kwargs def has_layer(kind): """ test whether this layer exists in custom layer """ return kind in custom_layers def compute_output_shape(kind, node): assert kind in custom...
org']) make_loc(session, name=loc_name, subnets=[subnet_name]) self.location.search(loc_name).click() session.nav.click(tab_locators['context.tab_subnets']) element = session.nav.wait_until_element( (strategy1, value...
self.assertIsNotNone(element) @run_only_on('sat') @tier2 def test_positive_remove_hostgroup(self): """Add a hostgroup and remove it by using the location name and hostgroup name @feature: Locations @assert: hostgroup is added to location then removed """ s...
or host_grp_name in generate_strings_list(): with self.subTest(host_grp_name): loc_name = gen_string('alpha') host_grp = entities.HostGroup(name=host_grp_name).create() self.assertEqual(host_grp.name, host_grp_name) set_cont...
self.assertRaises(ValueError, lambda x: x.choose([]), a) def test_array_ndmin_overflow(self): "Ticket #947." self.assertRaises(ValueError, lambda: np.array([1], ndmin=33)) def test_errobj_reference_leak(self, level=rlevel): """Ticket #955""" with np.errstate(all="ignore"):...
test_record.tobytes()) assert_(test_record_void_scalar == test_record) #Test pickle and unpickle of void and record scalars assert_(pickle.loads(pickle.dumps(test_string)) == test_string) assert_(p
ickle.loads(pickle.dumps(test_record)) == test_record) def test_blasdot_uninitialized_memory(self): """Ticket #950""" for m in [0, 1, 2]: for n in [0, 1, 2]: for k in range(3): # Try to ensure that x->data contains non-zero floats ...
# coding: utf-8 from __future__ import absolute_import # from esm.models.bind_resource import BindResource from .base_model_ import Model from ..util import deserialize_model class BindingRequest(Model): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class ...
lan from the catalog. MUST be a non-empty string. :param plan_id: The plan_id of this BindingRequest. :type plan_id: str """ if plan_id is None: raise ValueError("Invalid value for `plan_id`, must not be `None`") self._plan_id = plan_id @property def servi...
of this BindingRequest. ID of the service from the catalog. MUST be a non-empty string. :return: The service_id of this BindingRequest. :rtype: str """ return self._service_id @service_id.setter def service_id(self, service_id: str): """ Sets the servi...
")[1]) # Exception when the relation's destination is # an individual from the same class if relation["name"] == className: relation["name"] = '"self"' else: ...
# Writes the class in models.py modelsContents.append("\nclass "+ m["className"] +"(models.NodeModel):") # Defines properties and relations that every model have m["properties"].insert(0,
{ "name" : "_author", "type": "IntArrayProperty", # Verbose name "verbose_name": "author", "help_text": "People that edited this entity." } ) m["properties"].insert(1, ...
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 ...
() self.trigger_loop(actor_ids=[self._actor_id]) class TimerHandler(object): def __init__(self, node, actor): super(TimerHandler, self).__init__() self._actor = actor self.node = node def once(self, delay): return TimerEvent(self._actor.id, delay, self.node.sched.trigg...
""" Registers is called when the Event-system object is created. Place an object in the event object - in this case the nodes only timer object. Also register any hooks for actor migration. @TODO: Handle migration (automagically and otherwise.) """ return TimerHandler(n...
import serial ser = serial.Serial('/dev/ttyUSB2',38400) while True: try: x = ser.read() f=open('gesture_command.txt
','w') f.write(x) f.close() exce
pt: print "Gesture serial : port error!" break
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from molo.core.models import ArticlePage, ArticlePageRecommendedSections from wagtail.wagtailcore.blocks import StreamValue def create_recomended_articles(main_article, article_list): ''' Creates recommended arti...
le=article).save() def convert_articles(apps, schema_editor):
''' Derived from https://github.com/wagtail/wagtail/issues/2110 ''' articles = ArticlePage.objects.all().exact_type(ArticlePage) for article in articles: stream_data = [] linked_articles = [] for block in article.body.stream_data: if block['type'] == 'page': ...
e necessary logic. return field_list = [name for (name, value) in attrs.items() if (value.get('required_by_policy') or value.get('primary_key') or 'default' not in value)] plugin = manager.NeutronManager.get_plugin_for_resource(collection) if p...
pluralized=collection))] ex
cept oslo_policy.PolicyNotAuthorized: # This exception must be explicitly caught as the exception # translation hook won't be called if an error occurs in the # 'after' handler. Instead of raising an HTTPNotFound exception, # we have to set the status_code here to preven...
""" ==================== Breadth-first search ==================== Basic algorithms for breadth-first searching the nodes of a graph. """ import networkx as nx from collections import defaultdict, deque __author__ = """\n""".join(['Aric Hagberg <aric.hagberg@gmail.com>']) __all__ = ['bfs_edges', 'bfs_tree', 'bfs_prede...
e for breadth-first search and return ed
ges in the component reachable from source. reverse : bool, optional If True traverse a directed graph in the reverse direction Returns ------- T: NetworkX DiGraph An oriented tree Examples -------- >>> G = nx.Graph() >>> G.add_path([0,1,2]) >>> print(list(nx....
# Performs network checks from subprocess import Popen, PIPE from includes.output import * class FirewallChecks: # Constructor def __init__(self, uuid = None): # if uuid == None then check the host self.uuid = uuid def checkIpfwRule(self, permission, fromIP, toIP, toPort, direction): ...
lf, tableNum, value): cmd = ['ipfw', 'table',str(tableNum), 'list'] # add the jexec command if we're dealing with a container if (self.uuid is not None): cmd = ['jexec', 't
rd-' + self.uuid] + cmd process = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdOut, stdErr = process.communicate() stdOutString = stdOut.decode('utf-8') stdErrString = stdErr.decode('utf-8') if (process.returncode != 0): e_error("Failed to check ipfw table")...
InstrumentedAttribute.""" accepts_scalar_loader = True uses_objects = False supports_population = True collection = False __slots__ = '_replace_token', '_append_token', '_remove_token' def __init__(self, *arg, **kw): super(ScalarAttributeImpl, self).__init__(*arg, **kw) self....
VE_OFF): if self.key in dict_: return History.from_object_attribute(self, state, dict_[self.key]) else: if passive & INIT_OK: passive ^= INIT_OK current = self.get(state, dict_, passive=passive) if current is PASSIVE_NO_RESULT: ...
urrent) def get_all_pending(self, state, dict_, passive=PASSIVE_NO_INITIALIZE): if self.key in dict_: current = dict_[self.key] elif passive & CALLABLES_OK: current = self.get(state, dict_, passive=passive) else: return [] # can't use __hash__(),...
from django.test import TestCase from manager.models import Page from datetime import datetime, timedelta from django.utils import timezone class PageTestCase(TestCase): def setUp(self): now = timezone.now() Page.objects.create(url="testurl", description="test description") def test_regular_page_...
ast
is active.""" page = Page.objects.get(url="/testurl") page.paused_at = timezone.now() - timedelta(hours=48) self.assertFalse(page.is_paused()) self.assertTrue(page.is_active()) page.paused_at = timezone.now() morning = timezone.now().replace(hour=6) self.asser...
ne # Set from REDTabSettings self.script_manager = None # Set from REDTabSettings self.image_version = None # Set from REDTabSettings self.service_state = None # Set from REDTabSettings self.brickd_conf = {} self.cbox_brickd_ll.addItem('Error') self.cbox_brickd_ll.add...
t): red_file.release() if result and result.data is not None: self.brickd_conf = config_parser.parse(result.data.decode('utf-8')) self.update_brickd_widget_data() else:
QMessageBox.critical(get_main_window(), 'Settings | Brick Daemon', 'Error reading brickd config file.') self.brickd_button_refresh_enabled(True) self.brickd_button_save_enabled(False) red_...
# -*- coding: utf-8 -*- """ Created on Wed Aug 17 05:52:09 2016 @author: hclqaVirtualBox1 """ from object_test import session import random import string import model test_page = model.Page() N = 5 test_page.title = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N)) test...
he pageid field contained the value 1 # so that the comment was associated with the correct page via a foreign key. # # The Object-Relational API provides a much better approach: #""" # #comment1 = model.Comment() #comment1.name= u'James' #comment1.email = u'james@example.com' #comment1.conte
nt = u'This page needs a bit more detail ;-)' #comment2 = model.Comment() #comment2.name = u'Mike' #comment2.email = u'mike@example.com' #page.comments.append(comment1) #page.comments.append(comment2) #session.commit()
#!/usr/bin/env python ################################################################################################## ## mtrecv.py ## ## Receive message via RockBLOCK over serial ####################################################################################
############## import sys import os from rbControl import RockBlockControl if __name__ == '__main__': if len(sys.argv) == 1: # TODO: configurable serial device RockBlockControl("/dev/ttyUSB0").mt_recv() else: print "usage: %s" % os.path.basename
(sys.argv[0]) exit(1)
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP 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 # ...
. If not, see <http://www.gnu.org/licenses/>. from scap.Model import Model import logging logger = logging.getLogger(__name__) class EndorsementLineCodeType(Model): MODEL_MAP = { 'tag_name': 'EndorsementLineCode', 'attributes': { 'Type': {}, 'Code': {}, # from grPostal ...
.STOCK_ADD) self.widgets['splitSubsTB'] = Gtk.ToolButton() self.widgets['splitSubsTB'].set_tooltip_text('Split Subtitle') self.widgets['splitSubsTB'].set_stock_id(Gtk.STOCK_CUT) self.widgets['visualSyncTB'] = Gtk.ToolButton() self.widgets['visualSyncTB'].set_tooltip_text('Visual ...
CM-StartTime'].set_active(True) self.widgets['HCM-StopTime'].set_active(True) self.widgets['HCM-Duration'].set_active(True) self.widgets['HCM-Reference'].set_active(True) self.widgets['HCM-RS'].set_active(True) self.widgets['HCM-Count'].set_active(True) self.widgets['HCM-...
self.widgets['HCM-Duration'].show() self.widgets['HCM-Reference'].show() self.widgets['HCM-RS'].show() self.widgets['HCM-Count'].show() self.widgets['HCM-Info'].show() # TreeView Context Menu self.widgets['TVContextMenu'] = Gtk.Menu() self.widgets['TVCM-Delete']...
""" Django settings for myproject project. Generated by 'django-admin startproject' using Django 1.9.5. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os ...
'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', ...
import asyncio import unittest import random from gremlinpy import Gremlin from . import ConnectionTestCases, EntityTestCas
es, MapperTestCases from gizmo import Mapper, Request, Collection, Vertex, Edge from gizmo.mapper import EntityMapper class BaseTests(unittest.TestCase): def setUp(self): self.request = Request('localhost', port=8182) self.gremlin = Gremlin('gizmo_testing') self.mapper = Mapper(self.re
quest, self.gremlin) self.ioloop = asyncio.get_event_loop() super(BaseTests, self).setUp() def tearDown(self): super(BaseTests, self).tearDown() async def purge(self): script = "%s.V().map{it.get().remove()}" % self.gremlin.gv res = await self.mapper.query(script=scrip...
from yajuu.extractors.extractor import Extractor from yajuu.media.sources.source_list import SourceList class SeasonExtractor(Extractor): def __init__(self, media, season, range_): super().__init__(media) self.seasons = {} self.season = season self.start, self.end = range_ ...
source(self, identifier, source): if
identifier not in self.sources: self.sources[identifier] = SourceList() self.sources[identifier].add_source(source) return True def _add_sources(self, identifier, sources): returned = [] if sources is None: return for source in sources: ...
# -*- coding: utf-8 -*- # # Copyright (C) 2009 Uninett AS # # This file is part of Network Administration V
isualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under the # terms of the GNU General Public License version 3 as published by the Free # Software Foundation. #
# 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 GNU General Public # License along wit...
gamma = 1j*npy.ones(len(freq)) , z0 = 50*npy.ones(len(freq)), ) self.assertEqual(a.line(1),a.line(1)) with self.assertRaises(NotImplementedError): a.npoints=4 def test_write_csv(self): fname = ...
most_equal(ntw.a[:,0,1], Rs) npy.testing.assert_array_almost_equal(ntw.a[:,1,0], 1.0/Rp) npy.testing.assert_array_almost_equal(ntw.a[:,1,1], 1.0) def test_abcd_thru(self): """ Thru has ABCD ma
trix of the form: [ 1 0 ] [ 0 1 ] """ ntw = self.dummy_media.thru() npy.testing.assert_array_almost_equal(ntw.a[:,0,0], 1.0) npy.testing.assert_array_almost_equal(ntw.a[:,0,1], 0.0) npy.testing.assert_array_almost_equal(ntw.a[:,1,0], 0.0) npy.testing.ass...
#!/usr/bin/env python """Tests for API call routers.""" from absl import app from grr_response_core.lib.rdfvalues import structs as rdf_structs from grr_response_core.lib.util import compatibility from grr_response_proto import tests_pb2 from grr_response_server import access_control from grr_response_server.gui impo...
) with self.assertRaises(access_control.UnauthorizedAccess): router.SearchClients(None) class ApiSingleStringArgument(rdf_structs.RDFProtoStruct): protobuf = tests_pb2.ApiSingleStringArgument class RouterMethodMetadataTest(test_lib.GRRBaseTest): """Tests for RouterMethodMetadata.""" def testGetQue...
hod") self.assertEqual(m.GetQueryParamsNames(), []) def testGetQueryParamsNamesReturnsMandaotryParamsCorrectly(self): m = api_call_router.RouterMethodMetadata( "SomeMethod", http_methods=[("GET", "/a/<arg>/<bar:zoo>", {})]) self.assertEqual(m.GetQueryParamsNames(), ["arg", "zoo"]) def testGetQ...
ns import namedtuple from twisted.python import usage from twisted.trial.unittest import SynchronousTestCase from twisted.internet.defer import Deferred, succeed from txgithub.scripts import gist from . _options import (_OptionsTestCaseMixin, _FakeOptionsTestCaseMixin, ...
returns.callback( { "html_url": url, } ) self.successResultOf(response) self.assertEqual(self.print_calls, [(url,)]) _PostGistCall = namedtuple("_PostGistCall", ["reactor",
"token", "files"]) class RunTests(_FakeOptionsTestCaseMixin, _FakeSystemExitTestCaseMixin, _FakePrintTestCaseMixin): """ Tests for L{txgithub.scripts.gist.run} """ def setUp(self): super(RunTests, self).setUp() self.postGist_calls = [] self.postGi...
from __fut
ure__ import unicode_literals from django.apps import AppConfig class WawmembersConfig(AppConfig): name = 'w
awmembers'
d file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os import time # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root...
absolute, like shown here. # sys.path.append(os.path.abspath('sphinxext')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here,
as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx', 'sphinx.ext.extl...
# Copyright (C) 2010 Jeremy S. Sanders # Email: Jeremy Sanders <jeremy@jeremysanders.net> # # 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 # ...
atements with string format statements newfmt = _format_re.sub("%s", totfmt) # do formatting separately for all statements strings = [] i = 0 for f in _format_re.finditer(totfmt): code = f.group(2) if code == '%':
s = '%' else: try: s = f.group() % args[i] i += 1 except IndexError: raise TypeError("Not enough arguments for format string") s = s.replace('-', u'\u2212') if locale is not None and code in 'eEfFgG': ...
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
e async for response in page_result: print(response) # [
END area120tables_v1alpha1_generated_TablesService_ListTables_async]
tring args[]) { %s } } """ return template % content_to_add def filter_type_in_method(clazz, the_type, method_name): """ yields the result of filtering the given class for the given type inside the given method identified by its name. """ for path, node in clazz.filter(the_...
with self.assertRaises(parser.JavaSyntaxError): parse.parse(setup_java_class("(a b c) -> {};")) def test_cast_works(self): """ this tests that a cast expression works as expected. """ parse.parse(setup_java_class("String x = (String) A.x() ;")) class MethodReferenceSyntaxTest(unittest...
" def assert_contains_method_reference_expression_in_m( self, clazz, method_name='main'): """ asserts that the given class contains a method with the supplied method name containing a method reference. """ matches = list(filter_type_in_method( clazz, tree...
'ping' assert wire.poll(closest[0]) is None wire.empty() assert wire.messages == [] def test_eviction(): proto = get_wired_protocol() proto.routing = routing_table(1000) wire = proto.wire # trigger node ping node = proto.routing.neighbours(random_node())[0] proto.ping(node) m...
ping_adds_sender(): p = get_wired_protocol() assert len(p.routing) == 0 for i in range(10): n = random_node() p.recv_ping(n, 'some id %d' % i) assert len(p.routing) == i + 1 p.wire.empty() def test_two(): print one = get_wired_protocol() one.routing = routing_table(...
([one, two]) two.find_node(two.this_node.id) # print 'messages', wire.messages msg = wire.process([one, two], steps=2) # print 'messages', wire.messages assert len(wire.messages) >= kademlia.k_bucket_size msg = wire.messages.pop(0) assert msg[1] == 'find_node' for m in wire.messages[kade...
# -*- coding:utf-8 -*- __author__ = 'chenjun' import torch from torch.autograd import Variable from utils.util import * """Beam search module. Beam search takes the top K results from the model, predicts the K results for each of the previous K result, getting K*K results. Pick the top K results from K*K results, an...
all_hypothesis.append(self.hypothesis[i].extend(token, log_prob, state)) # Filter and collect any hypotheses that have the end token. self.hypothesis = [] for h in self.top_hypothesis(all_hypothesis): if h.latest_token == EOS_token: # Pull the hypothesis off the be...
oken is reached. self.results.append(h) else: # Otherwise continue to the extend the hypothesis. self.hypothesis.append(h) if len(self.hypothesis) == self.beam_size or len(self.results) == self.beam_size: break outputs = [(s...
# -*- coding: utf-8 -*- import subprocess import os cmd=['/Users/jehlke/workspace/epywing/src/epywing/utils/mecab/bin/mecab', '-Owakati', '--dicdir=mecab/dic/ipadic'] #cmd = ['mecab', '-Owakati', '--dicdir=../dic/ipadic'] a = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE...
e('utf8')) print 'test' print b.strip()#.split() print 'te
st'
record(migration, database): raise NotImplementedError() def run_migration_error(self, migration, extra_info=''): return ( ' ! Error found during real run of migration! Aborting.\n' '\n' ' ! Since you have a database that does not support running\n' '...
aint cache as it can be mutated by the dry run constraint_cache = deepcopy(south.db.db._constraint_cache) if self._ignore_fail: south.db.db.debug, old_debug = False, south.db.db.debug pending_creates = south.db.db.get_pending_creates() south.db.db.start_transaction() ...
on = self.direction(migration) try: try: migration_function() south.db.db.execute_deferred_sql() except: raise exceptions.FailedDryRun(migration, sys.exc_info()) finally: south.db.db.rollback_transactions_dry_run() ...
#!/usr/bin/python import sys, time for ts in sys.argv[1:]:
print ts, time.ctime(float(ts)) sys.exit(0
)
# __author__ = MelissaChan # -*- coding: utf-8 -*- # 16-4-16 下午10:53 import MySQLdb def connect(id,name,gender,region,status,date,inter): try: conn = MySQLdb.connect(host='localhost',user='root',passwd=' ',port=3306) cur = conn.cursor() # cur.exe
cute('create database if not exists PythonDB') conn.select_db('Facebook') # cur.execute('create table Test(id int,name varchar(20),info varchar(20))') value = [id,name,gender,region,status,date,inter] cur.execute('insert into info values(%s,%s,%s,%s,%s,%s,%s)',value) # values =...
ello World!','My number is '+str(i))) # # cur.executemany('insert into Test values(%s,%s,%s)',values) # cur.execute('update Test set name="ACdreamer" where id=3') conn.commit() cur.close() conn.close() print 'insert ok~' except MySQLdb.Error,msg: pr...
import sys
, re for fn in sys.argv[1:]: with open(fn, 'r') as f: s = f.read() xx = re.findall(r'([^\n]+)\s+\'\'\'(.*?)\'\'\'', s, re.M|re.S) for (obj, doc) in xx: s = re.findall('[^:`]\B(([`*])[a-zA-Z_][a-zA-Z0-9_]*\\2)\B', doc) if s: print '-'*50 ...
fn, obj print '.'*50 print doc print '.'*50 print [ss[0] for ss in s] # for vim: # :s/\([^`:]\)\([`*]\)\([a-zA-Z0-9_]\+\)\2/\1``\3``/
import components def AclContentCacheTest (): """ACL content cache test""" ctx = components.Context (['a', 'b', 'c', 'd', 'cc', 'f'],\
['ip_a', 'ip_b', 'ip_c', 'ip_d', 'ip_cc', 'ip_f']) net = components.Network (ctx) a = components.EndHost(ctx.a, net
, ctx) b = components.EndHost(ctx.b, net, ctx) c = components.EndHost(ctx.c, net, ctx) d = components.EndHost(ctx.d, net, ctx) cc = components.AclContentCache(ctx.cc, net, ctx) f = components.AclFirewall(ctx.f, net, ctx) net.setAddressMappings([(a, ctx.ip_a), \ (b...
# coding: utf-8 """ Salt Edge Account Information API API Reference for services # noqa: E501 OpenAPI spec version: 5.0.0 Contact: support@saltedge.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import swagger_cl...
port ApiException class TestRatesResponse(unittest.TestCase): """RatesResponse unit test stubs""" def setUp(self): pass def tearDown(self): pass def testRatesResponse(self): """Test RatesResponse""" # FIXME: construct object with mandatory attributes with example val...
501 pass if __name__ == '__main__': unittest.main()
#!/usr/bin/python from ops_i2cbase import I2CBase # =========================================================================== # SI1145 Class # # Ported from github.com/adafruit/Adafruit_SI1145_Library/ # =========================================================================== class SI1145: i2c = None # SI1...
the EN_UV bit in CHLIST, and configure UCOEF [0:3] to the default values of 0x7B, 0x6B, 0x01, and 0x00. self.i2c.write8(self.SI1145_REG_UCOEFF0, 0x7B) self.i2c.write8(self.SI1145_REG_UCOEFF1, 0x6B) self.i2c.write8(self.SI1145_REG_UCOEFF2, 0x01) self.i2c.write8(self.SI1145_REG_UCOEFF3, 0x00) # enable UV se...
G_PARAMWR, self.SI1145_PARAM_CHLIST_ENUV | self.SI1145_PARAM_CHLIST_ENALSIR | self.SI1145_PARAM_CHLIST_ENALSVIS | self.SI1145_PARAM_CHLIST_ENPS1) self.i2c.write8(self.SI1145_REG_COMMAND, self.SI1145_PARAM_CHLIST | self.SI1145_PARAM_SET) # measurement rate for auto self.i2c.write8(self.SI1145_REG_MEASRATE0, 0xFF...
# # This is the container for the palettes. To change them # simply edit this. # from numpy import * NTSC = array([ [0x00,0x00,0x00],[0x40,0x40,0x40],[0x6C,0x6C,0x6C],[0x90,0x90,0x90], [0xB0,0xB0,0xB0],[0xC8,0xC8,0xC8],[0xDC,0xDC,0xDC],[0xEC,0xEC,0xEC], [0x44,0x44,0x00],[0x64,0x64,0x10],[0x...
4,0xB4],[0xD0,0xD0,0xD0],[0xEC,0xEC,0xEC], [0x00,0x00,0x00],[0x28,0x28,0x28],[0x50,0x50,0x50],[0x74,0x74,0x74], [0x94,0x94,0x94],[0xB4,0xB4,0xB4],[0xD0,0xD0,0xD0],[0xEC,0xEC,0xEC] ],uint8) SECAM = repeat([[0x00,0x00,0x00], [0x21,0x21,0xFF], [0xF0,0x3C,0x79], ...
,0xFF], [0x7F,0xFF,0x00], [0x7F,0xFF,0xFF], [0xFF,0xFF,0x3F], [0xFF,0xFF,0xFF]],16).astype(uint8)
#!/home/mharris/Projects/DevOpsDays/venv/bin/python2 # $Id: rst2pseudoxml.py 4564 2006-05-21 20:44:42Z wiemann $ # Author: David Goodger <goodger@pytho
n.org> # Copyright: This module has been placed in the public domain. """ A minimal front end to the Docutils Publisher, producing pseudo-XML. """ try: import locale
locale.setlocale(locale.LC_ALL, '') except: pass from docutils.core import publish_cmdline, default_description description = ('Generates pseudo-XML from standalone reStructuredText ' 'sources (for testing purposes). ' + default_description) publish_cmdline(description=description)
#Schedule-generator for LHL use written by Acebulf (acebulf at gmail.com) #Current version 1.0 -- Jan 16 2014 #Copyrighted under the MIT License (see License included in the github repo) import random import time while 1: print "Starting random-schedule generation process..." starttime = time.time() kill ...
for x in days1game: for y in newmatchups: if not playing_day(y[0],x) and not playing_day(y[1],x):
x.append(y) newmatchups.remove(y) for x in schedule: if len(x) != 3: print "Problem encountered in stage 3; Restarting..." kill=True break if kill: continue print "Stage 3/3 Successfully Completed" break print "Schedule ...
# Copyright 2016, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
self.unary_stream = None self.stream_unary = None self.stream_stream = None if self.request_streaming and self.response_streaming: self.stream_stream =
handle_stream_stream elif self.request_streaming: self.stream_unary = handle_stream_unary elif self.response_streaming: self.unary_stream = handle_unary_stream else: self.unary_unary = handle_unary_unary class _GenericHandler(grpc.GenericRpcHandler): d...
""" sentry.plugins.sentry_useragents.models ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import httpagentparser import sentry from django.utils.translation import ugettext_lazy as _ from sentry.plu...
ot http: return [] if not http.headers: return [] if 'User-Agent' not in http.headers: return [] ua = httpagentparser.detect(http.headers['User-Agent']) if not ua: return [] result = self.get_tag_from_ua(ua) if not result: ...
ult] class BrowserPlugin(UserAgentPlugin): """ Automatically adds the 'browser' tag from events containing interface data from ``sentry.interfaes.Http``. """ slug = 'browsers' title = _('Auto Tag: Browsers') tag = 'browser' tag_label = _('Browser Name') def get_tag_from_ua(self, u...
pache.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 # li...
"key.with.dots": {}, } } ) def test_event_fields_works_with_nested_dot_keys(self): self.assertEquals( self.serialize( MockEvent( sender="@alice:localhost", room_id="!foo:bar", content...
"nested.dot.key": { "leaf.key": 42, "not_me_either": 1, }, }, ), ["content.nested\.dot\.key.leaf\.key"] ), { "content": { "n...
import os BASEDIR = os.path.abspath(os.path.dirname(__file__)) DEBUG = False ## # Database settings ## DB_HOST = 'localhost' DB_NAME = 'scoremodel' DB_USER = 'scoremodel' DB_PASS = 'scoremodel' ## # MySQL SSL connections ## use_ssl
= False SSL_CA = '/etc/mysql/certs/ca-cert.pem' SSL_KEY = '/etc/mysql/keys/client-key.pem' SSL_CERT = '/etc/mysql/certs/client-cert.pem' ## # Flask-WTF ## WTF_CSRF_ENABLED = True SECRET_KEY = 'secret_key' ## # Log-in ## REMEMBER_COOKIE_SECURE = True REMEMBER_COOKIE_HTTPONLY = True SESSION_PROTECTION = "strong" ## #...
FAULT_LOCALE = 'en' BABEL_DEFAULT_TIMEZONE = 'UTC' LANGUAGES = ['nl', 'en'] ## # Uploads ## UPLOAD_FOLDER = 'uploads' ALLOWED_EXTENSIONS = ('txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif') MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16 MB ## # Logger ## LOG_FILENAME = 'logs/scoremodel.log' if use_ssl is True: SQLALCHEMY_...
""" Tools for reading Mac resource forks. """ from __future__ import print_function, division, absolute_import from fontTools.misc.py23 import * import struct from fontTools.misc import sstruct from collections import OrderedDict try: from collections.abc import MutableMapping except ImportError: from UserDict import...
self.attr = resAttr def decompile(self, refData, reader): sstruct.unpack(ResourceRefItem, refData, self) # interpret 3-byte dataOffset as (padded) ULONG to unpack it with struct self.dataOffset, = struct.unpack('>L', bytesjoin([b"\0", self.dataOffset])) absDataOffset = reader.dataOffset + self.dataOffset ...
if self.nameOffset == -1: return absNameOffset = reader.absNameListOffset + self.nameOffset nameLength, = struct.unpack('B', reader._read(1, absNameOffset)) name, = struct.unpack('>%ss' % nameLength, reader._read(nameLength)) self.name = tostr(name, encoding='mac-roman') ResourceForkHeader = """ > # big...
# https://www.reddit.com/r/dailyprogrammer/comments/3fva66/20150805_challenge_226_intermediate_connect_four/ import sys, string xmoves = open(sys.argv[1]).read().translate(None, string.ascii_lowercase + ' \n')
omoves = open(sys.argv[1]).read().translate(None, string.ascii_uppercase + ' \n') board = [[' ' for x in range(6)] for x in range(7)] def insert(colchar, player): colnumber = ord(colchar.lower()) - ord('a') col = board[colnumber]
for i in range(len(col)): if col[i] == ' ': col[i] = player break def checkwinner(player): for x in range(6): for y in range(6): if board[x][y] == player: top = board[x][y+1:y+4] if len(top) == 3 and not ''.join(top).strip(player)...
ot(sig)] = 0.0 # self.denoised.append(coef) self.sig_supports.append(sig) self.p_cutoff.append(p_cutoff) # append the last approximation self.denoised.append(self.get_approx()) def decompose(self, level=5, boundary="symm", verbose=False): """ ...
he exact inverse procedure. arguments: * denoised: whether use the denoised coefficients * niter: number of iterations """ if denoised: decomposition = self.denoised else: decomposition = self.decomposition # L1 regularization ...
uct_ivst(denoised=denoised, positive_project=True) # iuwt = IUWT(level=self.level) iuwt.calc_filters() # iterative reconstruction if verbose: print("Iteratively reconstructing (%d times): " % niter, end="", flush=True, file=sys.stde...
""" Page view class """ import os from Server.Importer import ImportFromModule class PageView(ImportFromModule("Server.PageViewBase", "PageViewBase")): """ Page view class. """ _PAGE_TITLE = "Python Web Framework" d
ef __init__(self, htmlToLoad): """ Constructor. - htmlToLoad : HTML to load """ self.SetPageTitle(self._PAGE_TITLE) self.AddMetaData("charset=\"UTF-8\"") self.AddMetaData("name=\"viewport\" content=\"width=device-width, initial-scale=1\"") self.AddStyleS...
(os.path.dirname(__file__), "%s.html" % htmlToLoad)) self.SetPageData({ "PageTitle" : self._PAGE_TITLE })
"""create table for hierarchy of accounts Revision ID: 17fb1559a5cd Revises: 3b7de32aebed Create Date: 2015-09-16 14:20:30.972593 """ # revision identifiers, used by Alembic. revision = '17fb1559a5cd' down_revision = '3b7de32aebed' branch_labels = None depends_on = None from alembic import op,
context import sqlalchemy as sa def downgrade(): schema = context.get_context().config.get_main_option('schema') op.drop_table('lux_user_inheritance', schema=schema) op.execute("DROP FUNCTION IF EXISTS " "%(schema)s.getMainAccount(VARCHAR)"
% {"schema": schema}) def upgrade(): schema = context.get_context().config.get_main_option('schema') op.create_table( 'lux_user_inheritance', sa.Column( 'login', sa.VARCHAR(), autoincrement=False, nullable=False), sa.Column( 'login_father', sa.VARC...
# -*- coding: utf-8 -*- import os from django.db import models from django.db.models import Q from seahub.tags.models import FileUUIDMap from seahub.utils import normalize_file_path class RelatedFilesManager(models.Manager): def get_related_files_uuid(self, uuid): related_files_uuid = super(RelatedFi...
rent_path = os.path.dirname(o_file_path) r_file_path = normalize_file_path(r_path) r_filename = os.path.basename(r_file_path) r_parent_path = os.path.dirname(r_file_path) o_uuid = FileUUIDMap.objects.get_or_create_fileuuidmap(o_repo_id, o_parent_path, o_filename, is_dir=False) r...
=r_uuid) related_file_uuid.save() return related_file_uuid def get_related_file_uuid_by_id(self, related_id): try: return super(RelatedFilesManager, self).get(pk=related_id) except self.model.DoesNotExist: return None def delete_related_file_uuid(self, ...
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
EALINGS # IN THE SOFTWARE. from CIM14.ENTSOE.StateVariables.Element import Element class SvShuntCompensatorSections(Element): """State variable for the number of sections in service for a shunt compensator. """ def __init__(self, sections=0, continuousSections=0.0, ShuntCompensator=None, *args, **kw_arg
s): """Initialises a new 'SvShuntCompensatorSections' instance. @param sections: The number of sections in service. @param continuousSections: The number of sections in service as a continous variable. @param ShuntCompensator: The shunt compensator for which the state applies. ...
import numpy as np from bokeh.layouts import layout from bokeh.models import CustomJS, Slider, ColumnDataSource, WidgetBox from bokeh.plotting import figure, output_file, show output_file('dashboard.html') tools = 'pan' def bollinger(): # Define Bollinger Bands. upperband = np.random.random_integers(100, 1...
= data['x'] y = data['y'] for (i
= 0; i < x.length; i++) { y[i] = B + A*Math.sin(k*x[i]+phi); } source.trigger('change'); """) amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude", callback=callback, callback_policy='mouseup') callback.args["amp"] = amp_slider freq_slider = Slider(sta...
# This file is part of Invenio. # Copyright (C) 2014 CERN. # # Invenio 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. # # Invenio is d...
ill 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 Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """BibFormat element - Links to arXiv""" from cgi import escape from invenio.base.i...
from cast.analysers import log, mainframe class EmptyParagraphEndOfSection(mainframe.Extension): def __init__(self): self.program = None def start_program(self, program): self.program = program def end_program(self, _): self.program = None def start_section(self...
ctionEndParagraph', section.get_position()) elif len(children) == 1: kind = children[0].get_kind() if kind
not in ['exit', 'stop_run', 'goback']: self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) else: # violation test_ko1 self.program.save_violation('MyCompany_COBOL_Rules.sectionEndParagraph', section.get_position()) ...
#! /usr/bin/env python ''' Testsuite for the CustomParameter class ''' from __future__ import absolute_import, division, print_function import numpy as np from puq import * def _hisplot(y, nbins): n, bins = np.histogram(y, nbins, normed=True) mids = bins[:-1] + np.diff(bins) / 2.0 return mids, n def compa...
t=True)) assert np.allclose(c.pdf.mean, 7.0/3, atol=.3), "mean=%s" % c.pdf.mean assert np.allclose(c.pdf.dev, 0.4, atol=.4), "dev=%s" % c.pdf.dev # single data point. Must use Bayesian fit. def test_custom_pdf_single_fit(): a = np.ar
ray([42]) c = CustomParameter('x', 'unknown', pdf=ExperimentalPDF(a, error=NormalPDF(0,.1))) assert np.allclose(c.pdf.mean, 42), "mean=%s" % c.pdf.mean assert np.allclose(c.pdf.dev, .1, atol=.01), "dev=%s" % c.pdf.dev def test_custom_pdf_single(): a = np.array([42]) c = CustomParameter('x', 'unknow...
import logging from virttest import virsh from provider import libvirt_version from autotest.client.shared import error def run_cmd_in_guest(vm, cmd): """ Run command in the guest :params vm: vm object :params cmd: a command needs to be r
an """ session = vm.wait_for_login() status, output = session.cmd_status_output(cmd) logging.debug("The '%s' output: %s", cmd, output) if status: session.close() raise error.TestError("Can not run '%s' in gue
st: %s", cmd, output) else: session.close() return output def run(test, params, env): """ 1. Configure kernel cmdline to support kdump 2. Start kdump service 3. Inject NMI to the guest 4. Check NMI times """ for cmd in 'inject-nmi', 'qemu-monitor-command': if no...
import numpy as np import tensorflow as tf import os def get_inputs(split, config): split_dir = config['split_dir'] data_dir = config['data_dir'] dataset = config['dataset'] split_file = os.path.join(split_dir, dataset, split + '.lst') filename_queue = get_filename_queue(split_file, os.path.join(d...
) <= image) binary_image = tf.cast(binary_image, tf.float32) return binary_image de
f get_inputs_cifar10(filename_queue, config): output_size = config['output_size'] image_size = config['image_size'] c_dim = config['c_dim'] # Dimensions of the images in the CIFAR-10 dataset. # See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the # input format. label_byt...
] big_cnts = [] obj_points = [] image = timage thresh_limit = 10 thresh_limit = find_best_thresh(image, thresh_limit, 0) # find best thresh limit code here! line_objects = [] points = [] orphan_lines = [] _, thresh = cv2.threshold(image, thresh_limit, 255, cv2.THRESH_BINARY) (_, cnts, ...
ast_x,last_y), (200), 4) last_x = x last_y = y
last_ang = ang a, b = best_fit (cxs,cys) mnx = min(cxs) mny = min(cys) mmx = max(cxs) mmy = max(cys) cv2.rectangle(image, (mnx,mny), (mmx, mmy), (255),1) #print ("MIKE MIKE XS,", cxs) #print ("MIKE MIKE YS,", cys) clusters_ab.append((a,b...
''' Using the Python language, have the function MultiplicativePersistence(num) take
the num parameter being passed which will always be a positive integer and return its multiplicative persistence which is the number of times you must multiply the digits in num until you reach a single digit. For example: if num is 39 then your program should return 3 because 3 * 9 = 27 then 2 * 7 = 14 and finall...
op at 4. ''' def MultiplicativePersistence(num): steps = 0 while num > 9: snum = str(num) sdigits = list(snum) num = 1 for snum in sdigits: n = int(snum) num = num * n steps = steps + 1 return steps # keep this function call here # to see how to enter argument...
# Copyright 2021 ForgeFlow S.L. <https://www.forgeflow.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openupgradelib import openupgrade _xmlid_renames = [ ( "sale.access_product_product_attribute_custom_value", "sale.access_product_product_attribute_custom_value_sal...
", "sale.account_invoice_line_rule_see_all"), ( "sale.account_move_line_personal_rule", "sale.account_invoice_line_rule_see_personal", ), ] def fast_fill_sale_order_currency_id(env): if not openupgrade.column_exists(env.cr, "sale_order", "currency_id"
): openupgrade.logged_query( env.cr, """ ALTER TABLE sale_order ADD COLUMN currency_id integer""", ) openupgrade.logged_query( env.cr, """ UPDATE sale_order so SET currency_id = pp.currency_id FROM product_pricel...
lue 3. augment: Whether to fit on randomly augmented samples rounds: If `augment`, how many augmentation passes to do over the data seed: random seed. # Raises ValueError: in case of invalid input `x`. """ x = np.asarray(x, dtype=K....
se_std_normalization: self.std = np.std(x,
axis=(0, self.row_axis, self.col_axis)) broadcast_shape = [1, 1, 1] broadcast_shape[self.channel_axis - 1] = x.shape[self.channel_axis] self.std = np.reshape(self.std, broadcast_shape) x /= (self.std + K.epsilon()) if self.zca_whitening: flat_x = np....
# -*- coding: utf-8 -*- class Charset: c
ommon_name = u'Google Fonts: Extras' native_name = u'' def glyphs(self): glyphs = [0xe0ff] # PUA: Font logo glyphs += [0xeffd] # PUA: Font version number glyphs += [0xf000] # PUA: font ppem size indicator: run `ftview -f 1255 10 Ubuntu-Regular.ttf` to see it in action! return g
lyphs
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Philipp Wagner # 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...
, center=eye_left, angle=rotation) # crop the rotated image crop_xy = (eye_left[0] - scale*offset_h, eye_left[1] - scale*offset_v) crop_size = (dest_sz[0]*scale, dest_sz[1]*scale)
image = image.crop((int(crop_xy[0]), int(crop_xy[1]), int(crop_xy[0]+crop_size[0]), int(crop_xy[1]+crop_size[1]))) # resize it image = image.resize(dest_sz, Image.ANTIALIAS) return image if __name__ == "__main__": f = open(sys.argv[1], 'r') csv = open(sys.argv[2], "w") for line in f: lineArray = line.s...
# -*- cod
ing: utf-8 -*- import unittest from config.context import Attribute, attr class Data(object): pass class AttributeTestCase(unittest.TestCase): def setUp(self): self.data= Data() self.data.int2= 1 self.integer= 3 self.int1= Attribute("int1", destObj= ...
lf.data) self.int3= Attribute("integer", destObj= self) self.flt1= Attribute("flt", destObj= self.data, destName="float", valueType=float ) self.flt2= Attribute("value", valueType= float) self.str = A...
# -*- coding: utf-8 -*- # # # OpenERP, Open Source Management Solution # Authors: Raphaël Valyi, Renato Lima # Copyright (C) 2011 Akretion LTDA. # # 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 distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABI
LITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # {'name': 'Sale Exceptions', 'summary': 'Custom excep...
import numpy as np import openmc ############################################################################### # Simulation Input File Parameters ############################################################################### # OpenMC simulation parameters batches = 15 inactive = 5 particles = ...
+x4 | -y3 | +y4 | -z3
| +z4 # Use surface half-spaces to define regions inner_box.region = inner_cube middle_box.region = middle_cube & outside_inner_cube outer_box.region = outer_cube & ~middle_cube # Register Materials with Cells inner_box.fill = fuel1 middle_box.fill = fuel2 outer_box.fill = moderator # Instantiate root universe root ...
""" Copyright 2016, Paul Powell, All rights reserved. """ import team import round class Region: def __init__(self, name, teams, algorithm): self.initialize(name, teams) self.name = name self.rounds = [] self.algorithm = algorithm self.final = None def __call__(self, ma...
for team in game: if team.name == winner: print "found winner" team.sf = 3 if team.name == second:
print "found second" team.sf = 2
ne menu_select_color = ColorScheme.get_primary() def __init__(self, track_manager, status_pump, **kwargs): Builder.load_file(STATUS_KV_FILE) super(StatusView, self).__init__(**kwargs) self.track_manager = track_manager self.register_event_type('on_tracks_updated') self._...
es = status['sats'] dop = status['DOP'] self._add_item('Status', init_status) self._add_item('GPS Quality', quality) self._add_item('Location', location) self._add_item('Satellites', satellites) self._add_item('Dilution of precision', dop) def render_cell(self): ...
ell', 'init', status['init']) imei = status['IMEI'] signal_strength = self._get_enum_definition('cell', 'sig_str', status['sig_str'], 'Unknown') number = status['number'] self._add_item('Status', init_status) self._add_item('IMEI', imei) self._add_item('Signal strength',...
n idea which parts of the ensemble affect which part of ensembles """ def __init__(self, pathmover=None, ensembles=None, initial=None): super(MoveTreeBuilder, self).__init__() self.p_x = dict() self.p_y = dict() self.obj = list() self.ensembles = [] self.pat...
well (default True) Returns ------- :obj:`MoveTreeBuilder` """ try: # inp is a move scheme input_ensembles = scheme.list_initial_ensembles() except AttributeError: # inp is a path mover # ??? this is nonsense in...
heme.input_ensembles # using network.all_ensembles forces a correct ordering ensembles = scheme.network.all_ensembles if hidden_ensembles: ensembles += list(scheme.find_hidden_ensembles()) return MoveTreeBuilder( pathmover=scheme.root_mover, ...
""" Boolean Operations ~~~~~~~~~~~~~~~~~~ Perform boolean operations with closed surfaces (intersect, cut, etc.). Boolean/topological operations (intersect, cut, etc.) methods are implemented for :class:`pyvista.PolyData` mesh types only and are accessible directly from any :class:`pyvista.PolyD
ata` mesh. Check out :class:`pyvista.PolyDataFilters` and take a look at the following filters: * :func:`pyvista.PolyDataFilters.boolean_add` * :func:`pyvista.PolyDataFilters.boolean_cut` * :func:`pyvista.PolyDataFilters.boolean_difference` * :func:`pyvista.PolyDataFilters.boolean_union` For merging, the ``+`
` operator can be used between any two meshes in PyVista which simply calls the ``.merge()`` filter to combine any two meshes. Similarly, the ``-`` operator can be used between any two :class:`pyvista.PolyData` meshes in PyVista to cut the first mesh by the second. """ # sphinx_gallery_thumbnail_number = 6 import pyvi...
#!/usr/bin/env conda-execute # conda execute # env: # - python 2.7.* # - conda-smithy # - pygithub 1.* # - six # - conda-build # channels: # - conda-forge # run_with: python from __future__ import print_function import argparse import collections import os import six from github import Github import github im...
e') teams = {team.name: team for team in conda_forge.get_teams()} feedstocks_path = args.feedstocks_clone packages_visited = set() all_members = set() from random import choice superlative = ['awesome', 'slick', 'formidable', 'awe-inspiring', 'breathtaking', 'magnificent', 'wonderous', 'stunning', 'as...
', 'superb', 'splendid', 'impressive', 'unbeatable', 'excellent', 'top', 'outstanding', 'exalted', 'standout', 'smashing'] # Go through each of the feedstocks and ensure that the team is up to date and that # there is nobody in the team which doesn't belong (i.e. isn't in the maintainers ...
tion_namespace'] = config.namespace else: if instance_namespace: if self._check_unique_namespace_instance(instance_namespace): self._errors['application_namespace'] = ErrorList([ _('An application instance with this name...
ptions_for_parent(parent_node, position) return self._get_tree_options_for_root(position) def _get_tree_options_for_root(self, position): siblings = self.get_root_nodes().filter(site=self._site) try: target_node = siblings[position] except IndexError: # The ...
node, # relative to the current site. return (siblings.reverse()[0], 'right') return (target_node, 'left') def _get_tree_options_for_parent(self, parent_node, position): if position == 0: return (parent_node, 'first-child') siblings = parent_node.get_ch...
from blinker import Namespace import logging import json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class MySignal: def __init__(self): self.signals = {} self.signal = Namespace() def init_app(self, app): pass def addSignal(self, classname, option): ...
sname, option, func): logger.debug('connect signal {}.{} with func: {}()'.format(classname, option, func.__name__)) if not '{}.{}'.format(classname, option) in self.signals.keys(): self.signals['{}.{}'.format(classname, option)] = self.signal.signal('{}.{}'.format(classname, option)) ...
ption) in self.signals.keys(): self.signals['{}.{}'.format(classname, option)].disconnect(func)
# -*- coding: utf-8 -*- import re import string import random import pbkdf2 HASHING_ITERATIONS = 400 ALLOWED_IN_SALT = string.ascii_letters + string.digits + './' ALLOWD_PASSWORD_PATTERN = r'[A-Za-z0-9@#$%^&+=]{8,}' def gener
ate_random_string(len=12, allowed_chars=string.ascii_letters+string.digits): return ''.join(random.choice(allowed_chars) for i in range(len))
def make_password(password=None): if password is None: raise ValueError('password is required') salt = generate_random_string(len=32, allowed_chars=ALLOWED_IN_SALT) return pbkdf2.crypt(password, salt=salt, iterations=HASHING_ITERATIONS) def check_password(password, hashed_password): return has...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
lth_events: The list of health events reported on the entity. :type health_events: list of :class:`HealthEvent <azure.servicefabric.models.HealthEvent>` :param unhealthy_evaluations: :type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper <azure.servicefabric.
models.HealthEvaluationWrapper>` :param health_statistics: :type health_statistics: :class:`HealthStatistics <azure.servicefabric.models.HealthStatistics>` :param partition_id: :type partition_id: str :param replica_health_states: The list of replica health states associated with the parti...
""" Script that trains graph-conv models on ChEMBL dataset. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np np.random.seed(123) import tensorflow as tf tf.set_random_seed(123) import deepchem as dc from chembl_datasets import load_che...
et, test_dataset = datasets # Fit models metric = dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean) # Do setup required for tf/keras models # Number of features on conv-mols n_feat = 75 # Batch size of models batch_size = 128 graph_model = dc.nn.SequentialGraph(n_feat) graph_model.add(d
c.nn.GraphConv(128, n_feat, activation='relu')) graph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1)) graph_model.add(dc.nn.GraphPool()) graph_model.add(dc.nn.GraphConv(128, 128, activation='relu')) graph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1)) graph_model.add(dc.nn.GraphPool()) # Gather Pro...
units (int): Size of the hidden layers dist (str): Output distribution, parameterized by FC output logits. act (Any): Activation function """ super().__init__() self.layrs = layers self.units = units self.act = act if n...
self.stoch_size).to(self.device), torch.zeros(batch_size, self.stoch_size).to(self.device), torch.zeros(batch_size, self.stoch_size).to(self.device), torch.zeros(batch_size, self.deter_size).to(self.device), ] def observe(self, embed: TensorType, ...
state: List[TensorType] = None ) -> Tuple[List[TensorType], List[TensorType]]: """Returns the corresponding states from the embedding from ConvEncoder and actions. This is accomplished by rolling out the RNN from the starting state through eacn index of embed and action, sav...
# The MIT License (MIT) # # Copyright (c) 2014 Muratahan Aykol # # 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 w
ithout restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission no...
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, ARISING FROM, # O...
__all__ = ['jazPrint', 'jazShow'] class jazPrint: def __init__(self): self.command = "print"; def
call(self, interpreter, arg): return interpreter.GetScope().GetStackTop() class jazShow: def __init__(self): self.command = "show"; def call(self, interpreter, arg): return arg; # A dictionary of the classes in this file # used to autoload t
he functions Functions = {'jazShow': jazShow, 'jazPrint': jazPrint}
platform import socket import time import traceback import mozprocess __all__ = ["SeleniumServer", "ChromeDriverServer", "EdgeChromiumDriverServer", "OperaDriverServer", "GeckoDriverServer", "InternetExplorerDriverServer", "EdgeDriverServer", "ServoDriverServer", "WebKitDriverServer", "WebDriv...
processOutputLine=self.on_output, env=self.env, storeOutput=False) self.logger.debug("Starting WebDriver: %s" % ' '.join(self._cmd)) try: self._proc.run() except OSError as e: if e.errno == errno.ENOENT: raise IOError( ...
to become accessible: %s" % self.url) try: wait_for_service((self.host, self.port)) except Exception: self.logger.error( "WebDriver was not accessible " "within the timeout:\n%s" % traceback.format_exc()) raise if block: ...
rd, database def _conn_key(self, instance): ''' Return a key to use for the connection cache ''' host, username, password, database = self._get_access_info(instance) return '%s:%s:%s:%s' % (host, username, password, database) def _conn_string(self, instance): ''' Return...
ssage, tracebk)) if cache_failure: self.failed_connections[conn_key] = cxn_failure_exp
raise cxn_failure_exp conn = self.connections[conn_key] cursor = conn.cursor() return cursor def get_sql_type(self, instance, counter_name): ''' Return the type of the performance counter so that we can report it to Datadog correctly If the ...
"" if discovery_info is not None: host = urlparse(discovery_info[1]).hostname else: host = config.get(CONF_HOST) if host is None: _LOGGER.error("No TV found in configuration file or with discovery") return False # Only act if we are not already configuring this host ...
rator = get_component('configurator') # We got an error if this
method is called while we are configuring if host in _CONFIGURING: configurator.notify_errors( _CONFIGURING[host], 'Failed to pair, please try again.') return # pylint: disable=unused-argument def lgtv_configuration_callback(data): """Handle configuration changes.""" ...
# -*- coding: utf-8 -*- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django', 'USER': 'django', 'PASSWORD': 'PUTPAS
SWORDHERE', 'HOST': '1
27.0.0.1', 'PORT': '5432', } }
in Ok completely surround all sigmas. Returns either (True, xlist) with xlist a list of all a+t needed, or (False, []) """ xlist = [] for s in sigmas: if s.is_infinity(): continue ok, xlist1 = is_sigma_surrounded(s, alist, debug) if not ok: if d...
assert t2 in [-1,1,2] if debug: are_intersection_points_covered_by_one(a0, a1, a2, plot=True) if t2==2 or ([t,t2] in [[1,-1],[-1,1]]): if debug: print("t={}, t2={},
about to return True".format(t,t2)) return True assert t2 in [-1,1] and t in [0,t2] if debug: print("t={}, t2={}, setting t to {}".format(t,t2,t2)) t = t2 return False def is_alpha_surrounded(a0, alist, sigmas, pairs_ok=[], debug=False, plot=Fals...
#!/usr/bin/env python import roslib roslib.load_manifest('camera_controller') import rospy import tf if __name__ == '__main__': rospy.init_node('frame_broadcaster') br = tf.TransformBroadcas
ter() rate = rospy.Rate(10.0) target_frame = rospy.get_param("~target_frame") # Camera position # Translation x = rospy.get_param("~x",0) y = rospy.get_param("~y",0) z = rospy.get_param("~z",0) # Pose quaternion qm = rospy.get_param("~qm",0) qx = rospy.get_param("~qx",0) qy = rospy.get_param("~qy",0) qz =...
spy.is_shutdown(): br.sendTransform((x,y,z), (qm, qx, qy, qz), rospy.Time.now(), target_frame, "world") rate.sleep()
# Copyright (C) 2013 Statoil ASA, Norway. # # The file 'test_run.py' is part of ERT - Ensemble based Reservoir Tool. # # ERT 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, teither version 3 of...
----------------------------------------------------------- def get_args(self): return self.args #-----------------------------------------------------------------
def add_check( self , check_func , arg): if callable(check_func): self.check_list.append( (check_func , arg) ) else: raise Exception("The checker:%s is not callable" % check_func ) #----------------------------------------------------------------- def __run(self , ...
from equity i
mport EquityPricer class FuturePricer(EquityPricer): def __init__(self): super(
FuturePricer,self).__init__()
ile.delete() os.system('rm -rf %s/genomes/%s/%s' % (settings.BASE_DIR, username, individual_id)) self.object.delete() # response = JSONResponse(True, {}, response_mimetype(self.request)) # response['Content-Disposition'] = 'inline; filename=files.json' ...
messages.add_message(request, messages.INFO, "Individual deleted with success!") #return redirect('individuals_list') return redirect('individuals_list') def view(request, individual_id): individual = get_object_or_404(Individual, pk=individual_id) variant_list = Variant.objects.filter(in...
filter(variant_id = '.').count() individual.summary = [] #get calculated values from database summary_item = { 'type': 'Total SNVs', 'total': variant_list.values('genotype').count(), 'discrete': variant_list.values('genotype').annotate(total=Count('genotype...
from __future__ import (absolute_import, division, print_function) import unittest import mantid import os import numpy as np from sans.test_helper.test_director import TestDirector from sans.state.wavelength_and_pixel_adjustment import get_wavelength_and_pixel_adjustment_builder from sans.common.enums import (RebinTy...
method def _get_state(lab_pixel_file=None, hab_pixel_file=None, lab_wavelength_file=None, hab_wavelength_file=None, wavelength_low=None, wavelength_high=None, wavelength_step=None, wavelength_step_type=None): test_director = TestDirector() state = test_director....
wavelength_and_pixel_builder = get_wavelength_and_pixel_adjustment_builder(data_state) if lab_pixel_file: wavelength_and_pixel_builder.set_LAB_pixel_adjustment_file(lab_pixel_file) if hab_pixel_file: wavelength_and_pixel_builder.set_HAB_pixel_adjustment_file(hab_pixel_file...
from django.utils.translation import ugettext as _, ugettext_lazy as _lazy from django.core import urlresolvers from gasistafelice.rest.views.blocks.base import BlockSSDataTables, ResourceBlockAction from gasistafelice.consts import CREATE, EDIT, EDIT_MULTIPLE, VIEW from gasistafelice.lib.shortcuts import render_to_x...
-----------------------------------------------# # # #------------------------------------------------------------------------------#
class Block(BlockSSDataTables): # COMMENT fero: name of this block should be # something different from "order" (p.e: "make_order") # because usually we refer to "order" for GASSupplierOrder BLOCK_NAME = "order" BLOCK_DESCRIPTION = _("Order") BLOCK_VALID_RESOURCE_TYPES = ["gasmember"] CO...
from simulator.
sensors.SimSensor import SimSensor from environment.SensoryData import SensoryData class SimAudioSensor(SimSensor): def __init__(self, parentBot, name): super().__init__('Audio', parentBot, name) def receiveAudio(self, audio): return SensoryData(self.name
, 'Audio', audio)
# coding=latin-1 from flask import request, g from flask import abort, flash from functools import wraps def checa_permissao(permissao): def decorator(f): @wraps(f) def inner(*args, **kwargs): if g.user and g.user.checa_permissao(permissao): return f(*args,
**kwargs) else: flash(u'Atenção você não possui a pe
rmissão: %s. Se isto não estiver correto, entre em contato solicitando esta permissão.' % permissao.upper(),u'notice') abort(401) return inner return decorator
#!/usr/bin/env python """ @package mi.dataset.driver.velpt_ab.dcl @file mi-dataset/mi/dataset/driver/velpt_ab/dcl/velpt_ab_dcl_recovered_driver.py @author Joe Padula @brief Recovered driver for the velpt_ab_dcl instrument Release notes: Initial Release """ from mi.dataset.dataset_parser import DataSetDriverConfigKe...
ClassKey.METADATA_PARTICLE_CLASS: VelptAbDclDiagnosticsHeaderParticleRecovered, VelptAbDclParticleClassKey.DIAGNOSTICS_PARTICLE_CLASS: VelptAbDclDiagnosticsDataParticleRecovered, VelptAbDclParticleClassKey.INSTRUMENT_PARTICLE_CLASS: VelptAbDclInstrumentDataParticleRecovered }...
parser = VelptAbDclParser(parser_config, stream_handle, self._exception_callback) return parser
backs(cb, eb) def test_loseConnection(self): """ Verify that a protocol connected to L{StandardIO} can disconnect itself using C{transport.loseConnection}. """ errorLogFile = self.mktemp() log.msg("Child process logging to " + errorLogFile) p = StandardIOTes...
self.addCleanup(normal.close) kwargs = dict(stdout=normal.fileno()) if not platform.isWindows(): # Make a fake stdin so that StandardIO doesn't mess with the *real* # stdin.
r, w = os.pipe() self.addCleanup(os.close, r) self.addCleanup(os.close, w) kwargs['stdin'] = r connection = stdio.StandardIO(proto, **kwargs) # The reactor needs to spin a bit before it might have incorrectly # decided stdout is closed. Use this ...
from lexer import lang from ..tree import Node class
Integer(Node): datatype = lang.SEMANTIC_INT_TYPE """docstring for Integer.""" def __init__(self, symbol, token): super().__init__(symbol, token) def generate_code(self, **cond): array, line = Node.assignated_array() Node.array_append(ar
ray, f'{line} LIT {self.symbol}, 0')
# import multiprocessing to avoid this bug (http://bugs.python.org/issue15881#msg170215) import multiprocessing assert multiprocessing import re from setuptools import setup, find_packages def get_version(): """ Extracts the version number from the version.py file. """ VERSION_FILE = 'tour/version.py'...
nce :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Framework :: Django',
'Framework :: Django :: 1.7', 'Framework :: Django :: 1.8', ], license='MIT', install_requires=[ 'Django>=1.7', 'djangorestframework>=2.3.13', 'django-manager-utils>=0.8.2', 'django_filter>=0.7', ], tests_require=[ 'psycopg2', 'django-nose>=1....