prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Software License Agreement (BSD License) # # Copyright (c) 2010-2011, Antons Rebguns. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Red...
D' __maintainer__ = 'Antons Rebguns' __email__ = 'anton@email.arizona.edu' import sys from optparse import OptionParser import roslib roslib.load_manifest('dyna
mixel_driver') from dynamixel_driver import dynamixel_io if __name__ == '__main__': usage_msg = 'Usage: %prog [options] MOTOR_IDs' desc_msg = 'Sets various configuration options of specified Dynamixel servo motor.' epi_msg = 'Example: %s --port=/dev/ttyUSB1 --baud=57600 --baud-rate=1 --return-delay=1 5 9 ...
from direct.distributed import DistributedObject class DistributedTestObject(DistributedObject.DistributedObject): def setRequiredField(self, r):
self.requiredField = r def setB(self, B): self.B = B def setBA(self, BA): self.BA = BA def setBO(self, BO): self.BO = BO def setBR(self, BR): self.BR = BR def setBRA(self, BRA): self.BRA = BRA def setBRO(self, BRO): self.BRO = BRO ...
sattr(self, field): return True return False
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "csrf_example.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that...
mport django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise exe...
from django.http import Http
ResponseRedirect from django.utils.encoding import smart_str def serve_file(request, file, **kwargs): """Serves files by redirecting to file.url (e.g., useful for Amazon S3)""" return HttpResponseRedirect(smart_str(file.url)) def public_download_url(file, **kwargs): """Directs downlo
ads to file.url (useful for normal file system storage)""" return file.url
ing : parameter from client side @return : succ xxxxx ex. jsonString => {vid:100, pif:eth0} ex. return => """ #Pre-condition #check Physical Interface Name if vlan.pif not in self.pifs.keys(): msg = "Physical Interface(%s) does not ex...
@staticmethod def getVlans():
try: network = OvmNetwork() rs = toGson(network._getVlans()) logger.debug(OvmNetwork.getVlans, rs) return rs except Exception, e: errmsg = fmt_err_msg(e) logger.error(OvmNetwork.getVlans, errmsg) raise XmlRpcFault(toErrCode(O...
#!/bin/python3 impo
rt math import os import random import re import sys # Complete the migratoryBirds function below. # {1:2, 2:4, 3:3, 4:4} def migratoryBirds(arr): frequentBird, frequency = 1, 0 birdsDict = {} for i in arr: if i not in birdsDict.keys(): birdsDict[i
] = 1 else: birdsDict[i] = birdsDict[i] + 1 for bird in birdsDict.keys(): if birdsDict[bird] > frequency: frequency = birdsDict[bird] frequentBird = bird if birdsDict[bird] == frequency: if bird < frequentBird: fre...
# Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals, absolute_import, print_function import sys import click import cProfile import pstats import frappe import frappe.utils from functools import wraps from six import StringIO c...
bj=context).forward(cmd) def get_commands()
: # prevent circular imports from .docs import commands as doc_commands from .scheduler import commands as scheduler_commands from .site import commands as site_commands from .translate import commands as translate_commands from .utils import commands as utils_commands return list(set(doc_commands + scheduler_c...
import csv import numpy import pandas import pymongo import requests from datetime import datetime from io import StringIO mongo_client = pymongo.MongoClient("localhost", 27017) financial_db = mongo_client.financial_data financial_collection = financial_db.data class Pull: def __call__(self, source, tickers, ...
e_added": datetime.utcnow(), "data": df.to_dict(orient="records"), "close_prices": list(df.Close.values), "returns": list(df.Return.values), "daily_periodic_return": list(df.DailyPeriodicReturn.values), "continuous_daily_periodic_return": l...
date": end_date, "url": data_string } return results def database_call(self, tickers, start_date, end_date): """ database_call makes a call to mongodb for the latest data Args: None """ results = {} for ticker in ticker...
# # MLDB-2126-export-structured.py # Mathieu Marquis Bolduc, 2017-01-25 # This file is part of MLDB. Copyright 2017 mldb.ai inc. All rights reserved. # import tempfile import codecs import os from mldb import mldb, MldbUnitTest, ResponseException tmp_dir = os.getenv('TMP') class MLDB2126exportstructuredTest(MldbUni...
'1,2'
] self.assert_file_content(tmp_file.name, lines_expect) if __name__ == '__main__': mldb.run_tests()
# -*- coding: utf-8 -*- # Generated by Django 1.11.28 on 2020-03-17 20:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('astrobin_apps_platesolving', '0011_update_platesolvingadvanced_settings_sample_
raw_frame_file_verbose_name'), ] operations = [ migrations.CreateModel( name='PlateSolvingAdvancedTask', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('serial_number', models.CharField...
('task_params', models.TextField()), ], ), ]
# -*- co
ding: utf-8 -*- from __future__ import absolute_import, division, print_function from .modes import Modes from . import models from . import bridges from . import layers from . import processing from .libs import * # noqa from . import activations from . import initializations from . import losses from . import metr...
. import variables from . import datasets from . import estimators from . import experiments
else: raise UpdateError("Conflicting metadata values") for conditional_node, value in conditionals: if value != unconditional_value: self.node.set(self.property_name, value, condition=conditional_node.children[0]) class MaxAssertsUpdate(PropertyUpdate):...
alue(current_default, new_values) return True, new_value if new_value else None def group_conditionals(values, property_order=None, boolean_properties=None): """Given a list of Value objects, return a list of (conditional_node, status) pairs
representing the conditional expressions that are required to match each status :param values: List of Values :param property_order: List of properties to use in expectation metadata from most to least significant. :param boolean_properties: Set of properties in property_orde...
import os class Config(object): DEBUG = False TESTING = False SECRET_KEY = 'A0Zr18h/3yX R~XHH!jmN]LWX/,?RT' DATA
BASE = { 'engine': 'playhouse.pool.PooledPostgresqlExtDatabase', 'name': 'middleware', 'user': 'comunitea', 'port': '5434', 'host': 'localhost', 'max_connections': None, 'autocommit': True, 'a...
om_sync&task=sync.syncOdoo" NOTIFY_USER = os.environ.get('NOTIFY_USER') NOTIFY_PASSWORD = os.environ.get('NOTIFY_PASSWORD')
der 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. import io import os.path import boto3.session import botocore.exceptions import freezegu...
keys)) call_keys = [ "downloads:daily:12-01-{:02d}:foo".format(i) for i in reversed(range(1, 15)) ] + [ "downloads:daily:11-12-{:02d}:foo".format(i + 15) for i in reversed(range(17)) ] assert svc.get_monthly_stats("foo") == result ...
torage: def test_verify_service(self): assert verifyClass(IFileStorage, LocalFileStorage) def test_basic_init(self): storage = LocalFileStorage("/foo/bar/") assert storage.base == "/foo/bar/" def test_create_service(self): request = pretend.stub( registry=prete...
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 Savoir-faire Linux (<http://www.savoirfairelinux.com>). # # This program is free software: you can redistribute it and/or modify # it und...
that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # #
You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Hazard Risk", "version": "8.0.1.1.0", "author": "Savoir-faire Linu...
# -*- coding: utf-8 -*- """ celery.events.dumper ~~~~~~~~~~~~~~~~~~~~ THis is a simple program that dumps events to the console as they happen. Think of it like a `tcpdump` for Celery events. :copyright: (c) 2009 - 2011 by Ask Solem. :license: BSD, see LICENSE for more details. """ from __fu...
r()] except KeyError: return type.lower().replace("-", " ") class Dumper(object): def on_event(self, event): timestamp = datetime.fromtimestamp(eve
nt.pop("timestamp")) type = event.pop("type").lower() hostname = event.pop("hostname") if type.startswith("task-"): uuid = event.pop("uuid") if type in ("task-received", "task-sent"): task = TASK_NAMES[uuid] = "%s(%s) args=%s kwargs=%s" % ( ...
"""Config flow to configure the OVO Energy integration.""" import aiohttp from ovoenergy.ovoenergy import OVOEnergy import voluptuous as vol from homeassistant import config_entries from homeassistant.config_entries import ConfigFlow from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from .const import DOMA...
ticated = await client.authenticate( user_input[CONF_USERNAME], user_input[CONF_PASSWORD] ) except aiohttp.ClientError: errors["base"] = "cannot_connect" else: if authenticated:
await self.async_set_unique_id(user_input[CONF_USERNAME]) self._abort_if_unique_id_configured() return self.async_create_entry( title=client.username, data={ CONF_USERNAME: user_input[CONF_USERN...
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import _mssql import pymssql except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.da...
ide: http://pymssql.sourceforge.net/examples_pymssql.php API: http://pymssql.sourceforge.net/ref_pymssql.php Debian package: python-pymssql License: LGPL Possible connectors: http://wiki.python.org/moin/SQL%20Server Important note: pymssql library on your system MUST be version 1.0.2 to work, ...
self.initConnection() try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) except pymssql.OperationalError, msg: raise SqlmapConnectionExce...
# -*- coding: utf-8 -*- """ *************************************************************************** diff.py --------------------- Date : November 2013 Copyright : (C) 2013-2016 Boundless, http://boundlessgeo.com ************************************************************...
version. * * * **********************
***************************************************** """ __author__ = 'Victor Olaya' __date__ = 'November 2013' __copyright__ = '(C) 2013-2016 Boundless, http://boundlessgeo.com' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from feature import Feature from geogig...
The API version you wish to use for your application. Subsonic will throw an error if you try to use/send an api version higher than what the server supports. See the Subsonic API docs to find the Subso...
path.strip('/') serverPath = property(lambda s: s._serverPath, setServerPath) def setInsecure(self, insecure): self._insecure = insecure insecure =
property(lambda s: s._insecure, setInsecure) # API methods def ping(self): """ since: 1.0.0 Returns a boolean True if the server is alive, False otherwise """ methodName = 'ping' viewName = '%s.view' % methodName req = self._getRequest(viewName) ...
# -*- coding: utf-8 -*- from
__future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('universidades', '0001_initial'), ] operations = [ migrations.AlterField(
model_name='universidademodel', name='nome', field=models.CharField(max_length=256), preserve_default=True, ), migrations.AlterField( model_name='universidademodel', name='sigla', field=models.CharField(max_length=32), ...
from .common import * INTERNAL_IPS = ['127.0.0.1', ] CORS_ORIGIN_WHITELIST = ( 'localhost:8000', ) CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } Q_CLUSTER = { 'name': 'DjangORM', 'workers': 2, 'timeout': 90, 'retry': 120, 'queue_limit': 5...
LOGGING = { 'version': 1, 'disable_existing_loggers':
False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'reminders': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, 'messages': { 'handlers': ['console'], ...
CO
NFIG_SCREEN = 'config' RUNNING_SCREEN = 'running' SUCCESS_SCREEN = 'success' ERROR_SCREEN
= 'error'
from itertools import combinations START_P_HP = 100 START_P_DMG = 0 START_P_A = 0 START_B_HP = 100 START_B_DMG = 8 START_B_A = 2 WEAPONS = [ [8,4,0], [10,5,0], [25,6,0], [40,7,0], [74,8,0] ] ARMOR = [ [13,0,1], [31,0,2], [53,0,3], [75,0,4], [102,0,5] ] #Include 'no armor' option ARMOR.append([0,0,0]) RINGS = [ [25,1...
#We are seeking to lose the fight, so not win #We are also looking for highest cost if not win and (cost is
None or p_cost > cost): cost = p_cost print cost def is_win(b_hp, b_dmg, b_a, p_hp, p_dmg, p_a): b_dmg = max(b_dmg - p_a, 1) p_dmg = max(p_dmg - b_a, 1) #<= because we start first return (b_hp / p_dmg) <= (p_hp / b_dmg) def calc_bonuses(w,a,r): ret = [0, 0, 0] for i in [w,a,r]: for j in i: ret[0] += j...
import datetime import sys import pdb from directory import directory if False: pdb.set_trace() # avoid warning message from pyflakes class Logger(object): # from stack overflow: how do i duplicat sys stdout to a log file in python def __init__(self, logfile_path=None, logfile_mode='w', base_name=No...
(base_name) self.log = open(clean_path, logfile_mode) def wri
te(self, message): self.terminal.write(message) self.log.write(message) def flush(): pass if False: # usage example sys.stdout = Logger('path/to/log/file') # now print statements write on both stdout and the log file
""" Higher order classes and functions for Libvirt Sandbox (lxc) container testing :copyright: 2013 Red Hat Inc. """ import datetime import time import logging import lvsb_base # This utility function lets test-modules quickly create a list of all # sandbox aggregate types, themselves containing a list of individual...
Wait until numb
er of running sandboxes is zero if bool(self.are_running()): time.sleep(0.1) # Don't busy-wait continue else: # none are running break # Needed for accurate time in logging message below end = datetime.datetime.now() # Nee...
import boto from boto.swf.exceptions import SWFResponseError import sure # noqa from moto import mock_swf_deprecated # RegisterDomain endpoint @mock_swf_deprecated def test_register_domain(): conn = boto.connect_swf("the_key", "the_secret") conn.register_domain("test-domain", "60", description="A test domai...
"][0] domain["name"].should.equal("test-domain") @mock_swf_deprecated def test_deprecate_already_deprecated_domain(): co
nn = boto.connect_swf("the_key", "the_secret") conn.register_domain("test-domain", "60", description="A test domain") conn.deprecate_domain("test-domain") conn.deprecate_domain.when.called_with( "test-domain" ).should.throw(SWFResponseError) @mock_swf_deprecated def test_deprecate_non_existen...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys import traceback from argparse import ArgumentParser class SRDKRunError(Exception): def __init__(self, message): self.msg = message def run_commands(cmds): for cmd in cmds: cmd = u" ".join(cmd) print("Rhedeg %s" ...
%s" % cmd] raise SRDKRunError(u"\n".join(exception_str)) except SRDKRunError, arg: print 'Exception:', arg.msg def train_singleuser(userid, **args): """Hyfforddi model acwstig HTK / Train HTK acoustic model""" srdk_cmds = [] print "SRDK_Train : %s" % userid if userid...
lts/" + userid]) srdk_cmds.append(["mkdir -p results/" + userid]) srdk_cmds.append(["SRDK_2_PronunciationDictionary"]) srdk_cmds.append(["SRDK_4_Transcriptions"]) if userid: srdk_cmds.append(["SRDK_5_CodingAudioData " + userid ]) else: srdk_cmds.append(["SRDK_5_CodingAudioData"]) srdk_cmds.append(["SRDK...
#!/usr/bin/env python # # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it wil
l 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 GNU Radio; see the file COPYING. If not, write...
from django.conf.urls import
patterns, include, url from django.contrib import admin from leagueofladders import settings urlpatterns = patterns('', url(r'^l/', include('leagueofladder
s.apps.myleague.urls', namespace='myleague')), url(r'^admin/', include(admin.site.urls)), url(r'^%s$' % settings.LOGIN_URL[1:], 'django.contrib.auth.views.login'))
from .v2015_06_15.operations import StorageAccountsOperations as OperationClass elif api_version == '2016-01-01': from .v2016_01_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2016-12-01': from .v2016_12_01.operations import StorageAccount...
depends on the API version: * 2015-06-15: :class:`Us
ageOperations<azure.mgmt.storage.v2015_06_15.operations.UsageOperations>` * 2016-01-01: :class:`UsageOperations<azure.mgmt.storage.v2016_01_01.operations.UsageOperations>` * 2016-12-01: :class:`UsageOperations<azure.mgmt.storage.v2016_12_01.operations.UsageOperations>` * 2017-06-01: :cl...
from . uuid64 imp
ort *
#!/usr/bin/env python # take a large pcap and dump the data into a CSV so it can be analysed by something like R. # # This version we want to know what the source IP is, what the protocol is and based on those # peices of info run a function to grab that data and write a line to a CSV file # # Ignore all traffic sourc...
P(tpkt): #print "running par
seTCP" if len(tpkt.layers) > 3: # pass to http module decoded = tcpdecode(tpkt.layers[3],thisproto) rowlist[8]= str(decoded) #rowlist[8]= str(tpkt.layers[3]).replace('\n','') # Complete this section regardless rowlist[3]= 6 rowlist[4]= str(tpkt.ip.src).strip() rowlist...
from chainer import cuda from chainer import function from chainer.utils import type_check def _kern(): return cuda.elementwise( 'T cond, T x, T slope', 'T y', 'y = cond >= 0 ? x : (T)(slope * x)', 'lrelu') class LeakyReLU(function.Function): """Leaky rectifier unit.""" def __init__(se...
< 0] *= self.slope return gx, def backward_gpu(self, x, gy): if self.slope >= 0: y = self.output_data gx = _kern()(y[0], gy[0], self.slope) else: gx = _kern()(x[0], gy[0], self.slope) return gx, def leaky_relu(x, slope=0.2): """Leaky Rectifi...
essed as .. math:: f(x)=\\max(x, ax), where :math:`a` is a configurable slope value. Args: x (:class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): Input variable. A :math:`(s_1, s_2, ..., s_N)`-shaped float array. slope (float): Slope value...
meter def getTypeNameTuple(s
elf, param): type = '' name = '' for elem in param: if elem.tag == 'type': type = noneStr(elem.text) elif elem.tag == 'name': name = noneStr(elem.text) return (type, name) # # Retrieve the value of the len tag def getLen...
and len != 'null-terminated': # For string arrays, 'len' can look like 'count,null-terminated', indicating that we # have a null terminated array of strings. We strip the null-terminated from the # 'len' field and only return the parameter specifying the string count if ...
from
envi.archs.msp430.regs import * checks = [ # SWPB ( 'DEC r15', { 'regs': [(REG_R15, 0xaabb)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "8f10", 'data': "" }, { 'regs': [(REG_R15, 0xbbaa)], 'flags': [(SR_N, 0), (SR_Z, 0), (SR_C, 0), (SR_V, 0)], 'code': "8f10", 'data'...
import socket import nlp class NLPServer(object): def __init__(self, ip, port): self.sock = socket.socket() self.sock.bind((ip, port)) self.processor = nlp.NLPProcessor() print "Established Server" def list
en(self): import thread
self.sock.listen(5) print "Started listening at port." while True: c = self.sock.accept() cli_sock, cli_addr = c try: print 'Got connection from', cli_addr thread.start_new_thread(self.manageRequest, (cli_sock,)) except Exception, Argument: print Argument self.sock.close() quit() ...
from __future__ import division, print_function import numpy as np from lmfit.models import VoigtModel from scipy.signal import argrelmax import matplotlib.pyplot as plt def lamda_from_bragg(th, d, n): return 2 * d * np.sin(th / 2.) / n def find_peaks(chi, sides=6, intensity_threshold=0): # Find all potenti...
pute(self): x = [] y = [] for event in self._events: x.append(event['data'][self.x_name]) y.append(event['data'][self.y_name]) x = np.array(x) y = np.array(y) self.wavelength, self.wavelength_std = get_wavelength_from_std_tth(x, y, self.d_spacings...
""" if __name__ == '__main__': import os calibration_file = os.path.join('../../data/LaB6_d.txt') # step 0 load data d_spacings = np.loadtxt(calibration_file) for data_file in ['../../data/Lab6_67p8.chi', '../../data/Lab6_67p6.chi']: a = np.loadtxt(data_file) wavechange = [] ...
""" This test need a set of pins which can be set as inputs and have no external pull up or pull down connected. """ from machine import Pin import os mch = os.uname().machine if 'LaunchPad' in mch: pin_map = ['GP24', 'GP12', 'GP14', 'GP15', 'GP16', 'GP17', 'GP28', 'GP8', 'GP6', 'GP30', 'GP31', 'GP3', 'GP0', ...
in.PULL_UP, drive=pin.IN) # incorrect drive value except Exception: print('Exception') try: pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value except Exception: print('Exception') try: pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value except...
n = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode except Exception: print('Exception') try: pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode except Exception: print('Exception') try: pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect ...
from __future__ import absolute_import import os from celery import Celery # set the default Django set
tings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'su
garcub.settings') from django.conf import settings # noqa app = Celery('sugarcub') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_t...
ream_name = 'test-stream' >>> delete_stream(client, stream_name) Returns: Tuple (bool, bool, str, dict) """ success = False changed = False err_msg = '' results = dict() stream_found, stream_msg, current_stream = ( find_stream(client, stream_name, check_mode=check_mo...
m_name, action='start_encryption', encryption_type=encryption_typ
e, key_id=key_id, check_mode=check_mode ) ) if success: changed = True if wait: success, err_msg, results = ( wait_for_status( client, stream_name, 'ACTIVE', wait_timeout, check_mode=c...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-27 16:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0017_auto_20170327_1934'), ] operations = [ migrations.AlterField( ...
=models.ImageField(blank=True, upload_to='media/products/%Y/%m/%d/', verbose_name='Изображение товара4'), ), migrations.AlterField( model_name='tovar_img', name='tovar_image5', field=models.ImageField(blank=True, upload_to='media/products/%Y/%m/%d/', v
erbose_name='Изображение товара5'), ), migrations.AlterField( model_name='tovar_img', name='tovar_image6', field=models.ImageField(blank=True, upload_to='media/products/%Y/%m/%d/', verbose_name='Изображение товара6'), ), migrations.AlterField( ...
""" Copyright 2015 Brocade Communications Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed t...
NS OF ANY KIND, either express or implied. See the License for the specif
ic language governing permissions and limitations under the License. """ import logging import time import json import sys from clicrud.device.generic import generic def read(queue, finq, ranonceq, **kwargs): _cli_input = "['command', 'commands', 'listofcommands']" _command_list = [] _kwargs = {} _k...
from __future__ import division, absolute_import, print_function from flask import current_app, Blueprint, jsonify, url_for, request from idb.helpers.cors import crossdomain from .common import json_error, idbmodel, logger this_version = Blueprint(__name__,__name__) def format_list_item(t,uuid,etag,modified,versio...
limit = 100 offset = request.args.get("offset") if offset is not None: offset =
int(offset) else: offset = 0 r = {} l = [ format_list_item( st, v["uuid"], v["etag"], v["modified"], v["version"], v["parent"], ) for v in idbmodel.get_children_list(str(u), "".join(st[:-1]),limit=limit,offset=o...
device_pid, tid) if show_memory: self._chrome_trace.emit_obj_create('Tensor', output_name, start_time, tensors_pid, tid, tensor.object_id) self._emit_tensor_snapshot(tensor, end_time - 1, ten...
device_pids[device_name] is_gputrace = self._is_gputrace_device(device_name) for node_stats in dev_stats.node_stats: tid = node_stats.thread_id start_time = node_stats.all_start_micros end_time = node_stats.all_st
art_micros + node_stats.all_end_rel_micros self._emit_op(node_stats, device_pid, is_gputrace) if is_gputrace or node_stats.node_name == 'RecvTensor': continue _, _, inputs = self._parse_op_label(node_stats.timeline_label) for input_name in inputs: if input_name not ...
import blinker from concurrency.fields import IntegerVersionField from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save from django.dispatch.dispatcher import receiver from game.apps.core.models.planet.models import Planet from game.utils.models i...
abel = 'core' ordering = ('id', ) class Citadel(Building): class Meta: proxy = True def process_turn(self): warehouse = self.owner.buildings.filter(type='Warehouse') warehouse.add_resource("Aluminium", 10) warehouse.add_resource("Steel", 10) warehou...
tainer): class Meta: proxy = True class Terminal(Building): class Meta: proxy = True class Mine(Building): class Meta: proxy = True #TODO use Django ready() @receiver(post_save, sender=User, dispatch_uid="create_default_buildings") def create_default_buildings(...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'slidersd.ui' # # Created: Tue Mar 17 23:31:52 2015 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except Attri...
Label(Form) self.label_3.setObjectName(_fromUtf8("label_3")) self.horizontalLayout.addWidget(self.label_3) self.horizontalSlider = QtGui.QSlider(Form) self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal) self.horizontalSlider.
setObjectName(_fromUtf8("horizontalSlider")) self.horizontalLayout.addWidget(self.horizontalSlider) self.label_4 = QtGui.QLabel(Form) self.label_4.setObjectName(_fromUtf8("label_4")) self.horizontalLayout.addWidget(self.label_4) self.verticalLayout.addLayout(self.horizontalLayout...
""" Platform for a Generic Modbus Thermostat. This uses a setpoint and process value within the controller, so both the current temperature register and the target temperature register need to be configured. For more details about this platform, please refer to the documentation at https://home-assistant.io/component...
import ( CONF_NAME, CONF_SLAVE, ATTR_TEMPERATURE) from homeassistant.components.climate import ( ClimateDevice, PLATFORM_SCHEMA, SUPPORT_TARGET_TEMPERATURE) from homeassistant.components import
modbus import homeassistant.helpers.config_validation as cv DEPENDENCIES = ['modbus'] # Parameters not defined by homeassistant.const CONF_TARGET_TEMP = 'target_temp_register' CONF_CURRENT_TEMP = 'current_temp_register' CONF_DATA_TYPE = 'data_type' CONF_COUNT = 'data_count' CONF_PRECISION = 'precision' DATA_TYPE_INT...
# -*- coding: utf-8 -*- from greek_stemmer.c
losets.word_exceptions impo
rt exceptions def test_word_exceptions(): assert isinstance(exceptions, dict)
calculations ''' def __init__(self, files): super(VaspParser, self).__init__(files) self.settings = {} parser = OutcarParser() # Find the outcar file def _find_file(name): """Find a filename that contains a certain string""" name = name.upper() ...
lf): raw_path = self.outcar if raw_path[0:2] == "./": raw_path = raw_path[2:] retu
rn Property(files=[FileReference( relative_path=raw_path )]) def get_incar(self): if self.incar is None: return None raw_path = self.incar if raw_path[0:2] == "./": raw_path = raw_path[2:] return Value(files=[FileReference( relative_path=r...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Reading, writing, and describing memory. """ import gdb import pwndbg.compat import pwndbg.typeinfo PAGE_SIZE = 0x1000 PAGE_MASK = ~(PAGE_SIZE-1) MMAP_MIN_ADDR = 0x8000 def read(addr, count, partial=False): result = '' try: result = gdb.selected_infer...
self.permstr, self.memsz, self.offset, self.objfile or '') def __repr__(self): return "%s(%r)" % (self.__class__.__name__, self.__str__()) def __contains__(self, a): return self.vad
dr <= a < (self.vaddr + self.memsz) def __eq__(self, other): return self.vaddr == getattr(other, 'vaddr', other) def __lt__(self, other): return self.vaddr < getattr(other, 'vaddr', other) def __hash__(self): return hash((self.vaddr, self.memsz, self.flags, self.offset, self.objfile)...
> # Jeremy Katz <katzj@redhat.com> # Chris Lumens <clumens@redhat.com> # Paul Nasrat <pnasrat@redhat.com> # Erik Troan <ewt@rpath.com> # Matt Wilson <msw@rpath.com> # import os import sys import stat from glob import glob from tempfile import mkstemp import thread...
rom pyanaconda.bootloader import get_bootloader from pyanaconda import constants from pyanaconda import iutil from pyanaconda.iutil import open # pylint: disable=redefined-builtin from pyanaconda import addons import logging log = logging.getLogger("anaconda") stdoutLog = logging.getLogger("anaconda.stdout") class ...
self._bootloader = None self.canReIPL = False self.desktop = desktop.Desktop() self.dir = None self.displayMode = None self.gui_startup_failed = False self.id = None self._instClass = None self._intf = None self.isHeadless = False self.ksd...
""" WSGI config for Footer project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATI
ON`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application o...
ngo.core.wsgi import get_wsgi_application if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': from raven.contrib.django.raven_compat.middleware.wsgi import Sentry # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi...
# 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 ast import os.path import platform import re import sys class Config(object): '''A Config contains a dictionary that species a build configuratio...
') if not os.path.isfile(gn_file): return with open(gn_file, 'r') as f: for line in f: line = re.sub('\s*#.*', '', line) result = re.match('^\s*(\w+)\s*=\s*(.*)\s*$', line) if result: key = result.group(1) value = result.group(2) self.values[key...
value, value)) # Getters for standard fields ------------------------------------------------ @property def build_dir(self): '''Build directory path.''' return self.values['build_dir'] @property def target_os(self): '''OS of the build/test target.''' return self.values['target_os'] @prop...
import datetime import psycopg2 from collections import deque from tornado.stack_context import wrap from tornado.ioloop import IOLoop from tornado.concurrent import return_future class WrapCursor: def __init__(self,db,cur): self._db = db self._cur = cur self._oldcur = None self._i...
: conn = self._share_connpool[ random.randrange(len(self._share_connpool))] conn[1].append((self.OPER_CURSOR,None,wrap(_cb))) if conn[2] == False: conn[2] = True self._ioloop.add_callback(self._dispatch,conn[0],0) def _execute(self,cur,sql,p...
cur.connection.fileno()] conn[1].append((self.OPER_EXECUTE,(cur,sql,param),wrap(callback))) if conn[2] == False: conn[2] = True self._ioloop.add_callback(self._dispatch,conn[0],0) def _begin_tran(self,callback): if len(self._free_connpool) == 0: ...
import simplejson as json import urllib import urllib2 import time server = "" def GET(uri, params): params = urllib.urlencode(params) req = urllib2.Request(server + uri + "?" + params , headers={'Accept': 'application/json'}) return json.loads(urllib2.urlopen(req).read()) def POST(uri, params): para...
", has already been submitted!" else: raise e if __name__ == "__m
ain__": set_server_url("http://localhost:8080") detector = Detector("Histogram Regression Detector", "foobar") metric = Metric("metric100", "foobar", detector) post_alert(detector, metric, "foobar")
# -*- coding: utf-8 -*- # # (c) Copyright 2001-2009 Hewlett-Packard Development Company, L.P. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your opt...
QRadioButton.__init__(self, parent) s
elf.setFocusPolicy(Qt.NoFocus) self.clearFocus() def mousePressEvent(self, e): if e.button() == Qt.LeftButton: return QRadioButton.mousePressEvent(e) def mouseReleaseEvent(self, e): if e.button() == Qt.LeftButton: return QRadioButton.mouseRel...
_future__ import print_function from __future__ import division import numpy as np import sys import argparse import time import re import gzip import os import logging
from collections import defaultdict from operator import itemgetter __version__ = "1.0" def main(): parser=argparse.ArgumentParser(description='vcf2fasta (diploid)',formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-r', '--ref', dest='ref_fa
sta', type=str, required=True, help='input reference file (fasta)') parser.add_argument('-v', '--vcf', dest='vcf_file', type=str, required=True, help='input vcf file (vcf)') parser.add_argument('-n', '--name', dest='name', type=str, required=True, help='sample name (column header)') parser.add_argument('--v...
import socket import pytest import mock from pygelf import GelfTcpHandler, GelfUdpHandler, GelfHttpHandler, GelfTlsHandler, GelfHttpsHandler from tests.helper import logger, get_unique_message, log_warning, log_exception SYSLOG_LEVEL_ERROR = 3 SYSLOG_LEVEL_WARNING = 4 @pytest.fixture(params=[ GelfTcpHandler(hos...
host='127.0.0.1', port=12203, compress=False), GelfTlsHandler(host='127.0.0.1', port=12204), GelfHttpsHandler(host='127.0.0.1', port=12205, validate=False), GelfHttpsHandler(host='localhost'
, port=12205, validate=True, ca_certs='tests/config/cert.pem'), GelfTlsHandler(host='127.0.0.1', port=12204, validate=True, ca_certs='tests/config/cert.pem'), ]) def handler(request): return request.param def test_simple_message(logger): message = get_unique_message() graylog_response = log_warning(lo...
# -*- coding: utf-8 -*- # # Copyright 2013 - Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
for attr in self._wsme_attributes: if
not first: res += ', ' else: first = False res += "%s='%s'" % (attr.name, getattr(self, attr.name)) return res + "]"
# Copyright the Karmabot authors and contributors. # All rights reserved. See AUTHORS. # # This file is part of 'karmabot' and is distributed under the BSD license. # See LICENSE for more details. # dedicated to LC from json import JSONDecoder from urllib import urlencode from urllib2 import urlopen from karmabot.co...
g from karmabot.core.commands.sets import CommandSet from karmabot.core.register import facet_registry from karmabot.core.facets import Facet import re import htmlentitydefs ## # Function Placed in public domain by Fredrik Lundh # http://effbot.org/zone/copyright.htm # http://effbot.org/zone/re-sub.htm#unescape-html ...
g. # # @param text The HTML (or XML) source text. # @return The plain text, as a Unicode string, if necessary. def unescape(text): def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": retur...
ed from .lapack import get_lapack_funcs from scipy._lib.six import callable __all__ = ['qz'] _double_precision = ['i','l','d'] def _select_function(sort, typ): if typ in ['F','D']: if callable(sort): # assume the user knows what they're doing sfunction = sort elif sort =...
- '
lhp' Left-hand plane (x.real < 0.0) - 'rhp' Right-hand plane (x.real > 0.0) - 'iuc' Inside the unit circle (x*x.conjugate() <= 1.0) - 'ouc' Outside the unit circle (x*x.conjugate() > 1.0) Defaults to None (no sorting). check_finite : boolean If true check...
permissions and limitations # under the License. """ Helpers for comparing version strings. """ import functools import inspect import logging from oslo_config import cfg import pkg_resources import six from nova.openstack.common._i18n import _ LOG = logging.getLogger(__name__) CONF = cfg.CONF opts = [ ...
ature is used. If the system is configured for fatal deprecations then the message is logged at the 'critical' level and :class:`DeprecatedConfig` will be raised. Otherwise, the message will be logged (once) at the 'warn' level. :raises: :class:`DeprecatedConfig` if the system is configured for ...
_("Deprecated: %s") % msg CONF.register_opts(opts) if CONF.fatal_deprecations: logger.critical(stdmsg, *args, **kwargs) raise DeprecatedConfig(msg=stdmsg) # Using a list because a tuple with dict can't be stored in a set. sent_args = _deprecated_messages_sent.setdefault(msg, list()) ...
from exchanges import helpers from exchanges import kraken from decimal impo
rt Decimal ### Kraken opportunities #### ARBITRAGE OPPORTUNITY 1 def opportunity_1(): sellLTCbuyEUR = kraken.get_current_bid_LTCEUR() sellEURbuyXBT = kraken.get_current_ask_XBTEUR() sellXBTbuyLTC = kraken.get_current_ask_XBTLTC() opport = 1-((sellLTCbuyEUR/sellEURbuyBTX)*sellXBTbuyLTC) return Decimal(opport)...
yXBT = kraken.get_current_ask_XBTLTC() sellXBTbuyEUR = kraken.get_current_bid_XBTEUR() opport = 1-(((1/sellEURbuyLTC)/sellLTCbuyXBT)*sellXBTbuyEUR) return Decimal(opport)
import os from fs import enums import unittest class TestEnums(unittest.TestCase): def te
st_enums(self): self.assertEqual(enums.Seek.current, os.SEEK_CUR) self.assertEqual(enums.Seek.end, os.SEEK_END) self.assertEqual(e
nums.Seek.set, os.SEEK_SET) self.assertEqual(enums.ResourceType.unknown, 0)
#!/usr/bin/env python from __future__ import print_function # Use the srilm module from srilm import * # Initialize a trigram LM variable (1 = unigram, 2 = bigram and so on) n = initLM(5) # Read 'sa
mple.lm' into the LM variable readLM(
n, "corpu.lm") # How many n-grams of different order are there ? print("1. Number of n-grams:") print(" There are {} unigrams in this LM".format(howManyNgrams(n, 1))) print(" There are {} bigrams in this LM".format(howManyNgrams(n, 2))) print(" There are {} trigrams in this LM".format(howManyNgrams(n, 3))) print...
from flask import Flask from flask import request from flask.ext.sqlalchemy import SQLAlchemy import datetime import uuid as uid import sys import requests import urllib2 GOIP_SERVER_IP = '127.0.0.1' #'172.248.114.178' TELEPHONY_SERVER_IP = '127.0.0.1:5000/sms/in' sys.path.append('/home/csik/public_python/sms_...
n(deets)-1, deets_method) for deet in deets: s += str(deet) print s return deets @app.route("/", methods=['GET', 'POST']) def hello(): debug(request) return "Hello World!" @app.route("/init_goip", methods=['GET', 'POST']) def init_goip(): try: import send_sms_GOIP ...
eption("Wrong machine") except: print "Unable to init GOIP -- are you sure you called the right machine?" return "Unable to init GOIP", 404 @app.route("/out", methods=['GET', 'POST']) def sms_out(): """ Handles outgoing message requests. Currently only from GOIP8, ...
s to cache allow-update { any; }; // This is the default allow-query { any; }; // This is the default recursion no; // Do not provide recursive service }; zone "1.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa" { type master; file "rev.db"; notify no; allo...
w-update { key forge.md5.key; }; allow-query { any; }; }; key "forge.sha512.key" { algorithm hmac-sha512; secret "jBng5D6QL4f8cfLUUwE7OQ=="; }; key "forge.md5.key" { algorithm hmac-md5; secret "bX3Hs+fG/tThidQPuhK1mA=="; }; #Use with the following in named.conf, adjusting the allow list as neede...
="; }; controls { inet 127.0.0.1 port 53001 allow { 127.0.0.1; } keys { "rndc-key"; }; }; logging{ channel simple_log { file "/tmp/dns.log"; severity debug 99; print-time yes; print-severity yes; print-category yes; }; category default{ simple_log; }; category queries{ simp...
import sys import os import torch import time from engine import TetrisEngine from dqn_agent import DQN, ReplayMemory, Transition from torch.autograd import Variable use_cuda = torch.cuda.is_available() FloatTensor = torch.cuda.FloatTensor if use_cuda else torch.FloatTensor LongTensor = torch.cuda.LongTensor if use_c...
sor(state[None,None,:,:]) # Accumulate reward score += int(reward) print(engine) print(action) time.sleep(.1) if done: print('score {0}'.format(score)) break if len(sys.argv) <= 1: print('specify a filename to load the model') sys.exit(...
if os.path.isfile(filename): print("=> loading model '{}'".format(filename)) model = load_model(filename).eval() run(model) else: print("=> no file found at '{}'".format(filename))
import pandas as pd import logging import settings import os from scikits.audiolab import oggwrite, play, oggread from scipy.fftpack import dct from itertools import chain import numpy as np import math log = logging.getLogger(__name__) def read_sound(fpath, limit=settings.MUSIC_TIME_LIMIT): try: data, f...
zccn, spread, skewness, savss, mavss] + mels + [i[0] for (j, i) in enumerate(inter) if j % 5 == 0] for i in xrange(0, len(features)): try: features[i] = features[i].real except Exception: pass return features def extract_features(sample, freq): left = calc_feature...
features = extract_features(vec, f) except Exception: log.error("Cannot generate features for file {0}".format(f)) return None return features def generate_features(filepath): frame = None data, fs, enc = read_sound(filepath) features = process_song(data, fs) frame = pd.Seri...
import time from indy import anoncreds, wallet import json import logging from indy import pool from src.utils import run_coroutine, PROTOCOL_VERSION logger = logging.getLogger(__name__) async def demo(): logger.info("Anoncreds sample -> started") issuer = { 'did': 'NcYxiDXkpYi6ov5FcYDi1e', ...
on, _, _) = await anoncreds.issuer_create_credential(issuer['wallet'], i
ssuer['cred_offer'], issuer['cred_req'], issuer['cred_values'], None, None) prover['cred'] = cred_json # 9. Prover store Credential await anoncreds.prover_store_credential(prover['wallet'], None, prover['cred_req_metadata'], prover['cred'], ...
import gevent import socket from vnc_api.vnc_api import * from cfg
m_common.vnc_kombu import VncKombuClient from config_db import * from cfgm_common.dep
endency_tracker import DependencyTracker from reaction_map import REACTION_MAP import svc_monitor class RabbitConnection(object): _REACTION_MAP = REACTION_MAP def __init__(self, logger, args=None): self._args = args self.logger = logger def _connect_rabbit(self): rabbit_server = ...
i --targetname %s" % self.target process.system(cmd) cmd = "tgtadm --lld iscsi --op bind --mode target " cmd += "--tid %s -I ALL" % self.emulated_id process.system(cmd) else: target_strs = re.findall("Target\s+(\d+):\s+%s$" % ...
rocess.system("targetcli / saveconfig") def export_target(self): """ Export target in localhost for emulated iscsi """ selinux_mode = None # create image disk if not os.path.isfile(self.emulated_image): process.system(self.create_cmd) else: ...
e != self.emulated_expect_size: # No need to remvoe, rebuild is fine process.system(self.create_cmd) # confirm if the target exists and create iSCSI target cmd = "targetcli ls /iscsi 1" output = process.system_output(cmd) if not re.findall("%s$" % self.ta...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the projec
t root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause in
correct behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model from msrest.exceptions import HttpOperationError class Error(Model): """Cognitive Services error object. :param error: The error...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # # 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 # # Unle...
ter a column to drop # an unname
d unique constraint, so this code creates a named unique # constraint on the name column rather than an unnamed one. # (This is used in migration 16.) user_table = sql.Table( 'user', meta, sql.Column('id', sql.String(64), primary_key=True), sql.Col...
8') return value def unicode_http_header(value): # Coerce HTTP header value to unicode. if isinstance(value, six.binary_type): return value.decode('iso-8859-1') return value def total_seconds(timedelta): # TimeDelta.total_seconds() is only available in Python 2.7 if hasattr(timedelta...
options differs after 1.10. def get_names_and_managers(options): if django.VERSION >= (1, 10): # Django 1.10 onwards provides a `.managers` property on the Options. return [ (manager.name, manager) for manager in options.managers ] # For Django 1.8 an...
_info in (options.concrete_managers + options.abstract_managers) ] # field.rel is deprecated from 1.9 onwards def get_remote_field(field, **kwargs): if 'default' in kwargs: if django.VERSION < (1, 9): return getattr(field, 'rel', kwargs['default']) return getattr(field, 're...
""" generic tests from the Datetimelike class """ import numpy as np import pandas as pd from pandas.util import testing as tm from pandas import Series, Index, DatetimeIndex, date_range from ..datetimelike import DatetimeLike class TestDatetimeIndex(DatetimeLike): _holder = DatetimeIndex def setup_method(...
10', '2013-01-11'], freq='D') tm.assert_index_equal(result, expected) def test_pickle_compat_construction(self): pass def test_intersection(self): first = self.index second = self.index[5:] intersect = first.intersection(second) ...
for case in cases: result = first.intersection(case) assert tm.equalContents(result, second) third = Index(['a', 'b', 'c']) result = first.intersection(third) expected = pd.Index([], dtype=object) tm.assert_index_equal(result, expected) def test_unio...
# -*- coding: utf-8 -*- #----------------------------
-------------------------------------------------- # Copyright (c) 2012-2014, Michael Reuter # Distributed under the MIT License. See LICENSE.txt for more information. #------------------------------------------------------------------------------ from .moon_info import MoonInfo from .observing_site import Obser
vingSite class ObservingInfo(object): ''' This class is responsible for keeping the observing site information and the moon information object together. It will be responsible for updating any of the observing site information that then affects the moon information. ''' __shared_state = ...
import os import platform import sys import threading from concurrent.futures import ThreadPoolExecutor from os import environ, path from threading import Timer import grpc import ptvsd from getgauge import handlers, logger, processor from getgauge.impl_loader import copy_skel_files from getgauge.messages import runne...
dir, impl_dir)) load_files(d) def _handle_detached(): logger.info("No debugger attached. Stopping the execution.") os._exit(1) def start(): if environ.get('DEBUGGING'): ptvsd.enable_attach(address=( '127.0.0.1', int(environ.get('DEBUG_PORT')))) print(ATTACH_DEBUGGER_EVENT...
le_detached) t.start() ptvsd.wait_for_attach() t.cancel() logger.debug('Starting grpc server..') server = grpc.server(ThreadPoolExecutor(max_workers=1)) p = server.add_insecure_port('127.0.0.1:0') handler = handlers.RunnerServiceHandler(server) runner_pb2_grpc.add_RunnerServi...
impo
rt tests.model_control.test_ozone_custom_models_enabled as testmod testmod.build_model( ['Logit'] , ['MovingAverage'] , ['Seasonal_WeekOfYear'] ,
['NoAR'] );
import argparse import taichi as ti FRAMES = 100 def tes
t_ad_gravity(): from taichi.examples.simulation.ad_gravity import init, substep init() for _ in range(FRAMES): for _ in range(50): substep() def video_ad_gravity(result_dir): import numpy as np from taichi.examples.simulation.ad_gravity import init, substep, x video_manag...
ools.VideoManager(output_dir=result_dir, framerate=24, automatic_build=False) gui = ti.GUI('Autodiff gravity', show_gui=False) init() for _ in range(FRAMES): for _ in range(50): substep() gui.cir...
"""This script automates the copying of the default keymap into your own keymap. """ import shutil from pathlib import Path import qmk.path from qmk.decorators import automagic_keyboard, automagic_keymap from milc import cli @cli.argument('-kb', '--keyboard', help='Specify keyboard name. Example: 1upkeyboards/1up60h...
lt %s
does not exist!', keymap_path_default) return False if keymap_path_new.exists(): cli.log.error('Keymap %s already exists!', keymap_path_new) return False # create user directory with default keymap files shutil.copytree(keymap_path_default, keymap_path_new, symlinks=True) # e...
egg\Z') def __new__(cls, state, bssid, ssid='', regdtm='19000101000000', rssi=-200, bregap=False, bmap=False, optrcom='none', geoloc=None, priority=Priority.NORMAL): # Classify WiFi try: if ssid not in ('', None): ssid = re.sub(r'^\s*"(.*)"\s*$', r'\1', unicode(ssid)) ...
%s','%s','%s') ON DUPLICATED UPDATE lat = IF(VALUES(seq) > seq, VALUES(lat),
lat), lng = IF(VALUES(seq) > seq, VALUES(lng), lng), seq = IF(VALUES(seq) > seq, VALUES(seq), seq), acc = IF(VALUES(seq) > seq, VALUES(acc), acc), geosrc=VALUES(geosrc)""" try: strSql = strSql % (node.bssid, node.ssid, ...
# -*- coding: utf8 -*-
SQL = ( ('list_fonds_report1', """ select F.FKOD,F.FNAME, (F.A16+if(F.A22,A22,0)) as A16 FROM `af3_fond` F WHERE FNAME like ('%%%(qr)s%%') or A1 like ('%%%(qr)s%%') ORDER BY FKOD;"""), ) FOUND_ROWS = True ROOT = "fonds" ROOT_PREFIX = None ROOT_POSTFIX= None XSL_TEMPLATE = "da...
тесь назад" ORDER = None
from patchs import PatchsBackend from registry import register_backend TEST_DB_WITHOUT_COMMITS = bool(int(os.environ.get('TEST_DB_WITHOUT_COMMITS') or 0)) TEST_DB_DESACTIVATE_GIT = bool(int(os.environ.get('TEST_DB_DESACTIVATE_GIT') or 0)) class Heap(object): """ This object behaves very much like a sorted ...
time(21, 00) < t or t < time(06, 00) done_recently = now - self.last_transaction_dtime < timedelta(minutes=120) if is_night and not done_recently:
self.do_git_big_commit() # Catalog for path in docs_to_unindex: self.catalog.unindex_document(path) for resource, values in docs_to_index: self.catalog.index_document(values) self.catalog.save_changes() def
twice (retry after fail) self.assertEqual(self.cluster_manager.cluster_env_id, "correct") self.assertEqual(self.sdk.call_counter["search_cluster_environments"], 1) self.assertEqual(self.sdk.call_counter["create_cluster_environment"], 1) self.assertEqual(len(self.sdk.call_counter), 2) ...
= "correct" self.sdk.returns["create_cluster"] = _fail with self.assertRaises(ClusterCreationError): self.cluster_manager.start_cluster() def testSessionStartStartupError(self): self.cluster_manager.cluster_env_id = "correct" self.cluster_ma
nager.cluster_compute_id = "correct" self.sdk.returns["create_cluster"] = APIDict(result=APIDict(id="success")) self.sdk.returns["start_cluster"] = _fail with self.asser
from datetime import time from datetime import timedelta import pendulum from .constants import SECS_PER_HOUR from .constants import SECS_PER_MIN from .constants import USECS_PER_SEC from .duration import AbsoluteDuration from .duration import Duration from .mixins.default import FormattableMixin class Time(Formatt...
return "{}
({}, {}, {}{}{})".format( self.__class__.__name__, self.hour, self.minute, self.second, us, tzinfo ) # Comparisons def closest(self, dt1, dt2): """ Get the closest time from the instance. :type dt1: Time or time :type dt2: Time or time :rtype: Time...
# Copyright (c) 2021 PaddlePaddle Authors. All Right
s 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 ap
plicable 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 permissions and # limitations under the License. import logging import sys ...
# -*- coding: utf-8 -*- # # This file is part of the Christine project # # Copyright (c) 2006-2007 Marco Antonio Islas Cruz # # Christine 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...
ng with this program; if not, write to the Free Software #
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # # @category libchristine # @package Share # @author Miguel Vazquez Gocobachi <demrit@gnu.org> # @author Marco Antonio Islas Cruz <markuz@islascruz.org> # @copyright 2007-2009 Christine Development Group # @license http://www.gnu.org...
#!/usr/bin/env python """Exponential and Quaternion code for Lab 6. Course: EE 106, Fall 2015 Author: Victor Shia, 9/24/15 This Python file is a code skeleton Lab 6 which calculates the rigid body transform given a rotation / translation and computes the twist from rigid body transform. When you think you have the me...
ret_value = func_name(*args) if not isinstance(ret_value, np.ndarray): print('[FAIL] ' + func_name.__name__ + '() returned something other than a NumPy ndarray') elif ret_value.shape != ret_desired.shape: print('[FAIL] ' + func_name.__name__ + '() returned an ndarray with incorrect dimensions')...
: print('[PASS] ' + func_name.__name__ + '() returned the correct value!') def array_func_test_two_outputs(func_name, args, ret_desireds): ret_values = func_name(*args) for i in range(2): ret_value = ret_values[i] ret_desired = ret_desireds[i] if i == 0 and not isinstanc...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you
under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may 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 # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. "...
# A SCons tool for R scripts # # Copyright (c) 2014 Kendrick Boyd. This is free software. See LICENSE # for details. "
"" Basic test of producing output using save. """ import TestSCons test = TestSCons.TestSCons() # Add scons_r tool to test figure. test.file_fixture('../__init__.py', 'site_scons/site_tools/scons_r/__init__.py') test.write(['SConstruct'], """\ import os env = Environment(TOOLS = ['scons_r']) env.R('basic.r') """)...
t('x.rdata') test.pass_test()
from django.shortcuts import render_to_response from django.template import RequestContext from markitup import
settings from markitup.markup import filter_func from markitup.sanitize import sanitize_html def apply_filter(request): cleaned_data = sanitize_html(request.POST.get('data', ''), strip=True) markup = filter_func(
cleaned_data) return render_to_response( 'markitup/preview.html', {'preview': markup}, context_instance=RequestContext(request))
ow.python.lib.io import file_io from tensorflow.python.util.tf_export import keras_export TF_WEIGHTS_PATH = ( 'https://storage.googleapis.com/tensorflow/keras-applications/' 'xception/xception_weights_tf_dim_ordering_tf_kernels.h5') TF_WEIGHTS_PATH_NO_TOP = ( 'https://storage.googleapis.com/tensorflow/ker...
sepconv2')(x) x = layers.BatchNormalization(axis=channel_axis, name='block4_sepconv2_bn')(x) x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same', name='block4_pool')(x) x = layers.add([x, residual]) for i in range(8): ...
rs.Activation('relu', name=prefix + '_sepconv1_act')(x) x = layers.SeparableConv2D( 728, (3, 3), padding='same', use_bias=False, name=prefix + '_sepconv1')(x) x = layers.BatchNormalization( axis=channel_axis, name=prefix + '_sepconv1_bn')(x) x = layers.Activation('rel...
from __future__ import absolute_import, division, print_function class _slice(object): """ A hashable slice object >>> _slice(0, 10, None) 0:10 """ def __init__(self, start, stop, step): self.start = start self.stop = stop self.step = step def __hash__(self): r...
is tuple: # can't do isinstance due to hashable_list return tupl
e(map(hashable_index, index)) elif isinstance(index, list): return hashable_list(index) elif isinstance(index, slice): return _slice(index.start, index.stop, index.step) return index def replace_slices(index): if isinstance(index, hashable_list): return list(index) elif is...
tal time, idle time, processing time, time since prior interval start, busy since prior interval start), all in ms (int). """ now = get_ion_ts_millis() running_time = now - self._start_time idle_time = running_time - self._proc_time cur_interval = now / STAT_INTERVAL_LEN...
ild greenlet fails. Kills the ION process main greenlet. This propagates the error up to the process supervisor. """ # remove the child from the list of children (so we can shut down cleanly) for x in self.thread_manager.children: if x.proc == child: self.thre...
reak self._dead_children.append(child) # kill this process's main greenlet. This should be noticed by the container's proc manager self.proc.kill(child.exception) def add_endpoint(self, listener, activate=True): """ Adds a listening endpoint to be managed by this ION proces...
#! /usr/bin/python # Joe Deller 2014 # Finding out where we are in minecraft # Level : Beginner # Uses : Libraries, variables, functions # Minecraft worlds on the Raspberry Pi are smaller than # other minecraft worlds, but are still pretty big # So one of the first things we need to learn to do # is find out where w...
import mcpi.minecraft as minecraft # This program also uses another library, the time library # as we want the program to sleep for a short time - 1 second # so that we don't fill the screen with too much information # We will come across the time library later when we # make a minecraft digital clock import time #...
is a special kind of variable, called an "object" # but for now all we need to worry about is what to call it # Most computer languages are very strict about using capital letters # To the computer, playerPos, Playerpos and PlayerPOS are completely # different things, so once you decide on a name, you need to spell # ...
from pySDC import CollocationClasses as collclass import numpy as np from ProblemClass import sharpclaw #from examples.sharpclaw_burgers1d.TransferClass import mesh_to_mesh_1d from pySDC.datatype_classes.mesh import mesh, rhs_imex_mesh from pySDC.sweeper_classes.imex_1st_order import imex_1st_order import pySDC.Meth...
om pySDC import Log from pySDC.Stats import grep_stats, sort_stats # Sharpclaw imports from clawpack import pyclaw from clawpack import riemann from matplotlib import pyplot as plt if __name__ == "__main__": # set global logger (remove this if you do not want the output at all) logger = Log.setup_custom_log...
ms['maxiter'] = 20 # setup parameters "in time" t0 = 0 dt = 0.001 Tend = 100*dt # This comes as read-in for the problem class pparams = {} pparams['nvars'] = [(2,50,50)] pparams['nu'] = 0.001 # This comes as read-in for the transfer operations tparams = {} tparams['finter'...
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 KIND, either expr...
etIndexReader() pos = MultiFields.getTermPositionsEnum(rea
der, MultiFields.getLiveDocs(reader), "field", BytesRef("1")) pos.nextDoc() # first token should be at position 0 self.assertEqual(0, pos.nextPosition()) pos = MultiFields.getTermPositionsEnum(reader, MultiFields.getLiveDocs(reader), "field", BytesRef("2")) pos.nextDoc() ...
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.2' _lr_method = 'LALR' _lr_signature = '\x91\x95\xa5\xf7\xe0^bz\xc0\xf4\x04\xf9Z\xebA\xba' _lr_action_items = {'NAME':([0,2,5,7,11,12,13,14,],[1,8,8,8,8,8,8,8,]),')':([3,8,9,10,16,17,18,19,20,],[-9,-10,-7,16,-8,-4,-3,-5,-6,]),'(...
s\\test\\testpy\\testply.py',58), ('statement -> expression','statement',1,'p_statement_expr','D:\\repos\\test\\testpy\\testply.py',63), ('expression -> expression + expression','expression',3,'p_expression_binop','D:\\repos\\test\\testpy\\testply.py',
68), ('expression -> expression - expression','expression',3,'p_expression_binop','D:\\repos\\test\\testpy\\testply.py',69), ('expression -> expression * expression','expression',3,'p_expression_binop','D:\\repos\\test\\testpy\\testply.py',70), ('expression -> expression / expression','expression',3,'p_expression...