prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
import unittest from jsonschema import SchemaError from minibus import MiniBusClient class SyntaxTest(unittest.TestCase): def setUp(self): self.client = MiniBusClient() def callback(self): pass def callback2(self): pass def test_sub_good(self): self.client.subscribe("...
{"type": "number"}, self.callback) self.assertRaises(Exception, self.client.subscribe, "test_sub_schema_mismatch", {"type": "string"}, self.callback2) def test_sub_schema_dupcallback(self): self.client.subscribe("test_sub_schema_dupcallback", {"type": "number"}, self.callback) ...
"test_sub_schema_dupcallback", {"type": "number"}, self.callback) if __name__ == "__main__": unittest.main()
from model.contact import Contact from random import randrange def test_edit_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.create(Contact(first_name ="Sabina", last_name="test", company="Pewex", address="osiedle", phone_home="123456789", e_m...
sia', last_name='Bober') contact.id = old_contact[index].id app.contact.edit_contact_by_index(index, contact) assert len(old_contact) == app.contact.count() new_contact = db.get_contact_list() old_contact[index] = contact assert old_contact == new_contact if check_ui: assert
sorted(new_contact, key=Contact.id_or_max) == sorted( app.group.get_contact_list(), key=Contact.id_or_max )
efAssetHint(MozDefEvent): def validate(self): if not MozDefEvent.validate(self): return False # A hint event should always have details if len(self.details.keys()) == 0: return False return True def __init__(self, url): MozDefEvent.__init__(self, ...
self.compmsg['tags'] = { 'operator': 'it', 'autogroup': 'opsec' } self.compmsg['compliance'] = True self.compmsg['link'] = 'http://a.url' self.compmsg['policy'] = { 'url': 'http://another.url', 'name': 'system', 'level': ...
= { 'test': { 'type': 'nexpose', 'name': 'assess', 'value': 'nexpose' }, 'location': 'endpoint', 'ref': 'sysmediumupdates1', 'name': 'vulnerability scanner check', 'description': 'validate system patc...
e=32.*u.MHz, complex_data=False) data = fr.read(20000) # enough to fill one EDV3 frame. time1 = fr.tell(unit='time') # Get a file name in our temporary testing directory. vdif_file = str(tmpdir.join('converted.vdif')) # create and fill vdif file with converted data. ...
m = fm.read(20000) assert np.all(dm == dv) assert fm.offset == fv.offset assert fm.tell(unit='time') == fv.tell(unit='time') class TestVDIF0BPS1ToMark5B: """Real conversion: VD
IF EDV 3, BPS 1 to Mark 5B.""" def test_stream(self, tmpdir): with vdif.open(SAMPLE_BPS1_VDIF, 'rs', sample_rate=8*u.MHz) as fr: start_time = fr.start_time data = fr.read(5000) # Just one Mark 5B frame. fl = str(tmpdir.join('test.m5b')) with mark5b.open(fl, 'ws', s...
# # acrosby 2013 # def __call__(nc): s = {} fo
r attr in nc.ncattrs(): s[attr
] = nc.getncattr(attr) return s
# -*- coding: UTF-8 -*- """ Name: generic_task.py Porpose: Execute a generic task with FFmpeg Compatibility: Python3 (Unix, Windows) Author: Gianluca Pernigotto <jeanlucperni@gmail.com> Copyright: (c) 2018/2022 Gianluca Pernigotto <jeanlucperni@gmail.com> license: GPL3 Rev: Feb.14.2022 Code checker: flake8: --ignor...
License, or (at your option) any later version. Videomass is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warran
ty 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 Videomass. If not, see <http://www.gnu.org/licenses/>. """ from threading import Thread import platform import subpr...
#!/usr/bin/env python # coding: utf-8 from .interactiveapp import InteractiveApplication, ENCODING class InteractiveLoopApplication(InteractiveApplication): def __init__(self, name, desc, version, padding, margin, suffix, encoding=ENCODING): super(InteractiveLoopApplication, self).__in...
: self.write_error("Terminated.") self.exit(0) self.exit(0)
return mainloop
org/licenses. # contact: elmamyra@gmail.com # -*- coding: utf-8 -*- from Xlib.display import Display from Xlib import X, error import Xlib from collections import namedtuple from gtk import gdk import gtk from subprocess import Popen, PIPE from threading import Timer from itertools import groupby from operator import ...
ode, group, level = info if group == self._group: if level < len(LEVEL_MOD): mod = LEVEL_MOD[level] return keycode, mod return None def keysym2deadEntries(self, keysym): resp = () entry = se...
od), ) if not resp: deadKeys = self.findWithDeadKey(keysym) if deadKeys: keyKeysym, deadKeysym = deadKeys keyKeycodes = self.keysym2entry(keyKeysym) deadKeycodes = self.keysym2entry(deadKeysym) if keyKeycodes an...
from cx_Freeze import setup, Exe
cutable # Dependencies are automatically detected, but it might need # fine tuning. buildOptions = dict(packages = ["pyglet", "polytanks", "codecs", "encodings", "selectors"], excludes = ["tkinter", "PyQt5", "PIL", "setuptools"] , include_files="assets") import sys base = 'Win32GUI' if sys.platform=='win32' e...
e Polytanks', options = dict(build_exe = buildOptions), executables = executables)
otalLinks)+'[/B].' dialogWait.update(percent,'[B]Will load instantly from now on[/B]',remaining_display) if (dialogWait.iscanceled()): return False dialogWait.close() del dialogWait main.CloseAllDialogs() ...
thumbs=thumb[0] else: thumbs='' main.CloseAllDialogs() import urlresolver for url in match: host=re.compile("http://(.+?).com/.+?").findall(url) for hname in host: host=hname.replace('www.','') ...
e=host) sources.append(hosted_media) if (len(sources)==0): xbmc.executebuiltin("XBMC.Notification(Sorry!,Show doesn't have playable links,5000)") else: source = urlresolver.choose_source(sources) try: if sou...
import sys def addAbilities(core, actor, player): if actor.getLevel() >= 10: actor.addAbility("sp_cloaked_recovery_0") if actor.getLevel() >= 28: actor.addAbility("sp_cloaked_recovery_1") if actor.getLevel() >= 54: actor.addAbility("sp_cloaked_recovery_2") if actor.getLevel() >= 70: actor.addAbility("sp_cl...
Abilities(core, actor, player): actor.removeAbility("sp_cloaked_recovery_0") actor.removeAbility("sp_cloaked_recovery_1") actor.removeAbility("sp_cloaked_recovery_2") actor.removeAbility("sp_cloaked_recovery_3") actor.remove
Ability("sp_cloaked_recovery_4") return
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-01 13:05 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), ('...
odel_name='activity', name='target_id', field=models.PositiveSmallIntegerField(default=0, null=True), ), migrations.A
ddField( model_name='activity', name='target_type', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'), ), ]
or a specific single cell. 'target_cell' can be a full cell name like 'api!child-cell' or it can be an instance of the CellState class if the target is a neighbor cell. """ message_type = 'targeted' def __init__(self, msg_runner, ctxt, method_name, method_kwargs, direction, target_...
_cell, 'routing_path': routing_path} reason = _("destination is %(target_cell)s but routing_path " "is %(routing_path)s") %
reason_args raise exception.CellRoutingInconsistency(reason=reason) next_hop_name = dest_name_parts[next_hop_num] if self.direction == 'up': next_hop = self.state_manager.get_parent_cell(next_hop_name) else: next_hop = self.state_manager.get_child_cell(next_h...
from pyelt.datalayers.database import Column, Columns from pyelt.datalayers.dv import Sat, DvEntity, Link, Hub, HybridSat, LinkReference class Role: pass class Act: pass class Participation: pass class Zorgverlener(DvEntity, Role): class Default(Sat): zorgverlenernummer = Columns.TextCo...
voornaam = Columns.TextColumn() bijnaam = Columns.TextColumn() # wordt niet gebruikt in dwh2.0; hier gebruikt voor testen uitgevoerd in test03r_domain.py class ContactGegevens(HybridSat): class Types(HybridSat.Types): telefoon = 'telefoon' mobiel = 'mobiel' ...
lumns.DateColumn() landcode = Columns.TextColumn() default = Default() personalia = Personalia() contactgegevens = ContactGegevens() class Adres(DvEntity, Role): class Default(Sat): postcode = Columns.TextColumn() huisnummer = Columns.IntColumn() huisnummer_toevoeging...
s.get() def get_absolute_url(self): return reverse('layer_detail', args=(self.service_typename,)) def attribute_config(self): # Get custom attribute sort order and labels if any cfg = {} visible_attributes = self.attribute_set.visible() if (visible_attributes.count() > ...
dels.Model): """ Auxiliary model for storing layer attributes. This helps reduce the need for runtime lookups to other servers, and lets users customize attribute titles, sort order, and visibility. """ layer = models.ForeignKey( Layer, blank=False, nul...
_('attribute name'), help_text=_('name of attribute as stored in shapefile/spatial database'), max_length=255, blank=False, null=True, unique=False) description = models.CharField( _('attribute description'), help_text=_('description of attribute to be used in...
import unittest import scipy from SloppyCell.ReactionNetworks import * lorenz = Network('lorenz') lorenz.add_compartment('basic') lorenz.add_species('x', 'basic', 0.5) lorenz.add_species('y', 'basic', 0.5) lorenz.add_species('z', 'basic', 0.5) lorenz.add_parameter('sigma', 1.0) lorenz.add_parameter('r', 2.0) lorenz....
def test_withlogs(self): """ Test fixed-point finding with lo
gs """ net = lorenz.copy('test') fp = Dynamics.dyn_var_fixed_point(net, dv0=[1,1,1], with_logs=True) # This should find the fixed-point [sqrt(2), sqrt(2), 1] self.assertAlmostEqual(fp[0], scipy.sqrt(2), 6, 'Failed on logs 1,0.') self.assertAlmostEqual(fp[1], scipy.sqrt(2), 6, 'Fa...
#this model represents a request in our system from google.appengine.ext import ndb from datetime import datetime from datetime import timedelta class Request(ndb.Model): city = ndb.StringProperty() phone = ndb.StringProperty() date = ndb.DateTimeProperty() description = nd
b.StringProperty() isCarNeeded = ndb.BooleanProperty() @classmethod def add(self,cit,phoneNum,desc,carNeeded): req = Request() req.city = cit req.phone = phoneNum req.descripti
on = desc req.isCarNeeded = carNeeded req.date = datetime.utcnow() #converting UTC to GMT+2[Israel timezone] #utc = datetime.utcnow() #UTC_OFFSET = 3 #req.date = utc# - timedelta(hours=UTC_OFFSET) #(UTC+3 = GMT+2) req.put()
from pulp_puppet.common import constants from pulp_puppet.common.publish_progress import PublishProgressReport from pulp_puppet.common.sync_progress import SyncProgressReport class PuppetStatusRenderer(StatusRenderer): def __init__(self, context): super(PuppetStatusRenderer, self).__init__(context) ...
y state left to handle is if it failed else: self.prompt.render_failure_message(_('... failed')) self.prompt.render_spacer() self._render_error(sync_report.metadata_error_message, sync_report.metadata_exception, ...
k) # Before finishing update the state self.sync_metadata_last_state = sync_report.metadata_state def _display_sync_modules_step(self, sync_report): # Do nothing if it hasn't started yet or has already finished if sync_report.modules_state == constants.STATE_NOT_STARTED or \ ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2016-08-04 12:17 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class
Migration(migrations.Migration): dependencies = [ ('communities', '0013_auto_20160801_1241'), ] operations = [ migr
ations.AlterField( model_name='groupuser', name='group', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='group_users', to='communities.CommunityGroup', verbose_name='Group'), ), ]
from croplands_api import api from croplands_api.models import User from croplands_api.views.api.processors import api_roles, remove_relations from croplands_api.exceptions imp
ort Unauthorized from croplands_api.auth import is_anonymou
s, current_user, verify_role def can_edit_the_user(data=None, **kwargs): """ Determines if the current user can modify the specified user account. :param data: :param kwargs: :return: None """ if is_anonymous(): raise Unauthorized() if hasattr(current_user, 'id') and current_...
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2011 Noviat nv/sa (www.noviat.be). All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under ...
args, context=context, limit=limit) return self.name_get(cr, user, ids, context=context) class account_bank_statement_line(osv.osv): _inherit = 'account.bank.statement.l
ine' _columns = { 'val_date': fields.date('Value Date', states={'confirm': [('readonly', True)]}), 'globalisation_id': fields.many2one('account.bank.statement.line.global', 'Globalisation ID', states={'confirm': [('readonly', True)]}, help="Code to identify transactions belon...
DEBUG = True SQLALC
HEMY_DATABASE_URI = 'sqlite:////tmp/
test.db'
from django.template import Library, Node, Variable, VariableDoesNotExist from django.core.urlresolvers import revers
e from job_board.views import job_list_by_tag register = Library() def do_populate_tags(parser,token): """ render a list of tags, with it's link. the token is tag. Arguments: - `parser`: - `token`: """ bits = token.split_contents() print bits return PopulateTagsNode(
bits[1]) class PopulateTagsNode(Node): def __init__(self,tag): self.tag_tag = Variable(tag) def render(self,context): try: _tag = self.tag_tag.resolve(context) _font_size = _tag.font_size + 10 _font_weight = min(900,(300 + (_tag.font_size*100))) ...
# -*- coding: utf-8 -*- # Copyright 2016 KMEE # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). { 'name': 'L10n Br Resource', 'summary': """ This module extend core resource to create important brazilian informations. Define a Brazilian calendar and some tools to compute d...
': '8.0.1.0.0', 'license': 'AGPL-3', 'author': 'KMEE,Odoo Community Association (OCA)', 'website': 'www.odoobrasil.org.br', 'depends': [ 'l10n_br_base', 'resource', ], 'external_dependencies': { 'python': ['pybrasil'], }, 'data': [ 'views/resource_calendar...
xml', 'views/menu_resource_calendar.xml', 'wizard/workalendar_holiday_import.xml', ], }
nv, bandwidth, path = '/tmp', raise_exception=True): def cleanup_log(): logfd.close() os.system('rm -f %s' % tmp_file) timeout = TEST_TIME + 360 vm_ip = vm_inv.vmNics[0].ip ssh_cmd = 'ssh -oStrictHostKeyChecking=no -oCheckHostIP=no -oUserKnownHostsFile=/dev/null %s' % vm_ip ...
eip def create_vip(vip_name=None, l3_uuid=None, session_uuid = None, required_ip=None): if not vip_name: vip_name = 'test vip' if not l3_uuid: l3_name = os.environ.get('l3PublicNetworkName') l3_uuid = test_lib.lib_get_l3_by_name(l3_name).uuid vip_creation_option = test_uti...
reation_option.set_l3_uuid(l3_uuid) vip_creation_option.set_session_uuid(session_uuid) vip_creation_option.set_requiredIp(required_ip) vip = zstack_vip_header.ZstackTestVip() vip.set_creation_option(vip_creation_option) vip.create() return vip def create_vip_with_ip(vip_name=None, l...
""" Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor 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 la...
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 this program. If not, see <http://www.gnu.org/licenses/>. """ from smart_manager.models import CPUMetric...
t GenericSProbeView class CPUMetricView(GenericSProbeView): serializer_class = CPUMetricSerializer model_obj = CPUMetric
from django.template import Context
, loader from pokemon.models import Pokemon from django.http import HttpResponse from django.http import Http404 def index(request): Pokemons = Pokemon.objects.all().order_by('id_pokemon') t = loader.get_template('pokemon/index.html') c = Context({ 'Pokemons': Pokemons, }) return Ht
tpResponse(t.render(c)) def pokemon(request, id): try: Pkmn = Pokemon.objects.get(id_pokemon=id) except Pokemon.DoesNotExist: raise Http404 return HttpResponse(loader.get_template('pokemon/pokemon.html').render(Context({'Pokemon': Pkmn,})))
# # Copyright (c) 2011 Red Hat, Inc. # # This software is licensed to you under the GNU Lesser General Public # License as published by the Free Software Fou
ndation; either version # 2 of the License (LGPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the implied warranties of MERCHANTABILITY, # NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You s
hould # have received a copy of LGPLv2 along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/lgpl-2.0.txt. # # Jeff Ortel <jortel@redhat.com> # """ The I{metrics} module defines classes and other resources designed for collecting and reporting performance metrics. """ import time from math ...
__vers
ion_info__ = ('1', '0', '0') __version__ = '.'.joi
n(__version_info__)
from copper.cop.cop_node import CopNode import pyopencl as cl import numpy from PIL import Image class COP2_Comp_Add(CopNode): ''' This filter adds foreground over background using OpenCL ''' type_name = "add" category = "comps" def __init__(self, engine, parent): super(CLC_Comp_Add, self).__init__(engine, ...
self.engine.ctx, True, # Normalized coordinates cl.addressing_mode.CLAMP_TO_EDGE, cl.filter_mode.LINEAR) exec_evt = self.program.run_add(self.engine.queue, self.size, None, self.input(0).getOutDevBuffer(),
self.input(1).getOutDevBuffer(), self.devOutBuffer, sampler, numpy.int32(self.width), numpy.int32(self.height), ) exec_evt.wait() class COP2_Comp_Blend(CopNode): ''' This filter blends foreground over background using OpenCL ''' type_name = "blend" category = "comps" def __init__(self, en...
"""Scikit Flow Estimators.""" # Copyright 2015-present The Scikit Flow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "L
icense"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHO...
mitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.estimators.base import TensorFlowEstimator, TensorFlowBaseTransformer from tensorflow.contrib.learn.python.learn.estimators.linear import ...
from django import for
ms from models
import edi_address class DocumentForm(forms.ModelForm): docfile = forms.FileField() class Meta: model = edi_address fields = ["docfile",]
}phaseBins_swap.h5'.format(nSigmaRadioCutoff,nIdxToCheck,nBins) dataFilePath = path+'indPulseProfiles_{}sigma_P1_KS.h5'.format(nSigmaRadioCutoff) dataFile = tables.openFile(dataFilePath,mode='r') radioMax = dataFile.root.radioMax.read() counts = dataFile.root.counts.read()#-dataFile.root.skyCounts.read() giantPulseNumb...
adioIndexBinsFine = np.arange(1369
,1396)-.5 radioIndexBins = np.arange(143,179,1)-.5 radioIndexBinsFine = np.arange(143,179)-.5 if bUseFineIndexBins == True:#For statistical test, use fine binning, for figure, use coarse radioIndexBins = radioIndexBinsFine startRadioIndex = radioIndexBins[0] endRadioIndex = radioIndexBins[-1] probDict = probsOf...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import m
odels, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('main', '0019_auto_20170521_1332'), ] operations = [ migrations.CreateModel( name='RecentActivity', ...
fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('timestamp', models.DateTimeField()), ('type', models.CharField(max_length=255, choices=[(b'follow', b'Followers/Subscribers'), (b'support', b'Recurring S...
import
pytest import cv2 from plantcv.plantcv.visualize import auto_threshold_methods def test_auto_threshold_methods_bad_input(visualize_test_data): """Test for PlantCV.""" img = cv2.imread(visualize_test_data.small_rgb_img) with pyt
est.raises(RuntimeError): _ = auto_threshold_methods(gray_img=img) def test_auto_threshold_methods(visualize_test_data): """Test for PlantCV.""" img = cv2.imread(visualize_test_data.small_gray_img, -1) labeled_imgs = auto_threshold_methods(gray_img=img) assert len(labeled_imgs) == 5
# Copyright (c) 2014 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the impl...
t:5000', 'amqp://test-host', ] for _url in urls: url = URL(_url) self.assertEqual(str(url), url.canonical) class TestScheme(TestCase): def test_validated(self): for n in PORT: self.assertEqual(Scheme.validated(n), n.lower()) self.ass...
me.validated, 'unsupported')
lf, resource, docs): if resource in AuditResource.exclude: return user = getattr(g, 'user', None) if not user: return if not len(docs): return audit = { 'user': user.get('_id'), 'resource': resource, 'acti...
} for _id in notify] name = activity_name if notify_desks: activity['recipients'].extend([{'desk_id': ObjectId(_id), 'read': False} for _id in notify_desks]) name = activity_name if item: activity['item'] = str(item.get('guid', item.get('_id'))) if item.get('task') and ...
esk'): activity['desk'] = ObjectId(item['task']['desk']) get_resource_service(ActivityResource.endpoint_name).post([activity]) if can_push_notification: push_notification(name, _dest=activity['recipients']) return activity def notify_and_add_activity(activity_name, msg, resource=Non...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2016,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
hetype=archetype, compel=True) for dbstage in dbper
sona.stages.values(): validate_prod_personality(dbstage, user, justification, reason, logger) elif host_environment: dbenv = HostEnvironment.get_instance(session, host_environment) if isinstance(dbenv, Production): enforce_justification(user, justification...
_attributes(self): self.assertEqual( _extract_attributes({}, num_attrs_limit=4), ProtoSpan.Attributes(attribute_map={}), ) def test_extract_variety_of_attributes(self): self.assertEqual( _extract_attributes( self.attributes_variety_pack, n...
sting attributes in favor of the agent attribute self.assertEqual( _extract_attributes( {"attribute_key": "attr_value"}, num_attrs_limit=1, add_agent_attr=True, ), ProtoSpan.Attributes( attribute_map={"g.co/agent...
self.assertEqual( _format_attribute_value(self.str_300), AttributeValue( string_value=TruncatableString( value=self.str_300, truncated_byte_count=0, ) ), ) # huge string should truncate ...
ata']) levrec['chancenone'] = parseNum(sr[2]['data']) levrec['file'] = os.path.basename(rec['fullpath']) # Apparently, you can have LEV records that end before # the INDX subrecord. Found those in Tamriel_Data.esm if len(sr) > 3: listcount = parseNum(sr[3]['data']) listitems = [] ...
id_bs = b'' if rec['type'] == 'LEVC': start_bs += b'LEVC' id_bs = 'CNAM' else: start_bs += b'LEVI' id_bs = 'INAM' headerflags_bs = bytes(8) name_bs = packStringSubRecord('NAME', rec['name']) calcfrom_bs = packIntSubRecord('DATA', rec['calcfrom']) chance_bs =...
_bs, lid) subrec_bs += packIntSubRecord('INTV', lvl, 2) reclen = len(name_bs) + len(calcfrom_bs) + len(chance_bs) + len(subrec_bs) reclen_bs = packLong(reclen) return start_bs + reclen_bs + headerflags_bs + \ name_bs + calcfrom_bs + chance_bs + subrec_bs def packTES3(desc, numrecs, master...
#!/bin/python import sys def getSumOfAP(n, max):
size = (max - 1) // n return (size * (n + size * (n)) / 2) def getSumOfMultiples(n): return (getSumOfAP(3, n) + getSumOfAP(5, n) - getSumOfAP(15, n)) def main(): numInputs = int(raw_input().strip()) for idx in xrange(
numInputs): n = int(raw_input().strip()) ans = getSumOfAP(n) print(ans) if __name__ == '__main__': main()
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au> # # 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...
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, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from ansiblelint import AnsibleLintRule class MismatchedBracketRule(AnsibleLintRule): id = 'ANSIBLE0003' shortdesc = 'Mismatched { and }' description = 'If lines conta...
# -*- encoding: utf-8 -*- ################################################################################ # # # Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol # # ...
e = 'new' @api.one def bu
tton_activate(self): self.date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if not self.date_activation: self.date_activation = datetime.now().strftime('%Y-%m-%d %H:%M:%S') time.sleep(1.0) self.state = 'active' @api.one def button_inactivate(self): self...
def init_actions_(service, args): """ this needs to returns an array of actions representing the depencies between actions. Looks at ACTION_DEPS in this module for an example of what is expected """ # some default logic for simple actions return { 'test': ['install'] } de...
LT_OK % job.service.name test_repo_path = j.sal.fs.
joinPaths(j.dirs.varDir, 'tmp', 'test_validate_model') sample_bp_path = j.sal.fs.joinPaths('/opt/code/github/jumpscale/jumpscale_core8/tests/samples/test_validate_delete_model_sample.yaml') try: if j.sal.fs.exists(test_repo_path): j.sal.fs.removeDirTree(test_repo_path) test_repo = j...
#!/bin/python def swap(findex, sindex, ar): ar[findex], ar[sindex] = ar[sindex], ar[findex] def partition(ar, lo, hi): '''3 way djisktra partition method''' start = lo pivotIndex = (lo+hi)//2 # take the elemet @ hi as the pivot and swap it to pivotIndex position swap(pivotIndex, hi, ar) pi...
lo, pivotIndex, ar) return lo def quickSort(ar): '''Iterative unstable in-place sort''' n = len(ar) hi = n-1 lo = 0 stack = [(lo, hi)] while stack: lo, hi = stack.pop() pivot = partition(ar, lo, hi) if lo<pivot-1: stack.insert(0, (lo, pivot-1)) if...
hi if lo<pivot-1 and lo != pivot: quickSortRec(ar, n, lo, pivot-1) # print ' '.join(ar) if pivot+1<hi and pivot != hi: quickSortRec(ar, n, pivot+1, hi) # print ' '.join(ar)
from __future__ import absolute_import import re import json import copy import os from svtplay_dl.service import Service, OpenGraphThumbMixin from svtplay_dl.utils.urllib import urlparse from svtplay_dl.utils import filenamify from svtplay_dl.fetcher.http import HTTP from svtplay_dl.fetcher.hds import hdsparse from s...
iceError("Can't find video file for: %s" % self.url) return videoid = match.group(1) data = self.http.request("get", "http://svp.vg.no/svp/api/v1/vgtv/assets/%s?appName=vgtv-website" % videoid).text jsondata = json.loads(data) if options.output_auto: director...
.dirname(options.output) title = "%s" % jsondata["title"] title = filenamify(title) if len(directory): options.output = os.path.join(directory, title) else: options.output = title if self.exclude(options): yield Service...
from st2actions.runners.pythonrunner import Action from st2client.client import Client # Keep Compatability with 0.8 and 0.11 until st2build is upgraded try: from st2client.models.datastore import KeyValuePair except ImportError: from st2client.models.keyvalue import KeyValuePair class KVPAction(Action): ...
luePair() instance.id = key instance.name = key instance.value = value kvp = client.keys.update(instance) if action in ['create', 'update'] else None if action == 'delete': return kvp else:
return kvp.serialize()
from django.shortcuts import render, redirect, get_object_or_404 from django.urls import reverse from mainmodels.models import Course, FeaturedCourse # Create your views here. def index(req): mostPopularCourses = Course.objects.raw('SELECT * FROM mainmodels_course as main_course JOIN (SELECT main_tran.courseID, COU...
n_feat.course_id = main_course.courseID LIMIT 10;') return ren
der(req, 'index/main.html', {'pageTitle': 'Coursing Field', 'mostPopularCourses': mostPopularCourses, 'featureCourses': featureCourses})
#!/usr/bin/python import pygame import math import random import sys import PixelPerfect from pygame.locals import * from water import Water from menu import Menu from game import Game from highscores import Highscores from options import Options import util from locals import * import health import cloud impor...
en, endless = True).run() elif selection == 2: # Online Highscores(screen, endless = True, online = True).run() else: break elif main_selection == 2: # Options selection =
Options(screen).run() else: #if main_selection == 3: # Quit return if __name__ == '__main__': main()
# -*- coding: utf-8 -*- ############################################################################## # # Copyright
(C) 2015 ADHOC SA (http://www.adhoc.com.ar) # A
ll Rights Reserved. # # 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 distribu...
#!/usr/bin/python import os from autotest.client import utils version = 1 def setup(tarball, topdir): srcdir = os.path.join(topdir, 'src') utils.extract_tarball_to_dir(tarball, srcdir) os.chdir(srcdir) utils.make() os.envi
ron['MAKEOPTS'] = 'mandir=/usr/share/man' utils.make('install') os.chdir(t
opdir) pwd = os.getcwd() tarball = os.path.join(pwd, 'grubby-8.11-autotest.tar.bz2') utils.update_version(os.path.join(pwd, 'src'), False, version, setup, tarball, pwd)
########################################################################### # (C) Vrije Universiteit, Amsterdam (the Netherlands) # # # # This file is part of AmCAT - The Amsterdam Content Analysis Toolkit # # ...
tree = parse(c("{code_field.id}=={code.id}".format(code_field=code_field, code=codebook.codes[0]))) self.assertEquals(clean_tree(schema, tree), Non
e) self.assertRaises(ValidationError, clean_tree, amcattest.create_test_schema_with_fields()[0], tree) def test_parse(self): import functools o1, o2 = amcattest.create_test_code(), amcattest.create_test_code() schema_with_fields = amcattest.create_test_schema_with_fields() ...
import json from owlready import * # input parameters file_path = sys.argv[1] onto_path = sys.argv[2] # load ontology onto = get_ontology(onto_path).load() # course found list course_ids = [] # for each course, find the active version (avoid multi instances of one course) with open(file_path + '/modulestore.active_...
obj_name
+'_xml_id').append(obj_xml_id) # set display name property if 'display_name' in block['fields'].keys(): obj_display_name = block['fields']['display_name'] getattr(temp_obj,obj_name+'_display_name').append(obj_display_name) ...
for all characters to be sent. # def flush(self): raise NotImplementedError() # # Read a character, waiting for a most timeout seconds. Return the # character read, or None if the timeout occurred. # def read_byte(self, timeout): raise NotImplementedError() # # Release the serial p...
) # # Occasionally 0, then 2 is returned. If 0 comes back, # continue reading as this i
s more efficient than sending # an out-of sync reset and letting the data reads restore # synchronization. Occasionally, multiple 2's are returned. # Read with a fast timeout until all data is exhausted, if # we got a 2 back at all, we consider it a succe...
import datetime class AuthenticationInfo: def __init__(self, password, email): self.Password = password self.Email = email class ProfileInfo: def __init__(self, display_name): self.DisplayName = display_name class Token: def __init__(self, id_token, valid_until): self.Id =...
ion class ModifyProfileRequest: def __init__(self, username, token, profile): self.Username = username self.Token = token self.Profile = profile class AddUserToGroupRequest: def __init__(self, username, token, user_to_add, id_group): self.Username = username self.Token ...
er_to_add self.IdGroup = id_group class TokenSuccessResponse: def __init__(self, success, token): self.Success = success self.Token = token @staticmethod def invalid(): return TokenSuccessResponse( False, Token("", datetime.datetime.now())) class Co...
# # Copyright (C) 2013 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
tClient.create_client() def create_firewall(self, apply_list, firewall): """Create the Firewall with default (drop all) policy. The default policy will be applied on all the interfaces of
trusted zone. """ pass def delete_firewall(self, apply_list, firewall): """Delete firewall. Removes all policies created by this instance and frees up all the resources. """ pass def update_firewall(self, apply_list, firewall): """Apply t...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
l( name='Contact', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('first_name', models.CharField(max_length=200)), ('last_name', models.CharField(max_length=200)), ('addr...
length=200, null=True, blank=True)), ('city', models.CharField(max_length=200, null=True, blank=True)), ('state', models.CharField(max_length=200, null=True, blank=True)), ('zipcode', models.CharField(max_length=200, null=True, blank=True)), ('country', mo...
#!/usr/bin/python # -*- coding: utf-8 -*- import locale import os import sys from datetime import date from kargoxml import add_column script_dir = os.path.split(os.path.abspath(os.path.dirname(__file__
)))[0] project_dir = os.path.split(script_dir)[0] sys.path.append(project_dir) sys.path.append(os.path.split(project_dir)[0]) os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from oi.shipit.models import CdClient from oi.shipit.models import PardusVersion from django.template
.defaultfilters import slugify if __name__ == '__main__': args = sys.argv pardus_versions = PardusVersion.objects.all() if len(args) != 2: print("Usage: python %s [limit]") % __file__ sys.exit() try: limit = int(args[-1]) except ValueError: print("Invalid limit: %...
nt """ if self.top != top: self.top = top self.win = None def getLeft(self): """ Provides the left position where this subwindow is placed within its parent. """ return self.left def setLeft(self, left): """ Chan...
f a panel's draw method. Arguments: y - vertical location x - horizontal location length - length the line spans attr - text attributes """ if self.win and self.maxX > x and self.maxY > y: try: drawLength =...
self.win.vline(y, x, curses.ACS_VLINE | attr, drawLength) except: # in edge cases drawing could cause a _curses.error pass def addch(self, y, x, char, attr=curses.A_NORMAL): """ Draws a single character. This should only be called from the co...
#!/usr/bin/python3 import numpy as np import cv2 from collections import deque from obstacle_detector.distance_calculator import spline_dist from obst
acle_detector.perspective import inv_persp_new from obstacle_detector.perspective import regress_perspecive from obstacle_detector.depth_mapper import calculate_depth_map from obstacle_detector.tm.image_shift_calculator import find_shift_value def video_test(input_video_path=None, output_video_path=None): cx = 59...
one \ else input('enter video path: ')) old_images = deque() original_frames = deque() ret, frame = cap.read() for i in range(15): original_frames.append(frame) img, pts1 = inv_persp_new( frame, (cx, cy), (roi_width, roi_length), spline_dist, 200) old_i...
""" Settings for REST framework are all namespaced in the REST_FRAMEWORK setting. For example your project's `settings.py` file might look like this: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.YAMLRenderer', ) 'DEFAULT...
an initialize the class
val() api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
# -*- coding: utf-8 -*- # Generated by Django 1.
10.5 on 2017-03-14 17:12 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('volunteers', '0001
_initial'), ] operations = [ migrations.RenameField( model_name='volunteer', old_name='picture', new_name='avatar', ), ]
"""equinox_spring16_api URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='hom...
include, url from django.conf.urls.static import static from django.contrib im
port admin from rest_framework import routers from equinox_api.views import ApplicationViewSet, OperationViewSet, InstancesViewSet, UserViewSet, ItemViewSet from equinox_spring16_api import settings router = routers.DefaultRouter() router.register(r'applications', ApplicationViewSet) router.register(r'operations',...
# -*- coding: utf-8 -*- from __future__
import unicode_literals from privagal.core.utils import PrivagalTestCase from ...gallery.factories import GalleryFactory, ImageFactory class GalleryFactoryTestCase(PrivagalTestCase): def test_images_given(self): image = ImageFactory() gallery = GalleryFactory(images__images=[image]) sel...
(gallery.images.first().image, image) def test_images_default(self): gallery = GalleryFactory() self.assertEqual(gallery.images.count(), 3)
from sqlalchemy import and_ from DBtransfer import * from zlib import * #retrun compressed def generateFromDB(DBSession, InternData, tmp_name) : run_list=[] user_data = DBSession.query(InternData).filter(InternData.timestamp == tmp_name) for data in user_data : if not data.run in run_list : run_list.append(da...
oFil
l(DBSession, InternData, tmp_name, used_runs) : users_rows = getUserRows(DBSession, InternData, tmp_name) rows = [] for row in users_rows : if row.run in used_runs : rows.append(row) return rows #input compressed, not compressed def throughOutUsedRuns(run_list, used_runs) : # not compressed rl = decompressL...
#!/usr/bin/env python '''====================================================== Created by: D. Spencer Maughan Last updated: May 2015 File name: IRIS_DF_Controller.py Organization: RISC Lab, Utah State University Notes: ======================================================''' import roslib;...
===========================# # Rotate to Vehicle 1 Frame # #==================================#
psi = states.Obj[0].psi*np.pi/180 rotZ = np.matrix([[cos(psi), sin(psi), 0],[-sin(psi), cos(psi), 0],[0, 0, 1]]) Cart = np.matrix([[1, 0, 0],[0, -1, 0],[0, 0, -1]]) u[:-1] = Cart*rotZ*u[:-1] #===================================# # Normalize given the Thrust # ...
#!/usr/bin/env python # coding=utf-8 # Python Script # # Copyleft © Manoel Vilela # # from functools import reduce """ Digit fifth powers Problem 30 Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits: 1634 = 1^4 + 6^4 + 3^4 + 4^4 8208 = 8^4 + 2^4 + ...
digits, N <= n*9^5. Thus, 10^{n-1} <= n*9^5. We now show by induction that if n>=7, then 10^{n-6} > n. 1) Basis step (n=7): 10^{7-6} = 10 > 7. 2) Induction step: suppose 10^{n-6} > n for some n>=7. Show this true for n+1 too. Well, 10^{(n+1)-6} = 10*10^{n-6} > 10n > 2n > n+1 QED. It follows that if n>=7, th...
nte tentei pensar num limite para testes, seria o tamanho*9**5, mas não consegui deduzir o maior tamanho possível # Desse jeito, fiz alguns testes e descobri que a ocorrência de números que poderiam ser escritos como a soma de potência(5) # Era no tamanho intervalo de [4, 7) from itertools import combinations_with_repl...
re(c > 1.0, e1, np.nan) mu2_if_c = e2 - mu**2 mu2 = np.where(c > 2.0, mu2_if_c, np.nan) g1 = _lazywhere( c > 3.0, (c, e1, e2, e3, mu2_if_c), lambda c, e1, e2, e3, mu2_if_c: (e3 - 3*e2*e1 + 2*e1**3) / np.sqrt((mu2_if_c)**3), fillvalue=np.nan) ...
. .. [2] https://www.itl.nist.gov/div898/software/dataplot/refman2/auxillar/b12pdf.htm .. [3] "Burr distribution", https://en.wikipedia.org/wiki/Burr_distribution %(example)s """ def _pdf(self, x, c, d): # burr12.pdf(x, c, d) = c * d * x**
(c-1) * (1+x**(c))**(-d-1) return np.exp(self._logpdf(x, c, d)) def _logpdf(self, x, c, d): return np.log(c) + np.log(d) + sc.xlogy(c - 1, x) + sc.xlog1py(-d-1, x**c) def _cdf(self, x, c, d): return -sc.expm1(self._logsf(x, c, d)) def _logcdf(self, x, c, d): return sc.log1...
# -*- coding: utf-8 -*- # [HARPIA PROJECT] # # # S2i - Intelligent Industrial Systems # DAS - Automation and Systems Department # UFSC - Federal University of Santa Catarina # Copyright: 2006 - 2007 Luis Carlos Dill Junges (lcdjunges@yahoo.com.br), Clovis Peruchi Scotti (scotti@ieee.org), # Guilh...
uma chamada de sistema dependendo da avaliação binaria do pixel (0,0) da imagem de entrada." # ---------------------------------------------------------------------- def __del__(self): pass # ---------------------------------------------------------------------- def on_prop_confirm_clicked...
ock_properties: if Property.name == "cmdString": Property.value = unicode(self.widgets['cmdString'].get_text()) if Property.name == "enIsntZero": Property.value = unicode(self.widgets['enIsntZero'].get_active()) self.m_oS2iBlockProperties.SetPropertiesXML...
#coding=utf-8 #-*- encoding: utf-8 -*- import tornado.ioloop import tornado.iostream import socket import struct import NotifyTCPServer def readPacketHeader(): stream.read_bytes(NotifyTCPServer.PACKET_HEADER_LEN, parsePacketHeader) def parsePacketHeader(data): sign,cmd,bodySize = struct.unpack('>2sHH', data) p...
command == NotifyTCPServer.NOTIFY_COMMAND_PING: send_ping(data) readPacketHeader() def
send_register(userKey): send_packet(NotifyTCPServer.NOTIFY_COMMAND_REGISTER, userKey) def send_ping(msg): send_packet(NotifyTCPServer.NOTIFY_COMMAND_PING, msg) def send_packet(cmd, msg): data = bytes(msg) stream.write(struct.pack(">2sHH", "NT", cmd, len(data))) stream.write(data) def send_request(): readPa...
#! /usr/bin/env python import sys, os sys.path.append('./include/python') import proteomatic import string import re class TransposeDna(proteomatic.ProteomaticScript): def run(self): # convert all characters to upper case # Attention: parameters are Unicode because of the JSON p
arser # used behind the scenes, convert nucleotides to ASCII string dna = str(self.param['nucleotides']).upper() # remove invalid characters dna = re.sub('[^ACGT]', '', dna) # reverse sequence dna = dna[::-1] # replace nucleotides dna = dna.translate(stri...
') as f: f.write(dna + "\n") if __name__ == '__main__': script = TransposeDna()
#-*- coding: utf-8 -*- """OAuth 2.0 Django Models""" import time from hashlib import sha512 from uuid import uuid4 from django.db import models from django.contrib.auth.models import User from .consts import CLIENT_KEY_LENGTH, CLIENT_SECRET_LENGTH from .consts import SCOPE_LENGTH from .consts import ACCESS_TOKEN_LE...
t 30 character random string* * *redirect_uri:* A string representing the client redirect_uri. *Default None* """ name = models.CharField(max_length=256) user = models.ForeignKey(User) description = models.TextField(null=True, blank=True) key = models.CharField( unique=Tr
ue, max_length=CLIENT_KEY_LENGTH, default=KeyGenerator(CLIENT_KEY_LENGTH), db_index=True) secret = models.CharField( unique=True, max_length=CLIENT_SECRET_LENGTH, default=KeyGenerator(CLIENT_SECRET_LENGTH)) redirect_uri = models.URLField(null=True) class AccessR...
#!/usr/bin/env python #______________________________________# #Dexacker is an open source tool developed by Abdelmadjd Cherfaoui #Dexacker is designed for Educational Stuff to do a LEGAL DDOS Test and the developers is # not responsible for ILLEGAL USES #Contacting using:@Hexacker | fb.com/Hexacker #http://www.hackerc...
he website link you want to DDOS it: ") port = int(raw_input("Enter the port you want to Attack: ")) message = raw_input("Write the message you want to send it: ") connections = int(raw_input("How many beat you want to make: " )) IP = socket.gethostbyname(host) #/ #The Attacking Function def Attack(): attack = socket...
t socket.error,msg: print "Connection Failed" print "DDOS Attack Lunched" attack.close() for i in range(1,connections): Attack() print "______________________________________" print "The Operation is finished" #this is the restaring function def Restart(): program = sys.executable os.execl(program,program,* sy...
"""Describe group states.""" from ho
meassistant.components.group import GroupIntegrationRegistry from homeassistant.const import STATE_OK, STATE_PROBLEM from homeassistant.core import HomeAssistant, callback @callback def async_describe_on_off_states( hass: HomeAssistant, registry: GroupIntegrationRegistry ) -> None:
"""Describe group on off states.""" registry.on_off_states({STATE_PROBLEM}, STATE_OK)
AndReturn([self.servers.list(), False]) cinder.volume_list(IsA(http.HttpRequest), search_opts=None).\ AndReturn(volumes) api.nova.server_list(IsA(http.HttpRequest), search_opts=None).\ AndReturn([self.servers.list(), False]) cinder.tenant...
instance'].choice
s), 2) self.assertEqual(res.context['form'].fields['instance']._choices[1][0], server.id) self.assertEqual(res.status_code, 200) @test.create_stubs({cinder: ('tenant_absolute_limits', 'volume_list', ...
#!/usr
/bin/env python # encoding: utf-8 """ __init__.py The MIT License (MIT) Copyright (c) 2013 Matt Ryan
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, distribute, sublicense, and/or sell copies of the ...
import logging from django.core.management.base import BaseCommand
from citation.ping_urls import verify_url_status logger = logging.getLogger(__
name__) class Command(BaseCommand): help = '''Method that check if the code archived urls are active and working or not ''' def handle(self, *args, **options): verify_url_status() logger.debug("Validation completed")
from flask import Blueprint, flash, redirect, render_template, request, url_for from sqlalchemy.orm.exc import NoResultFound from ..sqltypes import HashableLocale as Locale from ..work import Trope, Work from .db import session adv_search_bp = Blueprint('adv_searc
h', __name__) @adv_search_bp.route('/', methods=['POST']) def result(): about = request.form.getlist('about[]', None) category = request.form.getlist('category[]', None)
detail = request.form.getlist('detail[]', None) error_redirect = redirect(url_for('index')) if about is None or category is None or detail is None: flash('Invalid arguments.', 'danger') return error_redirect if type(about) != list or type(category) != list or type(detail) != list: ...
#!/usr/bin/env python from flask import (Flask, request, render_template) from flask.ext import restful from flask.ext.restful import reqparse import pickle SETTINGS_P = 'settings.p' app = Flask(__name__) api = restful.Api(app) def get_settings(): settings = {'state':'off'} try: settings = pickle.l...
ings() parser = reqparse.RequestParser() parser.add_argument('value', type=str, location='args', choices=['on','off']) args = parser.parse_args() value = args['value'] if value: set_state(value) settings = get_se
ttings() print "Setting state to {}".format(value) return {'state':settings['state']} # View to present a form to change the light state @app.route('/', methods=['GET','POST']) def index(): if request.method == 'POST': set_state(request.form['state']) settings = get_settings() ...
__source__ = 'https://leetcode.com/problems/nested-list-weight-sum/' # https://github.com/kamyu104/LeetCode/blob/master/Python/nested-list-weight-sum.py # Time: O(n) # Space: O(h) # # Description: Leetcode # 339. Nested List Weight Sum # # Given a nested list of integers, return the sum of all integers in the list wei...
ay also be integers or other lists. # # Example 1: # Given the list [[1
,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1) # # Example 2: # Given the list [1,[4,[6]]], return 27. (one 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27) # # Companies # LinkedIn # Related Topics # Depth-first Search # Similar Questions # Nested List Weight Sum II Array Nes...
"""Edit the RWhois data on the account.""" # :license: MIT, see LICENSE for more details. import SoftLayer from SoftLayer.CLI import environment from SoftLayer.CLI import exceptions import click @click.command() @click.option('--abuse', help='Set the abuse email address') @click.option('--address1', help='Update th...
option('--firstname', help='Update the first name field') @click.option('--lastname', help='Update the last name field') @click.option('--postal',
help='Set the postal code field') @click.option('--public/--private', default=None, help='Flags the address as a public or private residence.') @click.option('--state', help='Set the two-letter state code') @environment.pass_env def cli(env, abuse, address1, address2, city, company, country,...
# -*- coding: utf-8 -*- # # RERO IL
S # Copyright (C) 2019 RERO # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affer
o General Public License as published by # the Free Software Foundation, version 3 of the License. # # 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 Affero General Publ...
s') namecopy = _('_Copy VoIP address') elif url[1] in terminal.matches.values(): # This is a plugin match for pluginname in terminal.matches: if terminal.matches[pluginname] == url[1]: break dbg("Fou...
] = 'hidden' self.config.save() terminator = Terminator() terminator.reconfigure() def add_encoding_items(self, menu): """Add the encoding list to the menu""" terminal = self.t
erminal active_encodings = terminal.config['active_encodings'] item = Gtk.MenuItem.new_with_mnemonic(_("Encodings")) menu.append (item) submenu = Gtk.Menu () item.set_submenu (s
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 Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/lgpl.txt>. impo...
t__(self, username, user_token, game_id, private_key): super(GameJoltTrophy, self).__init__() self.username = username self.user_token = user_token self.game_id = game_id self.private_key = private_key self.URL = 'http://gamejolt.com/api/game/v1' self.nativeTraceback = False #====== TOOLS ======# # Us...
fixing authentications """ self.username = username # def changeUserToken(self, user_token): """ Changes the *user token* contained on the object Used for changing, setting and/or fixing authentications """ self.user_token = user_token def setSignatureAndgetJSONResponse(self, URL): """ Generat...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2009, 2013 Zuza Software Foundation # # This file is part of Pootle. # # Pootle 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 t...
ense along with # Pootle; if not, see <http://www.gnu.org/licenses/>. from django import template re
gister = template.Library() @register.inclusion_tag('terminology/term_edit.html', takes_context=True) def render_term_edit(context, form): template_vars = { 'unit': form.instance, 'form': form, 'language': context['language'], 'source_language': context['source_language'], } ...
# Transform the returned sequences into the canonical form for comparing # to the explicit QGL1 version above. # EG, 'flatten' any embedded lists of sequences. seqs = testable_sequence(seqs) # Assert that the QGL1 is the same as the generated QGL2 self.assertEqual(len(seqs), 4*2...
.py", "PiRabi", (controlQR, targetQR, lengths, riseFall, amp, phase, calRepeats)) seqs = resFunction() seqs
= testable_sequence(seqs) self.maxDiff = None assertPulseSequenceEqual(self, seqs, expected_seq) def test_EchoCRLen(self): controlQ = QubitFactory('q1') targetQ = QubitFactory('q2') cR = QRegister('q1') # Equivalent to QRegister(controlQ) tR = QRegister('q2') ...
Key": present actions: - type: remove-tag tags: [OldTagKey1, OldTagKey2] """ batch_size = 1 permissions = ('elasticloadbalancing:RemoveTags',) def process_resource_set(self, resource_set, tag_keys): client = local_session( self....
.. code-block:: yaml policies: - name:
elb-set-listener-policy resource: elb actions: - type: set-ssl-listener-policy name: SSLNegotiation-Policy-01 attributes: - Protocol-SSLv3 - Protocol-TLSv1.1 - DHE-...
#! /usr/bin/python # -*- coding: utf-8 -*- """ Created on Fri Jan 27 18:31:59 2017 @author: katsuya.ishiyama """ from numpy import random # Definition of module level constants SUCCESS_CODE = 1 FAILURE_CODE = 0 class Strategy(): def __init__(self, n): _success_probability = _generate_success_proba...
trial_result( p=self._get_success_probability() ) if self.current_strategy == self.previous_strategy: self.count_same_strategy += 1 return self._result_of_trial def _get_trial_result(p): _trial_result = random.choice([FAILURE_CODE, SUCCESS_CODE], size=1, p=[1 - ...
andom.sample(size)
import urllib2 from HTMLParser import HTMLParser from traceback import print_exc from sys import stderr class _DeHTMLParser(HTMLParser): ''' 利用HTMLParse来解析网页元素 ''' def __init__(self): HTMLParser.__init__(self) self.img_links = [] def handle_starttag(self, tag, attrs): if tag == 'img': # print(attrs) ...
ry: parser = _DeHTMLParser() parser.feed(text) parser.close() return parser.img_links except: print_exc(file=stderr) return text de
f main(): html = urllib2.urlopen('http://tieba.baidu.com/p/2166231880') content = html.read() print(dehtml(content)) i = 0 for img_list in dehtml(content): img_content = urllib2.urlopen(img_list).read() path_name = str(i)+'.jpg' with open(path_name,'wb') as f: f.write(img_content) i+=1 if __name__ == '...
#!/usr/bin/env python2 """ This is the main module, used to launch the persistency engine """ #from persio import iohandler import persui.persinterface as ui def main(): """ Launches the user interface, and keeps it on.""" interface = ui.Persinterface() while True: interface.run() if __name__ == ...
aph_data2 = [(2, 3, 0, 1), (0, 6,
2, 8)] graph_data = [graph_data1, graph_data2] name = "tree.xml" root = iohandler.xh.createindex(keynames) for i in xrange(2): iohandler.xh.creategraph(root, graph_data[i], keynames[i], 2) iohandler.xh.writexml(root, name) """
# -*- coding: utf-8 -*- # # test_get_sp_status.py # # This file is part of NEST. # # Copyr
ight (C) 2004 The NEST Initiative # # NEST 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. # # NEST is distribu
ted in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <h...
from filer.app
s import FilerConfig class MyFilerConfig(FilerConfig): verbose_name = "Dateiverwaltung"
# Copyright (c) 2015 Aaron Kehrer # Licensed under the terms of the MIT License # (see fiddle/__init__.py for details) import os import unicodedata from io import StringIO from PyQt4 import QtCore, QtGui from fiddle.config import EDITOR_FONT, EDITOR_FONT_SIZE class PyConsoleTextBrowser(QtGui.QTextBrowser): def ...
init__() line_font = QtGui.QFont() line_font.setFamily(EDITOR_FONT) line_font.setPointSize(EDITOR_FONT_SIZE) self.setFont(line_font) self.history = [] self.history_idx = -1 def event(self, eve
nt): if event.type() == QtCore.QEvent.KeyPress: if event.key() == QtCore.Qt.Key_Tab: if self.text().strip() == '': self.setText(self.text() + ' ') return True elif event.key() == QtCore.Qt.Key_Up: if len(self.history)...
# Copyright (c) 2011 X.commerce, a business unit of eBay Inc. # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Piston Cloud Computing, Inc. # Copyright 2012 Cloudscaling Group, Inc. # All Rights Reserved. # # Licens...
olumns).keys() # NOTE(russellb): Allow models to specify other keys that can be looked # up, beyond the actual db columns. An example would be the 'name' # property for an Instance. columns.extend(self._extra_keys) self._i = iter(columns)
return self def next(self): n = six.advance_iterator(self._i) return n, getattr(self, n) def update(self, values): """Make the model object behave like a dict.""" for k, v in six.iteritems(values): setattr(self, k, v) def iteritems(self): """Make the m...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <davidam@gnu.org> # Maintainer: David Arroyo Menéndez <davidam@gnu.org> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as p...
# 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 GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Flo
or, # Boston, MA 02110-1301 USA, from bokeh.plotting import figure, show, output_file from bokeh.tile_providers import CARTODBPOSITRON output_file("tile.html") # range bounds supplied in web mercator coordinates p = figure(x_range=(-2000000, 6000000), y_range=(-1000000, 7000000), x_axis_type="mercator", y_...
#!/usr/bin/env python # coding=utf-8 from toughlogger.common import pyforms from toughlogger.common.pyforms import rules from toughlogger.common.pyforms.rules import button_style, input_style password_update_form = pyforms.Form( pyforms.Textbox("tra_user", description=u"管理员名", size=32, readonly="readonly", **inp...
le), pyforms.Password("tra_user_pass", rules.len_of(6, 32), description=u"管理员新密码", size=32,value="", required="required", **input_style), pyforms.Password("tra_user_pass_chk", rules.len_of(6, 32), description=u"确认管理员新密码", size=32,value="", required="required", **input_style), pyforms.Button("submit", type="...
utton_style), title=u"管理密码更新", action="/password" )
xample certificates have been started yet, returns None. """ try: latest = cls.objects.filter(course_key=course_key).latest() except cls.DoesNotExist: return None queryset = ExampleCertificate.objects.filter(example_cert_set=latest).order_by('-cr...
ample_cert_set=self) for cert in queryset: yield cert @staticmethod def _template_for_mode(mode_slug, course_key): """Calculate the template PDF based on the course mode. """ return ( u"certificate-template-{key.org}-{key.course}-verified.pdf".format(key=course_k...
_make_uuid(): """Return a 32-character UUID. """ return uuid.uuid4().hex class ExampleCertificate(TimeStampedModel): """Example certificate. Example certificates are used to verify that certificate generation is working for a particular course. An example certificate is similar to an ordinar...
#!/usr/bin/env python import binascii import hashlib from reversecoin.bitcoin.key import CKey as Key from reversecoin.bitcoin.base58 import encode, decode def myhash(s): return hashlib.sha256(hashlib.sha256(s).digest()).digest() def myhash160(s): h = hashlib.new('ripemd160') h.update(hashlib.sha256(s).di...
xtended_address) # Take the first 4 bytes of the second SHA-256 hash. This is the address checksum checksum = hash_address[:4] # Add the 4 checksum bytes from point 7 at the end of extended RIPEMD-160 hash from point 4. This is the 25-byte binary Bitcoin Address. binary_address = extended_address + chec...
blic_key_hex) # Perform SHA-256 and RIPEMD-160 hashing on public key hash160_address = myhash160(public_key_bytearray) # add version byte: 0x00 for Main Network extended_address = '\x00' + hash160_address # generate double SHA-256 hash of extended address hash_address = myhash(extended_address) ...
from pseudoregion import * class Edge(PseudoRegion): """EDGE Fringe field and other kicks for hard-edged field models 1) edge type (A4) {SOL, DIP, HDIP, DIP3, QUAD, SQUA, SEX, BSOL, FACE} 2.1) model # (I) {1} 2.2-5) p1, p2, p3,p4 (R) model-dependent parameters Edge type = SOL p1: BS [T] ...
UA p1: gradient [T/m] Edge type = SEX p1: b2 [T/m2] (cf. C. Wang & L. Teng, MC 207) Edge type = BSOL p1: BS [T] p2: BY
[T] p3: 0 for entrance face, 1 for exit face Edge type = FACE This gives vertical focusing from rotated pole faces. p1: pole face angle [deg] p2: radius of curvature of reference particle [m] p3: if not 0 => correct kick by the factor 1 / (1+δ) p4: if not 0 => apply horizontal focus with st...
from kaleidoscope.globals import SecType class OrderLeg(object): def __init__(self, quantity, contract): """ This class is an abstraction of an order leg of an option strategy. It holds the information for a single order leg as part of an entire option strategy. """ self.q...
of an stock leg """ def __init__(self,
symbol, quantity): self.sec_type = SecType.STK super().__init__(quantity, symbol)