prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
#!/usr/bin/env python import os import sys if __
name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_backend_test.settings") from django.core.management import execute_from_command_line execute_from_command_li
ne(sys.argv)
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2002-2007 Donald N. Allingham # Copyright (C) 2007-2008 Brian G. Matherly # Copyright (C) 2011 Tim G L Lyons # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as publ...
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """ Package providing filter...
from django.db import models from django.test import TestCase from ..models.compat import YAMLField class TestYAMLModel(models.Model): yaml_field = YAMLField() class TestYAMLField(TestCase): ... def test_to_python(self): yaml_data = """ main: - 1 - 2 - 3 ...
def test_get_prep_value(self): yaml_field = YAMLField() self.assertEqual("", yaml_field.get_prep_value(None)) yaml_field = YAMLField() data = {"aaa": "aaa😺",} self.assertEqual( "aaa: aa
a😺\n", yaml_field.get_prep_value(data) )
#!/usr/bin/env python3 from collections import namedtuple from pdfrw import PdfName, PdfDict, PdfObject, PdfString PageLabelTuple = namedtuple("PageLabelScheme", "startpage style prefix firstpagenum") defaults = {"style": "arabic", "prefix": '', "firstpagenum": 1} styles = {"arabic": PdfN...
st of the allowed styles""
" return styles.keys() def pdfobjs(self): """Returns a tuple of two elements to insert in the PageLabels.Nums entry of a pdf""" page_num = PdfObject(self.startpage) opts = PdfDict(S=styles[self.style]) if self.prefix != defaults["prefix"]: opts.P = PdfStr...
import operator from functools import reduce from collections import namedtuple from django.db.models import Q from mi.models import Target from wins.models import HVC HVCStruct = namedtuple('HVCStruct', ['campaign_id', 'financial_year']) def get_all_hvcs_referenced_by_targets(financial_years=None): """ Ge...
cial years instead of getting them from the Target :type financial_years: List[int] :returns a list of hvc (campaign_id, financial year) tuples that don't already exist: List[HVCStruct] """ hvc_ids_expected_by_targets = Target.objects.all().values_list('campaign_id', flat=True).distinct() if not...
to_create = [ HVCStruct(campaign_id=campaign_id, financial_year=int(str(financial_year)[-2:])) for campaign_id in hvc_ids_expected_by_targets for financial_year in financial_years ] filter_q = reduce( operator.or_, [Q(campaign_id=data.campaign_id, financial...
#!/usr/bin/env python """ NPR 2017-01-22 www.npr.org/2017/01/22/511046359/youve-got-to-comb-together-to-solve-this-one The numbers 5,000, 8,000, and 9,000 share a property that only five integers altogether have. Identify the property and the two other integers that have it. """ # The property is that they are superv...
o find the other such numbers. def is_supervocalic(w): ''' Determine if a word has one each of a, e, i, o, u We also want it not to have a 'y' ''' vowels = 'aeiou' for vowel in vowels: if w.lower().count(vowel) != 1: return False if 'y' in w.lower(): return False...
one','two','three','four','five','six','seven','eight','nine'] teens = ['','eleven','twelve','thirteen','fourteen','fifteen','sixteen', \ 'seventeen','eighteen','nineteen'] tens = ['','ten','twenty','thirty','forty','fifty','sixty','seventy', \ 'eighty','ninety'] thousands = ['','th...
""" Django settings for testproject project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ......
rib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.a...
ontrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'testproject.urls' WSGI_APPLICATION = 'testproject.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases DATABASES = { 'default': { 'ENGIN...
# Copyright 2020 Makani Technologies LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
keParams(): common_rotor_sensor = { # Calibration for rotor speed and torque. This applies both to # the speed sensed by and commanded to the motor controllers. # # TODO: The sign convention for rotor # velocity should be reversed both here and in the motor # controller.
'omega_cal': {'scale': -1.0, 'bias': 0.0, 'bias_count': 0}, 'torque_cal': {'scale': -1.0, 'bias': 0.0, 'bias_count': 0}, } return [common_rotor_sensor for _ in range(m.kNumMotors)]
import date, time, datetime, timedelta # from dateutil.relativedelta import relativedelta # # from django.conf import settings # from django.core.urlresolvers import reverse # from django.test import TestCase # # from eventtools.utils import datetimeify # from eventtools_testapp.models import * # # from _fixture im...
uld have some pagination (6 pages) # self.assertNotContains(r, "Earlier") #it's the first page # self.assertContains(r, "Later") # self.assertContains(r, "Showing 1–20 of 109") # # self.assertContains(r, "Friday, 1 January 2010", 1) #only print the date once #
self.assertNotContains(r, "Saturday, 2 January 2010") #there are no events # self.assertContains(r, "Sunday, 3 January 2010", 1) #only print the date once # # self.assertContains(r, "10am–​noon") # self.assertNotContains(r, "12am")# these are all-day # self.assertNotCo...
########################################################################## # # Copyright (c) 2012, John Haddon. All rights reserved. # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided t...
Gaffer.WeakMethod( self.__addItem ), "", IECore.V2iData( IECore.V2i( 0 ) ) ) } ) result.append( "/Add/V3i", { "command" : IECore.curry( Gaffer.WeakMethod( self.__addItem ), "", IECore.V3iData( IECore.V3i( 0 ) ) ) } ) result.append( "/Add/V2f", { "command" : IECore.curry( Gaffer.WeakMethod( self.__addItem ), "", IE...
) ) } ) result.append( "/Add/VectorDivider", { "divider" : True } ) result.append( "/Add/Color3f", { "command" : IECore.curry( Gaffer.WeakMethod( self.__addItem ), "", IECore.Color3fData( IECore.Color3f( 0 ) ) ) } ) result.append( "/Add/Color4f", { "command" : IECore.curry( Gaffer.WeakMethod( self.__addItem )...
#!/usr/bin/env python import datetime from run_utils import * class TestSuite(object): def __init__(self, options, cache): self.options = options self.cache = cache self.nameprefix = "opencv_" + self.options.mode + "_" self.tests = self.cache.gatherTests(self.nameprefix + "*", self...
isites() args = args[:] logs = [] test_list = self.getTestList(tests, black) date = datetime.datetime.now() if len(test_list) != 1: args = [a for a in args if not a.startswith("--gtest_output=")] ret = 0 for test in test_list: more_args = [...
userlog = [a for a in args if a.startswith("--gtest_output=")] if len(userlog) == 0: logname = self.getLogName(exe, date) more_args.append("--gtest_output=xml:" + logname) else: logname = userlog[0][userlog[0].find(":")+1:] ...
# Copyright (C) 2010-2014 GRNET S.A. # # 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 later version. # # This program is distributed i...
t is not public"), make_option( '--public', dest='public', default=False, action="store_true", help="Use this option if the snapshot is public"), ) @common.convert_api_faults def handle(self, *args, **options): if len(args) != 1: ...
r("Please provide a snapshot ID") snapshot_id = args[0] userid = options["userid"] public = options["public"] if (userid is None) and (public is False): raise CommandError("'user' option or 'public' option is required") try: with PlanktonBackend(userid)...
#!/usr/bin/env python import re import sys snappy_ver = "v3.0" html_header_string = """\ <html> <head> <title>Snappy Assembly</title> <style> BODY { margin-bottom: 200px; } TABLE TD { vertical-align: middle; } H2 { margin-bottom: 5px; margin-top: 24px; font-size: 20pt; } LI.section { font-size: 20pt; f...
ef write_markdown(self): with open(self.markdownfile, "w") as f: f.write("# Snappy RepRap Assembly Instructions\n\n") for mod_eng in self.module
s: f.write('## {0}\n\n'.format(mod_eng)) stepcnt = len(self.modinfo[mod_eng]) for stepinfo in self.modinfo[mod_eng]: stepinfo['base'] = ( 'https://raw.githubusercontent.com/' 'revarbat/snappy-reprap/{0}/...
#!/usr/bin/python """ skeleton code for k-means clustering mini-project """ import pickle import numpy import matplotlib.pyplot as plt import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit def Draw(pred, features, poi, mark_poi=False, name="image.png", f1_n...
in the dataset data_dict = pickle.load( open("../final_project/final_project_dataset.pkl", "r") ) ### there's an outlier--remove it! data_dict.pop("TOTAL", 0) ### the input features we want to use ### can be any key in the person-level dictionary (salary, director_fees, etc.) feature_1 = "salary" feature_2 = "exer...
data ) ### in the "clustering with 3 features" part of the mini-project, ### you'll want to change this line to ### for f1, f2, _ in finance_features: ### (as it's currently written, line below assumes 2 features) for f1, f2 in finance_features: plt.scatter( f1, f2 ) plt.show() from sklearn.cluster import KMe...
rname): # N = getN(username) # B = getB(username) # S = getS(username) # today = datetime.date.today() # yesterday = today - datetime.timedelta(1) # day_bf_yest = today - datetime.timedelta(2) # ns = N.objects.all().order_by('init_date')[:10] # bs = B.objects.all().order_by('init_date')[:10] # ...
post = request.POST.copy() #print 'post', post #T
ODO: move logic below t
import os.path import pygame from pygame.locals import * from tecles import * pygame.init() class Joc (object): WIDTH = 600 HEIGHT = 400 screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) background = pygame.image.load(os.path.join("Imatges","fons.jpg")) clock = pygame.time.Clock() dt = 0.05 pun...
pilota.restart() def main_loop(): while not Joc.quit: for event in pygame.event.get(): if event.type == KEYUP or event.type ==
KEYDOWN: handle_keys(event,Joc) elif event.type == QUIT: Joc.quit = True Joc.pales.update() Joc.pilotes.update() Joc.screen.blit(Joc.background,(0,0)) Joc.pilotes.draw(Joc.screen) Joc.pales.draw(Joc.screen) Joc.gol() pygame.display.update() Joc...
"""Produces the catalogue page for the VPHAS website.""" import os import json import datetime #i
mport httplib from astropy import log from jinja2 import Environment, FileSystemLoader from surveytools import SURVEYTOOLS_DATA # Load the column definitions from the JSON file filename_columns = os.path.join(SURVEYTOOLS_DATA, 'vphas-columns.json') columns = json.loads(open(filename_
columns).read()) def get_filesize(host, url): """Returns the filesize of a remote document.""" return 0 """ conn = httplib.HTTPConnection(host) conn.request("HEAD", url) res = conn.getresponse() try: size = float(res.getheader('content-length')) / (1024.*1024.) except Exception...
import sys from indra import reach from indra.assemblers import GraphAssembler orig_txt = [ln.strip() for ln in open('ras_pathway.txt', 'rt').readlines()] correct_txt = [ln.strip() for ln in open('correction.txt', 'rt').readlines()] for ln in correct_txt: if ln.startswith('<'): remove_line = ln[2:] ...
process_text(txt, offline=True) st = rp.statements for s in st: print '%s\t%s' % (s, s.evidence[0].text) graphpr = {'rankdir': 'TD'} nodepr = {'fontsize': 12, 'shape': 'plaintext', 'margin': '0,0', 'pad': 0} ga = GraphAssembler(st, graph_properties=graphpr, node_pro
perties=nodepr) ga.make_model() ga.save_dot('rps6ka_correction.dot') ga.save_pdf('rps6k1_correction.pdf')
nitialize_processes(self, num): self._workers = [] for i in range(num): rslt_q = multiprocessing.Queue() self._workers.app
end([None, rslt_q]) self._result_prc = ResultProcess(self._final_q, self._workers) self._result_prc.start() def _initialize_notifie
d_handlers(self, handlers): ''' Clears and initializes the shared notified handlers dict with entries for each handler in the play, which is an empty array that will contain inventory hostnames for those hosts triggering the handler. ''' # Zero the dictionary first by re...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2015-12-30 17:53 from __future__ import unicode_liter
als from django.conf import settings from django.db import migrations, models import django.db.m
odels.deletion class Migration(migrations.Migration): dependencies = [ ('wunderlist', '0011_auto_20151230_1843'), ] operations = [ migrations.AlterField( model_name='connection', name='owner', field=models.ForeignKey(blank=True, null=True, on_delete=dj...
Router(conf, self.logger) def _zero_stats(self): """Zero out the stats.""" self.stats = {'attempted': 0, 'success': 0, 'failure': 0, 'hashmatch': 0, 'rsync': 0, 'remove': 0, 'start': time.time(), 'failure_nodes': {}} def _add_failure_stats(self, fail...
headers['X-Backend-Storage-Policy-Index'] = int(job['policy']) failure_devs_info = set() begin = time.time() handoff_partition_deleted = False try: responses = [] suffixes = tpool.execute(tpool_get_suffixes, job['path']) synced_remote_regions = {} ...
['rsync'] += 1 kwargs = {} if node['region'] in synced_remote_regions and \ self.conf.get('sync_method', 'rsync') == 'ssync': kwargs['remote_check_objs'] = \ synced_remote_regions[node['region']] ...
ide failover region when requesting manual Failover for a hub. All required parameters must be populated in order to send to Azure. :ivar failover_region: Required. Region the hub will be failed over to. :vartype failover_region: str """ _validation = { 'failover_region': {'required': Tru...
ry_count': {'maximum': 100, 'minimum': 1}, } _attribute_map = { 'lock_duration_as_iso8601': {'key': 'lockDurationAsIso8601', 'type': 'duration'}, 'ttl_as_iso8601': {'key': 'ttlAsIso8601', 'type': 'dur
ation'}, 'max_delivery_count': {'key': 'maxDeliveryCount', 'type': 'int'}, } def __init__( self, *, lock_duration_as_iso8601: Optional[datetime.timedelta] = None, ttl_as_iso8601: Optional[datetime.timedelta] = None, max_delivery_count: Optional[int] = None, ...
e running processes socket/port information (or None).""" return self._socket or self.read_metadata_by_name(self._name, 'socket', self._socket_type) @classmethod def get_subprocess_output(cls, *args): """Get the output of an executed command. :param *args: An iterable representing the command to execu...
callbacks and write the child pid file. The double-fork here is necessary to truly daemonize the subprocess such that it can never take control of a tty. The initial fork and setsid() creates a new, isolated process group and also makes the first child a session leader (which can still acquire a tty). By f...
ess group. Additionally, a normal daemon implementation would typically perform an os.umask(0) to reset the processes file mode creation mask post-fork. We do not do this here (and in daemon_spawn below) due to the fact that the daemons that pants would run are typically personal user daemons. Having a...
# # Copyright 2008,2009 Free Software Foundation, Inc. # # This application is free software; you can redistribute it and/or modify # it under the terms of the GNU General Pub
lic License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This applicat
ion is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this p...
from datetime import datetime import subprocess import logging import os from flask import Flask, current_app from flask.ext.sqlalchemy import SQLAlchemy from jinja2 import FileSystemLoader from werkzeug.local import LocalProxy import yaml from flask.ext.cache import Cache from bitcoinrpc import AuthServiceProxy r...
tput[0] # celery won't work with this, so set some default except Exception: app.config['hash'] = '' app.config['revdate'] = '' # filters for jinja @app.template_filter(
'time_ago') def pretty_date(time=False): """ Get a datetime object or a int() Epoch timestamp and return a pretty string like 'an hour ago', 'Yesterday', '3 months ago', 'just now', etc """ now = datetime.utcnow() if type(time) is int: diff = now ...
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (http://tiny.be). All Rights Reserved # # # This program is free software: you can redistribute it and/or modify # ...
POSE. 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/. # #################
############################################################# import avanzosc_french_amortization import wizard
#!/usr/bin/env python3 import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "RankedChoiceRestaurants.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import m
ay fail for some other reason. Ensure tha
t the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your ...
#!/usr/bin/env python ########################################################################## # run/ec2-setup/spot.py # # Part of Project Thrill - http://project-thrill.org # # Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com> # # All rights reserved. Published under the BSD-2 license in the LICENSE file. #####...
rt datetime import sys with open('config.json') as data_file: data = json.load(data_file) client = boto3.client('ec2') ec2 = boto3.resource('ec2') job_id = int(time.time
()) blockMappings = [{'DeviceName': '/dev/sda1', 'Ebs': { 'VolumeSize': 8, 'DeleteOnTermination': True, 'VolumeType': 'gp2' } }] if data["VOL_SNAPSHOT_ID"]: blockMappings.append( { 'De...
@patch(PATH + 'PagureReview') @patch(PATH + 'PagureService._avatar') def test_request_reviews_with_repo(self, mock_avatar, mock_PagureReview, mock_has_new_comments, ...
return_value['requests'][0] ) mock_datetime.strptime.assert_called_with('mock_date', '%Y-%m-%d
%H:%M:%S.%f') mock_has_new_comments.assert_called_with( 'dummy_date', True ) mock_check_request_state.assert_called_with('mock_strptime_date', None) mock_avatar.assert_not_called() mock_PagureReview.assert_not_called() self.assertEqual(response, []) @patc...
"""Handle nice json response for error.""" from flask import jsonify def not_found(e): """Send a correct json for 404.""" response = jsonify({'status': 404, 'error': 'Not found', 'message': 'Invalid resource URI'}) response.status_code = 404 return response def method_not_su...
"""Send a correct json for 405.""" response = jsonify({'status': 405, 'error'
: 'Method not supported', 'message': 'This method is not supported'}) response.status_code = 405 return response def internal_server_error(e): """Send a correct json for 500.""" response = jsonify({'status': 500, 'error': 'Internal server error', 'messag...
vial constraints and " "a) at least one decision variable is unbounded " "above and its corresponding cost is negative, or " "b) at least one decision variable is unbounded below " "and its corresponding cost is positive. ") ...
e presolve, try turning " "off redundancy removal, or try turning off presolve " "altogether.") status = 4 if status != 0: complete = True return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
c0, x, undo, complete, status, message) def _parse_linprog(lp, options): """ Parse the provided linear programming problem ``_parse_linprog`` employs two main steps ``_check_sparse_inputs`` and ``_clean_inputs``. ``_check_sparse_inputs`` checks for sparsity in the provided constraints (``A_u...
self.assertEqual(x._proto, None) s = self.dumps(x, proto) self.assertEqual(x._proto, proto) y = self.loads(s) self.assertEqual(y._proto, None) def test_reduce_ex_overrides_reduce(self): for proto in protocols: x = REX_three() se...
# Test that internal data structures correctly deal with lots of # puts/gets. keys = ("aaa" + str(i) for i in xrange(100)) lar
ge_dict = dict((k, [4, 5, 6]) for k in keys) obj = [dict(large_dict), dict(large_dict), dict(large_dict)] for proto in protocols: dumped = self.dumps(obj, proto) loaded = self.loads(dumped) self.assertEqual(loaded, obj, "Failed protocol %...
t.text.lower() in ('off', 'no', 'false'): return False else: raise Exception("Invalid boolean value: %s in %s" % (element.text, element.tag)) else: return default_value def _get_elem_email_format_value(element, default_value): if element is not None: return Emai...
for task in element: if task.tag == 'sourcecontrol': if task.attrib['type'] in ('svn', 'git'): url = task.find('./url').text workingDirectory = _get_elem_str_value(task.find('./workingDirectory'), '') preCleanWorkingDirectory = _get_elem_bool_value( ...
tasks.append(svntask.SvnTask(url, workingDirectory, preCleanWorkingDirectory)) else: # git tasks.append(gittask.GitTask(url, workingDirectory, preCleanWorkingDirectory)) else: Logger.warning('Unsupported sourcecontrol type ' + task.att...
# Sumber: LMD/models.py from google.appengine.ext import db class Users(db.Model): username = db.St
ringProperty() passwd = db.StringProperty() email = db.StringProperty() fullname = db.StringProperty() address = db.TextProperty() phone = db.StringProperty() role = db.IntegerPropert
y(default=99) livecenter = db.ListProperty(db.Key,default=[])
# URL sorted by priority # If one URL does not work, the next one will be tried self.po_urls = po_urls def spawn_runner(self, module, module_file, language, port): """Launch a gladerunner instance. If a running process is attached to this session, it will be replaced. ...
levant modules with a list of stored PO files for it on this session, from the oldest to the newest. """ # Very basic check, msgfmt will crash anyway if the file is not valid if not name.
lower().endswith(".po"): raise DeckardException( "This is not a PO file", "%s is not a PO file." % name ) lang_root = tempfile.mkdtemp(prefix="deckard_") po_path = os.path.join(lang_root, "file.po") po = open(po_path, "bw") if fd is not None: ...
#!/usr/bin/env python import os import sys from autoprocess import autoProcessTV, autoProcessMovie, autoProcessTVSR, sonarr, radarr from readSettings import ReadSettings from mkvtomp4 import MkvtoMp4 from deluge_client import DelugeRPCClient import logging from logging.config import fileConfig logpath = '/var/log/sic...
o("Converting file %s at location %s." % (inputfile, settings.output_dir)) try: output = converter.process(inputfile) except: log.exception("Error converting file %s." % inputfile) path = converter.output_dir else: suffix = "copy" newpath = os.path.jo...
))) if not os.path.exists(newpath): os.mkdir(newpath) for filename in files: inputfile = os.path.join(path, filename) log.info("Copying file %s to %s." % (inputfile, newpath)) shutil.copy(inputfile, newpath) path = newpath delete_dir = newpath # Send to Sickbeard if (cat...
from django.conf.urls import url from rest_framework.urlpatterns import format_suffix_patterns from . import views from django.views.generic.base import View app_name = 'secapp' urlpatterns = [ # Index view url(r'^
$', views.index, name='index'), # List of events for a Log Source url(r'^(?P<id_log_source>[0-9]+)/event/$', views.events, name='events'), # Packet of an event (for a Log Source) url(r'^(?P<id_log_source>[0-9]+)/event/(?P<id_event>[0-9]+)$', views.event_information, name='event_information'), ...
>[0-9]+)/additional_info/$', views.additional_info, name='additional_info'), url(r'^api/events/$', views.EventsInformation().events_list, name='events_list'), url(r'^api/events/by_source/(?P<pk>[0-9]+)/$', views.EventsInformation().events_by_source, name='events_by_source'), url(r...
#!python """ VMController Host - a general purpose host-side virtual machine controller via exposed hypervisors apis. """ try: import os import sys import logging import warnings import multiprocessing import time import inject from twisted.internet import reactor from pkg_resource...
s=(config, server_event)) broker.daemon = False broker.name = 'VMController-Broker' broker.start() server_event.wait(brokerTimeout) if not server_event.is_set(): logger.fatal("Broker not available after %.1f seconds. Giving up", brokerTimeout) return -1 @inject.param('config') def ...
t_morbid(config): """ Starts up light weight, twisted based MorbidQ stomp broker. @param config: Injected config object. """ try: import morbid except ImportError, e: import sys print "Import error: %s\nPlease check." % e sys.exit() morbid_factory = morbid.St...
import sys out = sys.stdout class Colors: def black (self, fmt='', *args): self('\x1b[1;30m'+fmt+'\x1b[0m', *args) def red (self, fmt='', *args): self('\x1b[1;31m'+fmt+'\x1b[0m', *args) def green (self, fmt='', *args): self('\x1b[1;32m'+fmt+'\x1b[0m', *args) def yellow (self, fmt='', *args): sel...
oin('%.2x' % ord(c) for c in line)) printf(' ' * ((width-len(line))*3+1)) for c in line: if ord(c) < 32 or ord(c) > 126: printf.black('.') else: printf.whit
e('%c', c) writeln() offset += width __builtins__['printf'] = PrintF() __builtins__['writeln'] = WriteLine() __builtins__['hexdump'] = hexdump
.. versionadded:: 0.7 """ # TODO move most of this down to the Mongo layer? # TODO experiment with cursor.batch_size as alternative pagination # implementation def parse_aggregation_stage(d, key, value): for st_key, st_value in d.items(): if isinstance(st_value, dict): ...
e_embedded_fields(resource, req) soft_delete_enabled = config.DOMAIN[resource]['soft_delete'] if soft_delete_enabled: # GET requests should always fetch soft deleted documents from the db # They are handled and included in 404 respons
es below. req.show_deleted = True document = app.data.find_one(resource, req, **lookup) if not document: abort(404) response = {} etag = None version = request.args.get(config.VERSION_PARAM) latest_doc = None cursor = None # calculate last_modified before get_old_docum...
# -*- coding: utf-8 -*- # Define your
item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html class WebofknowledgePipeline(
object): def process_item(self, item, spider): return item
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from future.moves.urllib.parse import quote import logging from jinja2 import TemplateSyntaxError from flexget import plugin from flexget.event import event from flexget....
url: %s' % e) rss_config['all_entries'] = True for search_string in search_strings: rss_config['url'] = template.render({'search_term': search_string}) # TODO: capture some other_fields to try to find seed/peer/content_size numbers?
try: results = rss_plugin.phase_handlers['input'](task, rss_config) except plugin.PluginError as e: log.error('Error attempting to get rss for %s: %s', rss_config['url'], e) else: entries.update(results) return entries @event('plugin....
from . import visualize_classic_binning from . import visualize_tree_binning fr
om . import visualize_llh from . import visualize_model __all__ = ('visualize_classic_binning', 'vi
sualize_llh', 'visualize_tree_binning', 'visualize_model')
# -*- encoding: utf-8 -*- ############################################################################## # # Daniel Campos (danielcampos@avanzosc.es) Date: 07/10/2014 # # This program is
free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software
Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public L...
import sys import struct import logging import ibapi from ibapi.client import EClient from ibapi.wrapper import EWrapper, iswrapper import PyQt5.Qt as qt import PyQt5.QtNetwork as qtnetwork import tws_async.util as util util.allowCtrlC() __all__ = ['TWSClientQt', 'iswrapper'] class TWSClientQt(EWrapper, EClient)...
lf): EClient.disconnect(self) def _onSocketError(self, socke
tError): if self.conn.socket: self._logger.error(self.conn.socket.errorString()) def _onSocketReadyRead(self): self.dataHandlingPre() self._data += bytes(self.conn.socket.readAll()) while True: if len(self._data) <= 4: break # 4 b...
expected_text="foo\r\r\r\n", ac
tual_text="foo\n") tests.add('failures/expected/testharness.html', actual_text='This is a testharness.js-based test.\nFAIL: assert fired\n.Harness: the test ran to completion.\n\n', expected_text=None, actual_image=None, expected_image=None, actual_checksum=None) tests.ad...
ext.html') tests.add('failures/expected/skip_text.html', actual_text='text diff') tests.add('failures/flaky/text.html') tests.add('failures/unexpected/missing_text.html', expected_text=None) tests.add('failures/unexpected/missing_check.html', expected_image='missing-check-png') tests.add('failures/u...
import socket, sys,os,re from struct import * mymac=sys.argv[1] rmac=sys.argv[2] interface=sys.argv[3] mode=sys.argv[4] def address (a) : b = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(a[0]) , ord(a[1]) , ord(a[2]), ord(a[3]), ord(a[4]) , ord(a[5])) return b try: s = socket.socket( socket.AF_PACKET , socket.SO...
r = packet[:pack_length] pack = unpack('!6s6sH' , pack_header) pack_protocol = socket.ntohs(pack[2]) #print 'Destination MAC : ' + address(packet[0:6]) +
' Source MAC : ' + address(packet[6:12]) #print rmac, interface , mode router_mac=re.sub(r':',"",rmac) pc_mac=re.sub(r':',"",mymac) router_mac= router_mac[:-6] if mymac == address(packet[0:6]) : if rmac != address(packet[6:12]) and rmac != "01005e" and rmac != "ffffff" and rmac != "...
import uuid import base64 import re def generate_key(): """ generates a uuid, encodes it with base32 and strips it's padding. this reduces the string size from 32 to 26 chars. """ return base64.b32encode(uuid.uuid4().bytes).strip('=').lower()[0:12] def thousand_separator(x=0, sep='.', dot=','): """ creates a ...
) and value is not None: try: setattr(passed_object, item, value) except: setattr(passed_object, item, convert_to_date(value)) passed_object.id = gener
ate_key() return passed_object def edit_parser(passed_object, request_data): """ Maps value from passed json object for data edit purposes. You need to pass in object resulting from query into the passed_object variable """ for item in request_data.values: if item != "id" and hasattr(passed_object, item) and ...
tion: The type of videos to find (one of the globals MOVIES, MUSIC_VIDEOS or TVSHOWS). :rtype: list :return: A list of expired videos, along with a number of extra attributes specific to the video type. """ # A non-exhaustive list of pre-defined filters to use during JSON-RPC requests ...
= {u"field": u"inprogress", u"operator": u"false", u"value": u""} by_exc
lusion1 = {u"field": u"path", u"operator": u"doesnotcontain", u"value": get_setting(exclusion1)} by_exclusion2 = {u"field": u"path", u"operator": u"doesnotcontain", u"value": get_setting(exclusion2)} by_exclusion3 = {u"field": u"path", u"operator": u"doesnotcontain", u"value": get_setting(exclusion3)} ...
# file openpyxl/writer/strings.py # Copyright (c) 2010-2011 openpyxl # # 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, ...
ator(out=temp_buffer, encoding='utf-8') start_tag(doc, 'sst', {'xmlns': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', 'uniqueCount': '%d' % len(string_table)}) strings_to_write = sorted(string_table.items(), key=lambda pair: pair[1]) for key in [pair[0] for...
g(doc, 'si') if key.strip() != key: attr = {'xml:space': 'preserve'} else: attr = {} tag(doc, 't', attr, key) end_tag(doc, 'si') end_tag(doc, 'sst') string_table_xml = temp_buffer.getvalue() temp_buffer.close() return string_table_xml class String...
import os import peewee from rivr_peewee import Database DATABASE_URL = os.environ.get('DATABASE_URL') if DATABASE_URL and DATABASE_URL.startswith('postgres://'): DATABASE_URL = DATABASE_URL.replace('postgres://', 'postgres+pool://') # disable auto connection EXTRA_OPTIONS = 'autoconnect=false' if '...
apns_token = peewee.CharField(max_length=64, unique=True) def __repr__(self) -> str: return '<Device {}>'.format(self.apns_token) class Token(database.Model)
: PUSH_SCOPE = 'push' ALL_SCOPE = 'all' device = peewee.ForeignKeyField(Device) token = peewee.CharField(max_length=64, unique=True, primary_key=True) scope = peewee.CharField(max_length=10, choices=(PUSH_SCOPE, ALL_SCOPE)) def __repr__(self) -> str: return '<Token {} ({})>'.format(sel...
__author__ = "Johannes Köster" __copyright__ = "Copyright 2015, Johannes Köster" __email__ = "koester@jimmy.harvard.edu" __license__ = "MIT" import os import mimetypes import base64 import textwrap import datetime import io from docutils.parsers.rst.directives.images import Image, Figure from docutils.parsers.rst imp...
ves that use a base64 # data URI instead of pointing to a filename. class EmbeddedImage(Image, EmbeddedMixin): pass directives.register_directive('embeddedimage', EmbeddedImage) class EmbeddedFigure(Figure, EmbeddedMixin): pass directives.register_
directive('embeddedfigure', EmbeddedFigure) def data_uri(file, defaultenc="utf8"): """Craft a base64 data URI from file with proper encoding and mimetype.""" mime, encoding = mimetypes.guess_type(file) if mime is None: mime = "text/plain" logger.info("Could not detect mimetype for {}, assu...
p://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing...
in.endswith('.'): return cfg.CONF.dns_domain return '%s.' % cfg.CONF.dns_domain def _get_request_dns_name(data): dns_domain = _get_dns_domain() if ((dns_domain and dns_do
main != DNS_DOMAIN_DEFAULT)): return data return '' def convert_to_lowercase(data): if isinstance(data, six.string_types): return data.lower() msg = _("'%s' cannot be converted to lowercase string") % data raise n_exc.InvalidInput(error_message=msg) validators.add_validator('dns_name'...
#!/usr/bin/env python from distutils.core import setup setup(name = "quasi", version = "0.87", description = "A multiple-context Python shell", author
= "Ben Last", author_email = "ben@benlast.com", url = "http://quasi-shell.sourceforge.net/", license = "BSD", scripts = ["quas
i.py"], data_files = [("share/licenses/quasi", ["LICENSE"])], extra_path = "quasi", packages = ["."] )
from serial import Serial import time import platform import socke
t serialPort = Serial('COM3' if platform.system() == 'Windows' else '/dev/ttyUSB0', 9600) time.sleep(2) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('', 2222)) server.listen(1) while True: (client, address) = server.accept() print('Connected') while True: data = client.recv(6)#.decode...
lPort.write(data)
#!/usr/bin/env python3 # Copyright 2015, 2016 Endless Mobile, Inc. # This file is part of eos-event-recorder-daemon. # # eos-event-recorder-daemon 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 versi...
t sys class PrintingHTTPRequestHandler(http.server.BaseHTTPRequestHandler): def do_PUT(self): print(self.path, flush=True) content_encoding = self.headers['X-Endless-Content-Encoding'] print(content_encoding, flush=True) content_length = int(self.headers['Content-Length']) ...
print(len(decompressed_request_body), flush=True) sys.stdout.buffer.write(decompressed_request_body) sys.stdout.buffer.flush() status_code_str = sys.stdin.readline() status_code = int(status_code_str) self.send_response(status_code) self.end_headers() # A metrics ...
#! /usr/bin/env python #script that takes an optional argument for the date and target collection and calculates angular separation and elevation of each target from the moon. import ephem, subprocess, operator, argparse #host & port info hostName="veritase.sao.arizona.edu" portNum="" #hostName="lucifer1.spa.umn....
sed veritas.epoch = float(sourceEpoch) #Define ephem moon object and calculate position (ra, dec) and phase TheMoon = ephem.Moon(veritas) TheMoon.compute(veritas) illum = TheMoon.moon_phase*100. #Get angular separation of moon and target degFromMoon = 180./ephem.pi * ephem.separation((TheMoon.ra,TheMoon....
em object for source, to get elevation sourceobj = ephem.FixedBody() sourceobj._ra = float(sourceRA) sourceobj._dec = float(sourceDEC) sourceobj.compute(veritas) sourceALT = sourceobj.alt*180./ephem.pi moonlightsources[sourceName]=[(degFromMoon,sourceALT)] #end of for loop sorted_sources = sorted(moonl...
''' This script will remove the directories if that contains only xml files. ''' import os srcpath = raw_input("Enter the source path : ") for
root, sub, files in os.walk(os.path.abspath(srcpath)): if files:
files = [f for f in files if not f.endswith('.xml')] if not files: fpath = os.path.join(root) os.system('rm -rf %s' % fpath) print "removed", fpath
# -*- coding: utf-8 -*- import argparse import time import socket import sys import json __prog__ = 'xbmc-command' PROG = __prog__ __version__ = '0.4.1' VERSION = __version__ class XBMC(object): def __init__(self, host, port): self.address = (host, port) self.__socket = socket.socket(socket.AF_...
r("Please Implement this method") def run_command(self, args): try: self.xbmc.connect() except socket.timeout: raise CommandException("Unable to connect to host %s:%s" % \ (self.xbmc.address[0], self.xbmc.address[1])) except socket.error as err: ...
self.xbmc.close() raise CommandException("Could not open socket: " + err) self.call(args) def get_active_player_id(self): self.xbmc.Player.GetActivePlayers() result = self.xbmc.recv('Player.GetActivePlayers') if not result: raise CommandException('unable...
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by th
e Free Software Foundation) version 2.1, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for ...
# -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. # # The MIT License (MIT) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the ""Software""),...
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 following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial 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 MER...
# -*- coding: utf-8 -*- from __future__ import absolute_import from
solidspy.solids_GUI import solids_GUI s
olids_GUI()
class Reverb: pass class ScatterLocation: pass class Chorus: pass class Vocoder:
pass class S
huffleSound: pass
# -*- coding: utf8 -*- """ This is part of shot detector. Produced by w495 at 2017.05.04 04:18:27 """ from __future__ import absolute_import, division, print_function import collections import itertools import logging from shot_detector.utils.dsl import DslOperatorMixin from shot_detector.utils.dsl.dsl_kwarg...
erator( op_func=op_func, filters=filters, op_mode=op_mode, ) return filter_operator def apply_filter_operator(self, op_func=None, filters=None, op_mode=None, ...
op_mode: :param kwargs: :return: """ from .filter_operator import FilterOperator, FilterOperatorMode fo_op_mode = FilterOperatorMode.LEFT if op_mode is self.Operator.RIGHT: fo_op_mode = FilterOperatorMode.RIGHT # joined_filters = itertools.chain...
Inc. 2016 """ import jsonpickle import re class APIHelper: """A Helper Class for various functions associated with API Calls. This class contains static methods for operations that need to be performed during API requests. All of the methods inside this class are static methods, the...
(value[item], dict): # Loop through each item in the dictionary and add it retval.update(APIHelper.form_encode(value[item], instanceName + "[" + item + "]"))
else: # Add the current item retval[instanceName + "[" + item + "]"] = value[item] return retval @staticmethod def resolve_names(obj, names, retval): """Resolves parameters from their Model na...
from setuptools import setup, find_packages import sys, os version = '1.3' long_description = """The raisin.restyler package is a part of Raisin, the web application used for publishing the summary statistics of Grape, a pipeline used for processing and analyzing RNA-Seq data.""" setup(name='raisin.restyler', v...
S Independent', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural La
nguage :: English', 'Topic :: Software Development :: Libraries :: Python Modules', 'Operating System :: POSIX :: Linux'], keywords='RNA-Seq pipeline ngs transcriptome bioinformatics ETL', author='Maik Roder', author_email='maikroeder@gmail.com', url='http://big.crg.cat/servi...
sum = 1 curr = 3 for width in xr
ange(3,1002,2): inc = width - 1 sum = sum + curr #bottom right curr = curr + inc sum = sum + curr #bottom left curr = curr + inc
sum = sum + curr #top left curr = curr + inc sum = sum + curr #top right curr = curr + inc + 2 print sum
py as pythoncopy import scipy.optimize as spopt class rslc(): """ A regularly sampled lightcurve, typically obtained by regression. To make such a rslc from a usual lightcurve object, look at the factory function below. One idea is that we want to be able to add and subtract those, propagating errors. There is n...
method): """ Returns the wtv (weighted TV) of the difference between 2 curves. This is symmetric (no change if you invert rs1 and rs2), up to some smal
l numerical errors. """ out = subtract(rs1, rs2).wtv(method) #print out return float(out) def bruteranges(step, radius, center): """ Auxiliary function for brute force exploration. Prepares the "ranges" parameter to be passed to brute force optimizer In other words, we draw a cube ... radius is an int sayi...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorflow/contrib/lite/toco/toco_flags.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from goog...
pe=None, is_extension=False, extension_scope=None, options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto2', extension_ranges=[], o
neofs=[ ], serialized_start=98, serialized_end=500, ) _TOCOFLAGS.fields_by_name['input_format'].enum_type = _FILEFORMAT _TOCOFLAGS.fields_by_name['output_format'].enum_type = _FILEFORMAT _TOCOFLAGS.fields_by_name['inference_input_type'].enum_type = tensorflow_dot_contrib_dot_lite_dot_toco_dot_types__pb2._IODATAT...
""" crypto.aes AES Encryption Algorithm The AES algorithm is just Rijndael algorithm restricted to the default blockSize of 128 bits. Copyright (c) 2002 by Paul A. Lambert Read LICENSE.txt for license information. 2002-06-01 """ from crypto.cipher.rijndael import Rijndael from crypto.cipher...
e import BlockCipher, padWithPadLen, noPadding from crypto.errors import Ba
dKeySizeError class AES(Rijndael): """ The AES algorithm is the Rijndael block cipher restricted to block sizes of 128 bits and key sizes of 128, 192 or 256 bits """ def __init__(self, key = None, padding = padWithPadLen(), keySize=16): """ Initialize AES, keySize is in bytes """ if...
from ditutils.
core import setup setup( name = 'morpheusapi', packages = ['morpheusapi'], version = '2.11.1', description = 'A python wrapper for Morpheus APIs', author = 'Ad
am Hicks', author_email = 'thomas.adam.hicks@gmail.com', url = 'https://github.com/tadamhicks/morpheus-python', download_url = 'https://github.com/tadamhicks/morpheus-python/archive/2.11.1.tar.gz', keywords = ['morpheus', 'api', 'morpheus data'], classifiers = [], )
-) # # (C) 2001-2011 Chris Liechti <cliechti@gmx.net> # this is distributed under a free software license, see license.txt # # URL format: loop://[option[/option...]] # options: # - "debug" print diagnostic messages from serial.serialutil import * import threading import time import logging # map log level names t...
if the connection is blocked. May raise SerialException
if the connection is closed. """ if not self._isOpen: raise portNotOpenError # ensure we're working with bytes data = to_bytes(data) # calculate aprox time that would be used to send the data time_used_to_send = 10.0*len(data) / self._baudrate # when a wri...
# Import the helper gateway class from AfricasTalkingGateway import AfricasTalkingGateway, AfricasTalkingGatewayException from twitment.search import ClassTwitter # Specify your login
credentials cl
ass SMS(object): def __init__(self): pass def send(self,num): sendtweet_obj = ClassTwitter() x = sendtweet_obj.wordFrequency.wordslist username = "CATHERINERAKAMA" apikey = "676dbd926bbb04fa69ce90ee81d3f5ffee2692aaf80eb5793bd70fe93e77dc2e" # Specify the numbers ...
# Author: Bala Venkatesan # License: Apache 2.0 ######################################################################## # Wrote this file to separate out the loading of the data from the # python file where the actual display happens ######################################################################## impor...
averages_by_state.csv', 'r') csvreader = csv.reader(statefile) ######################################################################## # initializing a dataframe to parse only req
uired data from file ######################################################################## columns = ["STATE", "TOTAL_POPULATION", "WORKFORCE", "WORK_%_OF_POP", "EMPLOYED", "EMP_%_OF_POP", "UNEMPLOYED", "UNEMPLOMENT_RATE", ] data = ...
# coding: utf-8 # Copyright (c) 2012, SciELO <scielo-dev@googlegroups.com> # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # Redistributions of source code must retain the above copyright not...
ist
of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY ...
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identi
fier: (Apache-2.0 OR MIT) from spack import * class RSdmtools(RPackage): """Species Distribution Modelling Tools: Tools for processing data associated with species distribution modelling exercises This packages provides a set of tools for post processi
ng the outcomes of species distribution modeling exercises.""" homepage = "https://cloud.r-project.org/package=SDMTools" url = "https://cloud.r-project.org/src/contrib/SDMTools_1.1-221.tar.gz" list_url = "https://cloud.r-project.org/src/contrib/Archive/SDMTools" version('1.1-221.1', sha256='3...
#/u/Goldensights import praw import time import datetime '''USER CONFIG''' USERNAME = "" #This is the bot's Username. In
order to send mail, he must have some amount of Karma. PASSWORD = "" #This is the bot's Password. USERAGENT = "" #This is a short description of what the bot does. For example "/u/GoldenSights' Newsletter bot" MAXPOSTS = 1000 #This is how many posts you want to retrieve all at once. PRAW can downlo
ad 100 at a time. WAIT = 30 #This is how many seconds you will wait between cycles. The bot is completely inactive during this time. PRINTFILE = 'messages.txt' #This is the file, in the same directory as the .py file, where the messages are stored SUBJECTLINE = "Newsletterly" ITEMTYPE = 't4' #The type of item to gather...
.popped_tensor_lists[internal_capture]) elif internal_capture.dtype == dtypes.resource: grad_func_graph.outputs.append(internal_capture) else: raise ValueError("Tensor %s is in list of internal_captures but is" " neither a resource nor is in popped_tensor_lists." % ...
f t in tensor.graph.outputs: return t # tf.defun adds an Identity for each output, check whether that is the case. iden
tity_op = t.consumers()[0] if (identity_op.type == "Identity" and identity_op.outputs[0] in tensor.graph.outputs): return identity_op.outputs[0] return None for consumer in tensor.consumers(): # Find the consumer that is a TensorListPushBack node whose TensorList input # is in the list ...
from django.shortcuts import render, redirect from django.contrib.auth.decorators import user_passes_test from django.shortcuts import get_object_or_404 from django import forms from django.db.models import Max, Avg, Sum from opos.models import Customers from opos.forms import CustomerAddForm, CustomerForm def is_...
= customers return render (request, "customers.html", c) @user_passes_test (is_staff) def customeradd (request): if request.method == 'POST': form = CustomerAddForm (request.POST) if form.is_valid (): form.save () return redirect ('customers') c = {} c['customeredit'] = CustomerAddForm () return rende...
est, customerpk): customer = get_object_or_404 (Customers, pk=customerpk) if request.method == 'POST': form = CustomerForm (request.POST, instance=customer) if form.is_valid (): form.save () return redirect ('customers') else: form = CustomerForm (instance=customer) c = {} c['customer'] = customer...
from ajenti.api import * from ajenti.com impo
rt * class DebianNetworkCfg(Plugin): implements(IConfigurable) name = 'Network' id = 'network' platform = ['Debian', 'Ubuntu'] def list_files(self): dir = '/etc/network/' return [dir+'*', dir+
'*/*', dir+'*/*/*']
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','tango_with_django_project.settings') import django django.setup() from rango.models import Category, Page def populate(): # First, we will create lists of dictionaries containing the pages # we want to add into each category. # Then we will create...
hon_pages = [ {"title": "Official Python Tutorial", "url": "http://docs.python.org
/2/tutorial/", "views": 32}, {"title": "How to Think like a Computer Scientist", "url": "http://www.greenteapress.com/thinkpython/", "views": 16}, {"title": "Learn Python in 10 Minutes", "url": "http://www.korokithakis.net/tutorials/python/", "views": 8}] ...
# -*- coding: utf-8 -*- import codecs all_tables = { 'ktgg': ['main'], 'zgcpwsw': ['title', 'casecode'], # # # 'ktgg', # # 'cdfy_sfgk', # # 'newktgg', # # 'zyktgg', # # 'zgcpwsw', # # 'itslaw', # # 'qyxg_zgcpwsw', # # 'qyxg_wscpws', # 'zhixing': ['pname', 'case_co...
ljz': ['company_name', 'certificate_no'], 'qyxx_jzsgxkz': ['company_name', 'certificate_no'], 'qyxx_miit_jlzzdwmd': ['company_name', 'certificate_no'], 'qyxx_food_prod_cert': ['company_name', 'certificate_no'], 'qyxx_hai
guanzongshu': ['company_name', 'customs_code'], 'qyxx_gmpauth_prod_cert': ['company_name', 'certificate_no'], 'qyxx_hzp_pro_prod_cert': ['company_name', 'certificate_no'], 'qyxx_medi_jy_prod_cert': ['company_name', 'certificate_no'], 'qyxx_medi_pro_prod_cert': ['company_name', 'certificate_no'], 'qy...
# # Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U # # 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 unde...
t('active', None), 'name': scim.get('userName', None), 'description': scim.get('displayName', None), 'password': scim.get('password', None) } @_remove_
dict_nones def role_scim2key(scim): keystone = {} keystone['id'] = scim.get('id', None) if scim.get('domain_id', None): keystone['name'] = '%s%s%s' % ( scim.get('domain_id'), ROLE_SEP, scim.get('name', None)) else: keystone['name'] = scim.get('name', None) return keyston...
l the evaluations for the given file. Keys are the following: track_name : Name of the track ds_name : Name of the data set HitRate_3F : F-measure of hit rate at 3 seconds HitRate_3P : Precision of hit rate at 3 seconds HitRate_3R : Recall ...
keys(): context = msaf.prefix_dict[ds_prefix] else: context = "function" try: # TODO: Read hierarchical annotations if config["hier"]: ref_times, ref_labels, ref_levels = \ msaf.io.read_hier_references(ref_file, annotation_id=0, ...
ls=["function"]) else: ref_inter, ref_labels = jams2.converters.load_jams_range( ref_file, "sections", annotator=annotator_id, context=context) except: logging.warning("No references for file: %s" % ref_file) return {} # Read estimations with correct configur...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import optparse import os import sys from telemetry.core import util from telemetry.results import buildbot_output_formatter from telemetry.results import c...
ress_reporter from telemetry.results import html_output_formatter f
rom telemetry.results import json_output_formatter from telemetry.results import page_test_results from telemetry.results import progress_reporter # Allowed output formats. The default is the first item in the list. _OUTPUT_FORMAT_CHOICES = ('html', 'buildbot', 'csv', 'gtest', 'json', 'chartjson', 'csv-pivot-table...
import fechbase class Records(fechbase.RecordsBase): def __init__(self): fechbase.RecordsBase.__init__(self) self.fields = [ {'name': 'FORM TYPE', 'number': '1'}, {'name': 'FILER FEC CMTE ID', 'number': '2'}, {'name': 'COMMITTEE NAME', 'number': '3'}, ...
r': '14-'}, {'name': 'TOTAL COSTS', 'number': '15'}, {'name': 'FILER', 'number': '16-'}, {'name': 'SIGNED', 'number': '17-'}, {'name': 'TITLE', 'number': '18'}, ] self.fields_names = self.hash_names(self
.fields)
"""Test energy_p
rofiler module.""" import unittest from physalia.energy_profiler import AndroidUseCase # pylint: disable=missing-docstring class TestEnergyProfiler(unittest.TestCase): def test_empty_android_use_case(self): # pylint: disable=no-self-use use_case = AndroidUseCase( name="Test", ...
cleanup=None ) use_case.run()
""" Setup file for led-controller author: Luis Garcia Rodriguez 2017 Licence: GPLv3 """ from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) setup( name='led-controller', version='2.0.0',
description='A simple interface for controlling LEDs in circadian experiments', # The project's main homepage. url='https://github.com/polygonaltree/Led-control', # Author details author='Luis Garcia Rodriguez', author_email='luis.garcia@uni-muenster.de', license='GPLv3', packages=find_p...
my_module"] install_requires=['pyside2'], entry_points={ 'console_scripts': [ 'led-controller=gui:main', ], }, )
s_alive=True) self.cockatoo_white_d = self.cockatoo.variants.create(color='white', looks_alive=False) self.cockatoo_blue_a = self.cockatoo.variants.create(color='blue', looks_alive=True) self.cockatoo_blue_d = self.cockatoo.variants.create(color='blue', looks_alive=False) self.custom_se...
lient): cart = self._get_or_create_cart_for_client(client) cart.replace_item(self.macaw_blue, 1) cart.replace_item(self.macaw_blue_fake, Decimal('2.45')) cart.replace_item(self.cockatoo_white_a, Decimal('2.45')) return cart def _create_order(self, client): sel
f._create_cart(client) self._test_status(reverse(prepare_order), method='post', client_instance=client, status_code=302) return self._get_order_from_session(client.session) def test_order_is_deleted_when_all_cart_items_are_deleted(self): order = self._create_order(...
from tornado.web import RequestHandler class BaseHandler(RequestHandler): def initialize(self): _settings = self.application.settings self.db = self.application.db #self
.redis = _settings["redis"
] self.log = _settings["log"]
# Generated by Django 3.1.4 on 2020-12-06 08:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('p
rojects', '0023_auto_20201202_0349'), ] operations = [ migrations.AlterField( model_name='review', name='status', field=models.CharField(choices=[('PENDING', 'Pending'), ('REQUESTED', 'Requested'), ('CANCELLED', 'Cancelled'), ('ACC
EPTED', 'Accepted'), ('DECLINED', 'Declined'), ('COMPLETED', 'Completed'), ('EXTRACTING', 'Retrieval in progress'), ('EXTRACTED', 'Retrieved'), ('FAILED', 'Retrieval failed'), ('REGISTERED', 'Registered')], default='PENDING', help_text='The status of the review.', max_length=16), ), ]
import random import time from collections import OrderedDict from plenum.common.util import randomString try: import ujson as json except ImportError: import json import pytest from plenum.recorder.recorder import Recorder TestRunningTimeLimitSec = 350 def test_add_to_recorder(recorder): last_check_...
ement in lst1] return ls1 == ls2 for k, v in recorder.store.iterator(include_value=True): p = Recorder.get_parsed(v) assert sublist([i[1:] for i in p] , combined) p = Recorder.get_parsed(v, only_incoming=True) if p: assert sublist(p, incoming) for i i...
for i in p: outgoing.remove(i) assert not incoming assert not outgoing def test_recorder_get_next_incoming_only(recorder): incoming_count = 100 incoming = [(randomString(100), randomString(6)) for _ in range(incoming_count)] while incoming: recorder...
#_*_ coding: utf-8 _*_ t1 = () print type(t1) t3 = 1,2,3 print type(t3) r1 = (1) print r1 print type(r1) r1 = (1,) print r1 print type(r1) t = (1,2,3) print t*2 print t+('aaa','bbb') print t print print t[0], t[1:3] print len(t) print 1 in t print range(1,3) t= (12345,54321,'hhh') u = t,(1,2,3,4,5) print u t2 ...
3 = {1:'ggg',2:'hhh'} u3 = t3,(1,2,3) print u3 x,y,z=1,2,3 print x print y print z t = 1,2,'hello' x,y,z = t
# -*- coding: utf-
8 -*- fro
m .__version__ import __version__
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Animal(object): def run(self): print('Animal running...') class Dog(Animal): def run(self): print('Dog running...') def shout(self): print('Dog wang wang...') class Cat(Animal): def run(self): print('Cat running...') def shout(self): print('Cat mi...
ice(Dog())) print(run_twice(Cat())) print(run_twice(Pig()
))
#!/usr/bin/env python def pos_neg(a, b, negative): if negative: return a < 0 and b < 0 else: return (a < 0 and b > 0) or (a > 0 a
nd b < 0) if __name__ == "__main__": # run some tests if run as script # (from the codingbat site -- not all, I got bored) assert pos_ne
g(1, -1, False) is True assert pos_neg(-1, 1, False) is True assert pos_neg(-4, -5, True) is True assert pos_neg(-4, -5, False) is False assert pos_neg(-4, -5, True) is True assert pos_neg(-6, -6, False) is False assert pos_neg(-2, -1, False) is False assert pos_neg(1, 2, False) is False ...
on, TypeConstraint, TypeId from pants.util.contextutil import temporary_file_path from pants.util.objects import datatype logger = logging.getLogger(__name__) class ExecutionRequest(datatype('ExecutionRequest', ['roots'])): """Holds the roots for an execution, which might have been requested by a user. To crea...
e is SelectDependencies: self._native.lib.tasks_add_select_dependencies(self._tasks, product_constraint,
self._to_constraint(selector.dep_product), self._to_utf8_buf(selector.field), self._to_ids_buf(selector.field_types)) elif selector_type is SelectTransitiv...
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
_32, dtypes.int64))
return optimization._ChooseFastestBranchDataset( dataset, [branch_0, branch_1], num_elements_per_branch=3) self.run_core_tests(build_ds, None, 10) def testWithMoreOutputThanInput(self): def build_ds(): dataset = dataset_ops.Dataset.from_tensors(0).repeat(1000).batch(100) def branch(d...
from interfaces.labels_map import LabelsMap from helpers.python_ext import to_str class LTS: def __init__(self, init_states, model_by_signal:dict, tau_model:LabelsMap,
state
_name:str, input_signals, output_signals): self._output_models = model_by_signal self._tau_model = tau_model self._init_states = set(init_states) self._state_name = state_name self._output_signals = output_signals # TODO: duplication with _outp...
# Copyright 2013 IBM Corp # Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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/LICENS...
class TestFoo(test.BaseTes
tCase): expected_attr = not expected_to_skip @decorators.skip_unless_attr(attr) def test_foo(self): pass t = TestFoo('test_foo') if expected_to_skip: self.assertRaises(testtools.TestCase.skipException, t.test...