prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
""" The MIT License (MIT) Copyright (c) 2016 Daniele Linguaglossa <d.linguaglossa@mseclab.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation th...
ion i
mport PJFConfiguration import unittest import argparse import sys __TITLE__ = "Testing PJFConfiguration object" class TestPJFConfiguration(unittest.TestCase): def test_json_configuration(self): sys.argv.append("--J") sys.argv.append("[1]") sys.argv.append("--no-logo") parser = ar...
e ValueError('Unsupported destination buffer type %r', dst.dtype) dst_is_uint16 = (dst.dtype == 'uint16') with self.tile_request(tx, ty, readonly=True) as src: if src is transparent_tile.rgba: #dst[:] = 0 # <-- notably slower than memset() if dst_is_uint16: ...
""" dirty_tiles = set(self.tiledict.keys()) self.tiledict = {} state = {} state['buf'] = None # array of height N, width depends on image state['ty'] = y // N # current tile row being filled into buf state['frame_size'] = None def get_buffer(png_w, png_h): ...
buf_x0 = x // N * N buf_x1 = ((x + png_w - 1) // N + 1) * N buf_y0 = state['ty']*N buf_y1 = buf_y0+N buf_w = buf_x1-buf_x0 buf_h = buf_y1-buf_y0 assert buf_w % N == 0 assert buf_h == N if state['buf'] is not None: ...
from direct.directnotify import DirectNotifyGlobal from direct.distributed import DistributedObject from otp.speedchat import SpeedChatGlobals class DistributedScavengerHuntTarget(DistributedObject.DistributedObject):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedScavengerHu
ntTarget') def __init__(self, cr): DistributedObject.DistributedObject.__init__(self, cr) def setupListenerDetails(self): self.triggered = False self.triggerDelay = 15 self.accept(SpeedChatGlobals.SCCustomMsgEvent, self.phraseSaid) def phraseSaid(self, phraseId): s...
itorWidgetTms(), KNOWN_DRIVERS.WMS: EditorWidgetWms(), KNOWN_DRIVERS.WFS: EditorWidgetWfs(), KNOWN_DRIVERS.GEOJSON: EditorWidgetGeoJson(), } # init icon selector # self.txtIcon.set_dialog_ext(self.tr('Icons (*.ico *.jpg *.jpeg *.png *.svg);;All files (*.*)'))...
ical(self, self.tr('Error on save group'), self.tr('Data source with such id already exists! Select new id for data source!')) return False return True def feel_ds_info(self, ds_info): ds_info.id = self.txt
Id.text() ds_info.alias = self.txtAlias.text() # ds_info.icon = os.path.basename(self.txtIcon.get_path()) ds_info.icon = os.path.basename(self.__ds_icon) ds_info.lic_name = self.txtLicense.text() ds_info.lic_link = self.txtLicenseLink.text() ds_info.copyright_text = self...
"""log model admin.""" from django.contrib import admin from django.db import models from django.forms.widgets import TextInput from apps.managers.challenge_mgr import challenge_mgr from apps.managers.log_mgr.models import MakahikiLog from apps.admin.admin import challenge_designer_site, challenge_manager_site, develop...
admin.site.register(MakahikiLo
g, MakahikiLogAdmin) challenge_designer_site.register(MakahikiLog, MakahikiLogAdmin) challenge_manager_site.register(MakahikiLog, MakahikiLogAdmin) developer_site.register(MakahikiLog, MakahikiLogAdmin) challenge_mgr.register_admin_challenge_info_model("Status", 1, MakahikiLog, 1) challenge_mgr.register_developer_chall...
from ni.core.selection import Selection from ni.core.text import char_pos_to_tab_pos from ni.core.document import InsertDelta, DeleteDelta class Action(object): """Base class for all view actions.""" def __init__(self, view): self.grouped = False self.editor = view.editor self.view = ...
#print original_position, view.cursor_pos, start_offset, end_offset view.selection = Selection(doc, start_offset, end_offset) def move(self): raise NotImplementedError class EditAction(Action): """Base class
for all undoable actions.""" def __init__(self, view): super(EditAction, self).__init__(view) self.before_cursor_pos = None self.before_last_x_pos = None self.before_scroll_pos = None self.after_cursor_pos = None self.after_last_x_pos = None self.after_scro...
#!/usr/bin/env python from glob import glob from distutils.core import setup setup( name="mythutil
s_recfail_alarm", version="1.0", description="Autoamtically notify on Recorder Failed via Prowl service", author="Wylie Swanson", author_email="wylie@pingzero.net", url="http://www.pingzero.net", scripts=glob("bin/*"), data_file
s=[ ( '/etc/mythutils/', glob('etc/mythutils/*') ), ( '/etc/cron.d/', glob('etc/cron.d/*') ), ] )
## # You should have received a copy of the GNU General Public License # alo
ng
with EasyBuild. If not, see <http://www.gnu.org/licenses/>. ## """ EasyBuild support for xlmpich compiler toolchain (includes IBM XL compilers (xlc, xlf) and MPICH). @author: Jack Perdue <j-perdue@tamu.edu> - TAMU HPRC - http://sc.tamu.edu """ from easybuild.toolchains.compiler.ibmxl import IBMXL from easybuild.toolc...
sourceConformity classes = ('collapse closed',) extra = 1 class ResponsiblePartyRoleInline(admin.TabularInline): model = ResponsiblePartyRole classes = ('collapse closed',) extra = 1 class ResourceResponsiblePartyRoleInline(admin.TabularInline): model = ResourceResponsiblePartyRole classes...
.is_superuser: return qs return qs.filter(id__in = UserObjectRoleMapping.objects.filter(user=request.user, role__codename__in =('layer_readwrite','layer_admin') ...
) list_display = ('titleml',) inlines = [ # OnlineResourceInline, TemporalExtentInline, ReferenceDateInline, ConformityInline, ResponsiblePartyRoleInline, MdResponsiblePartyRoleInline, # ConnectionInli...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016 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...
ut even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PA
RTICULAR 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. # # In applying this license, CERN does n...
######### # Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
self.assertEqual(result['context']['key'], 'value') self.assertEqual(result['name'], 'test_provider') def test_post_provider_context_t
wice_fails(self): self.test_post_provider_context() self.assertRaises(self.failureException, self.test_post_provider_context) def test_update_provider_context(self): self.test_post_provider_context() new_context = {'key': 'new-value'} self.client.ma...
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you
under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtai
n 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 # ...
# -*- coding: utf-8 -*- from
__future__ import unicode_literals from .completion import Person def test_person_suggests_on_all_variants_of_name(write_client): Person.init(using=write_client) Person(name='Honza Král', popularity=42).save(refresh=True) s = Person.search().suggest('t', 'kra', completion={'field': 'suggest'}) respo...
Honza Král'
#this mod
ule here is to compute the formula to calculate the new means and #new variance. def update(mean1, var1, mean2, var2): new_mean = ((mean1 * var2) + (mean2*var1))/(var1 + var2) new_var = 1/(1/var1 + 1/var2) return [new_mean, new_var] def predict(mean1, var1, mean2, var2): new_mean = mean1 + mean...
12.,4.)
indentation = _remove_ansi_escape_sequences(formatted).find( lines[0] ) else: # Optimizes logging by allowing a fixed indentation. indentation = auto_indent lines[0] = formatted return ("...
% record.__dict__ def get_option_ini(config: Config, *names: str): for name in names: ret = config.getoption(name) # 'default' arg won't work as expected if ret is None: ret = config.getini(name) if ret: return ret def pytes
t_addoption(parser: Parser) -> None: """Add options to control log capturing.""" group = parser.getgroup("logging") def add_option_ini(option, dest, default=None, type=None, **kwargs): parser.addini( dest, default=default, type=type, help="default value for " + option ) ...
#! /usr/bin/env python """ this file converts simple html text into a docbook xml variant. The mapping of markups and links is far from perfect. But all we want is the docbook-to-pdf converter and similar technology being present in the world of docbook-to-anything converters. """ from datetime import date import ma...
i>") >> "</para></listitem>\n", ] class htm2dbk_conversion(htm2dbk_conversion_base): def __init__(self): self.version = "" # str(date.today) self.filename = "." def convert(self,text): # $text txt = text.replace("<!--VERSION--
>", self.version) for conv in self.regexlist: txt &= conv return txt.replace("--filename--", self.filename) def convert2(self,text): # $text txt = text.replace("<!--VERSION-->", self.version) for conv in self.regexlist: txt &= conv return txt class ht...
# Copyright 2013 Donald Stufft # # 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, so...
('clint', clint.__version__), ] def dep_versions(): return ', '.join( '{0}: {1}'.format(*dependency) for dependency in list_dependencies_and_versions() ) def dispatch(argv): registered_c
ommands = _registered_commands() parser = argparse.ArgumentParser(prog="twine") parser.add_argument( "--version", action="version", version="%(prog)s version {0} ({1})".format(twine.__version__, dep_versions()), ) parser.add_arg...
t. """ def solve_poly_system(seq, *gens, **args): """ Solve a system of polynomial equations. Examples ======== >>> from sympy import solve_poly_system >>> from sympy.abc import x, y >>> solve_po
ly_system([x*y - 2*y, 2*y**2 - x**2], x, y) [(0, 0), (2, -sqrt(2)), (2, sqrt(2))] """ try: polys, opt = parallel_poly_from_expr(seq, *gens, **args) except PolificationFailed, exc: raise Computat
ionFailed('solve_poly_system', len(seq), exc) if len(polys) == len(opt.gens) == 2: f, g = polys a, b = f.degree_list() c, d = g.degree_list() if a <= 2 and b <= 2 and c <= 2 and d <= 2: try: return solve_biquadratic(f, g, opt) except SolveFa...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration): dependencies = [ ('rh', '0001_initial'), ('estoque', '0005_auto_20141001_0953'), ('comercial', '0007_auto_20141006_1852'), ...
eField(default=datetime.datetime.now, verbose_name=b'Criado', auto_now_add
=True)), ('atualizado', models.DateTimeField(default=datetime.datetime.now, verbose_name=b'Atualizado', auto_now=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='LinhaListaMaterialCompra', ...
__author__ = "Martin Jakomin, Mateja Rojko" """ Classes for boolean operators: - Var - Neg - Or - And - Const Functions: - nnf - simplify - cnf - solve - simplify_cnf """ import itertools # functions def nnf(f): """ Returns negation normal form """ return f.nnf() def simplify(f): """ Simplifies th...
it__(self,v): self.value = v def __str__(self): return "~" + str(self.value.__str__()) def solve(self, v): return not(self.value.solve(v)) def simplify_cnf(self, v): if self.value.name in v: return Const(not(v[self.value.name])) else: return...
return v.value.nnf() elif isinstance(v, And): return Or([Neg(x) for x in v.value]).nnf() elif isinstance(v, Or): return And([Neg(x) for x in v.value]).nnf() elif isinstance(v, Const): return v.negate() def simplify(self): return self ...
from time import sleep from tqdm import tqdm import requests url = "http://raw.githubusercontent.com/Alafazam/lecture_notes/master/Cormen%20.pdf" response = requests.get(url, stream=True) with open("10MB", "wb") as handle: total_length = int(response.headers.get('content-length'))/1024 for data in tqdm(response.it...
= requests.get(url, stream=True) # for chunk in tqdm(r.iter_content()
): # f.write(chunk) # from tqdm import tqdm # for i in tqdm(range(10000)): # sleep(0.01)
from mock import patch from tests import BaseTestCase from redash.tasks import refresh_schemas class TestRefreshSchemas(BaseTestCase): def test_calls_refresh_of_all_data_sources(self): self.factory.data_source # trigger creation with patch( "redash.tasks.queries.maintenance.ref
resh_schema.delay" ) as refresh_job: refresh_schemas() refresh_job.assert_called() def test_skips_paused_data_sources(self): self.factory.data_source.pause() with patch( "redash.tasks.queries.maintenance.refresh_schema.delay"
) as refresh_job: refresh_schemas() refresh_job.assert_not_called() self.factory.data_source.resume() with patch( "redash.tasks.queries.maintenance.refresh_schema.delay" ) as refresh_job: refresh_schemas() refresh_job.assert_ca...
from pymongo impor
t MongoClient from passlib.app import custom_app_context as pwd client = MongoClient( host = "db" ) ride_sharing = client.ride_sharing users = ride_sharing.users users.insert_one( { 'username' : 'sid
', 'password_hash' : pwd.encrypt( 'test' ), 'role' : 'driver' } )
"""This module prints lists that may or may not contain ne
sted lists""" def print_lol(the_list):
"""This function takes a positional argument: called "the_list", which is any Python list which may include nested lists. Each data item in the provided lists recursively printed to the screen on its own line.""" for each_item in the_list: if isinstance(each_item,list): print_lol(each_item...
import os import PIL import math import PIL from PIL import Image class MandelbrotImage: def __init__(self, folder): self.folder = folder self.data_folder = os.path.join(folder, 'data') self.image_folder = os.path.join(folder, 'image') if not os.path.isdir(self.image_folder): os.makedirs(self.image_fo...
ata_to_image(self, filename, pixel_data, width, height): image = Image.new('RGB', (width, height)) image.putdata(pixel_data) image.save(os.path.join(self.image_folder, filename)) def coloring(escape_time, z_real, z_imag, max_iterations): escape_time = int(escape_time) z_real = float(z_real) z_imag
= float(z_imag) max_iterations = int(max_iterations) if escape_time == max_iterations + 1: return (255, 255, 255) else: q = escape_time - math.log(math.log((z_real ** 2 + z_imag ** 2))/(2*math.log(2))) return (int(q*255./max_iterations), 0, 0) f = "1" A = MandelbrotImage("1") for idx, file in enumerate(A.list...
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICA
TIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.obj
ect import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/bio_engineer/bio_component/shared_bio_component_food_duration_2.iff" result.attribute_template_id = -1 result.stfName("","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
"WandererActionsPlanned" MEM_CURRENT_ACTIONS = "WandererActionsInProgress" MEM_COMPLETED_ACTIONS = "WandererActionsCompleted" MEM_CURRENT_EVENT = "WandererEvent" MEM_MAP = "WandererMap" MEM_LOCATION = "WandererLocation" EVENT_LOOK_FOR_PEOPLE = "WandererEventLookForPeople" DEFAULT_CONFIG_FILE = "wanderer" PROPERTY_PLA...
return plan # return true if this event should cause the current plan to be executed and # a new plan created to react to it def does_event_interrupt_plan(self, event, state): return True def dispatch(self, event, state): methodName = 'handle'+ event.name() try: ...
dler for: {}".format(event.name())) def shutdown(self): pass ''' Base class for executing plans. Since we may need to trigger choreographe boxes we delegate actually performing a single action to an actionExecutor which in most cases will be the choreographe box that called us. The actionExecutor must i...
# -*- coding: utf-8 -*- from
__future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('attivita', '0012_attivita_centrale_operativa'), ] operations = [ migrations.AddField( model_name='partecipazione', name='central...
field=models.BooleanField(default=False, db_index=True), ), ]
# -*- coding: utf-8 -*- # # RERO ILS # Copyright (C) 2019 RERO # Copyright (C) 2020 UCLouvain # # 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, version 3 of the License. # # This program ...
on class.""" minter = organisation_id_minter fetcher = organisation_id_fetcher provider = OrganisationProvider model_cls = OrganisationMetadata @classmethod def get_all(cls): """Get all organisations.""" return sorted([
Organisation.get_record_by_id(_id) for _id in Organisation.get_all_ids() ], key=lambda org: org.get('name')) @classmethod def all_code(cls): """Get all code.""" return [org.get('code') for org in cls.get_all()] @classmethod def get_record_by_viewcode(cls, vie...
import numpy as np from rdkit.Chem import MolFromSmiles from features import atom_features, bond_features degrees = [0, 1, 2, 3, 4, 5] class MolGraph(object): def __init__(self): self.nodes = {} # dict of lists of nodes, keyed by node type def new_node(self, ntype, features=None, rdkit_ix=None): ...
ubgraph.nodes for ntype in set(old_nodes.keys()) | set(new_nodes.keys()): old_nodes.setdefault(ntype, []).extend(new_nodes.get(ntype, [])) def sort_nodes_by_degree(self, ntype): nodes_by_degree = {i : [] for i in degrees} for node in self.nodes[ntype]: nodes_by_degre...
e[degree] self.nodes[(ntype, degree)] = cur_nodes new_nodes.extend(cur_nodes) self.nodes[ntype] = new_nodes def feature_array(self, ntype): assert ntype in self.nodes return np.array([node.features for node in self.nodes[ntype]]) def rdkit_ix_array(self): ...
import csv import operator import itertools import math import logger1 import re #main piece of code for calculating & wwriting alignments from processed data def calculateAlignments(utterances, markers, smoothing, outputFile, shouldWriteHeader, corpusType='CHILDES'): markers = checkMarkers(markers) groupedUtterance...
toAppend["category"] = row[0] markers.
append(toAppend) #print(toAppend["marker"]+'\t'+toAppend["category"]) return markers # checks & adapts the structure of the marker list to the appropriate one def checkMarkers(markers): toReturn = [] for marker in markers: if isinstance(marker, str): toReturn.append({"marker": marker, "category": marker}) ...
" _repr_template = '{name}=%r' _field_template = '''\ {name} = _property(_itemgetter({index:d}), doc='Alias for field number {index:d}') ''' def namedtuple(typename, field_names, verbose=False, rename=False): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point'...
, name in enumerate(field_names): if (not name.isidentifier() or _iskeyword(name) or name.startswith('_') or name in seen): field_names[index] = '_%d' % index seen.add(name) for name in [typename] + field_names: ...
gs') if not name.isidentifier(): raise ValueError('Type names and field names must be valid ' 'identifiers: %r' % name) if _iskeyword(name): raise ValueError('Type names and field names cannot be a ' 'keyword: %r' % ...
#!/usr/bin/env python3 # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Test proper accounting with an equivalent malleability clone # from test_framework.test_framework im...
ations"], -2) assert_equal(tx1_clone["confirmations"], 2) assert_equal(tx2["confirmations"], 1) # Check node0's total bal
ance; should be same as before the clone, + 100 BTC for 2 matured, # less possible orphaned matured subsidy expected += 100 if (self.options.mine_block): expected -= 50 assert_equal(self.nodes[0].getbalance(), expected) assert_equal(self.nodes[0].getbalance("*", 0), ...
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** # ...
om", int, "the number of wavelength points in the zoomed-in grid", 100) definition.add_optional("packages", float, "the number of photon packages per wavelength", 2e5) definition.add_flag("selfabsorption", "enable dust self-absorption") definition.add_optional("dust_grid", str, "the type of dust grid to use (bintree, ...
-------------------------------
#!/usr/bin/env python2.7 """Docker From Scratch Workshop -
Level 4: Add overlay FS. Goal: Instead of re-extracting the image, use it as a read-only layer (lowerdir), and create a copy-on-write layer for changes (upperdir). HINT: Don't forget that overlay fs also requires a workdir. Read more on overlay FS here: https://www.kernel.org
/doc/Documentation/filesystems/overlayfs.txt """ from __future__ import print_function import linux import tarfile import uuid import click import os import stat import traceback def _get_image_path(image_name, image_dir, image_suffix='tar'): return os.path.join(image_dir, os.extsep.join([image_name, image_suf...
#!usr/bin/env python # -*- coding: utf-8! -*- from collections import Counter, OrderedDict import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy.cluster.hierarchy import ward, dendrogram from sklearn.decomposition import PCA from sklearn.metrics.pairwise import euclidean_distances from s...
trix = np.asarray(slice_matrix).transpose() # librosa assumes that data[1] = time axis segment_starts = agglomerative(data=slice_matrix, k=nb_segments) break_points = [] for i in segment_starts: if i > 0: # skip first one, since it's always a segm start! break_points.append(slice_names[i...
slice_names, prefix='en', nb_segments=3, random_state=2015): np.random.seed(random_state) corpus_matrix = np.asarray(corpus_matrix) sample_cnts = OrderedCounter() for sn in slice_names: sample_cnts[sn] = [] for i in range(nb_segments): sample_cnts[sn].append(0) for n...
from pycipher import Vigenere import unittest class TestVigenere(unittest.TestCase): def test_encipher(self): keys = ('GERMAN', 'CIPHERS') plaintext = ('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz',
'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz') ciphertext = ('gftpesmlzvkysrfbqeyxlhwkedrncqkjxtiwqpdzocwvjfuicbpl', 'cjrkiwyjqyrpdfqxfywkmxemfdrteltmkyalsatrfhszhaymozgo') for
i,key in enumerate(keys): enc = Vigenere(key).encipher(plaintext[i]) self.assertEqual(enc.upper(), ciphertext[i].upper()) def test_decipher(self): keys = ('GERMAN', 'CIPHERS') plaintext= ('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', ...
import unicodecsv from django.contrib.auth.models import User from django.http import HttpResponse from django.utils.encoding import force_text from six.moves import map from oioioi.base.permissions import make_request_condition from oioioi.base.utils import re
quest_cached from oioioi.participants.controllers import ParticipantsController from oioioi.participants.models import Participant def is_contest_with_participants(contest): rcontroller = contest.controller.registration_co
ntroller() return isinstance(rcontroller, ParticipantsController) def is_onsite_contest(contest): if not is_contest_with_participants(contest): return False from oioioi.participants.admin import OnsiteRegistrationParticipantAdmin rcontroller = contest.controller.registration_controller() ...
""" Support for Tellstick lights. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/light.tellstick/ """ from homeassistant.components import tellstick from homeassistant.components.light import ATTR_BRIGHTNESS, Light from homeassistant.components.tellstick...
ATTR_DISCOVER_DEVICES, ATTR_DISCOVER_CONFIG) # pylint: disable=unused-argument def setup_platform(hass, config, add_devices, discovery_info=None): """Setup Tellstick lights.""" if (discovery_info is None or discovery_info[ATTR_DISCOVER_DEV...
itions = discovery_info.get(ATTR_DISCOVER_CONFIG, DEFAULT_SIGNAL_REPETITIONS) add_devices(TellstickLight( tellstick.TELLCORE_REGISTRY.get_device(switch_id), signal_repetitions) for switch_id in discovery_info[ATTR_DISCOVER_DEVICES]) class Tellst...
eld(max_length=40, editable=False, unique=True) commit_time = models.DateTimeField( db_index=True, null=True, blank=True ) commit_message = models.CharField( max_length=150, editable=False, null=True, blank=True ) travis_raw = models.TextField(null=True, blank...
ss_sent = models.DateTimeField(null=True) skype = models.CharField(max_length=200, blank=True, null=True) discord = models.CharField(max_length=200, blank=True, null=True) phone = models.CharField(max_length=200, blank=True, null=True) city = models.CharField(max_length=200, blank=True, null=True) b...
default=None, blank=True, null=True, help_text=_("Browser string used when this user was created") ) created_from_ip = models.GenericIPAddressField(blank=True, null=True) timezone_str = models.CharField( max_length=50, db_index=True, default='UTC', ) #...
from .widget_svg_layout import SVGLayoutBox from .widget
_fullscreen im
port FullscreenBox
""" WSGI config for Bilyric project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` ...
ango WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os from django.cor...
'DJANGO_SETTINGS_MODULE') == 'config.settings.production': from raven.contrib.django.raven_compat.middleware.wsgi import Sentry # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each ...
= self.load_policy( { "name": "copy-related-tags", "resource": "aws.ebs-snapshot", "filters": [{"tag:Test": "Test"}], "actions": [ { "type": "copy-related-tag", "resource": "e...
'name': 'volume-detach', 'resource': 'ebs', 'filters': [{'VolumeId': 'vol-0850cf7c8e949c318'}], 'actions': [ { 'type': 'detach' } ] }, session_factory=factory) res...
ory(region="us-east-1").client('ec2') volumelist = [] volumelist.append(resources[0]['VolumeId']) response = client.describe_volumes(VolumeIds=volumelist) for resp in response['Volumes']: for attachment in resp['Attachments']: self.assertTrue(attachment['Stat...
# -*- coding: utf-8 -*- __all__ = ['host_blueprint'] from datetime import datetime, timedelta # dateutil from dateutil.parser import parse as dtparse # flask from flask import ( Flask, request, session, g, redirect, url_for, abort, render_template, flash, jsonify, Blueprint, abort, send_from_direc...
cals() if usertype != 'super': data = {} return jsonify(data) name = _host['name'] host = _host['host'] port = _host['port'] auth_username = _
host['auth_username'] auth_password = _host['auth_password'] ram_capacity = _host['ram_capacity'] ram_reserved = _host['ram_reserved'] if '[' in name and '-' in name and ']' in name and \ '[' in host and '-' in host and ']' in host: _hosts = [] hosts = [] # n...
的交易数量是否大于order2 lt = order1 < order2 # order1唯一的交易数量是否小于order2 """ def __init__(self, orders_pd, same_rule=EOrderSameRule.ORDER_SAME_BSPD): """ 初始化函数需要pd.DataFrame对象,暂时未做类型检测 :param orders_pd: 回测结果生成的交易订单构成的pd.DataFrame对象 :param same_rule: order判断为是否相同使用的规则, 默认EO...
R_SAME_BSPD 即:order有相同的symbol和买入日期和相同的卖出日期和价格才认为是相同 """ # 需要copy因为会添加orders_pd的列属性等 self.orders_pd = orders_pd.copy() self.same_rule = same_rule # 并集, 交集, 差集运算结果存储 self.op_result = None self.last_op_metrics = {} @contextmanager d...
orders_pd: 回测结果生成的交易订单构成的pd.DataFrame对象 :return: """ # 运算集结果重置 self.op_result = None # 实例化比较的ABuOrderPdProxy对象 other = AbuOrderPdProxy(orders_pd) try: yield self, other finally: if isinstance(self.op_result, pd.DataFrame): ...
from tabulate import tabulate class Response(): message = None; data = None; def print(self): if self.message: if type(self.message) == "str": print(self.message) elif type(self.message) == "list": for message in self.message: ...
print("{}\n".format(message)) if (self.data):
if len(self.data["rows"]) > 0: print(tabulate(self.data["rows"], headers=self.data["headers"])) else: print("Empty!")
import rply from ..lexer import lexers __all__ = ('parsers',) class Parsers(object): def __init__(self): self._fpg = None self._fp = None self._spg = None self._sp = None @property def fpg(self): if self._fpg is None: self._fpg = rply.ParserGenerato...
= rply.ParserGenerator( [rule.name for rule in lexers.slg.rules]
, precedence=[] ) return self._spg @property def sp(self): if self._sp is None: self._sp = self.spg.build() return self._sp parsers = Parsers() # Load productions from .filter import fpg # noqa from .structure import spg # noqa
# -*- coding: utf-8 -*- # (C) 2017 Muthiah Annamalai # This file is part of open-tamil examples # This code is released under public domain import joblib # Ref API help from : https://scikit-learn.org import numpy as np import random import string import time from sklearn.metrics import accuracy_score from sklearn.met...
t)) score = nn.score(X_test, Y_test) print("Score => ") print(score) print(confusion_matrix(Y_test, Y_pred.ravel())) print(classification_report(Y_test, Y_pred.ravel())) def process_word(s): if any([l in string.ascii_lowercase for l in s]): s = jaffna_transliterate(s) print(u"Transliterated to
%s" % s) print(u"Checking in NN '%s'" % s) try: f = Feature.get(s) scaled_feature = scaler.transform(np.array(f.data()).reshape(1, -1)) y = nn.predict(scaled_feature) print(scaled_feature) print(y) if y.ravel() > 0: print(u"%s -> TAMIL world (most like...
les serialization and deserialization, so we just need # to pass in the functions for each. if "create_trial" not in self._stubs: self._stubs["create_trial"] = self.grpc_channel.unary_unary( "/google.cloud.aiplatform.v1beta1.VizierService/CreateTrial", request...
on the server. """ # Generate a "stub function" on-the-fly which will actually make # the request.
# gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. if "list_trials" not in self._stubs: self._stubs["list_trials"] = self.grpc_channel.unary_unary( "/google.cloud.aiplatform.v1beta1.VizierService/ListTrials", ...
"""Response classes used by urllib. The base class, addbase, defines a minimal file-like interface, including read() and readline(). The typical response object is an addinfourl instance, which defines an info() method that returns headers and a geturl() method that returns the url. """ class addbase(object): ""...
ut on the underlying socket? def __init__(self, fp): # TODO(jhylton): Is there a better way to delegate using io? self.fp = fp self.read = self.fp.read self.readline = self.fp.readline # TODO(jhylton): Make sure an object with readlines() is also iterable if hasattr(...
fileno = self.fp.fileno else: self.fileno = lambda: None def __iter__(self): # Assigning `__iter__` to the instance doesn't work as intended # because the iter builtin does something like `cls.__iter__(obj)` # and thus fails to find the _bound_ method `obj.__iter__`. ...
import json from django.db.models import Q, Subquery from django.core.management.base import BaseCommand from readthedocs.oauth.models import RemoteRepository from readthedocs.oauth.services import registry from readthedocs.oauth.services.base import SyncServiceError from readthedocs.projects.models import Project fr...
.', ) # If owners does not have their RemoteRepository synced, it could # happen we don't find a matching Project (see --force-owners-social-resync) parser.add_argument( '--only-owners', action='store_true', default=False, help='Connect re...
sitories only to organization owners.', ) parser.add_argument( '--force-owners-social-resync', action='store_true', default=False, help='Force to re-sync RemoteRepository for organization owners.', ) def _force_owners_social_resync(self, orga...
-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.db import models class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." ...
ipversion = 4 if attr == "ipv4" else 6 subnet = nic.network.subnets.get(ipversion=ipversion) orm.IPAddress.objects.create(network=network, subnet=subnet, nic=nic, ...
backwards(self, orm): "Write your backwards methods here." for ip in orm.IPAddress.objects.filter(deleted=False): nic = ip.nic attr = "ipv4" if nic.subnet.ipversion == 4 else "ipv6" setattr(nic, attr, ip.address) nic.save() models = { 'db.bac...
r Render tsr samples and push direction vectors during planning """ HerbGrasp(robot, obj, manip=manip, preshape=preshape, tsrlist=tsrlist, render=render) @ActionMethod def PushGrasp(robot, obj, push_distance=0.1, manip=None, preshape=[0., 0., 0., 0.], push_required=True, ...
erforming the push grasp @param obj The object to lift @param distance The distance to lift the cup @para
m manip The manipulator to perform the grasp with (if None active manipulator is used) @param render Render tsr samples and push direction vectors during planning """ if manip is None: with robot.GetEnv(): manip = robot.GetActiveManipulator() # Check for collision and disabl...
import pygame import src.graphics as graphics import src.colours as colours import src.config as config import s
rc.scenes.scenebase as scene_base from src.minigames.hunt.input_handler import InputHandler from src.gui.clickable import Clickable from src.resolution_asset_sizer import ResolutionAssetSizer from src.tiled_map import TiledMap from src.game_object.deadly_area import DeadlyArea from src.minigames.hunt.player import Pla...
current_stage=1): self.current_stage = current_stage self.file = './assets/game-data/levels/minigames/hunt/minigame-hunt-' + str(self.current_stage) + '.tmx' self.surface = graphics.get_window_surface() self.tiled_map = TiledMap(self.file, self.surface) self.sprites = self.tiled...
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from flask import request from indico.modules.auth.controllers import (RHAccounts, RHAdminImpersonate, RH...
<provider>', 'register', RHRegister, methods=('GET', 'POST')) _bp.add_url_rule('/reset-password/', 'resetpass', RHResetPassword, methods=('GET', 'POST')) _bp.add_url_rule('/admin/users/impersonate', 'admin_impersonate', RHAdminImpersonate, methods=('POST',)) with _bp.add_prefixed_rules('/user/<int:user_id>', '/user'...
unts/<identity>/remove/', 'remove_account', RHRemoveAccount, methods=('POST',)) @_bp.url_defaults def _add_user_id(endpoint, values): if endpoint in {'auth.accounts', 'auth.remove_account'} and 'user_id' not in values: values['user_id'] = request.view_args.get('user_id') # Legacy URLs auth_compat_bluepr...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group, User
def add_moderator_group(apps, schema_editor): g = Group.objects.create(name="moderators") g.save() for user in User.objects.all(): #
add any existing admin users # to the moderators group when we create it if user.is_superuser: g.user_set.add(user) class Migration(migrations.Migration): dependencies = [("auth", "0008_alter_user_username_max_length")] operations = [migrations.RunPython(add_moderator_group)]
import nuk
e import
pyblish.api class ExtractSceneSave(pyblish.api.Extractor): """ """ hosts = ['nuke'] order = pyblish.api.Extractor.order - 0.45 families = ['scene'] label = 'Scene Save' def process(self, instance): self.log.info('saving scene') nuke.scriptSave()
"""Responses.""" from io import StringIO from csv import DictWriter from flask import Response, jsonify, make_response from .__version__ import __version__ class ApiResult: """A representation of a generic JSON API result.""" def __init__(self, data, metadata=None, **kwargs): """Store input argumen...
e(self): """Make a response from the data.""" metadata = self.metadata(self.extra_metadata) obj = { **self.data, **self.kwargs, 'metadata': metadata } return jsonify(obj) @staticmetho
d def metadata(extra_metadata=None): """Return metadata.""" from .models import SourceData obj = { 'version': __version__, 'datasetMetadata': [item.to_json() for item in SourceData.query.all()] } if extra_metadata: ...
# -*- coding: utf-8 -*- # Akvo RSR is covered by the GNU Affero General Public License. # See more details in the license.txt file located at the root folder of the Akvo RSR module. # For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >. def related_activities(project): ...
not specified')) elif rp.related_project and not rp.related_project.iati_activity_id: all_checks_passed = False checks.append(('error', 'related project (id: %s) has no IATI identifier specified' %
str(rp.related_project.pk))) if not rp.relation: all_checks_passed = False checks.append(('error', 'relation missing for related project')) if related_projects_count > 0 and all_checks_passed: checks.append(('success', 'has valid related project(s)')) return all_check...
from formatting import print_call import credentials import os.path import re import xmlrpclib def _get_ch_params(): # Initialise variables when required from core.config import FullConfParser fcp = FullConfParser() username = fcp.get("auth.conf").get("certificates").get("username") ch_host = fcp...
_path or ("%-key.pem" % username) cert_path = cert_path or ("%-cert.pem" % username) host = host or ch_host port = por
t or ch_port endpoint = endpoint or ch_end # Start logic creds_path = os.path.normpath(os.path.join(os.path.dirname(__file__), "../../..", "cert")) if not os.path.isabs(key_path): key_path = os.path.join(creds_path, key_path) if not os.path.isabs(cert_path):...
from twi
sted.internet import reactor,protocol class EchoClient(protocol.Protocol): def connectionMade(self): self.transport.write("hello a ") def dataReceived(self, data): print('Server said:',data) self.transport.loseConnection() def connectionLost(self,
reason): print('connection lost') class EchoFatoty(protocol.ClientFactory): protocol = EchoClient def clientConnectionFailed(self, connector, reason): print('Connection lost - goodbye!') reactor.stop() def main(): f = EchoFatoty() reactor.connectTCP('localhost',9090,f) reacto...
# -*- coding: utf-8 -*- """The function module of dolfin""" from dolfin.functions import multimeshfunction from dolfin.functions import functionspace from dolfin.functions import function from dolfin.functions import constant from dolfin.functions import expression from dolfin.functions import specialfunctions from ....
import
* # NOTE: The automatic documentation system in DOLFIN requires to _not_ define # NOTE: classes or functions within this file. Use separate modules for that # NOTE: purpose. __all__ = functionspace.__all__ + function.__all__ + constant.__all__ + \ expression.__all__ + specialfunctions.__all__ + \ ...
from pyramid.view import view_config import logging @view_config(route_name='hell
o_json', renderer='json') def hello_json(request): logger = logging.getLogger(__name__) logger.info("Got JSON from name: {n}".format(n = __name__)) request.session['co
unter'] = request.session.get('counter', 0) + 1 return { 'a': [1,2,request.session['counter']], 'b': ['x', 'y'], }
rn dict Charateristic of a tweet """ ret = {} text = tweet['text'] retweets = tweet['retweet_count'] favorites = tweet['favorite_count'] followers = tweet['author_followers'] friends = tweet['author_friends'] publishes = tweet['author_num_of_status'] blob = TextBlob(text) p...
ublishes, 2) ) return round(ret, 2) def tweets2film(tweet_characteristics): """ Aggreate tweet's characteristics to form a film's characteristics @param tweet_characterist
ics list of dict @return dict characteristics of a film """ ret = {} retweets_data = [] favorites_data = [] polarities_data = [] friends_data = [] followers_data = [] for t in tweet_characteristics: retweets_data.append(t['retweets']) favorites_data.append(t...
"""Mark the current profile as saved by colouring the text black. """ index = self.profile_combo.currentIndex() item = self.profile_combo.model().item(index) item.setForeground(QtGui.QColor('black')) def add_new_resource(self): """Handle add new resource requests. ...
minimum_parameter.value = 0.00 maximum_parameter = FloatParameter('UUID-7') maximum_parameter.name = tr('Maximum allowed') maximum_parameter.is_required = True maximum_parameter.precision = 2 maximum_parameter.minimum_allowed_value = -99999.0 maximum_parameter.maximu...
on. ') maximum_parameter.description = tr( 'The <b>maximum</b> is the maximum allowed quantity of the ' 'resource per person. For example you may dictate that the water ' 'ration per person per day should never be allowed to be more ' 'than 67l. This is enforced w...
# Copyright 2020 The gRPC 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 writ...
ty): state = channel.get_state() while state != expected_state: await cha
nnel.wait_for_state_change(state) state = channel.get_state() def inject_callbacks(call: aio.Call): first_callback_ran = asyncio.Event() def first_callback(call): # Validate that all resopnses have been received # and the call is an end state. assert call.done() first_...
def _save_device_metadata(self, context, instance, block_device_info): """Builds a metadata object for instance devices, that maps the user provided tag to the hypervisor assigned device address. """ metadata = [] metadata.extend(self._get_vif_metadata(context, instance.uuid...
e_event( instance, events, deadline=timeout, error_callback=self._neutron_failed_callback): yield except etimeout.Timeout: # We never heard from Neutron LOG.warning(_LW('Timeout waiting for vif plugging callback for '
'instance.'), instance=instance) if CONF.vif_plugging_is_fatal: raise exception.VirtualInterfaceCreateException() def _neutron_failed_callback(self, event_name, instance): LOG.error(_LE('Neutron Reported failure on event %s'), event_name...
r, False otherwise. """ try: int(output) error = False except ValueError as err: error = True LOGGER.error(err) return error def count_jobs(): """ Count the number of jobs in the queue on the cluster :return: number of jobs in the queue """ if comma...
n walltime
cmd = DAX_SETTINGS.get_cmd_get_job_walltime()\ .safe_substitute({'numberofdays': diff_days, 'jobid': jobid}) try: output = sb.check_output(cmd, stderr=sb.STDOUT, shell=True) if output: walltime = output.strip() ...
import argparse from cheat_ext.info import info, ls from cheat_ext.installer import ( install, upgrade, remove ) from cheat_ext.linker import link, unlink def _install(args): install(args.repository) link(args.repository) def _upgrade(args): upgrade(args.repository) link(args.repository) def ...
tory", type=str) upgrade_parser.set_defaults(func=_upgrade) remove_parser = subparsers.add_parser("remove") remove_parser.add_argument("repository", type=str) remove_parser.set_defaults(func=_remove) info_parser = subparsers.add_parser("info") inf
o_parser.add_argument("repository", type=str) info_parser.set_defaults(func=_info) ls_parser = subparsers.add_parser("ls") ls_parser.set_defaults(func=_ls) def main(): options = parser.parse_args() options.func(options)
from datetime import datetime from os.path import abspath, join, dirname import alabaster # Alabaster theme + mini-extension html_theme_path = [alabaster.get_path()] extensions = ['alabaster', 'sphinx.ext.intersphinx', 'sphinx.ext.doctest'] # Paths relative to invoking conf.py - not this shared file html_theme = 'al...
mat(year) master_doc = 'index' templates_path = ['_templates'] exclu
de_trees = ['_build'] source_suffix = '.rst' default_role = 'obj'
# -*- coding: utf8 -*- ''' Copyright 2009 Denis Derman <denis.spir@gmail.com> (former developer) Copyright 2011-2012 Peter Potrowl <peter017@gmail.com> (current developer) This file is part of Pijnu. Pijnu is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public Lic...
t = Sequence(IMPORTANT, inline, IMPORTANT)(liftValue) monospaceText = Sequence(MONOSPACE, inline, MONOSPACE)(
liftValue) styledText = Choice(distinctText, importantText, monospaceText) text = Choice(styledText, rawText) inline **= OneOrMore(text) parser = Parser('wikiLine', locals(), 'inline')
e_group_name: str, account_name: str, backup_policy_name: str, **kwargs: Any ) -> HttpRequest: api_version = "2021-08-01" # Construct URL url = kwargs.pop("template_url", '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/b...
ame}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/backupPolicies/{backupPolicyName}'} # type: ignore def _create_initial( self, resource_group_name: str, account_name: str, backup_policy_name: str, body: "_models.BackupPolicy", **kwargs: Any ) -> Opt...
ptional["_models.BackupPolicy"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) content_type = kwargs.pop('content_type', "application/json") # type: Optional[str] _...
# -*- coding: utf-8 -*- import logging, logging.handlers from django.conf import settings def get_logger(name, level=logging.INFO, format='[%(asctime)s] %(message)s', handler=None, filename=None): new_logger = logging.getLog
ger(name) new_logger.setLevel(level) if not handler: filename = filename or '%s/logs/%s.log' % (settings.HOME_DIR, name) handler = logging.FileHandler(filename) handler.setFormatter(logging.Formatter(format)) new_logger.addHandler(handler) return new_logger if hasattr(settings, ...
ingFileHandler(settings.LOG_FILENAME, when = 'midnight') logger = get_logger('default', handler=handler)
class Solution: def containVirus(self, grid: List[List[int]]) -> int: current_set_number = 1 grid_set = [[0 for i in range(len(grid[0]))] for j in range(len(grid))] set_grid = {} threaten = {} def getAdjacentCellsSet(row, col) -> List[int]: answer = [] ...
rid)-1 and grid_set[row+1][col] != 0 and grid_set[row+1][col] not in answer: answer.append(grid_set[row+1][col]) if col != len(grid[0])-1 and grid_set[row][col+1] != 0 and grid_set[row][col+1] not in answer:
answer.append(grid_set[row][col+1]) if -1 in answer: answer.remove(-1) if grid_set[row][col] in answer: answer.remove(grid_set[row][col]) return answer # Merge all regions to the first one. def merge(regions: List[int]): ...
import copy from .point import Point from .misc import * ''' Line is defined using two point(s). ''' class Line(object): _ID_NAME = '_LINE_ID' _DB_NAME = '_EXISTING_LINES' def __init__(self, geom, p0, p1): def check(p): if geom is None: return p if isinstance(p, Point): ...
found,idx = exist(geom,self) if found: return '' return '\n'.join([('Line(%d) = {%d,%d};') % (idx,self.pid[0],
self.pid[1])]) # NOTE: for uniqueness the sorted idx is used as "key" in the database def key(self, master=False): keystr=remove_bracket(str(sorted(map(abs,self.pid)) + self.pid)) if master: return remove_bracket(str(sorted(map(abs,self.pid)))) return keystr # this is ...
#!/usr/bin/env python2 # Copyright (C) 2013-2014 Computer Sciences 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 # #...
bake-support-django', version='2.1', description='Supporting library for integrating Django applications with EzBake.', license='Apache License 2.0', author='EzBake Developers', author_email='developers@ezbake.io', namespace_packages=['ezbake', 'ez
bake.support'], packages=find_packages('lib', exclude=['test*']), package_dir={'': 'lib'}, install_requires=[ 'ezbake-security-client==2.1', 'Django>=1.4', 'psycopg2>=2.5', ], )
#!/usr/bin/env python # encoding: utf-8 """An example for a function returning a function""" def surround(tag1, tag2): def wraps(content): return '{}{}{}'.format(tag1, content, tag2) re
turn wraps def printer(content, transform): return transform(content) print printer("foo bar", surround("<a>", "</a>")) print printer("foo bar", s
urround('<p>', '</p>'))
"""Module containing the logic for our debugging logic.""" from __future__ import print_function import json import platform
import setuptools def print_information(option, option_string, value, parser, option_manager=None): """Print debugging information used in bug reports. :param option: The optparse Option instance. :type option: optparse.Option :param str option_string: Th...
m the command-line :param parser: The optparse OptionParser instance :type parser: optparse.OptionParser :param option_manager: The Flake8 OptionManager instance. :type option_manager: flake8.options.manager.OptionManager """ if not option_manager.registered_plugi...
text="Access to the member's username. This implicitly enables access to anything the user is publicly sharing on Open Humans. Note that this is potentially sensitive and/or identifying.", verbose_name='Are you requesting Open Humans usernames?')), ('approved', models.BooleanField(default=False)), ...
_sharing.DataRequestProject'), ), migrations.AddField( model_name='datarequestproject', name='coordinator', field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='open_humans.Member'), ), migrations.AlterField( model_name=...
name='long_description', field=models.TextField(max_length=1000, verbose_name='A long description (1000 characters max)'), ), migrations.AlterField( model_name='datarequestproject', name='short_description', field=models.CharField(max_length=140, verbos...
from setuptools import setup, find_packages setup( name="simple-crawler", version="0.1", url="https://github.com/shonenada/crawler", author="shonenada", author_email="shone
nada@gmail.com", description="Simple crawler", zip_safe=True, platforms="any", packages=find_packages(), install_requires=["reque
sts==2.2.1"], )
# -*- mode: python -*- # -*- coding: iso8859-15 -*- ############################################################################## # # Gestion scolarite IUT # # Copyright (c) 2001 - 2006 Emmanuel Viennet. Al
l rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License,
or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy...
1 < len(screw_axes): next_axis = np.dot(np.transpose(M_rot), screw_axes[i + 1]) ideal_axis = geometry.rotation_matrix_to_axis_and_angle( theta_tau_to_rotation_matrix(THETA_MEAN, TAU_MEAN))[0] theta, tau = theta_tau_for_nexus(next_axis, ideal_axis) if not...
rotate_axis, angle_to_rotate) new_axis_global = np.dot(M_rot, axis1_global) new_axis_local = np.dot(np.transpose(M_init), new_axis_global) theta, tau = axis_to_theta_tau(new_axis_local) if check_theta_tau(theta, tau): screw_axes.append(new_axis_global) ...
omega) for i in range(1, 3): screw_axes.append(np.dot(M_rot, screw_axes[i - 1])) # Get the internal coordinates try: thetas, taus, M = get_theta_tau_and_rotation_matrix_from_screw_axes( screw_axes, M_init=M_init) except: return None, None return thetas[1:]...
from common.models import * from common.localization import txt, verbose_names @verbose_names class Patient(models.Model): # private first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) GENDER = ( (txt('M'), txt('male')), (txt('F'), txt('female')) ...
0Rh-'), txt('0Rh-')), (txt('0Rh+'), txt('0Rh+')), (txt('ARh-'), txt('ARh-')), (txt('ARh+'), txt('ARh+')), (txt('BRh-'), txt('BRh-')), (txt('BRh+'), txt('BRh+')), (txt('ABR-'), txt('ABRh-')), (txt(
'ABR+'), txt('ABRh+')), ) blood_type = models.CharField(max_length=4, choices=BLOOD_TYPE, blank=True, null=True) birth_date = models.DateField() pesel = PESELField() # address country = models.CharField(max_length=80, default="Polska") city = models.CharField(max_length=80) address = mo...
# Generated by Django 2.2.15 on 2020-11-24 06:44 from decimal import Decimal import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("assignments", "0015_assignmentvote_delegated_user"), ] operations = [ migrations...
"N", "No per c
andidate"), ("YN", "Yes/No per candidate"), ("YNA", "Yes/No/Abstain per candidate"), ], max_length=5, ), ), ]
g import time import unittest from unittest.case import skip import weakref logging.basicConfig(format="%(asctime)s %(levelname)-7s %(module)-15s: %(message)s") logging.getLogger().setLevel(logging.DEBUG) CONFIG_PATH = os.path.dirname(odemis.__file__) + "/../../install/linux/usr/share/odemis/" SECOM_LENS_CONFIG = C...
ebeam.dwellTime.value = self.ebeam.dwellTime.range[0] # start one image acquisition (so it should do the calibration) f = acq.acquire([st]) received, _ = f.result() self.assertTrue(received, "No image received after 30 s") # Check the correction metadata is there
md = self.sed.getMetadata() self.assertIn(model.MD_POS_COR, md) # Check the position of the image is correct pos_cor = md[model.MD_POS_COR] pos_dict = self.stage.position.value pos = (pos_dict["x"], pos_dict["y"]) exp_pos = tuple(p - c for p, c in zip(pos, pos_cor)...
#!/usr/bin/env python3 """ Created on 15 Aug 2016 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) Note: this script uses the Pt1000 temp sensor for temperature compensation. """ import time from scs_core.data.json import JSONify from scs_core.gas.afe_baseline import AFEBaseline from scs_core.gas.afe_ca...
000 = Pt1000(pt1000_calib) print(pt1000) print("-") afe_calib = AFE
Calib.load(Host) print(afe_calib) print("-") afe_baseline = AFEBaseline.load(Host) print(afe_baseline) print("-") sensors = afe_calib.sensors(afe_baseline) print('\n\n'.join(str(sensor) for sensor in sensors)) print("-") # ---------------------------------------------------------...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-08-20 01:22 from __future__ import
unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0002_auto_20170819_2342'), ] operations = [
migrations.RemoveField( model_name='tag', name='articles', ), ]
from django.db import models from django.core.validators import validate_email, validate_slug, validate_ipv46_address from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from ava.core.models import TimeStampedModel from ava.core_group.models import Group from ava.core_identi...
validate_ipv46_address(self.identifier) except ValidationError: raise ValidationError('Identifier is not a valid IPv4/IPv6 address') if self.identifier_type is 'UNAME' or self.identifier_type is 'NAME': try: validate_slug(self.identifier) ...
r name') if self.identifier_type is 'SKYPE': try: validate_skype(self.identifier) except ValidationError: raise ValidationError('Identifier is not a valid Skype user name') if self.identifier_type is 'TWITTER': try: va...
he 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 collections from cinderclient.v1 import client as cinder_client_v1 from cinde...
other_host:8776/v1/project_id', self.create_client().client.endpoint_override) def test_get_non_existing_volume(self): self.requests.get(self.URL + '/volumes/nonexisting', status_code=404)
self.assertRaises(exception.VolumeNotFound, self.api.get, self.context, 'nonexisting') def test_volume_with_image_metadata(self): v = self.stub_volume(id='1234', volume_image_metadata=_image_metadata) m = self.requests.get(self.URL + '/volumes/5678', json={'volume'...
def delete_document(func): """Remove and expunge the returned document.""" @functools.wraps(func) def wrapped(self, *args, **kwargs): document = func(self, *args, **kwargs) or self if settings.ADDREMOVE_FILES and document.tree: document.tree.vcs.delete(document.config) ...
) return result ret
urn wrapped class BaseFileObject(metaclass=abc.ABCMeta): """Abstract Base Class for objects whose attributes save to a file. For properties that are saved to a file, decorate their getters with :func:`auto_load` and their setters with :func:`auto_save`. """ auto = True # set to False to delay ...
try: from setuptools import setup except ImportError: from distutils.core import
setup config = { 'description': 'ex48', 'author': 'Zhao, Li', 'url': 'URL to get it at.', 'download_url': 'Where to download it.', 'author_email': 'zhaoace@gmail.com', 'version': '0.1', 'install_requires': ['nose'], 'packages': ['ex48'], 'scripts': [], 'name': 'ex48
' } setup(**config)
# -*- encoding: utf-8 -*- # # Copyright © 2013 IBM Corp # # Author: Tong Li <litong01@us.ibm.com> # # 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/LICEN...
been created. self.assertTrue(os.path.exists(handler.baseFilename)) def test_file_dispatcher_with_path_only(self): # Create a temporaryFile to get a file name tf = tempfile.NamedTemporaryFile('r') filename = tf.name tf.close() self.CONF.dispatcher_file.file_path = ...
me self.CONF.dispatcher_file.max_bytes = None self.CONF.dispatcher_file.backup_count = None dispatcher = file.FileDispatcher(self.CONF) # The number of the handlers should be 1 self.assertEqual(1, len(dispatcher.log.handlers)) # The handler should be RotatingFileHandler ...
#!/usr/bin/env python imp
ort os import sys from optparse import OptionParser def makeoptions(): parser = OptionParser() parser.add_option("-v", "--verbosity", t
ype = int, action="store", dest="verbosity", default=1, help="Tests verbosity level, one of 0, 1, 2 or 3") return parser if __name__ == '__main__': import djpcms import sys options, tags = makeoptions().parse_args()...
import tensorflow as tf import numpy as np import cv2 img_original = cv2.imread('jack.jpg') #data.camera() img = cv2.resize(img_original, (64*5,64*5)) # for positions xs = [] # for corresponding colors ys = [] for row_i in range(img.shape[0]): for col_i in range(img.shape[1]): xs.append([row_i, col_i]) ys.app...
_input=n_neurons[layer_i - 1], n_output=n_neurons[layer_i], activation=tf.nn.relu if (layer_i+1) < len(n_neurons) else None, scope='layer_' + str(layer_i)) Y_pred = current_input cost =
tf.reduce_mean(tf.reduce_sum(distance(Y_pred,Y),1) ) optimizer = tf.train.AdamOptimizer(0.001).minimize(cost) #training Neural Net n_iterations = 500 batch_size = 50 with tf.Session() as sess: sess.run(tf.initialize_all_variables()) prev_training_cost = 0.0 for it_i in range(n_iterations): idxs ...
from django import forms from django.core.urlresolvers import reverse from django.forms.widgets import RadioFieldRenderer from django.utils.encoding import force_text from django.utils.html import format_html from django.utils.safestring import mark_safe class BootstrapChoiceFieldRenderer(RadioFieldRenderer): """...
self.attrs = {'id': 'use_custom_reg'} self.widgets = ( forms.CheckboxInput(), forms.Select(attrs={'class': 'form-control'}),
forms.RadioSelect(renderer=BootstrapChoiceFieldRenderer) ) super(UseCustomRegWidget, self).__init__(self.widgets, attrs) def render(self, name, value, attrs=None): if not isinstance(value, list): value = self.decompress(value) final_attrs = self.build_attrs(attrs) ...
# Prints exactly what the script is about to do print "How many keys are there for the swedish alphabet?" # Prints the amount of the top row print "The top row has 11 letter keys" # Assig
ns a value to top top = 11.0 # Prints the amount of the middle row print "The middle row has 11 letter keys" # Assigns a value to middle middle = 11 # Prints the amount of the bottom row print "The bottom row has 7 letter keys" # Assigns a value to bottom bottom = 7 # P
rints text then the combined value of from the three rows print "The total number of letter keys are ", top + middle + bottom
import py import re from testing.test_interpreter import BaseTestInterpreter from testing.test_main import TestMain from hippy.main import entry_point class TestOptionsMain(TestMain): def test_version_compare(self, capfd): output = self.run('''<?php $versions = array( '1', '1.0', ...
'1rc.0.2', 'bullshit.rc.9.2beta', ); foreach ($versions as $version) { if (isset($last)) { $comp = version_compare($last, $version); echo $comp; } $last = $version; } ?>''', capfd) assert outp...
-10-11-11-11" def test_version_compare_with_cmp(self, capfd): output = self.run('''<?php $versions = array( '1', '1.0', '1.01', '1.1', '1.10', '1.10b', '1.10.0', '-3.2.1', '1rc.0.2', 'bullshit.rc.9.2beta', ); ...
""" Unit tests for the base mechanism class. """ import pytest from azmq.mechanisms.base import Mechanism from azmq.errors import ProtocolError @pytest.mark.asyncio async def test_expect_command(reader): reader.write(b'\x04\x09\x03FOOhello') reader.seek(0) result = await Mechanism._expect_command(reade...
Mechanism.read(reader=reader, on_command=on_command)
assert result == (b'foo', True) @pytest.mark.asyncio async def test_read_frame_large(reader): reader.write(b'\x02\x00\x00\x00\x00\x00\x00\x00\x03foo') reader.seek(0) async def on_command(name, data): assert False result = await Mechanism.read(reader=reader, on_command=on_command) asser...
# -*- coding: utf8 -*- from phystricks import * def MBWHooeesXIrsz(): pspict,fig = SinglePicture("MBWHooeesXIrsz") pspict.dilatation(0.3) l=4 A=Point(0,0) B=Point(l,0) C=Point(l,l) trig=Polygon(A,B,C) trig.put_mark(0.2,pspict=pspict) trig.edges[0].put_code(n=2,d=0.1,l=0.2,psp
ict=pspict) trig.edges[1].put_code(n=2,d=0.1,l=0.2,pspict=pspict) no_symbol(
trig.vertices) pspict.DrawGraphs(trig) pspict.comment="Vérifier la longueur des codages." fig.no_figure() fig.conclude() fig.write_the_file()
#!/usr/bin/env python3 # Copyright (c) 2016 Anki, 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 in the file LICENSE.txt or at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unles...
erver responds immediately. asyncio.ensure_future(read_name()) return web.Response(text="OK") # Attach the function as an HTTP handler. app.router.add_post('/iftttGmail
', serve_gmail) if __name__ == '__main__': cozmo.setup_basic_logging() cozmo.robot.Robot.drive_off_charger_on_connect = False # Use our custom robot class with extra helper methods cozmo.conn.CozmoConnection.robot_factory = IFTTTRobot try: sdk_conn = cozmo.connect_on_loop(app.loop) ...