prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
# 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 in the hope that it will be useful, # b...
): def test_plot_experiment(self): """ Tests the plot_experiment method. """ datasets = [self.datafile("bolts.arff"), self.datafile("bodyfat.arff"), self.datafile("autoPrice.arff")] cls = [ classifiers.Classifier("weka.classifiers.trees.REPTree"),
classifiers.Classifier("weka.classifiers.functions.LinearRegression"), classifiers.Classifier("weka.classifiers.functions.SMOreg"), ] outfile = self.tempfile("results-rs.arff") exp = experiments.SimpleRandomSplitExperiment( classification=False, runs=1...
from .. import Provider as CurrencyProvider class Provider(CurrencyProvider): # Format: (code, name) currencies = ( ("AED", "Dírham de los Emiratos Árabes Unidos"), ("AFN", "Afghaní"), ("ALL", "Lek albanés"), ("AMD", "Dram armenio"), ("ANG", "Florín de las Antillas Hola...
bo Verde"), ("CZK", "Corona checa"), ("DJF", "Franco yibutiano"), ("DKK", "Corona danesa"), ("DOP", "Peso dom
inicano"), ("DZD", "Dinar argelino"), ("EGP", "Libra egipcia"), ("ERN", "Nafka"), ("ETB", "Bir de Etiopía"), ("EUR", "Euro"), ("FJD", "Dólar fiyiano"), ("FKP", "Libra de las islas Falkland"), ("GBP", "Libra esterlina"), ("GEL", "Larí georgiano"), ...
import pytest from formulaic.parser.types import Factor, Term class TestTerm: @pytest.fixture def term1(self): return Term([Factor("c"), Factor("b")]) @pytest.fixture def term2(self): return Term([Factor("c"), Factor("d")]) @pytest.fixture def term3(self): return Ter...
assert hash(term1) == hash("b:c") def test_equality(self, term1, term2): assert term1 == term1 assert term1 == "b:c" assert term1 != term2 assert term1 != 1 def test_sort(
self, term1, term2, term3): assert term1 < term2 assert term2 < term3 assert term1 < term3 assert not (term3 < term1) with pytest.raises(TypeError): term1 < 1 def test_repr(self, term1): assert repr(term1) == "b:c"
le except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIN...
obs): """Maps a list of jobs to cleanup to a list of response objects (or exception objects) from the api""" return [(job, execute_chronos_api_call_for_job(client.delete, job)) for job in jobs] def cleanup_tasks(client, jobs): """Maps a list of tasks to cleanup to a list of response objects (or exception ...
_call_for_job(client.delete_tasks, job)) for job in jobs] def format_list_output(title, job_names): return '%s\n %s' % (title, '\n '.join(job_names)) def deployed_job_names(client): return [job['name'] for job in client.list()] def filter_paasta_jobs(jobs): """ Given a list of job name strings, ...
#!/usr/bin/env python import io import os import sys from efesto.Version import version from setuptools import find_packages, setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup.py bdist_wheel upload') sys.exit() readme = io.open('README.md', 'r', enco...
'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', ], entry_points=""" [console_scripts] efesto=efesto.Cli:Cli.main
""" )
"""SCons.Tool.sunf90 Tool-specific initialization for sunf90, the Sun Studio F90 compiler. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 20...
4 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sub...
he 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 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND...
#!/usr/bin/env python3 '''Conway's Game of Life in a Curses Terminal Window ''' import curses import time from GameOfLife import NumpyWorld from GameOfLife import Patterns from curses import ( COLOR_BLACK, COLOR_BLUE, COLOR_CYAN, COLOR_GREEN, COLOR_MAGENTA, COLOR_RED, COLOR...
(argv,msg=None,exit_value=-1): usagefmt = 'usage: {name} [[pattern_name],[X,Y]] ...' namefmt = '\t{n}' print(usagefmt.format(name=os.path.basename(argv[0]))) if msg: print(msg) print('pattern names:')
[print(namefmt.format(n=name)) for name in Patterns.keys()] exit(exit_value) if __name__ == '__main__': import sys import os from curses import wrapper try: wrapper(main,sys.argv) except KeyError as e: usage(sys.argv,'unknown pattern {p}'.format(p=str(e))) except ValueErr...
lib # Map swarming_client to use subprocess42 sys.path.append(common_lib.SWARMING_DIR) from utils import subprocess42 class TimeoutError(Exception): pass class ControllerProcessWrapper(object): """Controller-side process wrapper class. This class provides a more intuitive interface to task-side processes ...
eyword arguments. """ _processes = {} _process_next_id = 0 _creation_lock = threading.Lock() def __init__(self, cmd, key): self.s
tdout = '' self.stderr = '' self.key = key self.cmd = cmd self.proc = None self.cwd = None self.shell = False self.verbose = False self.detached = False self.complete = False self.data_lock = threading.Lock() self.stdout_file = open(self._CreateOutputFilename('stdout'), 'wb+'...
h == other.path def __lt__(self, other): return self.path < other.path @property def path(self): return os.path.join(self.dirpath, self.file) class BuildFile: """ Represent the state of a translatable file during the build process. """ def __init__(self, command, domain, ...
s(self, parser): parser.add_argument( '--locale', '-l', default=[], dest='locale', action='append', help='Creates or updates the message files for the given locale(s) (e.g. pt_BR). ' 'Can be used multiple times.', ) parser.add_argument
( '--exclude', '-x', default=[], dest='exclude', action='append', help='Locales to exclude. Default is none. Can be used multiple times.', ) parser.add_argument( '--domain', '-d', default='django', dest='domain', help='The domain of the message files (defa...
# -*- coding: utf-8 -*- import os from AppiumLibrary.keywords import * from AppiumLibrary.version import VERSION __version__ = VERSION class AppiumLibrary( _LoggingKeywords, _RunOnFailureKeywords, _ElementKeywords, _ScreenshotKeywords, _ApplicationManagementKeywords, _WaitingK...
=UiSelector().description('Apps') | Matches by Android UI Automator | | | ios | Click Element `|` ios=.buttons().withName('Apps') | Matches by iOS UI Automation | | | nsp | Click Element `|` nsp=name=="...
by iOSNsPredicate | Check PR: #196 | | chain | Click Element `|` chain=XCUIElementTypeWindow[1]/* | Matches by iOS Class Chain | | | css | Click Element `|` css=.green_button | Matches by c...
# # This file is part of pysnmp software. # # Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pysnmp/license.html # from pysnmp import error class MetaObserver(object): """This is a simple facility for exposing internal SNMP Engine working details to pysnmp applicat...
_observers[execpoint] = [] self.__observers[execpoint].append(cbFun) def unregisterObserver(self, cbFun=None): if cbFun is None: self.__observers.clear() self.__contexts.clear() else: for execpoint in dict(self.__observers): if cbFun...
vers[execpoint]: del self.__observers[execpoint] def storeExecutionContext(self, snmpEngine, execpoint, variables): self.__execpoints[execpoint] = variables if execpoint in self.__observers: for cbFun in self.__observers[execpoint]: cbFun(snmpEngine, ...
''' Problem: Find the kth smallest element in a bs
t without using static/global variables. ''' def find(node, k, items=0): # Base case. if not node: return items, None # Decode the nod
e. left, value, right = node # Check left. index, result = find(left, k, items) # Exit early. if result: return index, result # Check this node. next = index + 1 if next == k: return next, value # Check the right. return find(right, k, next) test = (((None, ...
# -*- coding: utf-8 -*- # Copyright(C) 2017 Juliette Fourcot # # This file is part of a weboob module. # # This weboob module is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of th...
cense, or # (at your option) any later version. # # This weboob module 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 Lesser General Public License for more details. # # You should h...
icenses/>. from __future__ import unicode_literals from .module import EnsapModule __all__ = ['EnsapModule']
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # ...
example, it will create multiple examples with the length of window_size x: (time_step) x (input_dim) y: (time_step) x (output_dim) x_out: (total_batch) x (batch_size) x (window_size) x (input_dim) y_out: (total_batch) x (batch_size) x (window_size) x (output_dim) total_batch x bat
ch_size <= examples ''' # (batch_size) x (window_size) x (dim) # n_examples is calculated by sliding one character with window_size n_examples = x.shape[0] - window_size + 1 # n_examples = batch_size x_batch = np.empty((n_examples, window_size, x.shape[1])) y_batch = np.empty((n_examples, w...
36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If ...
uals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tup
les # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'bitk3', u'BIoinformatics ToolKit 3 Documentation', [u'Davi Ortega'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output --------------------------...
from django.conf.urls import include, url from demo.views import common from demo.views.visadirect import fundstransfer, mvisa, reports, watchlist from demo.views.pav import pav from demo.views.dcas import cardinquiry from demo.views.merchantsearch import search from demo.views.paai.fundstransferattinq.cardattributes....
rts API url(r'^reports$', reports.index, name='vd_reports'), url(r'^reports/', include([ url(r'^transactiondata$', reports.transactiondata, name='vd_reports_transactiondata'), ])), # WatchList Inquiry methods
urls url(r'^watchlist$', watchlist.index, name='vd_wl'), url(r'^watchlist/', include([ url(r'^inquiry$', watchlist.inquiry, name='vd_wl_inquiry') ])) ])), ]
import sys if '' not in sys.path: sys.path.append('') import time import unittest from pyactors.logs import file_logger from pyactors.exceptions import EmptyInboxException from tests import ForkedGreActor as TestActor from multiprocessing import Manager class ForkedGreenletActorTest(unittest.TestCase): de...
stop() result = [] while True: try: result.append(actor.inbox.get()) except EmptyInboxException: break
self.assertEqual(len(result), 10) self.assertEqual(actor.processing, False) self.assertEqual(actor.waiting, False) if __name__ == '__main__': unittest.main()
from django import forms from django_roa_client.models import RemotePage, RemotePageWithRelations class TestForm(forms.Form): test_field = forms.CharFiel
d() remote_page = forms.ModelChoiceField(
queryset=RemotePage.objects.all()) class RemotePageForm(forms.ModelForm): class Meta: model = RemotePage class RemotePageWithRelationsForm(forms.ModelForm): class Meta: model = RemotePageWithRelations
from datetime import datetime, timedelta from django.core.files.storage import default_storage as storage import olympia.core.logger from olympia import amo from olympia.activity.models import ActivityLog from olympia.addons.models import Addon from olympia.addons.tasks import delete_addons from olympia.amo.utils imp...
eks_ago = days_ago(15) # Hard-delete stale add-ons with no versions. No email should be sent. versionless_addons = Addon.unfiltered.filter( versions__pk=None, created__lte=two_weeks_ago ).values_list('pk', flat=True) for chunk in chunked(versionless_addons, 100): delete_addons.delay(chun...
log.info( '[FileUpload:{uuid}] Removing file: {path}'.format( uuid=file_upload.uuid, path=file_upload.path ) ) if file_upload.path: try: storage.delete(file_upload.path) except OSError: pass file_uplo...
## This file is part of CDS Invenio. ## Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008 CERN. ## ## CDS Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (...
. __revision__ = "$Id$" import os import re from invenio.dbquery import run_sql from invenio.websubmit_config import InvenioWebSubmitFunctionStop def Check_Group(parameters, curdir, form, user_info
=None): """ Check that a group exists. Read from file "/curdir/Group" If the group does not exist, switch to page 1, step 0 """ #Path of file containing group if os.path.exists("%s/%s" % (curdir,'Group')): fp = open("%s/%s" % (curdir,'Group'),"r") group = fp.read() g...
* from scapy.sendrecv import srp,srp1 from scapy.arch import get_if_hwaddr ################# ## Tools ## ################# class Neighbor: def __init__(self): self.resolvers = {} def register_l3(self, l2, l3, resolve_method): self.resolvers[l2,l3]=resolve_method def resolve(sel...
IntField("pathcost", 0), ShortField("bridgeid", 0), MACField("bridgemac", ETHER_ANY), ShortField("portid", 0), BCDFloatField("age", 1), BCDFloatField("maxage", 20), BCDFloatField("hellotime", 2), ...
ddelay", 15) ] class EAPOL(Packet): name = "EAPOL" fields_desc = [ ByteField("version", 1), ByteEnumField("type", 0, ["EAP_PACKET", "START", "LOGOFF", "KEY", "ASF"]), LenField("len", None, "H") ] EAP_PACKET= 0 START = 1 LOGOFF = 2 KEY = 3 ASF = ...
# Copyright 2021 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 os from googleapiclient.discovery import build from google.oauth2 import service_account class RealTimeReportingServer(): SCOPES = ['https://www....
userKey='all', applicationName='chrome', customerId='C029rpj4z', eventName=eventName, startTime=startTime).execute() activities = results.get('items', []) for activity in activities: for event in activity.get('events', []): for parameter in event.get('parame...
and \ parameter['value'] in deviceId: containsEvent = True break return containsEvent
import logging import mapnik import xml.etree.ElementTree as ET import os import subprocess import tempfile # Set up logging logging.basicConfig(format="%(asctime)s|%(levelname)s|%(message)s", level=logging.INFO) # Parameters shpPath = "C:/Projects/BirthsAndPregnanciesMapping/data/2014-04-24/Zanzibar/Zanzibar.shp" ep...
nik.Rule() rule.symbols.append(symbolizer) style = mapnik.Style() style.rules.append(rule) # Create Datasource datasource = mapnik.Shapefile(file=shpPath) # Create layer layer = mapnik.Layer("boun
daries") layer.datasource = datasource layer.styles.append("boundariesStyle") # Calculate image output size envelope = datasource.envelope() dLong = envelope.maxx - envelope.minx dLat = envelope.maxy - envelope.miny aspectRatio = dLong / dLat if dLong > dLat: width = max_img_size height = int(width / aspectRa...
f, supports_virtualized=True) def makeRecipeBuild(self): """Create and return a specific recipe.""" chocolate = self.factory.makeProduct(name='chocolate') cake_branch = self.factory.makeProductBranch( owner=self.chef, name='cake', product=chocolate) recipe = self.factory...
, self.getUserBrowser, build_url + '/+rescore', user=self.chef) def test_rescore_build_wrong_state(self): """If the build isn't queued, you can't rescore it.""" build = self.makeRecipeBuild() build.cancelBuild() transaction.commit() build_url = canonical_url(buil...
escore build') def test_rescore_build_wrong_state_stale_link(self): """Show sane error if you attempt to rescore a non-queued build. This is the case where the user has a stale link that they click on. """ build = self.factory.makeSourcePackageRecipeBuild() build.cancelBuil...
ort topi.testing import xlwt import argparse import os import ctypes from tvm import autotvm from tvm.autotvm.tuner import XGBTuner, GATuner, RandomTuner, GridSearchTuner parser = argparse.ArgumentParser() parser.add_argument("-d", nargs=1, type=str, default=["resnet3"]) args = parser.parse_args() layer = args.d[0] ...
utput_height, output_width, in_channel): last_input_width_index = (ofw-1)*stride_width + s-1 last_input_height_index = (ofh-1)*stride_height + r-1 ry = tvm.reduce_axis((0, r), name='ry') rx = tvm.reduce_axis((0, s), name='rx') A = tvm.placeholder((rco,r,s,ifmblock, ofmblock), name='w') B = t...
input_height_index + 1,last_input_width_index + 1,ifmblock), name='b') k = tvm.reduce_axis((0, ifmblock), name='k') k_outer = tvm.reduce_axis((0, rco), name='k_outer') C = tvm.compute( (ofh,ofw,ofmblock), lambda z,m,n: tvm.sum(A[k_outer,ry,rx,k,n] * B[k_outer,ry + z*stride_height,rx + m...
e SubscribedTrackPage :param Version version: Version that contains the resource :param Response response: Response from the API :param room_sid: The SID of the room where the track is published :param participant_sid: The SID of the participant that subscribes to the track :re...
), } # Context self._context = None self._solution = { 'room_sid': room_sid, 'participant_sid': participant_sid, 'sid': sid or self._properties['sid'], } @property def _proxy(self): """ Genera
te an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: SubscribedTrackContext for this SubscribedTrackInstance :rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track....
#!/usr/bin/python # coding=utf-8 from setuptools import setup, find_packages setup( name = "HEIGVD_TimetableParser", version = "0.1", packages = find_packages(), install_requires = ['icalendar>=3.5', 'xlrd>=0.9.2'], # metadata for upload to PyPI author = "Leeroy Brun", author_email = "lee...
= "Transforme un horaire au format XLS provenant de l'intranet du département FEE de la HEIG-VD en un fichier ICS.", license = "MIT", keywords = "heig-vd ics xls fee", url =
"https://github.com/leeroybrun/heigvd-timetable-parser", )
import io from rich.console import Console from rich.measure import Measurement from rich.styled import Styled def test_styled(): styled_foo = Styled("foo", "on red") console = Console(file=io.StringIO(), force_terminal=True, _environ={}) assert Measureme
nt.get(console, console.options, styled_foo) == Measurement(3, 3) console.print(styled_foo) result = console.
file.getvalue() expected = "\x1b[41mfoo\x1b[0m\n" assert result == expected
for NON-LISTED DICOT seedlings exposed to Pesticide X in SEMI-AQUATIC areas """ self.out_nds_rq_semi = self.out_total_semi / self.ec25_nonlisted_seedling_emergence_dicot return self.out_nds_rq_semi def loc_nds_semi(self): """ Level of concern for non-listed dicot seedlings e...
sk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk." msg_fail = "The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 fo
r ratio in self.out_lds_rq_dry] self.out_lds_loc_dry = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_lds_rq_dry >= 1.0 #self.out_lds_loc_dry = exceed_boolean.map(lambda x: # 'The risk quotient for list...
from setuptools import setup version = '0.4' setup( name = 'django-cache-decorator', packages = ['django_cache_decorator'],
license = 'MIT', version = version, description = 'Easily add caching to functions within a django project.', long_description=open('README.md').read(), author = 'Richard Caceres', author_email = 'me@rchrd.net', url = 'https://github.com/rchrd2/django-cache-decorator/', download_url = 'htt...
tratos_api = restful.Api(contratos, prefix="/api/v1") # receita_api.decorators = [cors.crossdomain(origin='*')] # class Date(fields.Raw): # def format(self, value): # return str(value) # Parser for RevenueAPI arguments contratos_list_parser = RequestParser() contratos_list_parser.add_argument('cnpj') cont...
ent('nome_fornecedor') contratos_list_parser.add_argument('licitacao') contratos_list_parser.add_a
rgument('group_by', default='') contratos_list_parser.add_argument('order_by', 'id') contratos_list_parser.add_argument('page', type=int, default=0) contratos_list_parser.add_argument('per_page_num', type=int, default=100) # Fields for ContratoAPI data marshal contratos_fields = { 'id': fields.Integer() ...
# Copyright (c) 2011 CSIRO # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Epping NSW 1710, Australia # atnf-enquiries@csiro.au # # This file is part of the ASK
AP software distribution. # # The ASKAP software distribution is free software: you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the Lice
nse # or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a ...
# -*-
coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-09 13:44 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0002_tablefield_allow_null'), ] operations = [ migrations.AddField( ...
# -*- coding: utf-8 -*- from module.plugins.internal.XFSPAccount import XFSPAccount class RyushareCom(XFSPAccount): __name__ = "RyushareCom" __version__ = "0.03" __type__ = "account" __description__ = """ryushare.com account plugin""" __author_name__ = ("zoidberg", "trance4us") __author_mail__...
, "op": "login"}) if 'Incorrect Login or Password' in html or '>Error<' in html:
self.wrongPassword()
from numpy import matrix # integer Size; integer nPQ, Matrix G; Matrix B; Array U def JacMat(Size, nPQ, G, B, U): # Method Of Every Entry Of Jacbean Matrix f = U.real e = U.imag JacMat = zeros(Size, Size) def Hij(B, G, e, f): return -B*e+Gf def Nij(B, G, e, f): retur...
e: JacMat[m][n] = Hij(B[m][n], G[m][n], e[m], f[m]) for m in range(0, Size, 2): #N for n in range(1, Size, 2): if m==n: JacMat[m][n] = Nii(B[m][m], G[m][m], e[m], f[m]) else: JacMat[m][n] = Nij(B[m][n], G[m]...
f[m]) else: JacMat[m][n] = Jij(B[m][n], G[m][n], e[m], f[m]) for m in range(1, Size, 2): #L for n in range(1, nPQ*2, 2): if m==n: JacMat[m][n] = Lii(B[m][m], G[m][m], e[m], f[m]) else: JacMa...
""" WSGI config f
or batfinancas project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", ...
ngs") application = get_wsgi_application()
# -*- coding: utf-8 -*- """ *==LICENSE==* CyanWorlds.com Engine - MMOG client, server and tools Copyright (C) 2011 Cyan Worlds, Inc. 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...
s to be played back at # 0.035345 (2000 / 56585) frames per second. Which means animation # speed needs to be set to 0.0011781666 ((2000 / 56585) / 30) kDayAnimationSpeed = (DayFrameSize.value / kDayLengthInSeconds) / 30.0 # The Bahro symbol is set to trigger on frame 226 of 2000 which # is 11.3% (226 / 2000) into the...
r base # point for every other age that needs the Bahro symbol. kTimeWhenSymbolAppears = kDayLengthInSeconds * (float(SymbolAppears.value) / float(DayFrameSize.value)) #==================================== class xPodBahroSymbol(ptResponder): ########################### def __init__(self): ptResponder....
#!/bin/env python import npyscreen class MainFm(npyscreen.Form): def create(self): self.mb = self.add(npyscreen.MonthBox,
use_datetime = True) class TestApp(npyscreen.NPSAppManaged): def onStart(self):
self.addForm("MAIN", MainFm) if __name__ == "__main__": A = TestApp() A.run()
(reason=reason) step = make_step_decorator(context, instance, self._virtapi.instance_update) @step def fake_step_to_match_resizing_up(): pass @step def rename_and_power_off_vm(undo_mgr): self._resize_ensure_vm_is_shutd...
lf._session.call_xenapi('VDI.get_virtual_size', root_vdi['ref']) virtual_size = int(virtual_size) old_gb = virtual_size / (1024 * 1024 * 1024) new_gb = instance['root_gb'] if virtual_size < new_disk_size: # Resize up. Simple ...
%(vdi_uuid)s from %(old_gb)dGB to " "%(new_gb)dGB"), locals(), instance=instance) resize_func_name = self.check_resize_func_name() self._session.call_xenapi(resize_func_name, root_vdi['ref'], str(new_disk_size)) LOG.debug(_("Resize complete...
from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^$', 'recollect.views.home', nam
e='home'), url(r'^albums$', 'recollect.views.albums', name='albums'), url(r'^album/(?P<album_slug>[A-z0-9-]+)$',
'recollect.views.album', name='album'), )
# -*- coding: utf-8 -*- # Copyright (C) 2010 Holoscópio Tecnologia # Author: Luciana Fujii Pontello <luciana@holoscopio.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of...
seful, # 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. import gobject import gtk from sltv.settings import UI_DIR from core impor...
""" Author: Eric J. Ma License: MIT A Python module that provides helper functions and variables for encoding amino acid features in the protein interaction network. We encode features in order to feed the data into the neural f
ingerprinting software later on. """ amino_acids = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S",
"T", "V", "W", "X", "Y", "Z", ]
from abc import ABCMeta, abstractmethod class NotificationSource(): """ Abstract class for all notification sources. """ __metaclass__ = ABCMeta @abstractmethod def poll(self): """ Used to get a set of changes between data retrieved in this call and the las
t. """ raise NotImplementedError('N
o concrete implementation!') @abstractmethod def name(self): """ Returns a unique name for the source type. """ raise NotImplementedError('No concrete implementation!')
# -*- coding: utf-8 -*- """Example: Test for equality of coefficients across groups/regressions Created on Sat Mar 27 22:36:51 2010 Author: josef-pktd """ import numpy as np from scipy import stats #from numpy.testing import assert_almost_equal import scikits.statsmodels as sm from scikits.statsmodels.sandbox.regres...
00][0] example_size = [(10,2), (100,2)][0] example_groups = ['2', '2-2'][1] #'2-2': 4 groups, # groups 0 and 1 and groups 2 and 3 have identical parameters in DGP #generate example #---------------- np.random.seed(87654589) nobs, nvars = example_size x1 = np.random.normal(size=(nobs, nvars)) y1 = 10 + np.dot(x1,...
nt res1.params #print np.polyfit(x1[:,0], y1, 1) #assert_almost_equal(res1.params, np.polyfit(x1[:,0], y1, 1), 14) #print res1.summary(xname=['x1','const1']) #regression 2 x2 = np.random.normal(size=(nobs,nvars)) if example == 'null': y2 = 10 + np.dot(x2,[15.]*nvars) + 2*np.random.normal(size=nobs) # if H0 is tru...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ default_mail_footer = """<div style="padding: 7px; text-align: right; color: #888"><small>Sent via <a style="color...
b.get_default('desktop:home_page')
== 'desktop': print print "ERPNext can only be installed on a fresh site where the setup wizard is not completed" print "You can reinstall this site (after saving your data) using: bench --site [sitename] reinstall" print return False def set_single_defaults(): for dt in frappe.db.sql_list("""select name f...
s either # callback requests or callback notifications def cb_request(arg_name, response_func, convert_args = False): def cb_request_dec(func): if not hasattr(func, '_callbacks_'): func._callbacks_ = {} if response_func: func._callbacks_[arg_name] = ResponseCallback(response_...
('DISPATCHER', 'wake_requester') : ('REQUESTSERIALIZER', 'control'), } ) self.connections.append(connection) return connection class JsonSplitter(Axon.Component.component): Inboxes = { 'inbox': 'accepts arbitrary (sequential) pieces of json st...
a single complete json string', 'signal': 'outgoing shutdown requests' } def __init__(self, **kwargs): super(JsonSplitter, self).__init__(**kwargs) self.partial_data = '' if self.debug >= 3: print 'Created %s' % repr(self) def main(self): while not self.shutdown(...
''' 笔记 for i in range(10): #3次机会问一次 ''' age=22 c=0 while True: if c<3: cai=input("请输入要猜的年龄:") if cai.isdigit(): #判断是否为整数 print("格式正确") cai1=int(cai) #判断为整数把输入的变量变成int型 if cai1==age and c<3: print("猜对了") break eli...
续,继续请按:yes,不想继续请按no:") if p=="yes": c=0 cai=input("请输入要猜的年龄:") if cai.isdigit(): #判断是否为整数 print("格式正确2") cai1=int(cai) #判断为整数把输入的变量变成int型 if cai1==age and c<3: print("猜对了")
break elif cai1>age and c<3: print("猜大了") c+=1 elif cai1<age and c<3: print("猜小了") c+=1 else: #判断是否为整数 print("输入格式不正确") elif p=="no": print("你选择...
import numpy as np from ctypes import ( CDLL, POINTER, ARRAY, c_void_p, c_int, byref, c_double, c_char, c_char_p, create_string_buffer, ) from numpy.ctypeslib import ndpointer import sys, os prefix = {"win32": "lib"}.get(sys.platform, "lib") extension = {"darwin": ".dylib", "wi...
_lib, prefix + "core" + extension)) def set_assembleElementalMatrix2D_c_args(N): """ Assign function and set the input arguement types for a 2D elemental matrix (in
t, int, int, c_double(N), c_double(N,N)) """ f = libcore.assembleElementalMatrix2D_c f.argtypes = [ c_int, c_int, c_int, ndpointer(shape=(N, 2), dtype="double", flags="F"), ndpointer(shape=(N, N), dtype="double", flags="F"), ] f.restype = None return f ...
# Copyright (c
) 2021, Frappe Technologies Pvt. Ltd
. and Contributors # See license.txt # import frappe import unittest class TestCampaign(unittest.TestCase): pass
"""Make sure that existing Koogeek LS1 support isn't broken.""" from datetime import timedelta from unittest import mock from aiohomekit.exceptions import AccessoryDisconnectedError, EncryptionError from aiohomekit.testing import FakePairing import pytest from homeassistant.components.light import SUPPORT_BRIGHTNESS...
helper.poll_and_get_state() assert state.state == "off" chars = get_char.call_args[0][0] assert set(c
hars) == {(1, 8), (1, 9), (1, 10), (1, 11)} # Test that entity changes state when network error goes away next_update += timedelta(seconds=60) async_fire_time_changed(hass, next_update) await hass.async_block_till_done() state = await helper.poll_and_get_state() assert state.state == "on"
# Iterate over the data subsets for (row_i, col_j, hue_k), data_ijk in self.facet_data(): # If this subset is null, move on if not data_ijk.values.size: continue # Get the current axis modify_state = not str(func.__module__).startswith(...
[hue_k] # Stick the facet dataframe into the kwargs if self._dropna: data_ijk = data_ijk.dropna() kwargs["data"] = data_ijk # Draw the plot self._facet_plot(func, ax, args, kwargs) # For axis labels, prefer to use positional args for...
# but also extract the x/y kwargs and use if no corresponding arg axis_labels = [kwargs.get("x", None), kwargs.get("y", None)] for i, val in enumerate(args[:2]): axis_labels[i] = val self._finalize_grid(axis_labels) return self def _facet_color(self, hue_index, kw...
# -*- coding: utf-8 -*- # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
.client.dc = self.m.CreateMockAnything() self.client.dc.stop(self.client.container) self.client.dc.remove_container(self.client.container) self.m.ReplayAll() self.client.remove_container() self.m.VerifyAll() def test_run_deploy(self): self.client.execut
e_command = mock.MagicMock() self.client.execute_command.return_value = "Alls good" self.client.run_deploy("mycookbook") obs = self.client.run_test("fakecookbook") expected = "{'response': u'Alls good', 'success': True}" self.assertEqual(expected, str(obs)) def test_run_ins...
import itertools import random from hb_res.explanation_source import sources_registry, ExplanationSource __author__ = 'moskupols' ALL_SOURCES = sources_registry.sources_registered() ALL_SOURCES_NAMES_SET = frozenset(sources_registry.names_registered()) all_words_list = [] words_list_by_source_name = dict() for s i...
def explain_list(word, sources_names=None): """ Returns list of tuples (Explanations, asset_name) """ if word not in all_w
ords_set: return [] sources_filtered = _pick_sources_by_names(sources_names) res = list() for s in sources_filtered: res.extend(zip(s.explain(word), itertools.repeat(s.name))) random.shuffle(res) return res def explain(word, sources_names=None): """ Returns a tuple (Explana...
class DestinationNotFoundException(Exception): pass class InvalidDa
teFormat(Exce
ption): pass
ring': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}), 'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}...
Field', [], {'max_length': '500', 'blank': 'True'}), 'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'site': ('django.db.mo...
ue', 'blank': 'True'}), 'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}), 'updated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'zip_import': ('django....
find_byte(self, ifile, chunk, amount): """ Find if data chunk contains 'amount' number of bytes. Return value: (stat, pos, remaining-amount). If stat is True, pos is the result, otherwise pos is not used, remaining-amount is for the next run. """ length = len(chunk) ...
offset) except OSError: assert False, "unkown file seeking failure" chunk = ifile.rea
d(size) if self.mode == 'lines': return self.find_line(ifile, chunk, amount) else: return self.find_byte(ifile, chunk, amount) def run(self): """Find the offset of the last 'amount' lines""" ifile = self.ifile amount = self.amount orig_pos = s...
ments_txt in files_map.items(): path = Path(requirements_txt) if not path.exists() and group.lower() == "all" and freeze: cmd = envoy.run("pip freeze") self[group].loads(cmd.std_out) elif path.exists(): self[group].load(path) def l...
): click.secho("error: versions do not match ({} =/= {})".format( version, expected_version)) raise InvalidPackageError if "dependencies" in bower_json: for package, version in bower_json["dependencies"].items(): url = Bower.get_pac...
re_patterns = [GitIgnorePattern(ig) for ig in bower_json["ignore"]] path_spec = PathSpec(ignore_patterns) namelist = [path for path in zip_file.namelist() if PurePath(path).parts[0] == root] ignored = list(path_spec.match_files(namelist)) for path in namelist: ...
# Copyright 2016 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 applicable law or agreed to...
xpress or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Adds guards against function calls with side effects. Only standalone calls are guarded. WARNING: This mechanism...
rst sample one of the node from N nodes, and sample all the edges for that node. h(x) = 1/N 3.stratified-random-pair sampling We divide the edges into linked and non-linked edges, and each time either sample mini-batch from linked-edges or non-linked edges. g(x) = 1/N_0 ...
# we are dea
ling with undirected graph. edge = (min(nodeId, i), max(nodeId, i)) if edge in self.__held_out_map or edge in self.__test_map \ or edge in mini_batch_set: continue mini_batch_set.add(edge) return (mini_batch_set, self...
# -*- coding: utf-8 -*- from django.db import models from apps.postitulos.models.EstadoPostitulo import EstadoPostitulo from apps.postitulos.models.TipoPostitulo import TipoPostitulo from apps.postitulos.models.PostituloTipoNormativa import PostituloTipoNormativa from apps.postitulos.models.CarreraPostitulo import Carr...
itulo, self).__init__(*arg
s, **kwargs) self.estados = self.getEstados() def registrar_estado(self): from apps.postitulos.models.PostituloEstado import PostituloEstado registro = PostituloEstado(estado = self.estado) registro.fecha = datetime.date.today() registro.postitulo_id = self.id regist...
caller_object_type = type(caller_frame.f_locals["self"]) except KeyError: # we are in a regular function qualifier = caller_frame.f_globals["__name__"].split(".", 1)[-1] else: # we are in a method qualifier = caller_object_type.__name__ func_qualname = qualifier + "....
astTime) * 1000) self._lastTime = newTime def mark(self, msg=None): self(msg) def _newMsg(self, msg, *args): msg = " " * (self._depth - 1) + msg if self._delayed: self._msgs.append((msg, args)) else: self.flush() print(msg % ...
def finish(self, msg=None): """Add a final message; flush the message list if no parent profiler. """ if self._finished or self.disable: return self._finished = True if msg is not None: self(msg) self._newMsg("< Exiting %s, total tim...
import datetime import json from classrank.database.wrapper import Query """add_to_database.py: adds courses from Grouch to the ClassRank DB.""" def add_to_database(grouch_output, db): """ Add courses from Grouch's output to a db. Keyword arguments: grouch_output -- the output of Grouch (the scrap...
sections'] all_courses.append((c
ourse, sections)) return all_courses def _school_in_database(school_dict, db, q): """Check if a school is in the database. Keyword arguments: school_dict -- a dictionary specifying the school to check db -- the db to search in q -- the Query object used to query the database Returns Tru...
rom kubernetes import client, config, watch from airflow.exceptions import AirflowException from airflow.hooks.base import BaseHook def _load_body_to_dict(body): try: body_dict = yaml.safe_load(body) except yaml.YAMLError as e: raise AirflowException("Exception when loading resource definitio...
ient() @cached_property def api_client(self) -> Any: """Cached Kubernetes API client""" return self.get_conn() def create_custom_object( self, group: str, version: str, plural: str, body: Union[str, dict], namespace: Optional[str] = None ): """ Creates custom re...
:type version: str :param plural: api plural :type plural: str :param body: crd object definition :type body: Union[str, dict] :param namespace: kubernetes namespace :type namespace: str """ api = client.CustomObjectsApi(self.api_client) if nam...
""" Handling signals of the `core` app """ from django.dispatch import receiver from core import signals from reader import actions @r
eceiver(signals.app_link_ready) def app_link_ready(sender, **kwargs): actions.create_app_
link()
from setuptools import setup setup( name="agentarchives", description="Clients to retrieve, add, and modify records from archival management systems", url="https://github.com/artefactual-labs/agentarchives", author="Artefactual Systems", author_email="info@artefactual.com", license="AGPL 3", ...
=3.5.*", classifiers=[ "Development Status :: 4 - Beta", "License :: OSI Approved :: GNU Affero General Public License v3", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :
: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", ], )
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 applicable law or agreed to in writing,...
ed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future...
from ..proto.tensor_shape_pb2 import TensorShapeProto import os import time import numpy as np # import tensorflow as tf # from tensorboard.plugins.beholder import im_util # from . import im_util from .file_system_tools import read_pickle,\ write_pickle, write_file from .shared_config import PLUGIN_NAME, TAG_NA...
values=values, func='average' ) # Generate the expected values expected_values = range(0, window_size/2, step) for i in range(0, window_size/2, step): expected_values.append(1) self.assertEqual(expected_values, values) def test_merge_with_cache_wit...
1)) # merge the db results with the cached results with self.assertRaisesRegexp(Exception, "Invalid consolidation function: 'bad_function'"): values = merge_with_cache( cached_datapoints=cache_results, start=start, step=step, ...
nc='bad_function' ) # In merge_with_cache, if the `values[i] = value` fails, then # the try block catches the exception and passes. This tests # that case. def test_merge_with_cache_beyond_max_range(self): # Data values from the Reader: start = 1465844460 # (Mon Jun 13 1...
# Copyright (c) 2012-2013 Rackspace Hosting # 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 # # Unles...
ce_type. """ request_spec = weight_properties['request_spec'] instance_type = request_spec['instance_type'] memory_needed = instance_type['memory_mb'] ram_free = cell.capacities.get('ram_free',
{}) units_by_mb = ram_free.get('units_by_mb', {}) return units_by_mb.get(str(memory_needed), 0)
from django.conf import settings from .func import (check_if_trusted, get_from_X_FORWARDED_FOR as _get_from_xff, get_from_X_REAL_IP) trusted_list = (settings.REAL_IP_TRUSTED_LIST if hasattr(settings, 'REAL_IP_TRUSTED_LIST') else []) def get_from_X_FO...
IP': get_from_X_REAL_IP, 'HTTP_X_FORWARDED_FOR': get_from_X_FORWARDED_FOR} real_ip_headers = (settings.REAL_IP_HEADERS if hasattr(settings, 'REAL_IP_HEADERS') else ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR']) class DjangoRealIPMiddleware(object): def process_reque...
n be used return for header_name in real_ip_headers: try: # Get the parsing function func = func_map[header_name] # Get the header value header = request.META[header_name] except KeyError: contin...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # All Rights Reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Pu...
################################################ { 'name': 'Project and Analytic Account integration impprovements', 'version': '8.0.1.0.0', 'category': 'Projects & Services', 'sequence': 14, 'summary': '', 'description': """ Project and A
nalytic Account integration impprovements. ======================================================= Adds domains restriction to project task so that only projets that use task and are not in cancelled, done or tempalte state, can be choosen. Adds domains restriction to timesheet records so that only """, 'auth...
# Script to request hosts with DOWN status and total hosts by accessing MK Livestatus # Required field to be passed to this script from Splunk: n/a import socket,string,sys,re,splunk.Intersplunk,mklivestatus results = [] try: results,dummyresults,settings = splunk.Intersplunk.getOrganizedResults() for r in ...
data2 = (re.findall(r'(No UNIX socket)', data)) if data2: #Error: MK Livestatus module not loaded? s.close() else: livehosts2 = data.strip() livehosts = livehosts2.split(";") s.close() livehostsdownind = int(livehosts
[0]) livehoststotalind = int(livehosts[1]) livehostsdown = livehostsdown + livehostsdownind livehoststotal = livehoststotal + livehoststotalind r["livehostsdownstatus"] = livehostsdown r["livehoststotalstatus"] = livehoststotal except: r["livehostsdo...
import pyspeckit import os from pyspeckit.spectrum.models import nh2d import numpy as np import astropy.units as u if not os.path.exists('p-nh2d_spec.fits'): import astropy.utils.data as aud from astropy.io import fits f = aud.download_file('https://github.com/pyspeckit/pyspeckit-example-files/raw/master/...
setup spectral axis spec.xarr.refX = 110.153594*u.GHz spec.xarr.velocity_convention = 'radio' spec.xarr.convert_to_unit('km/s') # define useful shortcuts for True and False F=False T=True # Setup of matplotlib import matplotlib.pyplot as plt plt.ion() # Add NH2D fitter spec.Registry.add_fitter('nh2d_vtau', pyspeckit.m...
ecfit(fittype='nh2d_vtau', guesses=[5.52, 2.15, 0.166, 0.09067], verbose_level=4, signal_cut=1.5, limitedmax=[F,T,T,T], limitedmin=[T,T,T,T], minpars=[0, 0, -1, 0.05], maxpars=[30.,50.,1,0.5], fixed=[F,F,F,F]) # plot best fit spec.plotter(errstyle='fill') spec.specfit.plot_fit() #save figure plt.savefig('examp...
#!/usr/bin/env python import argparse import os import sqlite3 from Bio import SeqIO, SeqRecord, Seq from Bio.Align.Applications import ClustalwCommandline from Bio.Blast import NCBIXML from Bio.Blast.Applications import NcbiblastnCommandline as bn from Bio import AlignIO AT_DB_FILE = 'AT.db' BLAST_EXE = '~/opt/ncbi...
infer intron position based on ' \ 'Ara
bidopsis Thaliana genome' parser = argparse.ArgumentParser(description=description) ifh = 'Fasta formated file with sequence to search for introns' parser.add_argument('input_file', help=ifh) args = parser.parse_args() seqhandle = open(args.input_file) records = SeqIO.parse(seqhandle, 'fasta') for record in records: ...
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
interA specifie
d time period of the year, e.g., Spring, Summer, Fall, Winter """ def __init__(self, name="winter", startDate='', endDate='', SeasonDayTypeSchedules=None, *args, **kw_args): """Initialises a new 'Season' instance. @param name: Name of the Season Values are: "winter", "summer", "fall", "spring"...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import argparse import shutil import urllib2 from contextlib import closing from os.path import basename import gzip import tarfile # argparse for information parser = argparse.ArgumentParser() parser.add_argument("-d", "--directory", help="input dire...
) args = parser.parse_args() # sanity check if not len(
sys.argv) > 1: print "This script extracts all .gz files (not jet .tar) in a given directory, including sub directories." print "Which directory (including sub directories) would you like to extract?" parser.print_help() sys.exit(0) input = args.directory # in case of a extraction error, caused by a d...
from multiprocessing import Process,Queue import os class TestMP: def __init__(self,n): self.n = n @staticmethod def worker(q): """worker function""" # print('worker',*args) # print("ppid= {} pid= {}".format(os.getppid(),os.getpid())) q.put([1,'x',(os.getpid(),[])]) ...
elf.worker,args=(q,)) jobs.append((p,q)) p.start
() for i in range(self.n): j=jobs.pop(0) j[0].join() msg = j[1].get() print("job no {} ended, msg: {}".format(i,msg)) m=TestMP(10) m.main()
arams): conn_string = convert_unicode(self._connect_string()) return Database.connect(conn_string, **conn_params) def init_connection_state(self): cursor = self.create_cursor() # Set the territory first. The territory overrides NLS_DATE_FORMAT # and NLS_TIMESTAMP_FORMAT to t...
return int(self.oracle_full_version.split('.')[0]) except ValueError: return None class OracleParam(ob
ject): """ Wrapper object for formatting parameters for Oracle. If the string representation of the value is large enough (greater than 4000 characters) the input size needs to be set as CLOB. Alternatively, if the parameter has an `input_size` attribute, then the value of the `input_size` attribute...
"""Services for ScreenLogic integration.""" import logging from screenlogicpy import ScreenLogicError import voluptuous as vol from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError import homeassistant.helpers.config_validation as cv from homeassi...
f"Failed to call service '{SERVICE_SET_COLOR_MODE}'"
) # Debounced refresh to catch any secondary # changes in the device await coordinator.async_request_refresh() except ScreenLogicError as error: raise HomeAssistantError(error) from error hass.services.async_register( ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, _ from odoo.addons.http_routing.models.ir_http import url_for class Website(models.Model): _inherit = "website" def get_
suggested_controllers(self): suggested_controllers = super(Website, self).get_suggested_controllers() suggested_controllers.append((_('Events'), url_for('/event'), 'website_event')) return suggested_contr
ollers
from unittest import TestCase from netcontrol.util import single
ton @singleton class SingletonClass(object): pass @singleton class SingletonClassWithAttributes(object): @classmethod def setup_attributes(cls): cls.value = 1 class SingletonTest(TestCase): def test_that_only_instance_is_created(self): obj_one = SingletonClass() obj_two = S...
d_using_setup_method(self): obj = SingletonClassWithAttributes() self.assertEqual(1, obj.value)
import re from datetime import date from calendar import monthrange, IllegalMonthError from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ # from - https://github.com/bryanchow/django-creditcard-fields CREDIT_CARD_RE = r'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][...
ue and self.required: raise forms.util.ValidationError(self.error_messages['required']) if value and not re.match(VERIFICATION_VALUE_RE, value): raise f
orms.util.ValidationError(self.error_messages['invalid']) return value
ICULAR 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. # from .collections import Processe...
build_cache()`` method on the object. """ def __eq__(self, process): """For our purposes, two processes are equal when they have same name""" return self.pid == process.pid def __ne__(self, process): return not self.__eq__(process) def __hash__(self): return hash(self.pid) @staticmethod def safe_isfil...
rever if the shared FS is offline. Instead, use a subprocess that we can time out if we can't reach some file. """ process = Popen(['test', '-f', file_path], stdout=PIPE, stderr=PIPE) timer = Timer(timeout, process.kill) try: timer.start() process.communicate() return process.returncode == 0 finall...
#!/usr/bin/env python # # vim:syntax=python:sw=4:ts=4:expandtab """ test hasAttributes() --------------------- >>> from guppy import hasAttributes >>> class Foo(object): ... def __init__(self): ... self.a = 23 ... self.b = 42 >>> hasAttributes('a')(Foo()) True...
ributes('b')(Foo()) True >>> hasAttributes('a', '
b')(Foo()) True >>> hasAttributes('c')(Foo()) False """ """ test hasMethods() ----------------- >>> from guppy import hasMethods >>> class Bar(object): ... def a(self): return 23 ... def b(self): return 42 >>> hasMethods('a')(Bar()) True >>> hasMethods('b')(...
from tempfile import gettempdir from os.path import join, dirname import example_project ADMINS = ( ) MANAGERS = ADMINS DEBUG = True TEMPLATE_DEBUG = DEBUG DISABLE_CACHE_TEMPLATE = DEBUG DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = join(gettempdir(), 'django_ratings_example_project.db') TEST_DATABASE_NAME =join(ge...
CODE = 'en-us' SITE_ID = 1 US
E_I18N = True # Make this unique, and don't share it with anybody. SECRET_KEY = '88b-01f^x4lh$-s5-hdccnicekg07)niir2g6)93!0#k(=mfv$' EMAIL_SUBJECT_PREFIX = 'Example project admin: ' # templates for this app DEBUG = True TEMPLATE_DEBUG = DEBUG DISABLE_CACHE_TEMPLATE = DEBUG # TODO: Fix logging # init logger #LOGGING...
openAtoms = [x for x in face.atoms if x not in face.closed] plt.plot(face.pos[0],face.pos[1], 'rx', markersize=15., zorder=-2) plt.scatter(posList[openAtoms][:,0], posList[openAtoms][:,1], s=75., c='red') plt.scatter(posList[face.closed][:,0], posList[face.closed][:,1], s...
c, s = [],[] for i, z, name in zip(np.arange(6), [1,6,9,17,35], ['H', 'C', 'F', 'Cl', 'Br']): x.append(0.) y.append(-i*.2) c.append(atomColors[z]) s.append(1.5*
size_scale*radList[z]) ax.text(.005, -i*.2, name, fontsize=fs) ax.scatter(x,y , c=c, s=s, edgecolors='k') ax.axis('off') def bonds3d(molecule, sites=False, indices=False, save=False, linewidth=2.): """Draw the molecule's bonds Keywords: sites (bool): Set True t...
from time import sleep import math __author__ = 'sergio' ## @package clitellum.endpoints.channels.reconnectiontimers # Este paquete contiene las clases para los temporizadores de reconexion # ## Metodo factoria que crea una instancia de un temporizador # instantaneo def CreateInstantTimer(): return InstantRecon...
ReconnectionTimer: ## Crea una instancia del temporizador de reconexion def __init__(self): pass ## Se espera una vuelta del ciclo antes de continuar def wait(self): pass ## Reinicia el temporizador def reset(self): pass ## Clase que proporciona un temporizador de re...
or instantaneo def __init__(self): ReconnectionTimer.__init__(self) ## Convierte la instancia a string def __str__(self): return "Instant Reconnection Timer" ## Define un temporizador de reconexion en el que el tiempo de espera entre un ciclo # y el siguiente es logaritmico, . class Logar...
#!/usr/bin/env python """ ================================================= Draw a Quantile-Quantile Plot and Confidence Band ================================================= This is an example of drawing a quantile-quantile plot with a confidence level (CL) band. """ print __doc__ import ROOT from rootpy.interactive...
).GetXmax() gr.Draw('a3') gr.Draw('Xp same') # a straight line y=x to be a reference f_dia = ROOT.TF1("f_dia", "x", h1.GetXaxis().GetXmin(), h1.GetXaxis().GetXmax(
)) f_dia.SetLineColor(9) f_dia.SetLineWidth(2) f_dia.SetLineStyle(2) f_dia.Draw("same") leg = Legend(3, pad=pad, leftmargin=0.45, topmargin=0.45, rightmargin=0.05, textsize=20) leg.AddEntry(gr, "QQ points", "p") leg.AddEntry(gr, "68% CL band", "f") leg.AddEntry(f_dia, "Diagonal line", "l") le...
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-PsExec', 'Author': ['@harmj0y'], 'Description': ('Executes a stager on remote hosts using PsExec type functionality.'), 'Background' : Tru...
: '' }, 'ResultFile' : { 'Description' : 'Name of the file to write the results to on agent machine.', 'Required' : False, 'Value' : '' }, 'UserAgent' : {
'Description' : 'User-agent string to use for the staging request (default, none, or other).', 'Required' : False, 'Value' : 'default' }, 'Proxy' : { 'Description' : 'Proxy to use for request (default, none, or other).', ...
d in validateData.main_validate() validator_logger = logging.getLogger(validateData.__name__) # flush and close all handlers of this logger for logging_handler in validator_logger.handlers: logging_handler.close() # remove the handlers from the logger to reset it vali...
e script is
giving the proper error. ''' # build the argument list out_file_name = 'test_data/study_wr_clin/result_report.html~' print('==test_problem_in_clinical==') args = ['--study_directory', 'test_data/study_wr_clin/', '--portal_info_dir', PORTAL_INFO_DIR, '-v', ...
t=cls.rpc_timeout) @classmethod def tearDownClass(cls): if cls.app_cfg: return send('arbiter', 'kill_actor', cls.app_cfg.name) def setUp(self): self.assertEqual(self.p.url, self.uri) self.assertTrue(str(self.p)) proxy = self.p.bla self.assertEqual(proxy....
# Pulsar server commands def test_ping(self): response = yield from self.p.ping() self.assertEqual(response, 'pong') def test_functions_list(self): result = yield from self.p.functions_list() self.assertTrue(result) d = dict(result) self.assertTrue('ping' in d...
self.assertTrue('calc.divide' in d) def test_time_it(self): '''Ping server 5 times''' bench = yield from self.p.timeit('ping', 5) self.assertTrue(len(bench.result), 5) self.assertTrue(bench.taken) # Test Object method def test_check_request(self): result = yield ...
ef delete(self, key, txn=None) : if isinstance(key, str) : key = bytes(key, charset) return self._db.delete(key, txn=txn) def keys(self) : k = self._db.keys() if len(k) and isinstance(k[0], bytes) : return [i.decode(charset...
y pid: %s' % os.getpid() print '-=' * 38 def get_new_path(name) : get_new_path.mutex.acquire() try : import os path=os.path.join(get_new_path.prefix,
name+"_"+str(os.getpid())+"_"+str(get_new_path.num)) get_new_path.num+=1 finally : get_new_path.mutex.release() return path def get_new_environment_path() : path=get_new_path("environment") import os try: os.makedirs(path,mode=0700) except os.error: ...
# -*- coding: utf-8 -*- from distutils.core import setup import os.path classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Development Status :: 4 - B
eta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ] def read(fname): fname = os.path.join(os.path.dirname(__file__), fna...
ames)) setup( name = 'icall', version = '0.3.4', py_modules = ['icall'], description = 'Parameters call function, :-)', long_description = read_files('README.rst', 'CHANGES.rst'), author = 'huyx', author_email = 'ycyuxin@gmail.com', url = 'https://github.com/huyx/icall', keywords = ...
#! /usr/bin/python import sys import os import json import grpc import time import subprocess from google.oauth2 import service_account import google.oauth2.credentials import google.auth.transport.requests import google.auth.transport.grpc from google.firestore.v1beta1 import firestore_pb2 from google.firestore.v1be...
eta1 import write_pb2_grpc from google.protobuf import empty_pb2 from google.protobuf import timestamp_pb2 def first_messag
e(database, write): messages = [ firestore_pb2.WriteRequest(database = database, writes = []) ] for msg in messages: yield msg def generate_messages(database, writes, stream_id, stream_token): # writes can be an array and append to the messages, so it can write multiple Write ...
from ..subpackage1 import module1g def func1h(): print('1h') module1g.func1
g()
# Copyright (c) 2005, California Institute of Technology # All rights reserved. # Redistribution and use in source
and b
inary forms, with or without # modification, are permitted provided that the following conditions are # met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # ...
#!/usr/bin/env python3 import os import os.path from nipype.interfaces.utility import IdentityInterface, Function from nipype.interfaces.io import SelectFiles, DataSink, DataGrabber from nipype.pipeline.engine im
port Workflow, Node, MapNode from nipype.interfaces.minc import Resample, BigAverage, VolSymm import argparse def create_workflow( xfm_dir, xfm_pattern, atlas_dir, atlas_pattern, source_dir, source_pattern, work_dir, out_dir, name="new_data_to_atlas_space" ): wf = Workflow(nam...
sort_filelist=True ), name='datasource_source' ) datasource_source.inputs.base_directory = os.path.abspath(source_dir) datasource_source.inputs.template = source_pattern datasource_xfm = Node( interface=DataGrabber( sort_filelist=True ), name...
""" Created on 26 Aug 2019 @author: Bruno Beloff (bruno.beloff@southcoastscience.com) """ from collections import OrderedDict from enum import Enum from scs_core.data.json import JSONReport # -------------------------------------------------------------------------------------------------------------------- class...
f.length jdict['client-state'] = self.client_state.name jdict['publish-success'] = self.publish_success return jdict # ---------------------------------------------------------------------------------------------------------------- @property def length(self): return self....
h @property def client_state(self): return self.__client_state @client_state.setter def client_state(self, client_state): self.__client_state = client_state @property def publish_success(self): return self.__publish_success @publish_success.setter def publ...
#!/usr/bin/env python import numpy as np from scipy import special from ..routines import median, mahalanobis, gamln, psi from nose.tools import assert_true from numpy.testing import assert_almost_equal, assert_equal, TestCase class TestAll(TestCase): def test_median(self): x = np.random.rand(100) ...
) mah = 100. f_mah = mahalanobis(x, A) assert_almos
t_equal(mah, f_mah, decimal=1) def test_mahalanobis1(self): x = np.random.rand(100) A = np.random.rand(100, 100) A = np.dot(A.transpose(), A) + np.eye(100) mah = np.dot(x, np.dot(np.linalg.inv(A), x)) f_mah = mahalanobis(x, A) assert_almost_equal(mah, f_mah, decimal...
# -*- coding: utf-8 -*- # Generated by Django 1.9.12 on 2017-05-25 20:11 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('anagrafica', '0046_delega_stato'), ] operations = [ migrations.AlterIndexTogether( ...
), ('persona',
'inizio', 'fine', 'tipo'), ('persona', 'inizio', 'fine', 'tipo', 'stato'), ('persona', 'stato'), ('persona', 'inizio', 'fine'), ('inizio', 'fine', 'tipo'), ('persona', 'inizio', 'fine', 'tipo', 'oggetto_id', 'oggetto_tipo'), ('persona', 'tipo'), ('oggetto_tipo', 'oggetto_id'), ('inizio', 'fine', 'stato'), ('inizio', 'f...
# coding: utf-8 """ 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 in the hope that it will be use...
contact = Contact.objects.create( speaker=self.speaker, kind='E', value='henrique@bastos.net' ) self.assertEqual(1, contact.pk) def test_phone(self): """ Speaker should have email contact. """ contact = Contact.objects.create( ...
): """ Speaker should have email contact. """ contact = Contact.objects.create( speaker=self.speaker, kind='F', value='21-123456789' ) self.assertEqual(1, contact.pk) def test_kind(self): """ Contact kind must be li...