prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# -*- coding: utf-8 -*-
# ******************************************************************************
#
# Copyright (C) 2008-2010 Olivier Tilloy <olivier@tilloy.net>
#
# This file is part of the pyexiv2 distribution.
#
# pyexiv2 is free software; you can redistribute it and/or
# modify it under the terms of the GNU... | self.assertRaises(ZeroDivisionError, Rational.from_string, '1/0')
self.assertRaises(ZeroDivisionError, Rational.from_string, '0/0')
def test_to_string(self):
self.assertEqual(str(Rational(3, 5)), '3/5')
self.assertEqual(str(Rational(-3, 5)), '-3/5')
def test_repr(self):
sel... | elf.assertEqual(repr(Rational(0, 3)), 'Rational(0, 3)')
def test_to_float(self):
self.assertEqual(Rational(3, 6).to_float(), 0.5)
self.assertEqual(Rational(11, 11).to_float(), 1.0)
self.assertEqual(Rational(-2, 8).to_float(), -0.25)
self.assertEqual(Rational(0, 3).to_float(), 0.0)
... |
import unittest
import ray
from ray.rllib.agents.a3c import A2CTrainer
from ray.rllib.execution.common import STEPS_SAMPLED_COUNTER, \
STEPS_TRAINED_COUNTER
from ray.rllib.utils.test_utils import framework_iterator
class TestDistributedExecution(unittest.TestCase):
"""General tests for the distributed execut... | assert "sample_time_ms" in result["timers"]
assert "sample_throughput" in result["timer | s"]
assert "update_time_ms" in result["timers"]
def test_exec_plan_save_restore(ray_start_regular):
for fw in framework_iterator(frameworks=("torch", "tf")):
trainer = A2CTrainer(
env="CartPole-v0",
config={
"min_iter_time_s": 0,
... |
ient import SAMPIntegratedClient
from ..errors import SAMPProxyError
# By default, tests should not use the internet.
from .. import conf
from .test_helpers import random_params, Receiver, assert_output, TEST_REPLY
def setup_module(module):
conf.use_internet = False
class TestStandardProfile:
@property
... | mpdir)
self.client1.ecall(self.client2.get_public_id(), 'test-tag',
"table.load.votable", **params)
assert_output('table.load.votable', self.client2.get_private_key(),
self.client1_id, params, timeout=60)
# Test call_all
params = random... | self.client1.call_all('tag1',
{'samp.mtype': 'table.load.votable',
'samp.params': params})
assert_output('table.load.votable', self.client2.get_private_key(),
self.client1_id, params, timeout=60)
params = random_params... |
#!/usr/bin/python
#
# author:
#
# date:
# description:
#
'''Trains a memory network on the bAbI dataset.
References:
- Jason Weston, Antoine Bordes, Sumit Chopra, Tomas Mikolov, Alexander M. Rush,
"Towards AI-Complete Question a1ing: A Set of Prerequisite Toy Tasks",
http://arxiv.org/abs/1502.05698
- Sainbayar... | piling...')
print(inputs_train.shape)
print(queries_train.shape)
X = Input(shape=(story_maxlen,), dtype="int32")
Q = Input(shape=(query_maxlen,), dtype="int32")
embedding_dim = story_maxlen
# embed the input sequence into a sequence of vectors
m1 = Sequential()
m1.add(Embedding(input_dim=vocab_size,
... | ry_maxlen, embedding_dim)
# embed the question into a sequence of vectors
u1 = Sequential()
u1.add(Embedding(input_dim=vocab_size,
output_dim=embedding_dim,
input_length=query_maxlen)(Q))
# output: (samples, query_maxlen, embedding_dim)
# compute a 'w1' between input sequence elements ... |
# encoding: utf-8
from yast impo | rt import_module
import_module('UI')
from yast import *
class Heading2Client:
def main(se | lf):
UI.OpenDialog(
VBox(
Heading("This Is a Heading."),
Label("This is a Label."),
PushButton("&OK")
)
)
UI.UserInput()
UI.CloseDialog()
Heading2Client().main()
|
# -*- coding: utf-8 -*-
"""Copyright (C) 2013 COLDWELL AG
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 dist... | ror('premium is untested')
def on_download_free(chunk):
resp = chunk.account.get(chunk.url, use_cache=True)
check_errors(chunk, resp | )
resp = hoster.xfilesharing_download(resp, 1)[0]()
check_errors(chunk, resp)
m = re.search('You have to wait (.*?) till next download', resp.text)
if m:
wait = hoster.parse_seconds2(m.group(1)) + time.time()
if wait > 300:
chunk.ip_blocked(wait)
submit, data = hoster.x... |
""" Exit Status 1 is already used in the script.
Zdd returns with exit status 1 when app is not force
deleted either through argument or through prompt.
Exit Status 2 is used for Unknown Exceptions.
"""
class InvalidArgException(Exception):
""" This exception indicates invalid combination of arguments... | load, error):
super(AppCreateException, self).__init__(msg)
self.msg = msg
self.error = error
self.url = url
self.payload = payload
self.zdd_exit_status = 7
class AppDeleteException(Exception):
""" This exception i | ndicates there was a error while deleting the
old App and hence it was not deleted """
def __init__(self, msg, url, appid, error):
super(AppDeleteException, self).__init__(msg)
self.msg = msg
self.error = error
self.url = url
self.zdd_exit_status = 8
class AppScaleE... |
lib import pofile
from autotranslate.poutil import find_pos, pagination_range, timestamp_with_timezone
from autotranslate.signals import entry_changed, post_save
from autotranslate.storage import get_storage
from autotranslate.access import can_translate, can_translate_language
import json
import re
import autotransla... | ser, 'first_name', ' | Anonymous'),
getattr(request.user, 'last_name', 'User'),
getattr(request.user, 'email', 'anonymous@user.tld')
)).encode('ascii', 'ignore')
autotranslate_i18n_pofile.metadata['X-Translated-Using'] = u"dj-translate %s" % autotranslate... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | flow.contrib import integrate
from tensorflow.contrib import keras
from tensorflow.contrib import kernel_methods
from tensorflow.contrib import labeled_tensor
from tensorflow.contrib import layers
from tensorflow.contrib imp | ort learn
from tensorflow.contrib import legacy_seq2seq
from tensorflow.contrib import linalg
from tensorflow.contrib import linear_optimizer
from tensorflow.contrib import lookup
from tensorflow.contrib import losses
from tensorflow.contrib import memory_stats
from tensorflow.contrib import metrics
from tensorflow.con... |
import json
class AbstractionUtility(object):
@staticmethod
def read_json(json_file):
# read json data
with open(json_file, 'r') as f:
data = json.load(f)
# change json key string to int
converted_data = {}
for key, value in data.iteritems():
co... | ction.write('Abstraction #' + str(abstraction_id) + ' ' + abstraction['abstraction'] + '\n')
for line_id in abstracti | on['original_id']:
f_perabstraction.write(str(line_id) + ' ' + logs[line_id])
f_perabstraction.write('\n')
f_perabstraction.close()
@staticmethod
def write_perline(final_abstraction, log_file, perline_file):
# read log file
with open(log_file, 'r') as f:
... |
# Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from urbansim.abstract_variables.abstract_travel_time_variable_for_non_interaction_dataset import abstract_travel_time_variable_for_non_interaction_dataset
class SSS_travel_time_to_DDD(abstract... | by mode SSS to the zone whose ID is the DDD.
"""
default_value = 999
origin_zone_id = 'zone.zone_id'
def __init__(self, mode, number):
self.travel_data_attribute = "travel_data.%s" % mode
self.destination_zone_id = "destination_zone_id=%s+0*zone.zone_id" % number
abstr... | eraction_dataset.__init__(self)
from opus_core.tests import opus_unittest
from numpy import array, arange
from opus_core.tests.utils.variable_tester import VariableTester
class Tests(opus_unittest.OpusTestCase):
def do(self,sss, ddd, should_be):
tester = VariableTester(
__file__,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_equality
-------------------- | --------------
Tests for the `SetType` low() method
"""
| import unittest
from finitio.types import SetType, BuiltinType, Type
builtin_string = BuiltinType(str)
class TestSetTypeLow(unittest.TestCase):
class HighType(Type):
def low(self):
return builtin_string
subject = SetType(HighType(""))
def test_equals_itself(self):
expected... |
from djpcms import sites
if sites.settings.CMS_ORM == 'django':
from djpcms.core.cmsmodels._django import *
elif sites.settings.CMS_ORM == 'stdnet':
from djpcms.core.cmsmodels._stdnet import *
else:
raise NotImpleme | ntedError('Objecr Relational Mapper {0} not available for CMS models'.format(sites.settings | .CMS_ORM)) |
import time
import arcpy
from arcpy import env
from arcpy.sa import *
# Set | environment settings
env.workspace = "" # set your workspace
arcpy.env.overwriteOutput = True
# Check out the ArcGIS Spatial Analyst extension license
arcpy.CheckOutExtension("Spa | tial")
tic = time.clock()
a_file = "random_a.tif"
b_file = "random_b.tif"
c_file = "random_c.tif"
out_file = "output.tif"
a = Raster(a_file)
b = Raster(b_file)
c = Raster(c_file)
out = 3 * a + b * c
out.save(out_file) |
# -*- coding: utf-8 -*-
"""
pygments.styles.vs
~~~~~~~~~~~~~~~~~~
Simple style with MS Visual Studio colors.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyword, Name, Co... | d: "#0000ff",
Operator.Word: "#0000ff",
Keyword.Type: "#2b91af",
Name.Class: "#2b91af",
String: "#a315 | 15",
Generic.Heading: "bold",
Generic.Subheading: "bold",
Generic.Emph: "italic",
Generic.Strong: "bold",
Generic.Prompt: "bold",
Error: "border:#FF0000"
}
|
# -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License... | 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. #
from org.o3pr... |
id)
return res
@api.multi
def _get_user_domain(self, dest_company):
self.ensure_one()
group_purchase_user = self.env.ref('purchase.group_purchase_user')
return [
('id', '!=', 1),
('company_id', '=', dest_company.id),
('id', 'in', group_purchas... | sale_line_data['value']['tax_id'] = ([
[6, 0, sale_line_data['value']['tax_id']]])
| sale_line_data['value']['auto_purchase_line_id'] = purchase_line.id
return sale_line_data['value']
@api.multi
def action_cancel(self):
|
#from: http://stackoverflow.com/questions/10361820/simple-twisted-echo-client
#and
#from: http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user
from twisted.internet.threads import deferToThread as _deferToThread
from twisted.int | ernet import reactor
class ConsoleInput(object):
def __init__(self, stopFunction, reconnec | tFunction):
self.stopFunction = stopFunction
self.reconnectFunction = reconnectFunction
def start(self):
self.terminator = 'q'
self.restart = 'r'
self.getKey = _Getch()
self.startReceiving()
def startReceiving(self, s = ''):
if s == self.terminator:
... |
# -*- coding: utf-8 -*-
import mock
from rest_framework import serializers
from waffle.testutils import override_switch
from olympia.amo.tests import (
BaseTestCase, addon_factory, collection_factory, TestCase, user_factory)
from olympia.bandwagon.models import CollectionAddon
from olympia.bandwagon.serializers im... | ctive=True)
@mock.patch('olympia.lib.akismet.models.AkismetReport.comment_check')
def test_ham(self, comment_check_mock):
comment_check_mock.return_value = AkismetReport.HAM
self.validator(self.data)
# Akismet check is there
assert AkismetReport.objects.count() == 2
nam... | assert name_report.comment_type == 'collection-name'
assert name_report.comment == self.data['name']['en-US']
summary_report = AkismetReport.objects.last()
# en-US description won't be there because it's an existing description
assert summary_report.comment_type == 'collection-descr... |
from dj | ango.conf.urls import include, url
urlpatterns = [
url(r' | ^avatar/', include('avatar.urls')),
]
|
import setuptools
setuptools.setup(
name="sirius",
version | ="0.5",
author="",
author_email="simon.pintarelli@cscs.ch",
description="pySIRIUS",
url="https://github.com/electronic_structure/SIRIUS",
packages=['sirius'],
install_requires=['mpi4py', 'voluptuous', 'numpy', 'h5py', 'scipy', 'PyYAML'],
class | ifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
)
|
from csacompendium.locations.models import Precipitation
from csacompendium.utils.pagination import APILimitOffsetPagination
from csacompendium.utils.permissions import IsOwnerOrReadOnly
from csacompendium.utils.viewsutils import DetailViewUpdateDelete, CreateAPIViewHook
from rest_framework.filters import DjangoFilterB... | _serializer['PrecipitationListSerializer']
filter_backends = (DjangoFilterBackend,)
filter_class = PrecipitationListFilter
pagination_class = APILimitOffsetPagination
class PrecipitationDetailAPIView(DetailViewUpdateDelete):
"""
Updates a record.
"""
queryset... | ation.objects.all()
serializer_class = precipitation_serializer['PrecipitationDetailSerializer']
permission_classes = [IsAuthenticated, IsAdminUser]
lookup_field = 'pk'
return {
'PrecipitationListAPIView': PrecipitationListAPIView,
'PrecipitationDetailAPIView': Precipitation... |
as submodule
elif args.command == 'numevents':
import numevents as submodule
elif args.command == 'events':
import get_events as submodule
elif args.command == 'staypos':
import staypos as submodule
elif args.command == 'info':
import info as submodule
elif args.comma... | ensive analysi | s)
20 = num skips in complement (is actually number 0 moves found in extensive analysis)
21 = num stays in template (is actually number 2 moves found in extensive analysis, any 3,4,5 moves not counted here)
22 = num stays in complement (is actually number 2 moves found in extensive analysis, any 3,4,5 moves not counted... |
LOG = logging.getLogger(__name__)
class CbBackup(base.RestoreRunner):
"""
Implementation of Restore Strategy for Couchbase.
"""
__strategy_name__ = 'cbbackup'
base_restore_cmd = 'sudo tar xpPf -'
def __init__(self, *args, **kwargs):
super(CbBackup, self).__init__(*args, **kwargs)
... | t_exist:
raise base.RestoreError("Failed to create bucket '%s' "
"within %s seconds"
% (bucket_name,
timeout_in_seconds))
# Quer... | while ((time.time() - start) <= timeout_in_seconds):
url = (system.COUCHBASE_REST_API +
'/pools/default/buckets/' +
bucket_name)
outfile = system.COUCHBASE_DUMP_DIR + '/' + bucket_name
... |
from __future__ import division
import numpy as np
from .._shared.utils import assert_nD
from . import _hoghistogram
def hog(image, orientations=9, pixels_per_cell=(8, 8),
cells_per_block=(3, 3), visualise=False, normalise=False):
"""Extract Histogram of Oriented Gradients (HOG) for a given image.
Co... | ns * np.pi)
dy_arr = radius * np.sin(orientations_arr / orientations * np.pi)
cr2 = cy + cy
cc2 = cx + cx
hog_image = np.zeros((sy, sx), dtype=float)
for x in range(n_cellsx):
for y in range(n_cellsy):
for o, dx, dy in zip(orientations_arr, dx_arr, dy_... | dx),
int(centre[1] + dy),
int(centre[0] + dx),
int(centre[1] - dy))
hog_image[rr, cc] += orientation_histogram[y, x, o]
"""
The fourth stage computes normalisation, which ta... |
# 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, software
# d... | CONDITIONS OF ANY KIND, | either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""oslo.i18n integration module.
See http://docs.openstack.org/developer/oslo.i18n/usage.html
"""
import oslo_i18n
_translators = oslo_i18n.TranslatorFactory(domain='murano')
# T... |
max_length=100,
unique=True)
title = models.CharField(_(u"title"),
| max_length=50)
logo = models.ImageField(_(u"Logo"),
upload_to='media_root',
# TEMP -> pbs with PIL...
blank=True)
ndds = models.ManyToManyField(Site,
related_na... | ner')
domain = models.ForeignKey(Site,
related_name="website_set",
unique=True,
on_delete=models.PROTECT,
help_text=_(u"Represents the main domain of the "
... |
tes_sec_max_length")
if params.get("read_bytes_sec_max_length"):
cmd += " --read-bytes-sec-max-length %s" % params.get("read_bytes_sec_max_length")
if params.get("write_bytes_sec_max_length"):
cmd += " --write-bytes-sec-max-length %s" % params.get("write_bytes_sec_max_length")
... | ndardized virsh function API keywords
:return: CmdResult instance
"""
cmd = "cpu-models %s %s" % (arch, options)
return command(cmd, **dargs)
def net_dhcp_leases(network, mac=None, options="", **dargs):
"""
Print lease info for a given network
:param network: Network name or uuid
:par... | s" % (network, options)
if mac:
cmd += " --mac %s" % mac
return command(cmd, **dargs)
def qemu_monitor_event(domain=None, event=None, event_timeout=None,
options="", **dargs):
"""
Listen for QEMU Monitor Events
:param domain: Domain name, id or UUID
:param event... |
# -*- coding: utf-8 -*-
#
# Author: François Rossigneux <francois.rossigneux@inria.fr>
#
# 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... | IS, 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 climate import tests
class DBUtilsTestCase(tests.TestCase):
"""Test case for DB Utils."""
| pass
|
#!/home/bolt/.python_compiled/bin/python3
import math
from PIL import Image
def complex_wrapper(func, scale_factor=1):
"""
Modifies a complex function that takes a complex
argument and returns a complex number to take a
tuple and return a tuple.
"""
def inner(real, imag):
complex_num=c... | if angle<=2/3*math.pi:
return (255-mixing, mixing, 0)
elif 2/3*math.pi<angle<=4/3*math.pi:
return (0, 255-mixing, mixing)
else:
return (mixing, 0, 255-mixing)
def color_intensity(position, radius, gradient):
"""
This fun | ction assigns an intensity based on the radial distance and the gradient
"""
x,y=position
shade_tuple=assign_color_shade(position)
if x**2+y**2<radius**2:
r,b,g=shade_tuple
ratio=((x**2+y**2)/(radius**2))**gradient
r_new,b_new,g_new=255-ratio*(255-r),255-ratio*(255-b),255-ratio*(... |
#!/usr/bin/env python
# -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; coding: utf-8 -*-
# vim: tabstop=4 softtabstop=4 expandtab shiftwidth=4 fileencoding=utf-8
#
# Shell command
# Copyright 2010, Jeremy Grosser <synack | @digg.com>
import argparse
import os
import sys
import clusto
from clusto import script_helper
class Console(script_helper.Script):
'''
Use clusto's hardware port mappings to console to a remote server
using the serial console.
'''
def __init__(self):
script_he | lper.Script.__init__(self)
def _add_arguments(self, parser):
user = os.environ.get('USER')
parser.add_argument('--user', '-u', default=user,
help='SSH User (you can also set this in clusto.conf too'
'in console.user: --user > clusto.conf:console.user > "%s")' % user)
... |
from datetime import datetime
#####################
# Account Test Data #
#####################
account = {
'name': 'Test Account Name',
'type': 'Checking',
'bank_name': 'Bank of Catonsville',
'account_num': '1234567890'
}
account_put = {
'name': 'Savings Account',
'type': 'Savings'
}
db_accou... | 'date': datetime(2014,8,1),
'type': 'EFT',
'payee': 'Costco',
'reconciled': 'R',
'amount': -123.45,
'memo': 'Test transaction memo',
'cat_or_acct_id': '2'
},
{
'id': '53f69e77137a001e344259c9',
'date': datetime(2014,8,6),
'type': 'EF... | unt': -40.92,
'memo': '',
'cat_or_acct_id': '2'
},
{
'id': '53f69e77137a001e344259ca',
'date': datetime(2014,8,18),
'type': 'DEP',
'payee': 'U.S. Government',
'reconciled': '',
'amount': 2649.52,
'memo': 'Kyle\'s Salary',
'cat_or_ac... |
# fabfile.py
# TODO - Description.
#
###########################################################################
##
## Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the Lice... | OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
############# | ##############################################################
from fabric.api import *
from textwrap import dedent, wrap
import io
import re
import pickle
import sys
import os
import yaml
script_dir = os.path.dirname(__file__)
with open(script_dir+"/config.yaml", "r") as f:
config = yaml.load(f)
if os.path.isfile(... |
# Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com>
#
# 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, ... | OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Contains data about certain markup, like HTML tags and external links.
When updating this file, please also update the the C tokeniz... | is_parsable",
"is_visible",
"is_single",
"is_single_only",
"is_scheme",
]
URI_SCHEMES = {
# [wikimedia/mediawiki.git]/includes/DefaultSettings.php @ 5c660de5d0
"bitcoin": False,
"ftp": True,
"ftps": True,
"geo": False,
"git": True,
"gopher": True,
"http": True,
"http... |
if __name__ == '__main__':
# We want to call _enable_attach inside an import to make sure that it works properly that way.
| import | _debugger_case_wait_for_attach_impl
|
# -*- codeing: utf-8 -*-
def bubble_sort(to_sort):
index = 0
while index < len(to_sort):
offset = index
while offset > 0 and to_sort[offset - 1] > to_sort[offset]:
temp = to_sort[offset]
to_sort[offset] = to_sort[offset - 1]
to_sort[offset - 1] = temp
... |
def test_sorts_2_1_3_list(self):
self.assertEqual([1, 2, 3], quick_sort([2, 1, 3]))
def test_sorts_1_3_2_list(self):
self.assertEqual([1, 2, 3], quick_sort([1, 3, 2]))
def test_sorts_3_2_1_list(self):
self.assertEqual([1, 2, 3], quick_sort([3, 2 | , 1]))
|
duplicados=[]
data = get_source(host)
data = scrapertools.find_single_match(data, 'data-toggle="dropdown">Géneros.*?multi-column-dropdown">.*?"clearfix"')
if 'Genero' in item.title:
patron = '<li><a href="([^"]+)">([^<]+)</a>'
matches = re.compile(patron, re.DOTALL).findall(data)
... |
patron='<a href="([^"]+)"><img class="thumb-item" src="([^"]+)" alt="[^"]+" >'
patron += '<div class="season-item">Temporada (\d+)</div>'
matches = re.compile(patron, re.DOTA | LL).findall(data)
infoLabels = item.infoLabels
for scrapedurl, scrapedthumbnail, season in matches:
infoLabels['season']=season
title = 'Temporada %s' % season
itemlist.append(Item(channel=item.channel, title=title, url=scrapedurl, action='episodesxseasons',
... |
string, returns "file", "template". If the string
is of the form "file" (without a template), returns "file", "file.in"."""
if ':' in s:
return s.split(':', 1)
return s, '%s.in' % s
def get_config_files(data):
config_status = mozpath.join(data['objdir'], 'config.status')
if not os.path.ex... | it ourselves.
command += ['--no-create']
print prefix_lines('configuring', relobjdir)
print prefix_lines('running %s' % ' '.join(command[:-1]), relobjdir)
sys.stdout.flush()
try:
output += subprocess.check_out | put(command,
stderr=subprocess.STDOUT, cwd=objdir, env=data['env'])
except subprocess.CalledProcessError as e:
return relobjdir, e.returncode, e.output
# Leave config.status with a new timestamp if configure is newer than
# its original mtime.
if config_statu... |
#!/usr/bin/env python
import glob
import os
import sys
import unittest
import common
if len(sys.argv) > 1:
builddir = sys.argv[1]
no_import_hooks = True
else:
builddir = '..'
no_import_hooks = False
common.run_import_tests(builddir, no_import_hooks)
SKIP_FILES = ['common', 'runtests']
dir = os.path.... | not in SKIP_FILES]
return files
suite = unittest.TestSuite()
loader = unittest.TestLoader()
for name in gettestnames():
suite.a | ddTest(loader.loadTestsFromName(name))
testRunner = unittest.TextTestRunner()
testRunner.run(suite)
|
# Kevin Nash (kjn33)
# EECS 293
# Assignment 12
from entity import Entity
from random import randint
class Passenger(Entity):
""" Entities that need to be checked in following queueing """
def __init__(self):
"""
Passengers follow Entity initialization,
are randomly given special par... | # 50% chance of being a frequent flyer
self.frequent = randint(1, 2) % 2 == 0
# 10% chance of having a given special condition
self.oversize = randint(1, 10) % 10 == 0
self.rerouted = randint(1, 10) % 10 == 0
self. | overbook = randint(1, 10) % 10 == 0
self.time = 2
self.calc_time()
def __str__(self):
""" Represent Passenger by name, ID, and flyer type """
flyer_type = "regular"
if self.frequent:
flyer_type = "frequent"
return "%s %d (%s)" % (self.__class__.__name__,... |
import pygame
pygame.init()
screen = pygame.display.s | et_mode((400, 300))
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.displa | y.flip()
|
from twisted.internet import protocol, reactor
class Echo(pro | tocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)
class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()
reactor.listenTCP(1234 | , EchoFactory())
reactor.run() |
#!/usr/bin/env python
'''em_dict_basic.py - Basic benchmark for external memory dictionary.'''
__author__ = 'huku <huku@grhack.net>'
imp | ort sys
import shutil
import random
import time
import util
import pyrsistence
def main(argv):
# Initialize new external memory dictionary.
util.msg('Populating external memory dictionary')
t1 = time.time()
dirname = util.make_temp_name('em_dict')
em_dict = pyrsisten | ce.EMDict(dirname)
for i in util.xrange(0x1000000):
em_dict[i] = i
t2 = time.time()
util.msg('Done in %d sec.' % (t2 - t1))
# Close and remove external memory dictionary from disk.
em_dict.close()
shutil.rmtree(dirname)
return 0
if __name__ == '__main__':
sys.exit(main(sys.a... |
# -*- coding: utf-8 -*-
# $Id$
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language... | list-table',
#'qa (translation required)': 'questions',
#'faq (translation required)': 'questions',
'meta (translation required)': 'meta',
'math (translation required)': 'math',
#'imagemap (translation required)': 'imagemap',
'image (translation required)': 'image',
'figure (tr... | 'replace (translation required)': 'replace',
'unicode (translation required)': 'unicode',
u'日期': 'date',
'class (translation required)': 'class',
'role (translation required)': 'role',
u'default-role (translation required)': 'default-role',
u'title (translation required)': 'titl... |
ame(u'digiapproval_message_last_read_by')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
| ('message', models.ForeignKey(orm[u'digiapproval.message'], null=False)),
('user', models.ForeignKey(orm[u'auth.user'], null=False))
))
db.create_unique(m2m_table_name, ['message_id', 'user_id'])
def backwards(self, orm):
# Removing M2M tabl | e for field last_read_by on 'Message'
db.delete_table(db.shorten_name(u'digiapproval_message_last_read_by'))
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django... |
# -*-coding:Utf-8 -*
# Copyright (c) 2013 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# lis... | tten permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR... | OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SU... |
# Copyright 2015 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
#
# Unless required by applicable law... | f
from neutron.agent.metadata import agent
from neutron.agent.metadata import config as metadata_conf
from neutron.common import config
from neutron.common import utils
from neutron.openstack.common.cache import cache
LOG = logging.getLogger(__name__)
def main():
cfg.CONF.register_opts(metadata_conf.UNIX_DOMAIN_... | etadata_conf.METADATA_PROXY_HANDLER_OPTS)
cache.register_oslo_configs(cfg.CONF)
cfg.CONF.set_default(name='cache_url', default='memory://?default_ttl=5')
agent_conf.register_agent_state_opts_helper(cfg.CONF)
config.init(sys.argv[1:])
config.setup_logging()
utils.log_opt_values(LOG)
# metadat... |
e is no datacenter defined.")
sys.exit(1)
self.logger.debug('Configuration seems sane.')
def _before_connect(self, url=None, rpc=None, routing_key=None):
pass
# same behaviour as masta
def _after_connect(self):
self.rpc.set_json_encoder(StorageJSONEncoder)
self.... | he id of the database entry.
:return: The data of the keystone entry with the given id, or an error code if not found.
"""
return 400
@Out("keystone_list", list)
def get_keystones(self):
"""
Get keystone entries contained in the database.
:return: A list of ke... | -------
# DATACENTERS
# Every datacenter has a respective set of keystone credentials and a region.
# Keystone does not have to be installed on the actual datacenter, but could.
# ----------------------------------------------------------
@In("datacenter", dict)
@Out("datacenter_id", int)
d... |
from neo.Storage.Common.DataCache import DataCache
class CloneCache(DataCache):
def __init_ | _(self, innerCache):
super(CloneCache, self).__init__()
self.innerCache = innerCache
def AddInternal(self, key, value):
self.innerCache.Add(key, value)
def DeleteInternal(self, key):
self.innerCache.Delete(key)
def FindInternal(self, key_prefix):
for k, v in self.i... | Cache[key].Clone()
def TryGetInternal(self, key):
res = self.innerCache.TryGet(key)
if res is None:
return None
else:
return res.Clone()
def UpdateInternal(self, key, value):
self.innerCache.GetAndChange(key).FromReplica(value)
|
#!/usr/bin/env python
#Copyright (c) 2010 Gerson Minichiello
#
#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 l | imitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or su... |
defined in
# absolute terms ex. miles/gallon for subsectors with inputs defined
# in energy service terms ex. kilometers to consistent efficiency
# units of energy_unit/service_demand_unit ex. gigajoule/kilometer
if eff_def == 'absolute' and sd_unit_type == 'service':
eff = u... | ck.techs.keys())]
setattr(self.stock, 'primary_efficiency_ID', primary_key)
setattr(self.stock, 'primary_efficiency_numerator_unit',
stock.techs[primary_key].clean_main_efficiency_numerator_unit)
setattr(self.stock, 'primary_efficiency_denominator_unit',
... | n ['main', 'aux']:
data = getattr(self.stock.techs[key],
'clean_%s_efficiency' % eff_type)
unit_from_denominator = getattr(self.stock.techs[key],
'clean_%s_efficiency_denominator_unit' % eff_ty... |
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | r.jpg',
retrain.get_image_path(image_lists, 'label_two', 1,
'image_dir', 'testing'))
def testGetBottleneckPath(self):
image_lists = self.dummyImageLists()
self.assertEqual('bottleneck_dir/somedir/image_five.jpg_imagenet_v3.txt',
| retrain.get_bottleneck_path(
image_lists, 'label_one', 0, 'bottleneck_dir',
'validation', 'imagenet_v3'))
def testShouldDistortImage(self):
self.assertEqual(False, retrain.should_distort_images(False, 0, 0, 0))
self.assertEqual(True, retrain.should_dist... |
#!/usr/bin/env python
# Shellscript to verify r.gwflow calculation, this calculation is based on
# the example at page 167 of the following book:
# author = "Kinzelbach, W. and Rausch, R.",
# title = "Grundwassermodellierung",
# publisher = "Gebr{\"u}der Borntraeger (Berlin, Stuttgart)",
# year = "1995"
#
import sys
im... | rass.run_command("r.mapcalc", expression="hydcond=0.001")
grass.run_command("r.mapcalc", expression="recharge=0.000000006")
grass.run_command("r.mapcalc", expression="top=20")
grass.run_command("r.mapcalc", expression="bottom=0")
grass.run_command("r.mapcalc", expression="syield=0.001")
grass.run_command("r.mapcalc", e... | head", \
status="status", hc_x="hydcond", hc_y="hydcond", s="syield", \
recharge="recharge", output="gwresult", dt=864000000000, type="unconfined", budget="water_budget")
|
""" Module summary:
Variables:
db | _session - A connection to the farmfinder database.
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from dbsetup import Base
############################################################################
# Connect to database and create database session:
engine = create_engine("sqlite... | b")
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
db_session = DBSession() |
import unittest
from cStringIO import StringIO
from ..backends import static
# There aren't many tests here because it turns out to be way more convenient to
# use test_serializer for the majority of cases
class TestStatic(unittest.TestCase):
def compile(self, input_text, input_data):
return static.com... | ldren[0]
| self.assertEquals(section.get("other_key"), "value_3")
def test_get_3(self):
data = """key:
if a == "1": value_1
if a[0] == "ab"[0]: value_2
"""
manifest = self.compile(data, {"a": "1"})
self.assertEquals(manifest.get("key"), "value_1")
manifest = self.compile(data, {"a":... |
#!/usr/bin/env python
# -*- coding:UTF-8
__author__ = 'shenshijun'
import copy
class Queue(object):
"""
使用Python的list快速实现一个队列
"""
def __init__(self, *arg):
super(Queue, self).__init__()
self.__queue = list(copy.copy(arg))
self.__size = len(self.__queue)
def enter(self, val... | _queue[0]
return value
def __len__(self):
return self.__size
def empty(self):
| return self.__size <= 0
def __str__(self):
return "".join(["Queue(list=", str(self.__queue), ",size=", str(self.__size)])
|
from distutils.core import setup
setup(
name = 'voxgenerator',
packages = ['voxgenerator',
'voxgenerator.core',
'voxgenerator.plugin',
'voxgenerator.pipeline',
'voxgenerator.generator',
'voxgenerator.service',
| 'voxgenerator.control'],
version = '1.0.3',
description = 'Vox generator',
url = 'https://github.com/benoitfragit/VOXGenerator/tree/master/voxgenerator',
author = 'Benoit Franquet',
author_email = 'benoitfraubunt | u@gmail.com',
scripts = ['run_voxgenerator.py', 'run_voxgenerator', 'run_voxgenerator_gui.py'],
keywords = ['voice', 'control', 'pocketsphinx'],
classifiers = ["Programming Language :: Python",
"Development Status :: 4 - Beta",
"Environment :: Other Environment"... |
'''
New Integration Test for migrate between clusters
@author: Legion
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.test_lib as test_lib
test_obj_dict = test_state.TestStateDict()
test_stub = test_lib.lib_get_test_stub()
data_migration = ... | ata_migration.create_vm()
data_migration.migrate_vm()
test_stub.migrate_vm_to_random_host(data_migration.vm)
data_migration.vm.check()
data_migration.vm.destroy()
test_util.test_pass('Migrate migrated VM Test Success')
#Will be called only if exception happens in test().
de | f error_cleanup():
if data_migration.vm:
try:
data_migration.vm.destroy()
except:
pass |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-25 00:10
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import filer.fields.file
class Migration(migrations.Migration):
initial = True
dependen... | ODEL),
]
operations = [
migrations.AddField(
model_name='revenueitem',
name='purchasedVoucher',
field=models.OneToOneField(blank=True, null=True, | on_delete=django.db.models.deletion.CASCADE, to='vouchers.Voucher', verbose_name='Purchased voucher/gift certificate'),
),
migrations.AddField(
model_name='revenueitem',
name='registration',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.del... |
"\{")
j.sal.fs.writeFile(filename=dest2, contents=content)
return dest2
def __s | tr__(self):
C = "<!-- toc -->\n"
C += "## %s\n\n" % self.location
C += "- % | s\n" % self.path
if self.properties != []:
C += "- Properties\n"
for prop in self.properties:
C += " - %s\n" % prop
C += "\n### Methods\n"
C += "\n"
if self.comments is not None:
C += "\n%s\n\n" % self.comments
keys = sorte... |
"""Tests `numpy_utils.py`."""
# Copyright (c) 2021 Aubrey Barnard.
#
# This is free, open software released under the MIT license. See
# `LICENSE` for details.
import random
import unittest
import numpy.random
from .. import numpy_utils
class NumpyAsStdlibPrngTest(unittest.TestCase):
def test_random_floats... | _utils.NumpyAsStdlibPrng(
numpy.random.default_rng(seed))
actual = [wrap_prng.random() for _ in range(n_samples)]
self.assertEqual(expected, actual)
class NumpyBitGeneratorTest(unittest.TestCase):
def test_random_floats(self):
seed = 0xdeadbeeffeedcafe
n_samples = 10
... | or(
numpy_utils.numpy_bit_generator(
random.Random(seed)))
actual = [new_prng.random() for _ in range(n_samples)]
self.assertEqual(expected, actual)
|
sg_helper.make_inbound("inbound")
yield self.worker_helper.dispatch_inbound(msg, 'foo')
self.assertEqual(msgs, [msg])
@inlineCallbacks
def test_set_default_endpoint_handler(self):
conn, consumer = yield self.mk_consumer(connector_name='foo')
consumer.unpause()
msgs = []
... | .append)
msg = self.msg_helper.make_inbound("inbound")
yield self.worker_helper.dispatch_inbound(msg, 'foo')
self.assertEqual(msgs, [msg])
@inlineCallbacks
def test_set_event_handler(self):
msgs = []
conn = yield self.mk_connector(connector_name='foo', setup=True)
... | conn.set_event_handler(msgs.append)
msg = self.msg_helper.make_ack()
yield self.worker_helper.dispatch_event(msg, 'foo')
self.assertEqual(msgs, [msg])
@inlineCallbacks
def test_set_default_event_handler(self):
msgs = []
conn = yield self.mk_connector(connector_na... |
from django.apps import AppConfig
class InvestmentsConfig(AppConfig):
name = 'charcoallog.investment | s'
def ready(self):
# using @receiver decorator
# do not op | timize import !!!
import charcoallog.investments.signals # noqa: F401
|
c_backlinks', 'action': 'store_const', 'const': 'entry',
'default': 'entry'}),
('Link from section headers to the top of the TOC.',
['--toc-top-backlinks'],
{'dest': 'toc_backlinks', 'action': 'store_const', 'const': 'top'}),
('Disable backlinks to the table of contents.... |
('Report system messages at or higher than <level>: "info" or "1", '
'"warning"/"2" (default), "error"/"3", "severe"/"4", "none"/"5"',
['--report', '-r'], {'choices': threshold_choices, 'default': 2,
'dest': 'report_level', 'metavar': '<level>',
... | 'dest': 'report_level'}),
('Report no system messages. (Same as "--report=5".)',
['--quiet', '-q'], {'action': 'store_const', 'const': 5,
'dest': 'report_level'}),
('Halt execution at system messages at or above <level>. '
... |
import os
from flask import Flask, render_template, request
from PIL import Image
import sys
import pyocr
import pyocr.builders
import re
import json
__author__ = 'K_K_N'
app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.a | bspath(__file__))
def ocr(image_file):
tools = pyocr.get_available_tools()
if len(tools) = | = 0:
print("No OCR tool found")
sys.exit(1)
# The tools are returned in the recommended order of usage
tool = tools[0]
#print("Will use tool '%s'" % (tool.get_name()))
# Ex: Will use tool 'libtesseract'
langs = tool.get_available_languages()
#print("Available languages: %s" % ",... |
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | ocation.invocation_link(
channel, 'nonexistent', None, {}, {})
invocation_link.start()
invocation_link.stop()
def _test_lonely_invocation_with_termination(self, termination):
test_operation_id = object()
test_group = 'test packag | e.Test Service'
test_method = 'test method'
invocation_link_mate = test_utilities.RecordingLink()
channel = _intermediary_low.Channel('nonexistent:54321', None)
invocation_link = invocation.invocation_link(
channel, 'nonexistent', None, {}, {})
invocation_link.join_link(invocation_link_mate... |
#!/usr/bin/env python
import numpy as np
import torch as th
from torchvision import datasets, transforms
from nnexp | import learn
if __name__ == '__ | main__':
dataset = datasets.MNIST('./data', train=True, download=True, transform=transforms.ToTensor())
learn('mnist_simple', dataset)
|
#!/usr/bin/env python
#########################################
# Installation module for arachni
#########################################
# AUTHOR OF MODULE NAME
AUTHOR="Nathan Underwood (sai nate)"
# DESCRIPTION OF THE MODULE
DESCR | IPTION="Website / webapp vulnerability scanner."
# INSTALLATION TYPE
# OPTIONS GIT, SVN, FILE, DOWNLOAD
I | NSTALL_TYPE="GIT"
#LOCATION OF THE FILE OR GIT / SVN REPOSITORY
REPOSITORY_LOCATION="https://github.com/Arachni/arachni.git"
# WHERE DO YOU WANT TO INSTALL IT
INSTALL_LOCATION="arachni"
# DEPENDS FOR DEBIAN INSTALLS
DEBIAN=""
#COMMANDS TO RUN AFTER
AFTER_COMMANDS=""
|
import os
__version__ = 'v0.0.7' # update also in setup.py
root_dir = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
info = {
"name": "NiLabels",
"version": __version__,
"description": "",
"repository": {
"type": "git",
"url":... | }
}
definition_template = """ A template is the average, computed with a chose protocol, of a series of images acquisition
of the same anatomy, or in genreral of different objects that share common features.
"""
definition_atlas = """ An atlas is the segmentation of the template, obtained avera... | tocol,
the series of segmentations corresponding to the series of images acquisition that generates the template.
"""
definition_label = """ A segmentation assigns each region a label, and labels
are represented as subset of voxel with the same positive integer value.
"""
nomenclature_conventions = """ pfi_xxx = path... |
from requests import post
import io
import base64
class ZivService(object):
def __init__(self, cnc_url, user=None, passwo | rd=None, sync=True):
self.cnc_url = cnc_url
self.sync = sync
self.auth = None
if | user and password:
self.auth = (user,password)
def send_cycle(self, filename, cycle_filedata):
"""Send a cycle file to the concentrator service
Keyword arguments:
filename -- the name of our file (doesn't matter)
cycle_filedata -- the file to send, encoded as a base64 ... |
from s | etuptools import setup
setup(
name='ipy',
packages=['ipy'],
include_package_data=True,
install_requires=[
'flask | '
],
)
|
#!/usr/bin | /env python
from setuptools import setup, Extension
setup(
name = "python-libmemcached",
version = "0.17.0",
description="python memcached client wrapped on libmemcached",
maintainer="subdragon",
maintainer_email="subdragon@gmail.com",
requires = ['pyrex'],
# This assumes that libmemcache i... | Extension('cmemcached', ['cmemcached.pyx'],
libraries=['memcached'],
)],
test_suite="cmemcached_test",
)
|
#-----------------------------------------------------------------------------
# Copyright (c) 2005-2016, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this s... | ------
# The 'sysconfig' module requires Makefile and pyconfig.h files from
# Python installation. 'sysconfig' parses these files to get some
# information from them.
# TODO Verify that bundling Makefile and pyconfi | g.h is still required for Python 3.
import sysconfig
import os
from PyInstaller.utils.hooks import relpath_to_config_or_make
_CONFIG_H = sysconfig.get_config_h_filename()
if hasattr(sysconfig, 'get_makefile_filename'):
# sysconfig.get_makefile_filename is missing in Python < 2.7.9
_MAKEFILE = sysconfig.get_m... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..model import Level1Design
def test_Level1Design_inputs():
input_map = dict(bases=dict(mandatory=True,
),
| contrasts=dict(),
ignore_exception=dict(nohash=True,
usedefault=True,
),
interscan_interval=dict(mandatory=True,
),
model_serial_correlations=dict(mandatory=True,
),
orthogonalization=dict(),
session_info=dict(mandatory=True,
),
)
inputs = Level1Design.input_spec()
... | assert getattr(inputs.traits()[key], metakey) == value
def test_Level1Design_outputs():
output_map = dict(ev_files=dict(),
fsf_files=dict(),
)
outputs = Level1Design.output_spec()
for key, metadata in list(output_map.items()):
for metakey, value in list(metadata.items()):
... |
#!/usr/bin/env python
import sys, json, psycopg2, argparse
parser = argparse.ArgumentParser(description='Imports word data into the taboo database.')
parser.add_argument('--verified', dest='verified', action='store_true', help='include if these words are verified as good quality')
parser.add_argument('--source', dest=... | or()
count = 0
for word in data:
try:
cur.execute("INSERT INTO words (word, skipped, correct, status, source) VALUES(%s, %s, %s, %s, %s) RETURNING wid",
(word, 0, 0, 'approved' if args.verified == True else 'unverified', args.source))
wordid = cur.fetchone()[0]
prohibited_cou... | d_count + 1
cur.execute("INSERT INTO prohibited_words (wid, word, rank) VALUES(%s, %s, %s)",
(wordid, prohibited, prohibited_count))
count = count + 1
except Exception as e:
print e
cur.close()
conn.close()
print 'Inserted ' + str(count) + ' words'
|
import psidialogs
s = psidial | ogs.choice(["1", "2", "3"], "Choo | se a number!")
if s is not None:
print(s)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2010 Jérémie DECOCK (http://www.jdhp.org)
import numpy as np
from pyarm import fig
class MuscleModel:
"Muscle model."
# CONSTANTS ###############################################################
name = 'Fake'
##################################################... | lder +', 'shoulder -',
# 'elbow +', 'elbow -'))
def compute_torque(self, angles, velocities, command):
"Compute the torque"
torque = np.zeros(2)
if len(command) > 2:
torque[0] = (command[0] - command[1])
torque[1] = (command[2] - command[3]... | torque = np.array(command)
fig.append('command', command[0:2])
return torque
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import bs4
import json
import re
def xml2json(s):
global timestamp
timestamp = 0
s = s.replace(u'\xa0', u' ')
soup = bs4.BeautifulSoup(s, features="lxml")
interventi | on_vierge = {"intervenant": "", "contexte": ""}
intervention_vierge["source"] = "https://www.assemblee-nationale.fr/dyn/15/comptes-rendus/seance/"+soup.uid.string
m = soup.metadonnees
dateseance = str(m.dateseance.string)
intervention_vierge["date"] = "%04d-%02d-%02d" % (int(dateseance[0:4]), int(dates... | intervention_vierge["heure"] = "%02d:%02d" % (int(dateseance[8:10]), int(dateseance[10:12]))
intervention_vierge["session"] = str(m.session.string)[-9:].replace('-', '')
contextes = ['']
numeros_lois = None
intervenant2fonction = {}
last_titre = ''
for p in soup.find_all(['paragraphe', 'point']... |
self.norm) for v in self.variables]
def reverse_normalize(self, variables, with_offset=True):
# ensures numpy array
out = np.empty_like(variables)
for i, v in enumerate(variables):
out[i] = self.variables[i].reverse_normalize(v, self.norm, with_offset=with_offset)
return... |
This is a wrapper which does 3 things:
1. Convert input values from normalized to regular values
2. Update internal variables with the value currently being
runned.
3. Check if the values have already been calc | ulated, if so
return the metric directly from the stored table.
4. Else, calculate the metric using the ``self.__call__``
5. Append values to the data and hash it.
Parameters
----------
norm_variables : array_like
normed variables to be minimized
*a... |
# 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, software
# distributed under th... | if version == 4:
iptables = "iptables"
elif version == 6:
iptables = "ip6tables"
else:
raise RuntimeError("Invalid version: %s" % version)
if self._has_w_argument is False:
return iptables
else:
return "{} -w 90".format(i... | (version), cmd)
if self._has_w_argument is None:
result = self.run_expect([0, 2], ipt_cmd, *args)
if result.rc == 2:
self._has_w_argument = False
return self._run_iptables(version, cmd, *args)
else:
self._has_w_argument = True
... |
he effect of uploading to an existing blob depends on the
"versioning" and "lifecycle" policies defined on the blob's
bucket. In the absence of those policies, upload will
overwrite any existing contents.
See the `object versioning
<https://cloud.google.com/stora... | """Retrieve the ETag for the object.
See: http://tools.ietf.org/html/rfc2616#section-3.11 and
https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: string or ``NoneType``
:returns: The blob etag or ``None`` if the property is not set locally.
"""
retur... | g')
@property
def generation(self):
"""Retrieve the generation for the object.
See: https://cloud.google.com/storage/docs/json_api/v1/objects
:rtype: integer or ``NoneType``
:returns: The generation of the blob or ``None`` if the property
is not set locally.
... |
#!/usr/bin/env python
# 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
#
# Authors:
# - Mario Lassnig, mario.lassnig@cern.ch, 2016-2017
# - Daniel Dr... | %(asctime)s | %(levelname)-8s | %(message)s'))
logging.getLogger('').addHandler(console)
trace = main()
logging.shutdown()
if not trace:
logging.getLo | gger(__name__).critical('pilot startup did not succeed -- aborting')
sys.exit(FAILURE)
elif trace.pilot['nr_jobs'] > 0:
sys.exit(SUCCESS)
else:
sys.exit(ERRNO_NOJOBS)
|
"""Colle | ction of helpers | for online deployment."""
|
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..brainsresample import BRAINSResample
def test_BRAINSResample_inputs():
input_map = dict(args=dict(argstr='%s',
),
defaultValue=dict(argstr='--defaultVa | lue %f',
),
deformationVolume=dict(argstr='--deformationVolume %s',
),
environ=dict(nohash=True,
usedefault=True,
),
gridSpacing=dict(argstr='--gridSpacing %s',
sep=',',
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
inputVolume=dict(argstr='--inputVolume %... | rseTransform ',
),
numberOfThreads=dict(argstr='--numberOfThreads %d',
),
outputVolume=dict(argstr='--outputVolume %s',
hash_files=False,
),
pixelType=dict(argstr='--pixelType %s',
),
referenceVolume=dict(argstr='--referenceVolume %s',
),
terminal_output=dict(deprecated='1.0.... |
astores": [component_generator(
"datastores", source_provider, provider,
get_data(source_provider, "datastores", "nfs").type,
get_data(provider, "datastores", "nfs").type)],
"networks": [
component_generator("vlans", source_provider, provider,
... | est.param[1][1]
),
],
},
)
vm_obj = get_vm(request, appliance, source_provider, request.param[2])
return FormDataVmObj(in | fra_mapping_data=infra_mapping_data, vm_list=[vm_obj])
@pytest.fixture(scope="function")
def mapping_data_vm_obj_single_datastore(request, appliance, source_provider, provider):
"""Return Infra Mapping form data and vm object"""
infra_mapping_data = infra_mapping_default_data(source_provider, provider)
re... |
import process_common as pc
import process_operations as po
import module_dialogs
import module_info
from header_dialogs import *
start_states = []
end_states = []
def compile_dialog_states(processor, dialog_file):
global start_states
global end_states
unique_state_list = ["start", "party_encounter", "prisoner_... | get_dialog_name(start_state, end_state, text):
global dialog_names
name = "dlga_%s:%s" % (pc.convert_to_identifier(start_state), pc.convert_to_ident | ifier(end_state))
text_list = dialog_names.setdefault(name, [])
for i, existing_text in enumerate(text_list):
if text == existing_text:
name = "%s.%d" % (name, i + 1)
break
else:
text_list.append(text)
return name
def process_entry(processor, txt_file, entry, index):
name = get_dialog_nam... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin | g, 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 apache_beam as beam
import logging
from typing import Dict, Any, List
from uploaders.google_ads.customer_match.abstract_uploader import GoogleAdsCustomerMatchAbstractUploaderDoFn
from uploaders import utils
from models.execution import DestinationType, AccountConfig
class GoogleAdsCustomerMatchContactInfo... |
import unittest
import urllib
import logging
from google.appengine.ext import testbed
from google.appengine.api import urlfetch
from conference import ConferenceApi
from models import ConferenceForm
from models import ConferenceForms
from models import ConferenceQueryForm
from models import ConferenceQueryForms
from p... | logging.DEBUG)
tb = testbed.Testbed()
tb.setup_env(current_version_id='testbed.version')
tb.activate()
self.testbed = init_stubs(tb)
def testUrlfetch(self):
# response = urlfetch.fetch('http://www.google | .com')
url = 'http://localhost:9000/_ah/api/conference/v1/conference'
# form_fields = {
# "name": "Albert"
# }
form_fields = ConferenceForm(name='steven')
form_data = protojson.encode_message(form_fields)
# form_data = urllib.urlencode(form_fields)
res... |
import os
import unittest
from vsg.rules import architecture
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_016_test_input.vhd'))
lExpected_require_blank = []
lExpected_require_blank.append('')
utils.... | l(oRule.violations, [])
def test_rule_016_no_blank(self):
oRule = architecture.rule_016()
oRule.style = 'no_blank_line'
lExpected = [23]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def te... |
lActual = self.oFile.get_lines()
self.assertEqual(lExpected_no_blank, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
|
):
""" Decode the KoradSerial status byte.
It appears that the firmware is a little wonky here.
SOURCE:
Taken from http://www.eevblog.com/forum/testgear/korad-ka3005p-io-commands/
Contents 8 bits in the following format
Bit Item Description
0 CH1 0=CC mod... | t, 9600, timeout=1)
def read_character(self):
c = self.port.read(1).decode('ascii')
if self.debug:
if len(c) > 0:
print("read: {0} = '{1}'".format(ord(c), c))
else:
print("read: timeout")
return c
... | terminated strings.
:return: str
"""
result = []
c = self.read_character()
while len(c) > 0 and ord(c) != 0:
result.append(c)
if fixed_length is not None and len(result) == fixed_length:
break
... |
#!/usr/bin/env pyth | on
import os, sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "conext.settings")
from django.core.management import execute_from_command_line
| import conext.startup as startup
startup.run()
execute_from_command_line(sys.argv)
pass
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# health.py file is part of slpkg.
# Copyright 2014-2021 Dimitris Zlatanidis <d.zlatanidis@gmail.com>
# All rights reserved.
# Slpkg is a user-friendly package manager for Slackware installations
# https://gitlab.com/dslackw/slpkg
# Slpkg is free software: you can redistr... | not line.startswith("dev/") and
not line.startswith("install/") and
"/incoming/" not in line):
if not os. | path.isfile(r"/" + line):
self.cn += 1
print(f"Not installed: {self.red}/{line}{self.endc} --> {pkg}")
elif not self.mode:
print(line)
except IOError:
print()
raise SystemExit()
def test(self):
"""Ge... |
# -*- coding: utf-8 -*-
"""Module to daemonize the current process on Unix."""
#
# (C) Pywikibot team, 2007-2015
#
# Distributed under the terms of the MIT license.
#
from __future__ import absolute_import, unicode_literals
__version__ = '$Id$'
import codecs
import os
import sys
is_daemon = False
def daemonize(cl... | os.dup2(0, 1)
os.dup2(1, 2)
if chdir:
os.chdir('/')
return
else:
| # Write out the pid
path = os.path.basename(sys.argv[0]) + '.pid'
with codecs.open(path, 'w', 'utf-8') as f:
f.write(str(pid))
os._exit(0)
else:
# Exit to return control to the terminal
# os._exit to prevent the cleanup to run
os._exit(0... |
fr | om .tobii_pro_wrapper import *
| |
radm.URL_LOGIN,
auth=(user.name, user.pwd))
assert r.status_code == 200
utoken = r.text
# test cases
for status, page, per_page in [
(None, None, None),
('pending', None, None),
('accepted', None, None),
... | ICE,
path_params={'id': dev_pending.id})
assert r.status_code == 404
# log in an accepted device
dev_acc = filter_and_page_devs(devs_authsets, status='accepted')[0]
body, sighdr = deviceauth_v1.auth_req( | dev_acc.id_data,
dev_acc.authsets[0].pubkey,
dev_acc.authsets[0].privkey,
tenant_token)
r = devapid.call('POST',
deviceauth_v1.URL_AUTH_REQS,
... |
#!/home/mjwtom/install/pyt | hon/bin/python
# -*- coding: utf-8 -*-
import os
import subprocess
from nodes import storage_nodes as ips
def generate_rings():
print (os.environ["PATH"])
os.environ["PATH"] = '/home/mjwtom/install/python/bin' + ":" + os.env | iron["PATH"]
print (os.environ["PATH"])
dev = 'sdb1'
ETC_SWIFT='/etc/swift'
if not os.path.exists(ETC_SWIFT):
os.makedirs(ETC_SWIFT)
if os.path.exists(ETC_SWIFT+'/backups'):
cmd = ['rm',
'-rf',
'%s/backups' % ETC_SWIFT]
subprocess.call(cmd)
p... |
x)
self._Az = np.empty_like(self._Ax)
if 'hMTF' in self.compute:
self._hMTF = (np.empty(2 * int(self.counts[self.rank]), dtype=np.float32).
reshape(2, int(self.counts[self.rank] / self.Nx), int(self.Nx)))
self.dt = dt
self.t_l_last = -1.
... | Dy_f = None
Dz_f = None
if 'Diff' in self.compute:
Diffx_f = None
Diffy_f = None
if 'Diff2' in self.compute:
Diffxx_f = None
Diffyy_f = None
... | Vx_f = None
Vy_f = None
Vz_f = None
if 'A' in self.compute:
Ax_f = None
Ay_f = None
Az_f = None
if 'hMTF' in self.compute:
hMTF_f = None... |
from unittest import TestCase
from settings import settings
from office365.outlookservices.outlook_client import OutlookClient
from office365.runtime.auth.authentication_context import AuthenticationContext
class OutlookClientTestCase(TestCase):
"""SharePoint specific test case base class"""
@classmethod
... | API v1.0 BasicAuth Deprecation
# (refer https://developer.microsoft.com/en-us/office/blogs/outlook-rest-api-v1-0-basicauth-deprecation/)
# NetworkCredentialContext class should be no longer utilized
# ctx_auth = NetworkCredentialContext(username=settings['user_credentials']['username'] | ,
# password=settings['user_credentials']['password'])
ctx_auth = AuthenticationContext(url=settings['tenant'])
ctx_auth.acquire_token_password_grant(client_credentials=settings['client_credentials'],
user_credentia... |
from django.db import models
from django.utils import timezone
class ReceiveAddress(models.Model):
address = models.CharField(max_length=128, blank=True)
available = models.BooleanField(default=True)
@classmethod
def newAddress(cls, address):
receive_address = cls()
receive_address.add... | us = MoneySent.CREATED
money_sent.creationDate = timezone.now()
money_sent.lastChangeDate = money_sent.creationDate
| return money_sent
def touch(self):
self.lastChangeDate = timezone.now()
def sent(self, transaction_hash):
self.status = MoneySent.SENT
self.transaction_hash = transaction_hash
self.touch()
self.save()
def confirm_ipn(self):
if self.status == MoneySent.CR... |
pos = [randint(-c_w, w - c_w), randint(-c_h, h - c_h)]
vel = [vx * random0(), vy * random0()]
cs.append((pos, vel, s))
elif cp is not None:
self.current_cp = cp
data = conf.LEVELS[ID]
# background
self.bgs = data.get('bgs', conf.DEF... | ng:
r_x0, r_y0, w, | h = r
r_x1, r_y1 = r_x0 + w, r_y0 + h
p_x0, p_y0, w, h = p
p_x1, p_y1 = p_x0 + w, p_y0 + h
x, dirn = min((p_x1 - r_x0, 0), (p_y1 - r_y0, 1),
(r_x1 - p_x0, 2), (r_y1 - p_y0, 3))
axes.add(dirn % 2)
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.