prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from model import FreebieItem, Distributor, Contributor import datetime import logging head = ''' <html> <head> <title>%s</title> <script src="/static/sorttable.js"></script> <style> body { background-c...
ime.utcnow().isoformat(' ') message += '<tr><th>Row</th><th>Owner</th><th>Giver ID</th><th>Name</th><th>Version</th><th>Update Date</th><th>Distributor Locatio
n</th><th>Texture Key</th><th>Texture Server</th><th>Texture Updatetime</th></tr><br />\n' query = FreebieItem.gql("") content =[] for record in query: owner = record.freebie_owner if (owner == None): owner = '***Not assigned***' if (rec...
from PyQt5.Q
tDesigner import *
# no instance_key attached to it), and another instance # with the same identity key already exists as persistent. # convert to an UPDATE if so. if not has_identity and \ instance_key in uowtransaction.session.identity_map: instance = \ uowtransact...
state_str(existing))) base_mapper._log_debug( "detected row switch for identity %s. " "will update %s, remove %s from " "transaction", instance_key, state_str(state), state_str(existing)) # remove t...
uowtransaction.remove_state_actions(existing) row_switch = existing if (has_identity or row_switch) and mapper.version_id_col is not None: update_version_id = mapper._get_committed_state_attr_by_column( row_switch if row_switch else state, ...
#!/usr/bin/env python import yaml import pwd import sys import subprocess import json import os __author__ = "Anoop P Alias" __copyright__ = "Copyright Anoop P Alias" __license__ = "GPL" __email__ = "anoopalias01@gmail.com" installation_path = "/opt/nDeploy" # Absolute Installation Path if __name__ == "__main_...
eluser.get('sub_domains') # Since we have all domains now..check XtendWeb domain-data files for HHVM enabled # Turn off HHVM if no domain using HHVM hhvm_flag = False with open(installation_path + "/domain-data/" + main_domain, 'r') as domain_data_stream: ...
ckend_category = yaml_parsed_domain_data.get('backend_category', None) if backend_category == 'HHVM': hhvm_flag = True for the_sub_domain in sub_domains: if the_sub_domain.startswith("*"): subdom_config_dom = "_wildcard_."+the_sub_domain.replac...
class Corpus: """
Interface for corpus """ def __i
nit__(self): pass
ptr = self.malloc(S) old1_ptr.someInt = 900 self.stackroots.append(old1_ptr) old2_ptr = self.malloc(S) old2_ptr.someInt = 800 self.stackroots.append(old2_ptr) pinned_ptr = self.malloc(T) pinned_ptr.someInt = 100 assert self.gc.pin(llmemor...
adr = llmemory.cast_ptr_to_adr(ptr) self.stackroots.append(ptr) ptr.someInt = 100 assert self.gc.pin(adr) self.gc.id(ptr) # allocate shadow collect_func() assert self.gc.is_in_nursery(adr) assert ptr.someInt == 100 self.gc.unpin(adr) collect_func()...
dr) def test_pin_shadow_1_minor_collection(self): self.pin_shadow_1(self.gc.minor_collection) def test_pin_shadow_1_major_collection(self): self.pin_shadow_1(self.gc.collect) def test_malloc_different_types(self): # scenario: malloc two objects of different type and pin them. Do ...
from couchpotato.core.event import addEvent, fireEvent from couchpotato.core.logger import CPLog from couchpotato.core.plugins.base import Plugin from couchpotato.environment import Env log = CPLog(__name__) class Automation(Plugin): def __init__(self): addEvent('app.load', self.setCrons) if n...
movies = fireEvent('automation.get_mo
vies', merge = True) movie_ids = [] for imdb_id in movies: prop_name = 'automation.added.%s' % imdb_id added = Env.prop(prop_name, default = False) if not added: added_movie = fireEvent('movie.add', params = {'identifier': imdb_id}, force_readd = Fals...
#!/usr/bin/env python # Standard packages import sys import cyvcf2 import argparse import geneimpacts from cyvcf2 import VCF def get_effects(variant, annotation_keys): effects = [] effects += [geneimpacts.SnpEff(e, annotation_keys) for e in variant.INFO.get("ANN").split(",")] return effects def get_t...
= [] for effect in effects: if effect.gene not in genes_list: genes_list.append(effect.gene) return genes_list def get_transcript_effects(effects): transcript_effects = dict() for effect in effects: if effect.transcript is not None: transcript_effects[effect...
effect=effect.impact_severity) return transcript_effects if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-a', '--annotated_vcf', help="snpEff annotated VCF file to scan") parser.add_argument('-o', '--output', help="File for outp...
# # Copyright (C) 2013 Stanislav Bohm # # This file is part of Kaira. # # Kaira 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, version 3 of the License, or # (at your option) any later versi...
erested only in variables variable = inscription.expr if variable in variabl
e_sources: # Variable take from input so we do not have to deal here with it continue if variable in variable_sources_out: # Variable already prepared for output continue if inscription.is_bulk(): # No token, just build variable var...
import mock from olympia.amo.tests import addon_factory, TestCase, user_factory from olympia.ratings.models import Rating from olympia.ratings.tasks import addon_rating_aggregates class TestAddonRatingAggregates(TestCase): # Prevent <Rating>.refresh() from being fired when setting up test data, # since it'd ...
addon=addon, rating=1, user=user, is_latest=False, body=u'old') new_rating = Rating.objects.create(addon=addon, rating=3, user=user, body=u'new') Rating.objects.create(addon=addon, rating=3, user=user_factory(), body=u'foo') ...
. Rating.objects.create(addon=addon2, rating=1, user=user_factory()) Rating.objects.create(addon=addon2, rating=1, user=user_factory(), body=u'two') # addon_rating_aggregates should ignore replies, so let's add one. Rating.objects.create( addon=...
of the layer (IGNORED) Returns: int: index of embedding layer """ return 0 def _recompile_model(self, emb_layer_idx): """Change model by removing the embedding layer and . Args: emb_layer_idx (int): index of the embedding layer Returns: ...
given word. Args: a_word (str): word whose embedding index should be retrieved Returns: int: embedding index of the given word """ a_word = normlex(a_word) if a_word in self._w2i: return self._w2i[a_word] elif sel...
t_w_emb_i(self, a_word): """Obtain embedding index for the given word. Args: a_word (str): word whose embedding index should be retrieved Returns: int: embedding index od the given word """ a_word = normlex(a_word) return sel...
tip, which no longer falls back to # 0-8 for unknown ids. transport.AMQP_PROTOCOL_HEADER = str_to_bytes("AMQP\x01\x01\x08\x00") class Connection(amqp.Connection): # pragma: no cover def _dispatch_basic_return(self, channel, args, msg): reply_code = args.read_short() reply_text = args.read_shorts...
return amqp_method(channel, args, content) def read_timeout(self, timeout=None): if timeout is None: return self.method_reader.read_method() sock = self.transport.sock prev = sock.gettimeout() sock.settimeout(timeout) try: try: ret...
raise socket.timeout() raise finally: sock.settimeout(prev) def _wait_multiple(self, channel_ids, allowed_methods, timeout=None): for channel_id in channel_ids: method_queue = self.channels[channel_id].method_queue for queued_method in method...
# -*- coding: utf-8 -*- # Generated by Djan
go 1.11.3 on 2017-08-14 06:27 from __future__ import unicode_literals import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('edgar', '0007_auto_20170706_2215'), ] operations = [ migrations.AddField( ...
rayField(base_field=models.TextField(blank=True), blank=True, help_text='URL we parsed out of the content', null=True, size=None), ), ]
as pickle import eventlet.queue import fairywren import itertools import logging import array def sendBencodedWsgiResponse(env,start_response,responseDict): headers = [('Content-Type','text/plain')] headers.append(('Cache-Control','no-cache')) start_response('200 OK',headers) yield bencode.bencode(responseDic...
uffer.tostring() else: for peer in itertools.islice(peersForResponse,0,p['numwant']): #For non-compact responses, use a bogus peerId. Hardly any client #uses this type of response anyways. There is no real meaning to the #peer ID except informal agreements. response['peers'].append({'peer id'...
('!I',peer.ip)),'port':peer.port}) #For stop event, just remove the
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2021-2022 Daniel Estevez <daniel@destevez.net> # # This file is part of gr-satellites # # SPDX-License-Identifier: GPL-3.0-or-later # from gnuradio import gr, digital import pmt from ...hier.sync_to_pdu_packed import sync_to_pdu_packed from ...hdlc_deframer ...
self.deframer = sync_to_pdu_packed( packlen=256, sync=_syncword, threshold=0) self.crop = crop_and
_check_crc() self.connect(self, self.slicer, self.deframer) self.msg_connect((self.deframer, 'out'), (self.crop, 'in')) self.msg_connect((self.crop, 'out'), (self, 'out'))
# Generated by Django 3.0.5 on 2020-04-17 14:12 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import easy_thumbnails.fields import userena.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_...
cy', models.CharField(choices=[('open', 'Open'), ('registered', 'Registered'), ('closed',
'Closed')], default='registered', help_text='Designates who can view your profile.', max_length=15, verbose_name='privacy')), ('email', models.CharField(blank=True, max_length=250, null=True)), ('score', models.IntegerField(default=1)), ('last_activity', models.DateTimeF...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-13 11:29 from __future__ import unicode_literals from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( ...
Choose Type operation')), ('is_visible', models.BooleanField(default=True, verbose_name='visible')), ('created_date', models.DateTimeField(auto_now_add=Tru
e, verbose_name='date')), ('updated_date', models.DateTimeField(auto_now=True)), ], options={ 'db_table': 'dashboard_stats', 'verbose_name': 'dashboard stats', 'verbose_name_plural': 'dashboard stats', }, ), ...
# Copyright 2012 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 agre...
ault='br-tun', help=_("Tunnel bridge to use.")), cfg.StrOpt('int_peer_patch_port', default='patch-tun', help=_("Peer patch port in integration bridge for tunnel " "bridge.")), cfg.StrOpt('tun_peer_patch_port',
default='patch-int', help=_("Peer patch port in tunnel bridge for integration " "bridge.")), cfg.StrOpt('local_ip', default='', help=_("Local IP address of GRE tunnel endpoints.")), cfg.ListOpt('bridge_mappings', default=DEFAULT_BRIDGE_MAPPING...
#author CongThuc 12/13/2015 import MySQLdb from database.DBHelper import DBHelper from database.DBConnectManager import DBConnectManager from resourcefactories.AnalysisInitDefaultValue import AnalysisInitDefaultValue db_helper = DBHelper() class DataUtils: def __init__(self): print "init DataUtils" ...
activities: if db_connector is not None: try: select_stmt = "SELECT * FROM package_analysis WHERE srcClass like %(ac_name)s" cursor = db_connector.cursor() cursor.execute(select_stmt, { 'ac_name': "%" + ac[1]+ "%...
.fetchall() packages.extend(rows) except Exception as e: print e return packages def get_SensitiveAPIs(self, db_connector, table): packages = [] if db_connector is not None: for sen_APIs in AnalysisInitDefaultVa...
dels = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields...
('django.db.models.fields.related.ForeignKey', [], {'to': "orm['package.Package']"}), 'title'
: ('django.db.models.fields.CharField', [], {'max_length': "'100'"}), 'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}) }, 'package.version': { 'Meta': {'ordering': "['-created']", 'object_name': 'Version'}, 'created': ('django.db.models.fields.Da...
#!/usr/bin/python import os, s
ubprocess amsDecode = "/usr/local/bin/amsDecode" path = "/usr/local/bin" specDataFile = "specData.csv" f = open("processFile.log", "w") if os.path.exists(specDataFile): os.remove(specDataFile) for fileName in os.listdir('.'): if fileName.endswith('.bin'): #print 'file :' + fileName cmnd = [amsDecode, ...
out=f) f.close
Crypt2Selected", "B2", True), ("CryptoCaidTandbergSelected", "TB", True), ) self.ecmdata = GetEcmInfo() self.feraw = self.fedata = self.updateFEdata = None def getCryptoInfo(self, info): if info.getInfo(iServiceInformation.sIsCrypted) == 1: data = self.ecmdata.getEcmData() self.current_source = da...
self.current_caid = data[1] self.current_provid = data[2] self.current_ecmpid = data[3
] else: self.current_source = "" self.current_caid = "0" self.current_provid = "0" self.current_ecmpid = "0" def createCryptoBar(self, info): res = "" available_caids = info.getInfoObject(iServiceInformation.sCAIDs) for caid_entry in self.caid_data: if int(caid_entry[0], 16) <= int(self.curren...
# -*- coding: utf-8; -*- # # Licensed to CRATE Technology GmbH ("Crate") under one or more contributor # license agreements. See the NOTICE file distributed with this work for # additional information regarding copyright ownership. Crate licenses # this file to you under the Apache License, Version 2.0 (the "License"...
nittest import TestCase from unittest.mo
ck import patch, MagicMock import sqlalchemy as sa from sqlalchemy.orm import Session from sqlalchemy.ext.declarative import declarative_base from crate.client.cursor import Cursor fake_cursor = MagicMock(name='fake_cursor') FakeCursor = MagicMock(name='FakeCursor', spec=Cursor) FakeCursor.return_value = fake_curso...
def is_lazy_user(user): """ Return True if the passed user is a lazy user. """ # Anonymous users are not lazy. if user.is_anonymous: return False # Check the user backend. If the lazy sign
up backend # authenticated them, th
en the user is lazy. backend = getattr(user, 'backend', None) if backend == 'lazysignup.backends.LazySignupBackend': return True # Otherwise, we have to fall back to checking the database. from lazysignup.models import LazyUser return bool(LazyUser.objects.filter(user=user).count() > 0)
from djpcms import test from djpcms.core.exceptions import AlreadyRegistered import djpcms class TestSites(test.TestCase): def
testMake(self): self.assertRaises(AlreadyRegistered,djpcms.MakeSite,__file__) site = djpcms.MakeSite(__file__, route = '/extra/') self.assertEqual(site.route,'/extra/') def testClenUrl(self): p = self.makepage(bit = 'test') self.assertEqual(p.url,'/test/') ...
res = self.get('/test////', status = 302, response = True) self.assertEqual(res['location'],'http://testserver/test/')
# -*- coding: utf-8 -*- # Copyright(C) 2012 Romain Bignon # # This file is part of weboob. # # weboob 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 opti...
oob.capabilities import NotAvailable from weboob.capabilities.pricecomparison import Product, Shop, Price class IndexPage(Page): def get_token(self): input = self.parser.select(self.document.getroot(), 'div#localisation input#recherche_recherchertype__token', 1) return input.attrib['v
alue'] def iter_products(self): for li in self.parser.select(self.document.getroot(), 'div#choix_carbu ul li'): input = li.find('input') label = li.find('label') product = Product(input.attrib['value']) product.name = unicode(label.text.strip()) ...
# Copyright 2012 the rootpy developers # distributed under the terms of the GNU General Public License """ This module supports monitoring TObject deletions. .. warning:: This is not recommended for production """ from __future__ import absolute_import from weakref import ref import ctypes from ctypes import CFUN...
def void (*CleanupCallback)(PyObject*); CleanupCallback _callback; RootpyObjectCleanup(CleanupCallback callback) : _callback(callback) {} virtual void RecursiveRemove(TObject* object) { // When arriving here, object->ClassName() will _always_ be TObject // since we're c
alled by ~TObject, and virtual method calls don't // work as expected from there. PyObject* o = TPython::ObjectProxy_FromVoidPtr(object, "TObject"); PyGILState_STATE gstate; gstate = PyGILState_Ensure(); PyObject *ptype, *pvalue, *ptraceback; PyEr...
# -*- coding: utf-8 -*- from flask import Flask, jsonify, request, abort, make_response from futu_server_api import * from db import save_update_token from db import delete_tokens from db import list_cards import logging import logging.config import json app = Flask(__name__) logging.config.fileConfig('./conf/log.ini...
获取订单列表') no_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/get_list_trades', methods=['POST']) def get_list_trades(): cc = check_parameters(request.json) message = cc.get_list_trades() logtext = log_handler(message, '获取交易列表') n
o_db_logger.info(logtext) return json.dumps(message, ensure_ascii=False) @app.route('/api/v1/place_order', methods=['POST']) def place_order(): code = request.json['code'] quantity = request.json['quantity'] price = request.json['price'] side = request.json['side'] ltype = request.json['type'] cc = check_param...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Modulos import sys import pygame from pygame.locals import * # Constantes venx = 640 veny = 4
48 # Clases class Pieza(pygame.sprite.Sprite): # 64x64 px tamaño def __init
__(self, tipo): pygame.sprite.Sprite.__init__(self) if tipo == 0: self.image = load_image("tablero.png", True) elif tipo == 1: self.image = load_image("laser.png", True) elif tipo == 2: self.image = load_image("diana.png", True) elif tipo == 3:...
from Chip import OpCodeDefinitions from Test
s.OpCodeTests.OpCodeTestBase import OpCodeTestBase class TestNopOpCode(OpCodeTestBase): def test_nop_implied_command_calls_nop_method(self): self.assert_opcode_execution(OpCodeDef
initions.nop_implied_command, self.target.get_nop_command_executed)
# Copyright (c) 2012 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or its affiliates. # All rights reserved. # # 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, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and t...
rtions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ...
sholds((x for x in [200, 200, 900]), [300, 400], 900), [2, 2, -999]) self.assertEqual(self.proc._first_above_thresholds((x for x in [200, 200, 400]), [300, 400], 400), [2, 2, -999]) self.assertEqual(self.proc._first_above_thresholds((x for x in [200, 350, 450, 550]), [300, 400], 550), [1, 2, -999]) ...
iggerOffsetTests): def setUp(self): warnings.filterwarnings('ignore') self.source_path = self.create_tempfile_from_testdat
a() self.source_data = tables.open_file(self.source_path, 'r') self.dest_path = self.create_tempfile_path() self.dest_data = tables.open_file(self.dest_path, 'a') self.proc = process_events.ProcessEventsFromSourceWithTriggerOffset( self.source_data, self.dest_data, DATA_GROUP...
SEFARIA_API_NODE = "https://www.sefaria.org/api/texts/" CACHE_MONITOR_LOOP_DELAY_IN_SECONDS = 86400 CACHE_LIFETIME_SECONDS = 604800 category_colors = { "Commentary": "#4871bf", "Tanakh": "#004e5f", "Midrash": "#5d956f", "Mishnah": "#5a99b7", "Talmud": "#c...
"sefaria_branding": False, "branding_height": 0 }, "facebook": { "font_size": 70, "additional_line_spacing_he": 12, "additional_line_spacing_en": -20, "image_width": 1200, "image_height": 630, "margin": 40, "category_color_line_width": 15, ...
0 }, "instagram": { "font_size": 70, "additional_line_spacing_he": 12, "additional_line_spacing_en": 0, "image_width": 1040, "image_height": 1040, "margin": 40, "category_color_line_width": 13, "sefaria_branding": True, "branding_height":...
#!/usr/bin/env python # encoding: utf-8 """ models.py Created by Darcy Liu on 2012-03-03. Copyright (c) 2012 Close To U. All rights reserved. """ from django.db import models from django.contrib.auth.models import User # class Setting(models.Model): # sid = models.AutoField(primary_key=True) # option = model...
.TextField(blank=True, verbose_name='script') style = models.TextField(blank=True, verbose_name='style') text_html = models.TextField(blank=True, verbose_name='html') minisite = models.ForeignKey(Minisite,ve
rbose_name='minisite') author = models.ForeignKey(User,verbose_name='author') created = models.DateTimeField(auto_now_add=True,verbose_name='created') updated = models.DateTimeField(auto_now=True,verbose_name='updated') def __unicode__(self): result = self.name return unicode(result) ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from itertools import combinations __all__ = [ 'network_complement
' ] def network_complement(network, cls=None): """Generate the complement network of a network. The compl
ement of a graph G is the graph H with the same vertices but whose edges consists of the edges not present in the graph G [1]_. Parameters ---------- network : :class:`~compas.datastructures.Network` A network. Returns ------- :class:`~compas.datastructures.Network` The com...
f, partNumber): self.lastPartNumber = partNumber if partNumber == 0: return self.object key = self.privatePartNumber(partNumber) if key in self.object: return self.object[key] else: return getattr(self.object, key) class SequenceInspec...
SliceInspector(Inspector): def namedParts(self): return ['start', 'stop', 'step'] ### Initialization initializeInspectorMap() class InspectorWindow: def __init__(self, inspector): self.inspectors = [inspector] def topInspector(self): return self.inspectors[len(self.inspectors) - ...
: return self.topInspector().object def open(self): self.top= Toplevel() self.top.geometry('650x315') self.createViews() self.update() #Private - view construction def createViews(self): self.createMenus() # Paned widget for dividing two halves ...
#example from kivy.base import runTouchApp fro
m kivy.lang import Builder from kivy.garden.light_indicator import Light_indicator from kivy.uix.button import Button # LOAD KV UIX runTouchApp(Builder.load_file('example.kv
'))
e License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distrib...
f.event_chains = event_chains def _fit_validate(self, X): """Validate input to fit() Validate data passed to fit(). Includes a transpose operation to change the row/column order of X and z-scoring in time. Parameters ---------- X: time by voxel ndarray, or a list o...
.unique(self.event_chains)) > 1: raise RuntimeError("Cannot fit chains, use set_event_patterns") # Copy X into a list and transpose X = copy.deepcopy(X) if type(X) is not list: X = [X] for i in range(len(X)): X[i] = check_array(X[i]) X[i] ...
"""bubble - re-emit a log record with superdomain | bubble [field=host] [parts=3] adds 'superhost' field """ import sys,splunk.Intersplunk import re ipregex = r"(?P<ip>((25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]\d\d|\d?\d))" ip_rex = re.compile(ipregex) def super_domain(host, output_parts)...
(results, field, num_parts)) except: import traceback stack = traceback.format_exc() results = splunk.Intersplunk.generateErrorResults("Error : Traceback: " + str(stack)) splunk.Intersplunk
.outputResults( results )
#!/usr/bin/env python # -*- coding: utf-8 -*- try: import cPickle as pickle except ImportError: import pickle import os.path class FileCache(dict): def __init__(self, filename): self.filename = os.path.abspath(filename) try: self.update(pickle.load(open(self.filename))) ...
key, value) def get_stats(self): pass try: import pylibmc as memcache except ImportError: import memcache class Cache(object): def __init__(self, servers=None, default='.cache', **kargs): if servers is None: self.cache = memcache.Client(**kargs) else: ...
gs) if not self.cache.get_stats(): self.cache = FileCache(default) def __getitem__(self, key): return self.cache.get(key) def __setitem__(self, key, value): self.cache.set(key, value) def get(self, key): return self.cache.get(key) def set(self, key, value...
_good_raw_ytilt = 0.0 # Supercall: stop current drag return super(InkingMode, self).button_release_cb(tdw, event) def motion_notify_cb(self, tdw, event): current_layer = tdw.doc._layers.current if not (tdw.is_sensitive and current_layer.get_paintable()): return False ...
if pos is None: continue r = gui.style.FLOATING_BUTTON_ICON_SIZE r += ma
x( gui.style.DROP_SHADOW_X_OFFSET, gui.style.DROP_SHADOW_Y_OFFSET, ) r += gui.style.DROP_SHADOW_BLUR x, y = pos tdw.queue_draw_area(x-r, y-r, 2*r+1, 2*r+1) def _queue_draw_node(self, tdw, i): node = self.nodes[i] x, y =...
########################################################################## # # Copyright (c) 2011-2012, John Haddon. All rights reserved. # Copyright (c) 2011, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided ...
efinition.append( prefix + "/Documentation...", { "command" : IECore.curry( GafferUI.showURL, os.path.expandvars( "$GAFFER_ROOT/doc/gaffer/html/index.html" ) ) } ) menuDefinition.append( prefix + "/Quit", { "command" : quit, "shortCut" : "Ctrl+Q" } ) def quit( menu ) : scriptWindow = menu.ancestor( GafferUI.ScriptW...
tion = scriptWindow.scriptNode().ancestor( Gaffer.ApplicationRoot ) unsavedNames = [] for script in application["scripts"].children() : if script["unsavedChanges"].getValue() : f = script["fileName"].getValue() f = f.rpartition( "/" )[2] if f else "untitled" unsavedNames.append( f ) if unsavedNames : ...
from flask_sqlalchemy import SQLAlchemy from sqlalchemy.orm import relationship from sqlalchemy.sql import func db = SQLAlchemy() class BaseTable(db.Model): __abstract__ = True updated = db.Column(db.DateTime, default=func.now(), onupdate=func.current_timestamp()) created = db.Column(db.DateTime, default=func....
me = db.Column(db.String(255)) namespace_id = db.Column(db.Integer, db.ForeignKey('namespace.id')) branch = relationship("Branch", order_by="Branch.updated.desc()", backref="repository") class Branch(BaseTable): __tablename__ = 'branch' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(...
__tablename__ = 'commit' id = db.Column(db.Integer, primary_key=True) sha = db.Column(db.String(40)) name = db.Column(db.String(255)) description = db.Column(db.String(1024)) status = db.Column(db.Enum('ERROR', 'WARNING', 'OK', 'UNKNOWN', 'RUNNING', name='commit_status_type')) runtime = db.Column(db.Integ...
""" The MIT License (MIT) Copyright (c) [2015-2018] [Andrew Annex] 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, modif...
ubstantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMA...
, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from .spiceypy import * from .utils import support_types __author__ = 'AndrewAnnex' # Default setting for error reporting so that programs don't just exit out! erract("set", 10, "return") er...
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Julien Chaumont" __copyright__ = "Copyright 2014, Julien Chaumont" __licence__ = "MIT" __version__ = "1.0.2" __contact__ = "julienc91 [at] outlook.fr" import flickrapi import os, sys import re from config import * class ShFlickr: ## # Connexion to F...
return files_to_sync ## # Performs the upl
oad. # @param photos_to_sync A dictionary containing the list of # pictures to upload for each subfolder. # @param photoset_ids Dict of albums and their Flickr ids. # @param folder Path to the main folder. # def upload(self, photos_to_sync,...
URL, 'SOCKET_URL': socket_url, 'login': 'true', 'project_name': project_name, 'latitude': latitude, 'longitude': longitude, 'zoom': zoom, 'default_hash': default_hash, 'min_zoom': min_zoom, 'max_zoom': max_zoom, 'project_logo': project_logo, 'project_icon': project_icon, 'project_home_page': ...
uid) viewable, respo
nse = bookmark.is_viewable(request.user) if not viewable: return response bookmark.delete() return HttpResponse(status=200) except: return HttpResponse(status=304) def add_bookmark(request): try: bookmark = Bookmark(user=request.user,
# -*- coding: utf-8 -*- # Author: Mikhail Polyanskiy # Last modified: 2017-04-02 # Original data: Rakić et al. 1998, https://doi.org/10.1364/AO.37.005271 import numpy as np import matplotlib.pyplot as plt # Lorentz-Drude (LD) model parameters ωp = 9.03 #eV f0 = 0.760 Γ0 = 0.053 #eV f1 = 0.024 Γ1 = 0.241 #eV ω1 = 0....
================= DATA OUTPUT ================================= file
= open('out.txt', 'w') for i in range(npoints-1, -1, -1): file.write('\n {:.4e} {:.4e} {:.4e}'.format(μm[i],n[i],k[i])) file.close() #=============================== PLOT ===================================== plt.rc('font', family='Arial', size='14') plt.figure(1) plt.plot(eV, -ε.real, label="...
r option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Gener...
module.fail_json(msg='Invalid MAC address format', proposed_mac=proposed_mac) joined_mac = ''.join(splitted_mac) mac = [joined_mac[i:i+4] for i in range(0, len(joined_mac), 4)] return '.'.join(mac).upper() def main(): argument_spec = dict( anycast_gateway_mac=dic...
argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) args = [ 'anycast_gateway_mac' ] existing = invoke('get_existing', module, args) end_state = existing proposed = dict((k, v) for k, v in module.params....
#!/usr/bin/env python3 # import re import evdev import subprocess import time import argparse def process_test_line(line, controls): tmp = line.strip() fields = tmp.split() operation = fields[1].lower() if operation == 'receive': target = fields[2].lower() if target == 'syn': return (...
('^\s*(button|axis)\s+(\S+)\s*=\s*(\S+)') for line in f: m = test_re.match(line) if m:
tst = process_test_line(line, controls) if tst: sequence.append(tst) continue m = dev_re.match(line) if m: devname = m.group(2) continue m = def_re.match(line) if m: if m.group(1) == 'axis': controls[m.group(2)] = (evde...
#!/usr/bin/env python import os import re import sys import socket import httplib import urlparse from urllib import urlencode from urllib2 import urlopen from argparse import ArgumentParser from collections import OrderedDict def _get_discover_url(given_discover_url, update_type): if update_type == '4': r...
date failed. error is {}'.for
mat(response.code) print >>sys.stderr, content raise SystemExit(3) parsed_content = re.match(r'^(?P<key>badauth|nochg|good|noipv6)(\s(?P<value>.*))?$', content) if parsed_content is None: print >>sys.stderr, 'error: unknown returned response: {}'.format(content) raise SystemExit(...
from django.conf.urls import patterns, include, url from misago.threads.views.privatethreads import PrivateThreadsView urlpatterns = patterns('', url(r'^private-threads/$', PrivateThreadsView.as_view(), name='private_threads'), url(r'^private-threads/(?P<page>\d+)/$', PrivateThreadsView.as_view(), name='priva...
url(r'^private-thread/(?P<thread_slug>[\w\d-]+)-(?P<thread_id>\d+)/(?P<page>\d+)/$', ThreadView.as_view(), name='private_thread'), ) # goto views from misago.threads.views.privatethreads import (GotoLastView, GotoNewView, GotoPostView) urlpatterns += patterns('', ...
='private_thread_last'), url(r'^private-thread/(?P<thread_slug>[\w\d-]+)-(?P<thread_id>\d+)/new/$', GotoNewView.as_view(), name='private_thread_new'), url(r'^private-thread/(?P<thread_slug>[\w\d-]+)-(?P<thread_id>\d+)/post-(?P<post_id>\d+)/$', GotoPostView.as_view(), name='private_thread_post'), ) # reported ...
# -*- coding: utf-8 -*- import ast import os import requests import models from config import config, sqla from gevent.pool import Pool from helpers import random_str, down base_path = config.get('photo', 'path') base_path = os.path.join(base_path, 'celebrity') cookies = { 'bid': '' } def create_down(str_u...
_id, category): urls = ast.literal_eval(str_urls or "[]") path = os.path.join(base_path, category) for url in urls: filename = str(douban_id) + '_' + url.split('/')[-1].strip('?') cookies['bid'] = random_str(11) down(url, cookies, path, filename) def create_requests_and_save_datas...
: session = sqla['session'] cookies['bid'] = random_str(11) celebrity = session.query(models.Celebrity).filter_by( douban_id=douban_id ).one() cover_url = celebrity.cover thumbnail_cover_url = celebrity.thumbnail_cover photos_url = celebrity.photos thumbna...
self.sid is not None and self.sid[-33] == 'S' def is_accessed(self): """Returns True if any value of this session has been accessed.""" return self._accessed def ensure_data_loaded(self): """Fetch the session data if it hasn't been retrieved it yet.""" self._accessed = True ...
if self.sid: memcache.delete(self.sid, namespace='') # not really needed; it'll go away on its own try: db.delete(self.db_key) except: pass # either it wasn't in the db (maybe cookie/memcache-only) or db is down => cron will expire it de...
session after retrieving it from memcache or the datastore. Assumes self.sid is set. Checks for session expiration after getting the data.""" pdump = memcache.get(self.sid, namespace='') if pdump is None: # memcache lost it, go to the datastore if self.no_datas...
import itchat, time, re from itchat.content import * import urllib2, urllib import json from watson_developer_cloud import ConversationV1 response={'context':{}} @itchat.msg_register([TEXT]) def text_reply(msg): global response request_text = msg['Text'].encode('UTF-8') conversation =
ConversationV1( username='9c359fba-0692-4afa-afb1-bd5bf4d7e367', password='5Id2zfapBV6e', version='2017-04-21') # replace with your own workspace_id workspace_id = 'd3e50587-f36a-4bdf-bf3e-38c382e8d63a' print "request ==>", request_text try: type(eval(response)) except: print "first call" re...
input={ 'text': request_text}, context=response['context']) else: print "continue call" response = conversation.message(workspace_id=workspace_id, message_input={ 'text': request_text}, context=response['context']) if len( response['output']['text']) >0: response_text = response['output']['tex...
# Copyright 2008-2013 Nokia Siemens Networks Oyj # # 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...
_missing(positional, named, self._argspec) def _validate_limits(self, positional, named, spec): count = len(positional) + self._named_positionals(named, spec) if not spec.minargs <= count <= spec.maxargs: self._raise_wrong_count(count, spec) def _named_positionals(self, named, spec...
return sum(1 for n in named if n in spec.positional) def _raise_wrong_count(self, count, spec): minend = plural_or_not(spec.minargs) if spec.minargs == spec.maxargs: expected = '%d argument%s' % (spec.minargs, minend) elif not spec.varargs: expected = '%d to %...
# -*- coding: utf-8 -*- import nltk import csv import random import codecs import re from nltk.corpus import stopwords stopset = list(set(stopwords.words('spanish'))) hil_tweets = [] trump_tweets = [] bernie_tweets = [] cruz_tweets = [] classes = {} def transform(temp): if temp == "imo": return "opinion"...
#print type(line) if t.lower() in line: op.add(key) if key in op: break return list(op) def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs): csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs) for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row] # Process Tweet def processTweet(tweet): tweet = tweet.lower() # Convert www.* or https?://* to URL tweet = re.sub('((www\.[^\s]+)|(https?://[^\s]+))', 'URL', tweet) # Convert @username to AT_USER tweet = re.sub('@[^\s]+', 'AT_USER', tweet) #...
# =============================================================================== # Copyright 2016 ross # # 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/LICE...
as rfile: client.storbinary('STOR {}'.format(dest), rfile, 1024) else: with open(src, 'r') as rfile: client.storlines('STOR {}'.format(dest), rfile) class SFTPStorage(FTPStorage): url_name = 'SFTP' def _get_client(self): ssh = paramiko.SSHClient() ...
t_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(self.host, username=self.username, password=self.password, timeout=2) except (socket.timeout, paramiko.AuthenticationException): self.warning_dialog('Could not connect to server') return return ssh.open_...
ctypes.wintypes import BOOL from ctypes.wintypes import LPCWSTR _stdcall_libraries = {} _stdcall_libraries['kernel32'] = WinDLL('kernel32') from ctypes.wintypes import DWORD from ctypes.wintypes import WORD from ctypes.wintypes import BYTE INVALID_HANDLE_VALUE = HANDLE(-1).value class _SECURITY_ATTRIBUTES(Structure):...
TE = 1073741824 # Variable c_long PURGE_TXCLEAR = 4 # Variable c_int FILE_FLAG_OVERLAPPED = 1073741824 # Variable c_int EV_DSR = 16 # Variable c_int MAXDWORD = 4294967295L # Variable c_uint EV_RLSD = 32 # Variable c_int ERROR_IO_PENDING = 997 # Variable c_long MS_CTS_ON = 16 # Variable c_ulong EV_EVENT1 = 2048 # Variab...
riable c_int PURGE_RXABORT = 2 # Variable c_int FILE_ATTRIBUTE_NORMAL = 128 # Variable c_int PURGE_TXABORT = 1 # Variable c_int SETXON = 2 # Variable c_int OPEN_EXISTING = 3 # Variable c_int MS_RING_ON = 64 # Variable c_ulong EV_TXEMPTY = 4 # Variable c_int EV_RXFLAG = 2 # Variable c_int MS_RLSD_ON = 128 # Variable c_u...
""" Tests for the Gauges template tags and filters. """ from django.http import HttpRequest from django.template import Context from django.test.utils import override_settings from analytical.templatetags.gauges import GaugesNode from analytical.tests.utils import TagTestCase from analytical.utils import AnalyticalEx...
yTagName('script')[0]; s.parentNode.insertBefore(t, s); })(); </script> """, GaugesNode().render(Context())) @override_settings(GAUGES_SITE_ID=None) def test_no_account_number(self): self.assertRaises(AnalyticalException, GaugesNode) @override_settings(GAUGES_SITE_ID='123abQ') ...
aises(AnalyticalException, GaugesNode) @override_settings(ANALYTICAL_INTERNAL_IPS=['1.1.1.1']) def test_render_internal_ip(self): req = HttpRequest() req.META['REMOTE_ADDR'] = '1.1.1.1' context = Context({'request': req}) r = GaugesNode().render(context) self.assertTrue(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os def get_ki2_list(parser): parser.add_argument('-p', '--path_2chkifu', default='~/data/shogi/2chkifu/', help='2chkifu.zipを展開したディレクトリ') args = parser.parse_args() path_2chkifu = args.path_2chkifu
sub_dir_list = ['00001', '10000', '20000', '30000', '40000'] path_ki2_list = [] # Extract paths of KI2 files
for sub_dir in sub_dir_list: path_dir = os.path.expanduser(os.path.join(path_2chkifu, sub_dir)) ki2files = os.listdir(path_dir) for ki2file in ki2files: path_ki2_list.append(os.path.join(path_dir, ki2file)) return sorted(path_ki2_list)
from flask import Blueprint, jsonify, request routes_api = Blueprint('routes_api', __name__) @routes_api.route('/v1/routes', methods=['GET']) def routes_get(): ''' Get a list of route
s
It is handler for GET /routes ''' return jsonify()
TFORM, CONF_NAME, CONF_CODE, CONF_DELAY_TIME, CONF_PENDING_TIME, CONF_TRIGGER_TIME, CONF_DISARM_AFTER_TRIGGER) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.event import track_point_in_time CONF_CODE_TEMPLATE = 'code_template' DEFAULT_ALARM_NAME = 'HA Alarm' DEFAULT_DELAY_TIM...
for state in SUPPORTED_PENDING_STATES: if CONF_PENDING_TIME not in config[state]: config[state][CONF_PENDING_TIME] = config[CONF_PENDING_TIME] return config def _state_schema(state): schem
a = {} if state in SUPPORTED_PRETRIGGER_STATES: schema[vol.Optional(CONF_DELAY_TIME)] = vol.All( cv.time_period, cv.positive_timedelta) schema[vol.Optional(CONF_TRIGGER_TIME)] = vol.All( cv.time_period, cv.positive_timedelta) if state in SUPPORTED_PENDING_STATES: ...
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2012 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistrib
ute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # #
This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero Gene...
from django import forms, template from django.core.cache import cache from repertoire_telephonique.models import Phone regi
ster = template.Library() @register.simple_tag def simple_add(a, b): return a + b @register.inclusion_tag('vcard/tags/form_phone.html') def get_form_phone(contact_id): # get from cache cache_key = 'phone_choices_%s' % contact_id choices = cache.get(cache_key) # not in cache generate choices ...
for _p in Phone.objects.filter(contact_id=contact_id)] # cache update cache.set(cache_key, choices) # dynamic form to manage dynamic choices class PhoneForm(forms.Form): phone = forms.MultipleChoiceField(choices=choices) return { 'contact_id': contact...
""" set up an example custom response problem using a check function """ test_csv = self.CUSTOM_RESPONSE_SCRIPT expect = self.CUSTOM_RESPONSE_CORRECT cfn_problem_xml = CustomResponseXMLFactory().build_xml(script=test_csv, cfn='test_csv', expect=expect) ItemFactor...
one problem, and then muck with the student_answers # dict inside its state to try different data types (str, int, float, # none) self.submit_question_answer('p1', {'2_1': u'Correct'}) # Now fetch the state entry f
or that problem. student_module = StudentModule.objects.get( course_id=self.course.id, student=self.student_user ) for val in ('Correct', True, False, 0, 0.0, 1, 1.0, None): state = json.loads(student_module.state) state["student_answers"]['{}_2_1'...
# -*- coding: utf-8 -*- """ logbook.testsuite ~~~~~~~~~~~~~~~~~ The logbook testsuite. :copyright: (c) 2010 by Armin Ronacher, Georg Brandl. :license: BSD, see LICENSE for more details. """ import sys import unittest import logbook _skipped_modules = [] _missing = object() _func_ident = lambda f...
try: f(*args, **kwargs) finally: if old is _missing: del sys.modules[name] else: sys.modules[name] = old return wrapper return decorate def suite(): loader = unittest.TestLoader() suite = Log...
ite.addTests(loader.loadTestsFromName ('logbook.testsuite.test_contextmanager')) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
import unittest import pandas as pd from pandas.util.testing import assert_series_equal import numpy as np from easyframes.easyframes import hhkit class TestStataMerge(unittest.TestCase): def setUp(self): """ df_original = pd.read_csv('sample_hh_dataset.csv') df = df_original.copy() print(df.to_dict()) ...
from_dict(self.df_using_hh) correct_values = pd.Series([1, 1, 1, 3, 1, 1, 3, 3, 3, 3, 2, 2, 2]) myhhkit.statamerge(myhhkit_using
_hh, on=['hh'], mergevarname='_merge_hh') assert_series_equal(correct_values, myhhkit.df['_merge_hh']) def test_check_proper_merged_variable_created_and_is_correct_ind_level(self): myhhkit = hhkit(self.df_master) # myhhkit.from_dict(self.df_master) myhhkit_using_ind = hhkit(self.df_using_ind) # myhhkit...
# Copyright 2021 Red Hat, Inc. Jake Hunsaker <jhunsake@redhat.com> # This file is part of the sos project: https://github.com/sosreport/sos # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # version 2 of the GNU General ...
return tarfile.is_tarfile(arc_path) and 'insights-' in arc_path except Exception: return False def get_archiv
e_root(self): top = self.archive_path.split('/')[-1].split('.tar')[0] if self.tarobj.firstmember.name == '.': top = './' + top return top
#!/usr/bin/env python # -*- coding: utf-8 -*- """ tools for imr datasets @author: Chris Mantas @contact: the1pro@gmail.com @since: Created on 2016-02-12 @todo: custom formats, break up big lines @license: http://www.apache.org/licenses/LICENSE-2.0 Apache License """ from ast import literal_eval from collections impor...
ry, catego
ry, l_encoder=None): """ Creates a label point from a text line that is formated as a tuple :param entry: a tuple of format (3, 2, 1, [3,4,4 ..]), where the first entries in the tuple are labels, and the last entry is a list of features :param category: which one of the labels in...
#!/usr/bin/python2.7 # Copyright 2012 Google Inc. All Rights Reserved. """Support for simple JSON
templates. A JSON template is a dictionary of JSON data in which string values may be simple templates in string.Template format (i.e., $dollarSignEscaping). By default, the template is expanded against its own data, optionally updated with additional
context. """ import json from string import Template import sys __author__ = 'smulloni@google.com (Jacob Smullyan)' def ExpandJsonTemplate(json_data, extra_context=None, use_self=True): """Recursively template-expand a json dict against itself or other context. The context for string expansion is the json dic...
""" raven.transport.exceptions ~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more deta
ils. :license: BSD, see LICENSE for more details. """ class InvalidScheme(ValueError): """ Raised when a transport is constructed using a URI which is not handled by the transport """ class DuplicateScheme(StandardError): """ Raised when registering a handler for a particular s...
is already registered """
# -*- cod
ing: utf-8 -*- """ Created on Tue Jul 07 13:58:49 2015 @author: Wasit """ import serial import re import datetime #ser = serial.Serial('/dev/tty.usbserial', 9600) #ser = serial.Serial('COM7', 9600) #ser = serial.Serial(0) # open first serial port ser=None for i in xrange(10): try: ser = serial.Serial(i) ...
rint "Connecting to port: "+ser.name endTime = datetime.datetime.now() + datetime.timedelta(seconds=5) while True: if datetime.datetime.now() >= endTime: break record=re.split(',',ser.readline()) record = map(int, record) print record ser.close()
or class ExecutionSchedulesTestCase(BaseServerTestCase): DEPLOYMENT_ID = 'deployment' fmt = '%Y-%m-%dT%H:%M:%S.%fZ' an_hour_from_now = \ datetime.utcnow().replace(microsecond=0) + timedelta(hours=1) two_hours_from_now = \ datetime.utcnow().replace(microsecond=0) + timedelta(hours=2) ...
execution_schedules.create(
schedule_id, self.deployment_id, 'install', since=self.an_hour_from_now, recurrence='1 minutes', count=5) schedules = self.client.execution_schedules.list() self.assertEqual(len(schedules), 2) self.assertSetEqual({s.id for s in schedules}, set(schedule_ids)) def tes...
#!/usr/bin/env python from sys import argv, stderr usage = \ """ Usa
ge: {program} <sample rate> <A4 freq.> [octaves=8] e.g.: {program} 64000 442.0 5 """.format(program=argv[0]) if len(argv) < 3 or len(argv) > 4 : prin
t(usage, file = stderr) exit(1) A4 = 0 sample_rate = 0 octaves = 8 try: A4 = float(argv[2]) except: print("Error, invalid argument: Freq. must be a number!", file = stderr) print(usage, file = stderr) exit(1) try: sample_rate = int(argv[1]) except: print("Error, invalid argument: Sample r...
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2017-07-27 15:04 from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('press', '0001_initial'), ] operations = [ mig...
tors.MinValueValidator(9)]), ), migrations.AddField( model_name='press', name='password_number', field=models.BooleanField(default=False, help_text='If set, passwords must include one number.'), ), migrations.AddField( model_name='press', ...
field=models.BooleanField(default=False, help_text='If set, passwords must include one upper case.'), ), ]
# -*- coding: utf8 -*- "CountColumn filter" from .abstract import AbstractFilter class CountColumn(Abstra
ctFilter): "Count a flux's column and put the result in a variable"
name = 'Compter colonnes' description = "Compte le nombre de colonnes d'un flux et met le résultat dans une variable" node_in = ['cible'] parameters = [ { 'name': 'Variable', 'key': 'target', 'type': 'integer' } ] def run(self): "Execut...
import bitcoin import struct import serialize class BlockHeader: def __init__(self): self.height = None @classmethod def deserialize(cls, raw): assert len(raw) == 80 self = cls() self.version = struct.unpack('<I', raw[:4])[0] self.previous_block_hash = raw[4:36][::...
self.value = None self.script = "" def __
repr__(self): return "TxOut(value=%i.%08i script=%s)" % (self.value // 100000000, self.value % 100000000, self.script.encode("hex")) def serialize(self): return serialize.ser_txout(self) @staticmethod def deserialize(bytes): return serialize.deser_txout(bytes) class TxIn(object):...
__author__ = 'sondredyvik' class ConstraintNet: def __init__(self):
self.const
raints = {} def add_constraint(self,key,constraint): if key in self.constraints: self.constraints[key].append(constraint) else: self.constraints[key] = [constraint]
# # Graphene schema for exposing ProcessClassification model # import graphene from valuenetwork.valueaccounting.models import ProcessType from valuenetwork.api.types.Process import ProcessClassification from valuenetwork.api.types.EconomicEvent import Action from django.db.models import Q class Query(object): #gra...
stractType): process_classification = graphene.Field(ProcessClassification, id=graphene.Int()) all_process_classifications = graphene.List(ProcessClassification) def resolve_process_classification(self, args, *rargs): id = args.get('id') if id i...
s.get(pk=id) if pt: return pt return None def resolve_all_process_classifications(self, args, context, info): return ProcessType.objects.all()
""" This module implement a filesystem storage adapter. """ from __future__ import unicode_literals import errno import logging import os from flask import current_app from .interface import ImagineAdapterInterface from PIL import Image LOGGER = logging.getLogger(__name__) class ImagineFilesystemAdapter(ImagineAdapt...
ontent: Image :retu
rn: str """ if isinstance(content, Image.Image): item_path = '%s/%s/%s' % ( current_app.static_folder, self.cache_folder, path.strip('/') ) self.make_dirs(item_path) content.save(item_path) if o...
""" Flask routing """ from flask import Flask, request, session, send_from_directory, render_template from werkzeug.contrib.fixers import ProxyFix app = Flask(__name__, static_path="/") app.wsgi_app = ProxyFix(app.wsgi_app) import api import json import mimetypes import os.path from datetime import datetime from ap...
.set_cookie('token', csrf_token) # JB: This is a hack. We need a better solution if request.path[0:19] != "/api/autogen/serve/":
response.mimetype = 'appication/json' return response @app.route('/api/time', methods=['GET']) @api_wrapper def get_time(): return WebSuccess(data=int(datetime.utcnow().timestamp()))
# Django settings for sensible_data_platform project. import os import LOCAL_SETTINGS from utils import SECURE_platform_config DEBUG = True TEMPLATE_DEBUG = DEBUG MAINTENANCE_MODE = False ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS BASE_DIR = LOCAL_SETTINGS.BASE_DIR ROOT_DIR = LOCA...
handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://example.com/media/", "http://media.example.com/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "...
atic files. # Example: "http://example.com/static/", "http://static.example.com/" STATIC_URL = ROOT_URL+'static/' # Additional locations of static files STATICFILES_DIRS = ( ROOT_DIR+'static/', # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Win...
c_value, traceback): try: if self._local.con is None: raise RuntimeError("Exit connection pool with no connection?") if exc_type is not None: self.rollback() else: self.commit() if len(self._free) < self.max_idle: ...
:cat} #print('about to compare',type(rt[k]['created_at']),'with',type(cat)) if rt[k]['created_at']<=cat: rt[k]['created_at']=cat rt[k]['value']=v return rt def validate_save(C,tid,fetch_stamp,exc=True): C.execute("select changed_at,changed_by from tasks w...
=fetch_stamp if exc: assert eq,"task %s: fetch stamp!=changed_at by %s (%s , %s)"%(tid,res.get('changed_by'),fetch_stamp,res and res['changed_at']) or None else: return eq,res['changed_at'],res['changed_by'] return True,res and res.get('changed_at') or None,res and res.get('c...
new and not all the same, so add it to the dictionary kMerDict[sequences[i]] = count count = count + 1 motifListFile.close() return kMerDict def getFastaList(fastaFileList): # Get the next fasta from each file in a list fastaList = [] for fastaFile in fastaFileList: # Iterate through th...
LL GET CUT OFF IF THE WINDOWS DO NOT EXACTLY ENCOMPASS THE SEQUENCE numWindows = math.trunc(float(len(sequenceOneA) - WINDOWSIZE)/float(WINDOWSTRIDE)) + 1 kMerCounts = numpy.zeros(numWindows*len(kMerDict), 1) for l in range(numWindows): # Iterate through the windows and get the k-mer counts in each windo...
+ 1): # Iterate through the k-mers in the current window mark a 1 in the appropriate k-mer sequenceToLookUp = "" for j in range(K): # Iterate through the bases in the k-mer and make the sequence combination that represents it sequenceToLookUp = sequenceOneA[i + j] + sequenceTwoA[i + j] + sequence...
# Copyright (c) 2020, Michael Boyle # See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE> ### NOTE: The functions in this file are intended purely for inclusion in the Grid class. In ### particular, they assume that the first argument, `self` is an instance of Grid. They ...
or not the given array can broadcast against this object""" import numpy as np if isinstance(array, type(self)): try: if reverse: np.broadcast(array, self) else: np.broadcast(self, array) except ValueError: return False ...
else: if np.ndim(array) > np.ndim(self)-2: raise ValueError(f"Cannot broadcast array of {np.ndim(array)} dimensions against {type(self).__name__} " f"object of fewer ({np.ndim(self)-2}) non-grid dimensions.\n" "This is to ensure that scalars ...
# # Copyright © 2012–2022 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <https://weblate.org/> # # 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 3 of the Licens...
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 this program. If not, see ...
s import AppConfig class MetricsConfig(AppConfig): name = "weblate.metrics" label = "metrics" verbose_name = "Metrics"
# -*- coding: utf-8 -*- import sys #Éú³ÉºòÑ¡¼¯C1 #return£º×Öµäkey=item;value=item³öÏֵĴÎÊý def getC1(srcdata): c1 = {} for transaction in srcdata: for item in transaction: key = frozenset(set([item])) #frozenset²Å¿ÉÒÔ×÷Ϊ×ÖµäµÄkey #¼ÆÊýitem if key in c1: ...
del c[key] #if c != {}: #print c return c #¸ù¾ÝÉÏÒ»¸öL²úÉúºòÑ¡¼¯C #ɨÃèÔ´Êý¾
Ý£¬¼ÆÊýitem def getnextcandi(preL, srcdata): c = {} for key1 in preL: for key2 in preL: if key1 != key2: # preL ºÍ preL Éú³ÉµÑ¿¨¶û»ý key = key1.union(key2) c[key] = 0 #¼ÆÊýitem for i in srcdata: for item in c: ...
#!/usr/bin/env python # encoding: utf-8 import urllib from con
fig import USERNAME, EXTENSION, PASSWORD, APP_KEY, APP_SECRET, SERVER, MOBILE from ringcentral import SDK def main(): sdk = SDK(APP_KEY, APP_SECRET, SERVER) platform = sdk.platform() platform.login(USERNAME, EXTENSION, PASSWORD) to_numbers = "1234567890" params = {'from': {'phoneNumber': USERNAM...
) print 'Sent SMS: ' + response.json().uri if __name__ == '__main__': main()
# encoding: utf-8 ''' @author: Jose Emilio Romero Lopez @copyright: Copyright 2013-2014, Jose Emilio Romero Lopez
. @license: GPL @contact: jemromerol@gmail.com This file is part of APASVO. 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 3 of the License, or (at your option) any...
lied 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 PySide import QtGui from apasvo.gui.views...
from fibonacci import Fibonacci def ans(): return Fib
onacci.index(Fibonacci.after(int('9' * 999)
)) if __name__ == '__main__': print(ans())
# -*- coding: utf-8 -*- import json import re import unicodedata import string from urllib import urlencode from requests import get languages = {'de', 'en', 'es', 'fr', 'hu', 'it', 'nl', 'jp'} url_template = 'https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&{query}&props=labels%7Cdatatype%7Cclai...
labels = data.get('labels', {}) for language in languages: name = labels.get(language, {}).get('value', None) if name != None: add_currency_name(name, iso4217)
add_currency_label(name, iso4217, language) aliases = data.get('aliases', {}) for language in aliases: for i in range(0, len(aliases[language])): alias = aliases[language][i].get('value', None) add_currency_name(alias, iso4217) def fetch_data(wikidata_ids...
#!/usr/bin/env python # # __COPYRIGHT__ # # 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, ...
value(s) for option: foo """ + test.python_file_line(SConstruct_path, 19) test.run(arguments='shared=ical,foo,x11', stderr=expect_stderr, status=2) expect_stderr = """ scons: *** Error converting option: shared Invalid value(s) for option: foo,bar """ + test.python_file_line(SConstruct_path, 19) test.run(arguments='...
""" from SCons.Variables import ListVariable opts = Variables(args=ARGUMENTS) opts.AddVariables( ListVariable('gpib', 'comment', ['ENET', 'GPIB'], names = ['ENET', 'GPIB', 'LINUX_GPIB', 'NO_GPIB']), ) env = Environment(variables=opts) Help(opts.GenerateHelpText(en...
from django.conf.urls import patterns, include, url from django.conf import settings from cabot.cabotapp.views import ( run_status_check, graphite_api_data, checks_run_recently, duplicate_icmp_check, duplicate_graphite_check, duplicate_http_check, duplicate_jenkins_check, duplicate_instance, acknowledge_ale...
name='dashboard'), url(r'^subscriptions/', view=subscriptions, name='subscriptions'), url(r'^accounts/login/', view=login, name='login'), url(r'^accounts/logout/', view=logout,
name='logout'), url(r'^accounts/password-reset/', view=password_reset, name='password-reset'), url(r'^accounts/password-reset-done/', view=password_reset_done, name='password-reset-done'), url(r'^accounts/password-reset-confirm/', view=password_reset_confirm, name=...
"""Testing for ORM""" from unittest import TestCase import nose from nose.tools import eq_ from sets import Set from mdcorpus.orm import * class ORMTestCase(TestCase): def setUp(self): self.store = Store(create_database("sqlite:")) self.store.execute(MovieTitlesMetadata.CREATE_SQL) self...
"m", "3")) url = self.store.add(RawScriptUrl("http://www.dailyscript.com/scripts/10Things.html")) conversation = self.store.add(MovieConversation(0, 2, 0)) line194 = self.stor
e.add(MovieLine( 194, "Can we make this quick? Roxanne Korrine and Andrew Barrett are having an incredibly horrendous public break- up on the quad. Again.")) line195 = self.store.add(MovieLine( 195, "Well, I thought we'd start with pronunciation, if that's okay with you.")) lin...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). """Core rules for Pants to operate correctly. These are always activated and cannot be disabled. """ from pants.core.goals import check, fmt, lint, package, publish, repl, run, tailor, t...
onment.rules(), *target_type_rules(), ] def target_types(): return [ ArchiveTarget, FileTarget, FilesGeneratorTarget, GenericTarget, ResourceTarget, ResourcesGeneratorTarget, RelocatedFi
les, ]
from django.db import models class MaternalArvPostModManager(models.Manager): def get_by_natural_key( self, arv_code, report_datetime, visit_instance, appt_status, visit_
definition_code, subject_identifier_as_pk): MaternalVisit = models.get_model('mb_maternal', 'MaternalVisit')
MaternalArvPost = models.get_model('mb_maternal', 'MaternalArvPost') maternal_visit = MaternalVisit.objects.get_by_natural_key( report_datetime, visit_instance, appt_status, visit_definition_code, subject_identifier_as_pk) maternal_arv_post = MaternalArvPost.objects.get(maternal_visi...
#!/usr/bin/env python """ 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");...
) def hcat(): import params XmlConfig("hive-site.xml", conf_
dir = params.hive_conf_dir, configurations = params.config['configurations']['hive-site'], owner=params.hive_user, configuration_attributes=params.config['configuration_attributes']['hive-site'] ) @OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT) def hcat(): import params Di...
from django.test import TestCase from app_forum.models import Forum, Comment from app_forum.forms import CommentForm, ThreadForm # test for forms class CommentFormTest(TestCase): def test_comment_forms(self): form_data = {
'comment_content' : 'comment' } form = CommentForm(data=form_data) self.assertTrue(form.is_valid()) class ThreadFormTest(TestCase): def test_thread_forms(self): thread_data = { 'forum_title' : 'title', 'forum_category' : 'category', 'forum...
} thread = ThreadForm(data=thread_data) self.assertFalse(thread.is_valid())
#!/usr/bin/env python # coding: UTF-8 from __future__ import division import numpy as np def left_multiplica
tion(g, x): """ Multiplication action of a group and a vector. """ return np.dot(g, x) def trans_adjoint(g, x): return np.dot(np.dot(g,x),g.T) class RungeKutta(object): def __init__(self, method): self.method = method self.movement = self.method.movement self.nb_stages...
for the stages. """ return np.array([movement_field(stage) for stage in stages]) def get_iterate(self, movement_field, action): def evol(stages): new_stages = stages.copy() for (i,j, transition) in self.method.edges: # inefficient as a) only some vect...
from ete3 import Tree,TreeStyle,TextFace t = Tree('tagfrog.phy') for node in t.traverse(): nod
e.img_style['size'] = 3 if node.
is_leaf(): name_face = TextFace(node.name) ts = TreeStyle() ts.show_scale = True t.render('tagfrog.pdf')