prefix
stringlengths
0
918k
middle
stringlengths
0
812k
suffix
stringlengths
0
962k
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from resources.datatables import FactionStatus from java.util import Vector def addTemplate(cor...
) templates.add('object/mobile/shared_battle_droid.iff') mobileTemplate.setTemplates(templates) weaponTemplates = Vector() weapontemplate = WeaponTemplate('object/weapon/ranged/carbine/shared_carbine_e5.iff', WeaponType.CARBINE, 1.0, 15, 'energy') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemp...
ponTemplates) attacks = Vector() mobileTemplate.setDefaultAttack('rangedShot') mobileTemplate.setAttacks(attacks) core.spawnService.addMobileTemplate('battle_droid_rebel', mobileTemplate) return
raise errors.AnsibleError("expected current_args to be a basestring") # we use parse_kv to split up the current args into a dictionary final_args = parse_kv(current_a
rgs) if isinstance(new_args, dict): final_args.update(new_args) elif isinstance(new_args, basestring): new_args_kv = parse_kv(
new_args) final_args.update(new_args_kv) return serialize_args(final_args) def parse_yaml(data, path_hint=None): ''' convert a yaml string to a data structure. Also supports JSON, ssssssh!!!''' stripped_data = data.lstrip() loaded = None if stripped_data.startswith("{") or stripped_data.s...
er events connected to milestones - :clipboard: - all other events connected to tasks - :bulb: - all other events connected to issues *Text formatting*: if there has been a change of a property, the new value should always be in bold; otherwise the subject of US/task should be in bold. """ from __future__ import abso...
ject)s**.', 'set_milestone': u':calendar: %(user)s added user story **%(subject)s** to sprint %(new)s.', 'unset_milestone': u':calendar: %(user)s removed user story **%(subject)s** fro
m sprint %(old)s.', 'changed_milestone': u':calendar: %(user)s changed sprint of user story **%(subject)s** from %(old)s' ' to %(new)s.', 'changed_status': u':chart_with_upwards_trend: %(user)s changed status of user story **%(subject)s**' ' from %(old)s to %(new)s.', 'closed': u...
from __future__ import absolute_import from __future__ import unicode_literals NAMES = [ 'grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' ] def get_pairs(): for i, name in enumerate(NAMES): yield(name, str(30 + i)) yield('intense_' + name, str(30...
for (name, code) in get_pairs(): globals()[name] = make_color_fn(code) def rainbow(): cs = ['cyan', 'yellow', 'green', 'magenta', 'red', 'blue',
'intense_cyan', 'intense_yellow', 'intense_green', 'intense_magenta', 'intense_red', 'intense_blue'] for c in cs: yield globals()[c]
ses for Omnivor input file Copyright (C) 2013 DTU Wind Energy Author: Emmanuel Branlard Email: ebra@dtu.dk Last revision: 25/11/2013 Namelist IO: badis functions to read and parse a fortran file into python dictonary and write it back to a file The parser was adapted from: fortran-namelist on code.google with the f...
?[0-9]+)?\.)?[0-9]*([eE][-+]?[0-9]+)?') valueBool = re.compile(r"(\.(true|false|t|f)\.)",re.I) valueTrue = re.compile(r"(\.(true|t)\.)",re.I) spaces = r'[
\s\t]*' quote = re.compile(r"[\s\t]*[\'\"]") namelistname = re.compile(r"^[\s\t]*&(" + varname + r")[\s\t]*$") paramname = re.compile(r"[\s\t]*(" + varname+r')[\s\t]*=[\s\t]*') namlistend = re.compile(r"^" + spaces + r"/" + spaces + r"$") #split sections/namelists mynml...
"""Test the National Weather Service (NWS) config flow.""" from unittest.mock import patch import aiohttp from homeassistant import config_entries from homeassistant.components.nws.const import DOMAIN async def test_form(hass, mock_simple_nws_config): """Test we get the form.""" hass.config.latitude = 35 ...
nws_config): """Test we handle cannot connect error.""" mock_instance = mock_simple_nws_config.return_value mock_instance.set_station.side_effect = aiohttp.ClientError result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) result2 =...
hass.config_entries.flow.async_configure( result["flow_id"], {"api_key": "test"}, ) assert result2["type"] == "form" assert result2["errors"] == {"base": "cannot_connect"} async def test_form_unknown_error(hass, mock_simple_nws_config): """Test we handle unknown error.""" mock_in...
def f(x=2): return x lis = [1] dic = { "x": 2 } f(1) # call_function f(*lis) # call_function_var f(**dic) # call_function_kw f(*[], **dic) # call_function_var_kw class C(object): # call_function def __enter__(self): x = 1 return x def __exit__(self, *args, **kwargs): ...
1 = fn_dec("1") @fn_dec("2") # call_function @dec1 # call_function def fw(x): return x @fn_dec("2"
) # call_function @dec1 # call_function class D(object): pass [a for a in lis] # nothing {a for a in lis} # call_function {a: a for a in lis} # call_function f(a for a in lis) # call_function gen, call_function with C() as r: # WITH_CLEANUP pass assert True # nothing assert True, "wat" # call_functi...
# ------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additi
onal 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...
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. # # ---------------------------------------------...
"""Provides some useful utilities for the Discord bot, mostly to do with cleaning.""" import re import discord __all__ = ['clean', 'is_clean'] mass_mention = re.compile('@(everyone|here)') member_mention = re.compile(r'<@\!?(\d+)>') role_mention = re.compile(r'<@&(\d+)>') channel_mention = re.compile(r'<#(\d+)>') ...
*, mass=True, member=True, role=True, channel=True): """Cleans the message of anything specified in the parameters passed.""" if text is None: text = ctx.message.content if ma
ss: cleaned_text = mass_mention.sub(lambda match: '@\N{ZERO WIDTH SPACE}' + match.group(1), text) if member: cleaned_text = member_mention.sub(lambda match: clean_member_name(ctx, int(match.group(1))), cleaned_text) if role: cleaned_text = role_mention.sub(lambda match: clean_role_name(c...
from lib.base import BaseJiraAction __all__ = [ 'Transiti
onJiraIssueAction' ] class TransitionJiraIssueAction(BaseJiraAction): def run(self, issue_key, transition): resul
t = self._client.transition_issue(issue_key, transition) return result
## Need to fin
d a libr
ary
# Copyright (c) 2007, Simon Edwards <simon@simonzone.com> # Copyright (c) 2014, Raphael Kubo da Costa <rakuco@FreeBSD.org> # Redistribution and use is allowed according to the terms of the BSD license. # For details see the accompanying COPYING-CMAKE-SCRIPTS file. import PyQt4.QtCore import os import sys def get_defa...
= True elif in_t: if item.startswith('Qt_4'): return item else: in_t = False raise ValueError('Cannot find Qt\'s tag in PyQt4\'s SIP flags.') if __name__ == '__main__': try: import PyQt4.pyqtconfig pyqtcfg = PyQt4.pyqtconfig.Configuration(...
qtcfg.pyqt_sip_flags except ImportError: # PyQt4 >= 4.10.0 was built with configure-ng.py instead of # configure.py, so pyqtconfig.py is not installed. sip_dir = get_default_sip_dir() sip_flags = PyQt4.QtCore.PYQT_CONFIGURATION['sip_flags'] print('pyqt_version:%06.x' % PyQt4.QtC...
py import deepcopy from numbers import Real, Integral import warnings from xml.etree import ElementTree as ET import sys if sys.version_info[0] >= 3: basestring = str import openmc from openmc.checkvalue import check_type, check_value, check_greater_than from openmc.clean_xml import * # A list of all IDs for all...
cent, percent_type='ao'): """Add a nuclide to the material Parameters ---------- nuclide : str or openmc.nuclide.Nuclide Nuclide to add percent : float Atom or weight percent percent_type : str 'ao' for atom percent and 'wo' for weight...
msg = 'Unable to add a Nuclide to Material ID={0} with a ' \ 'non-Nuclide value {1}'.format(self._id, nuclide) raise ValueError(msg) elif not isinstance(percent, Real): msg = 'Unable to add a Nuclide to Material ID={0} with a ' \ 'non-floating poi...
def get_mcrouter(self): return self.add_mcrouter(self.config, extra_args=self.extra_args) def test_dev_null(self): mcr = self.get_mcrouter() # finally setup is done mcr.set("good:key", "should_be_set") mcr.set("key", "should_be_set_wild") mcr.set("null:key", "sho...
ake sure all ops go to
# the old host only self.assertEqual(mcr.get("get-key-1"), str(1)) mcr.set("set-key-1", str(42)) self.assertEqual(self.wild_old.get("set-key-1"), str(42)) self.assertEqual(self.wild_new.get("set-key-1"), None) mcr.delete("get-key-1") #make sure the delete went to ...
"opus_core.bhhh_mnl_estimation", "sampler":"opus_core.samplers.weighted_sampler", "sample_size_locations":30, "weights_for_estimation_string":"urbansim.zone.number_of_non_home_based_jobs", "compute_capacity_flag":True, ...
d_worker_without_workplace_zone'", "data_objects": "datasets", "chunk_specification":"{'records_per
_chunk':5000}", "debuglevel": run_configuration['debuglevel'] } }, "prepare_for_estimate": { "name": "prepare_for_estimate", "arguments": { "agent_set":"person", "join_datasets": "False", "agent...
############################################################################ # Copyright (C) Internet Systems Consortium, Inc. ("ISC") # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, you can obtain one at https://mozil...
td_theme' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] latex_engine = 'xelatex' latex_elements = { ...
CN Medium:style=Medium,Regular} \setmonofont{Source Han Sans CN:style=Regular} \setCJKfamilyfont{song}{Source Han Serif CN:style=Regular} \setCJKfamilyfont{heiti}{Source Han Sans CN:style=Regular} ''', 'pointsize': '11pt', 'preamble': r'\input{../mystyle.tex.txt}' } latex_documents = [ (master_do...
from RGT.XML.SVG.basicSvgNode import BasicSvgNode from RGT.XML.SVG.Attribs.conditionalProcessingAttributes import ConditionalProcessingAttributes from RGT.XML.SVG.Attribs.xlinkAttributes import XlinkAttributes from RGT.XML.SVG.Attribs.animationTimingAttributes import AnimationTimingAttributes class BaseAnimatio...
se ValueError('Value not allowed, only ' + values + 'are allowed') else: self._setNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED, data) def getExternalResourcesRequired(self): node = self._getNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED
) if node is not None: return node.nodeValue return None
# -*- coding: utf-8 -*- """ Created on Fri Dec 11 11:34:27 2015 @author: JonasAdler """ # Imports for common Python 2/3 codebase from __future__ import print_function, division, absolute_import from future import standard_library standard_library.install_aliases() # External import numpy as np # Internal import odl...
ufunc.add(-1.0/la). ufunc.maximum(0.0)) b = b + Phi(x) - d fig = x.show(clim=[0.0, 1.1], fig=fig, show=True) n = 100 # Create spaces d = odl.uniform_discr([0, 0], [1, 1], [n, n]) ran =
odl.uniform_discr([0, 0], [1, np.pi], [np.ceil(np.sqrt(2) * n), n]) # Create phantom phantom = odl.util.shepp_logan(d, modified=True) # These are tuing parameters in the algorithm la = 500. / n # Relaxation mu = 20000. / n # Data fidelity # Create projector Phi = odl.trafos.WaveletTransform(d, nscales=3, wbasis='...
import re class CommandError(Exception): pass class BaseCommand(): """ Base command, this will accept and handle some generic features of all commands. Like error handling, argument retrieving / checking """ def __init__(self, args): """ Initialize the class """ ...
eve a set of argument """ if keys: return [self.arg(k) for k in keys] else: return self._args def value(self, key): """ Retrieve a single argument """ key = '<{0}>'.format(key) return self.arg(key) def option(self, key, va...
args_context(self): """ Convert all options and values into a context usable by the template parser """ context = dict(options={}, values={}) for key, value in self.args().items(): expressions = { 'options': r'--(.*)', 'values': r'<(....
""" Configuration for a project. """ rails = { 'models.engine': 'sql
alchemy', 'models.db.type': 'postgres', 'models.db.user': 'rails', 'models.db.password': 'rails',
'views.engine': 'jinja', }
import sys from contextlib import contextmanager from StringIO i
mport StringIO @contextmanager def string_stdout(): output
= StringIO() sys.stdout = output yield output sys.stdout = sys.__stdout__
########################################################################## #This file is part of WTFramework. # # WTFramework 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 L...
h multiple configs loads the config preferences in order. ''' config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertEqual("hello", config.get("setting_from_config1")) # this will take the config from config2, which has...
om_config2")) def test_get_with_missing_key_and_no_default(self): "An error should be thrown if the key is missing and no default provided." config = ConfigReader("tests/TestConfig2;tests/TestConfig1") # should take config from config1 self.assertRaises(KeyError, config.get, "setti...
# -*- coding: utf-8 -*- import os.path import wx from outwiker.core.system import getImagesDir class SearchReplacePanel (wx.Panel): def __init__(self, parent): super(SearchReplacePanel, self).__init__( parent, style=wx.TAB_TRAVERSAL | wx.RAISED_BORDER) self._controller =...
Replace with: ")) # Кнопка "Заменить" self._replaceBtn = wx.Button(self, -1, _(u"Replace")) # Кнопка "Заменить все" self._replaceAllBtn = wx.Button(self, -1, _
(u"Replace All")) self._closeBtn = wx.BitmapButton( self, -1, wx.Bitmap(os.path.join(getImagesDir(), "close-button.png"), wx.BITMAP_TYPE_ANY)) self._layout() def _layout(self): self._mainSizer = wx.FlexGridSizer(cols=6) sel...
""" Contains methods for working with the Lakeshore 475 Gaussmeter """ from quantities import Quantity from typing import Optional from instruments.lakeshore import Lakeshore475 as _Lakeshore475 from time import sleep class Lakeshore475(object): """ Adapter layer for IK's Lakeshore 475 implementation """ ...
sleep(1) return self._managed_instance @property def field(self) -> Quantity: """ :return: The measured magnetic field from the Gaussmeter """ try: return self._magnetometer.field except ValueError: return -100000.0 * self._m...
ntity
../../../../../../../share/py
shared/orca/scripts/apps/packagemanager/script
_settings.py
quota_project_id, client_info=client_info, always_use_jwt_access=True, ) def delete_unary( self, request: Union[compute.DeleteTargetTcpProxyRequest, dict] = None, *, project: str = None, target_tcp_proxy: str = None, retry:...
\* [Global](/compute/docs/reference/rest/v1/globalOperations) \* [Regional](/compute/docs/reference/rest/v1/regionOperations) \* [Zonal](/compute/docs/reference/rest/v1/zoneOperations) You can use an operation resource to ma...
gional or zonal. - For global operations, use the globalOperations resource. - For regional operations, use the regionOperations resource. - For zonal operations, use the zonalOperations resource. For more information, read Global, Regional...
ng to get events for offense ID: {offense_id}, ' f'offense_start_time: {offense_start_time}, ' f'additional_where: {additional_where}, ' f'events_limit: {events_limit}.') num_of_failures = 0 while num_of_failures <= max_retries: try: ...
_response", "Not specified - ok")}') events = search_results_response.get('events', []) sanitized_events = sanitize_outputs(events) print_debug_msg(f'Fetched {len(sanitized_events)} events for offense {offense_id}.') return sanitized_events, failure_messag...
fetch sleep (or after) print_debug_msg(f'Still fetching offense {offense_id} events, search_id: {search_id}.') start_time = time.time() time.sleep(EVENTS_INTERVAL_SECS) except Exception as e: print_debug_msg( f'Error while fetching offense...
import os from collections import defaultdict from dataclasses import asdict from pathlib import Path from unittest import mock import numpy as np import pydicom import pytest from panimg.image_builders.dicom import ( _get_headers_by_study, _validate_dicom_files, format_error, image_builder_dicom, ) fr...
m_intercept and dicom_slope has been modified to add a small intercept (0.01) or slope (1.001) respectively. """ files = [ Path(d[0]).joinpath(f) for d in os.walk(RESOURCE_PATH / folder) for f in d[2] ] result = _build_files( builder=image_builder_dicom
, files=files, output_directory=tmpdir ) assert len(result.new_image_files) == 1 mha_file_obj = [ x for x in result.new_image_files if x.file.suffix == ".mha" ][0] headers = parse_mh_header(mha_file_obj.file) assert headers["ElementType"] == element_type def test_dicom_window_level(t...
" measurements available for state " + state) sliced_data = None for j in self.memory[state]['arrayMeas']: #self.my_logger.debug("DOKMEANS self.memory[state]['arrayMeas'][j]: "+ str(j)) # If this measurement belongs in the slice we're insterested in ...
cpu, time tick ten_min_l.append(float(m[1])) ten_min.append(float(m[5])) # run running average on the 10 mins lambda measurements n = 5 run_avg_gen = self.moving_average(ten_min_l, n) run_avg = [] for r in run_avg_gen: ...
intercept, r_value, p_value, stderr) = linregress(ten_min, ten_min_l) (slope, intercept, r_value, p_value, stderr) = linregress(ten_min_ra, run_avg) # fit the running average in a polynomial coeff = np.polyfit(ten_min, ten_min_l, deg=2) self.log.debug("Slope (a): " + str(slope) + " Inte...
from django.contrib import admin from django.contrib.flatpages.admin import FlatPageAdmin from dj
ango.contrib.flatpages.models import FlatPage from django.db import models from suit_redactor.widgets import RedactorWidget class FlatPageCustom(FlatPageAdmin): formfield_overrides = { models.TextField: {'widget': RedactorWidget(editor_options={'lang': 'en'})} } admin.site.unregist
er(FlatPage) admin.site.register(FlatPage, FlatPageCustom)
# # Utility functions # import sys from functools import partial from uuid import UUID from hashlib import sha1 from os import path, listdir from zipfile import ZipFile from subprocess import Popen, TimeoutExpired import nacl.utils import nacl.secret def isValidUUID(uid): """ Validate UUID @param uid: UU...
enSSL = False # check for openssl requirement (downloaded during installer run) files = sorted((path.isdir(f), f) for f in listdir(resDir) if f.lower().startswith('openssl-')) # check for expanded directory and executable for isDir, ofile in files: if isD...
newDir = ofile break if not hasOpenSSL and files: # sorted filename to list newest version first) for ofile in sorted(f for isDir, f in files if not isDir and path.splitext(f)[1] == '.zip'): # extract archive ...
# Copyright 2011, Thomas G. Dimiduk # # This file is part of GroupEng. # # GroupEng is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later versi...
elif re.match('student_identifier', line) or re.match('[Ii][Dd]', line): dek['student_identifier'] = split_key(line)[1] elif re.match('number_of_groups', line): dek['number_of_groups'] = int(split_key(line)[1]) elif re.match('tries', line): dek['tries'] = int(spl...
wer() rule['attribute'] = split_key(line)[1] # read extra arguments while i+1 < len(lines) and lines[i+1][0] != '-': i += 1 line = lines[i] key, val = split_key(line) val = tuple([v.strip() for v in val.split(',')]) ...
import agents as ag import envgui as gui # change this line ONLY to refer to your project import submissions.Porter.vacuum2 as v2 # ______________________________________________________________________________ # Vacuum environmenty class Dirt(ag.Thing): pass class VacuumEnvironment(ag.XYEnvironment): """Th...
[0] agent.performance += 100
self.delete_thing(dirt) else: super(VacuumEnvironment, self).execute_action(agent, action) if action != 'NoOp': agent.performance -= 1 # # Launch a Text-Based Environment # print('Two Cells, Agent on Left:') # v = VacuumEnvironment(4, 3) # v.add_thing(Dirt(), (1, 1)) # v.add_t...
''' Author Joshua Pitts the.midnite.runr 'at' gmail <d ot > com Copyright (C) 2013,2014, Joshua Pitts License: GPLv3 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, ei...
See the GNU General Public License for more details. See <http://www.gnu.org/licenses/> for a copy of the GNU General Public License Currently supports win32/64 PE and linux32/64 ELF only(intel architecture). This program is to be used for only legal activities by IT security professionals an...
ELFIntel x32 shellcode class """ def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None): #could take this out HOST/PORT and put into each shellcode function self.HOST = HOST self.PORT = PORT self.e_entry = e_entry self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE ...
from djan
go.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cms', '0014_auto_20160404_1908'), ] operations = [ migrations.AlterField( model_name='cmsplugin', name='position', field=models.PositiveSmallIntegerField(default=...
]
from . import
font from .indicator import Indicator, IndicatorOptions from .airspeed import AirspeedIndicator from .altitude import AltitudeIn
dicator from .attitude import AttitudeIndicator from .compass import CompassIndicator from .pfd import PFD from .joystick import Joystick from . import base_test
import src import random class Bomb(src.items.Item): """ ingame item to kill things and destroy stuff """ type = "Bomb" name = "bomb" description = "designed to explode" usageInfo = """ The explosion will damage/destroy
everything on the current tile or the container. Activate it to trigger a exlosion. """ bolted = False walkable = True def __init__(self): """ initialise state """ super().__init__(display=src.canvas.displayChars.bomb) def apply(self, character): """ ...
character: the character trying to use this item """ character.addMessage("the bomb starts to fizzle") event = src.events.RunCallbackEvent( #src.gamestate.gamestate.tick+random.randint(1,4)+delay src.gamestate.gamestate.tick+1 ) event.setCallback({"conta...
from django.db imp
ort models class Salary(models.Model): id = models.AutoField(primary_key = True) bh = models.CharField(max_length = 10) xm = models.CharField(max_length = 12) status = models.CharField(max_length = 8) c
lass Meta: db_table = 'swan_salary' def __str__(self): return self.id
import unittest import serializer __author__ = 'peter' class SerializationTests(unittest.TestCase): def tes
t_serialize_single_key_value_pair(self): input = [{ 'name': 'value' }] expected_output = "name=value" output = serializer.serialize(input) self.assertEquals(cmp(expected_output, output), 0) def test_serialize_non_string_type(self): input = [{ 'name': 5.0 }] expected_...
er.serialize(input) self.assertEquals(cmp(expected_output, output), 0) def test_serialize_single_key_multi_value(self): input = [{ 'name': ['first', 'second']}] expected_output = 'name={\r\n\tfirst\r\n\tsecond\r\n}' output = serializer.serialize(input) self.assertEquals(cmp(...
#!/usr/bin/python # -*- coding: utf-8 -*- """ This file is part of XBMC Mega Pack Addon. Copyright (C) 2014 Wolverine (xbmcmegapack
@gmail.com) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hop
e that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see...
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au> # # 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 Softwar
e without restriction, including without limitation 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 substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF...
or frustrating debugging if stderr is directed to our wrapper. So be paranoid about catching errors and reporting them to sys.__stderr__, so that the user has a higher chance to see them. """ print( isinstance(message, str) and message or repr(message), file=sys.__stderr__) def fix_default_encodin...
ugs.python.org/issue6058>.""" # <http://msdn.microsoft.com/en-us/library/dd317756.aspx> try: codecs.lookup('cp65001') return False except LookupError: codecs.register( lambda name: name == 'cp65001' and codecs.lookup('utf-8') or None) return True class WinUnicodeOutputBase(object): """...
s.stdout or sys.stderr to behave correctly on Windows. Setting encoding to utf-8 is recommended. """ def __init__(self, fileno, name, encoding): # Corresponding file handle. self._fileno = fileno self.encoding = encoding self.name = name self.closed = False self.softspace = False s...
import sqlalchemy.pool import time import math class S
AAutoPool(sqlalchemy.pool.QueuePool): """ A pool class similar to QueuePool but rather than holding some minimum number of connections open makes an estimate of how many connections are needed. The goal is that new connections should be opened at most once every few seconds and shouldn't create so ...
will be many idle. """ def __init__(self, creator, pool_size=20, open_interval=5, **kw): """ Create a new SAAutoPool. pool_size is passed to to the QueuePool parent. You shouldn't need to adjust this, it's more to provide a hard maximum on the number of connections. open_i...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright (c) 2017 Ste
phen Bunn (stephen@bunn.io
) # GNU GPLv3 <https://www.gnu.org/licenses/gpl-3.0.en.html> from ._common import * from .rethinkdb import RethinkDBPipe from .mongodb import MongoDBPipe
lass LdapSearchException(Exception): pass def get_connection_from_server(server=None): ldap_servers = desktop.conf.LDAP.LDAP_SERVERS.get() if server and ldap_servers: ldap_config = ldap_servers[server] else: ldap_config = desktop.conf.LDAP return get_connection(ldap_config) def get_connecti...
if result_data: for dn, data in result_data: # Skip Active Directory # refldap entries. if dn is not None: # Case insensitivity data = CaseInsensitiveDict.from_dict(data) # Skip unnamed entries. if group_name_attr not in data: LOG.warn('Could n...
: group_name = group_name.lower() ldap_info = { 'dn': dn, 'name': group_name } if group_member_attr in data and 'posixGroup' not in data['objectClass']: ldap_info['members'] = data[group_member_attr] else: ldap_info['m...
Note that if the user is only reserved we don't do PAM authentication if data.get('use_pam_authentication') == 'Y' and CFG.pam_auth_service: # Check the password with PAM import rhnAuthPAM if rhnAuthPAM.check_password(username, password, CFG.pam_auth_service) <= 0: # Bad password...
characters!!!! invalid_re = re.compile(".*[\s&+%'`\"=#]", re.I) tmp = invalid_re.match(username) if tmp is not None: pos = tmp.regs[0] raise rhnFault(15, _("username = `%s', invalid character `%s'") % ( username
, username[pos[1]-1])) # use new password validation method validate_new_password(password) return username, password # Do some minimal checks on the e-mail address def check_email(email): if email is not None: email = string.strip(email) if not email: # Still supported r...
#!/usr/bin/env impala-python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (...
node_type in ('map', 'array'): result_node = Node(1, node_type) else: num_fields = randint(1, MAX_NUM_STRUCT_FIELDS) self._num_scalars_created += num_fields - 1 result_node = Node(num_fields, 'struct') self._nodes.append(result_node) return
result_node def _get_random_existing_node(self): nodes = [] for node in self._nodes: for _ in range(node.num_fields - len(node.fields)): nodes.append(node) return choice(nodes) def _generate_rest(self): while self._num_scalars_created < self._target_num_scalars: node = self._g...
def standard_text_from_block(block, offset, max_length): str = '' for i in range(offset, offset + max_length): c = block[i] if c == 0: return str else: str += chr(c - 0x30) return str def standard_text_to_byte_list(text, max_length): byte_list = [] t...
e ValueError("String cannot be written in {} bytes or less: {}".format( max
_length, text )) elif num_bytes < max_length: byte_list.append(0) return byte_list def standard_text_to_block(block, offset, text, max_length): byte_list = standard_text_to_byte_list(text, max_length) block[offset:offset+len(byte_list)] = byte_list
INSTALL_PATH
= '/home/fred/workspace/
grafeo/'
""" Module with location helpers. detect_location_info and elevation are mocked by default during tests. """ import asyncio import collections import math from typing import Any, Dict, Optional, Tuple import aiohttp ELEVATION_URL = "https://api.open-elevation.com/api/v1/lookup" IP_API = "http://ip-api.com/json" IPAP...
n() except (aiohttp.ClientError, ValueError): return None return { "ip": raw_info.get("ip"), "country_code": raw_info.get("country"), "country_name": raw_info.get("country_name"), "region_code": raw_info.get("region_code"), "region_name": raw_info.get("region"), ...
raw_info.get("city"), "zip_code": raw_info.get("postal"), "time_zone": raw_info.get("timezone"), "latitude": raw_info.get("latitude"), "longitude": raw_info.get("longitude"), } async def _get_ip_api(session: aiohttp.ClientSession) -> Optional[Dict[str, Any]]: """Query ip-api.c...
# Copyright (C) 2015 Google Inc., authors, and contributor
s <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: jernej@reciprocitylabs.com # Maintained By: jernej@reciprocitylabs.com from lib import environment from lib.constants import url from lib.page.widget.base import Widget class AdminPeople(Wi
dget): URL = environment.APP_URL \ + url.ADMIN_DASHBOARD \ + url.Widget.PEOPLE
er the terms of the GNU Lesser General Public License (LGPL) * # * as published by the Free Software Foundation; either version 2 of * # * the License, or (at your option) any later version. * # * for detail see the LICENCE text file. * # * ...
ux_objects = heatflux_obj self.initialtemperature_objects = initialtemperature_obj self.beamsection_objects = beamsection_obj self.shellthickness_objects = shellthickness_obj self.analysis_type = anal
ysis_type self.dir_name = dir_name if not dir_name: print('Error: FemInputWriter has no working_dir --> we gone make a temporary one!') self.dir_name = FreeCAD.ActiveDocument.TransientDir.replace('\\', '/') + '/FemAnl_' + analysis_obj.Uid[-4:] if not os.path.isdir(self.di...
""" The extropy """ from ..helpers import RV_MODES from ..math.ops import get_ops import numpy as np def extropy(dist, rvs=None, rv_mode=None): """ Returns the extropy J[X] over the random variables in `rvs`. If the distribution represents linear probabilities, then the extropy is calculated with un...
# Handle binary extropy. float(dist) except TypeError: pass else: # Assume linear probability for binary extropy. import dit dist = dit.ScalarDistribution([dist, 1-dist]) rvs = None rv_mode = RV_MODES.INDICES if dist.is_joint():
if rvs is None: # Set to entropy of entire distribution rvs = list(range(dist.outcome_length())) rv_mode = RV_MODES.INDICES d = dist.marginal(rvs, rv_mode=rv_mode) else: d = dist pmf = d.pmf if d.is_log(): base = d.get_base(numerical=Tru...
# Yum plugin to re-patch container rootfs after a yum update is done # # Copyright (C) 2012 Oracle # # Authors: # Dwight Engen <dwight.engen@oracle.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou...
return # See what packages have files that were patched confpkgs = conduit.confString('main', 'packages') if not confpkgs: return tmp = confpkgs.split(",") for confpkg in tmp: pkgs.append(confpkg.strip()) conduit.info(2, "lxc-patch: checking if updated pkgs need patching..."...
tch_required: conduit.info(2, "lxc-patch: patching container...") os.spawnlp(os.P_WAIT, "lxc-patch", "lxc-patch", "--patch", "/")
# -*- coding: utf-8 -*- # # SPDX-License-Identifier: AGPL-3.0-or-later # # snippy - software development and maintenance notes manager. # Copyright 2017-2020 Heikki J. Laaksonen <laaksonen.heikki.j@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU ...
m snippy.config.source.api import Api from snippy.constants import Constants as Const from snippy.logger import Logger from snippy.server.rest.base import ApiResource from snippy.server.rest.base import ApiNo
tImplemented from snippy.server.rest.generate import Generate class ApiAttributes(object): """Access unique resource attributes.""" def __init__(self, content): self._logger = Logger.get_logger(__name__) self._category = content.category self._content = content @Logger.timeit(ref...
t.raises(IllegalValueError): validator.coerce_boolean(value, ['whatever']) @pytest.mark.parametrize( 'value, expected', [ ('3', 3.0), ('9.80', 9.80), ('3.141592654', 3.141592654), ('"3.141592654"', 3.141592654), ("'3.141592654'", 3.141592654), ('-3',...
] ) def test_coerce_float(value: str, expected: float): """Test coerce_float.""" assert ( ParsecValidator.coerce_float(value, ['whatever']) == approx(expected) ) def test_coerce_float__empty(): # not a number assert ParsecValidator.coerce_float('', ['whatever']) is None @pytest.mark...
ef test_coerce_float__bad(value: str): with pytest.raises(IllegalValueError): ParsecValidator.coerce_float(value, ['whatever']) @pytest.mark.parametrize( 'value, expected', [ ('', []), ('3', [3.0]), ('2*3.141592654', [3.141592654, 3.141592654]), ('12*8, 8*12.0', [8....
import click from arrow.cli import pass_context, json_loads from arrow.decorators import custom_exception, dict_output @click.command('get_comments') @click.argument("feature_id", type=str) @click.option( "--organism", help="Organism Co
mmon Name", type=str ) @click.option( "--sequence", help="Sequence Name", type=str ) @pass_context @custom_exception @dict_output def cli(ctx, feature_id, organism="", sequence=""): """Get a feature's comments Output: A standard apollo feature dictionary ({"features": [{...}]}) """ ret...
.gi.annotations.get_comments(feature_id, organism=organism, sequence=sequence)
# -*- coding: utf-8 -*- """ *************************************************************************** SelectByAttribute.py --------------------- Date : May 2010 Copyright : (C) 2010 by Michael Minn Email : pyqgis at michaelminn dot com *******************...
'does not contain' ] STRING_OPERATORS = ['begins with', 'contains', 'does not contain'] def tags(self): return self.tr('select,attribute,value,contains,null,field').split(',') def group(self): return self.tr('V...
= ['=', '!=', '>', '>=', '<', '<=', self.tr('begins with'), self.tr('contains'), ...
import chainer import chainer.functions as F import chainer.links as L class vgga(chainer.Chain): insize = 224 def __init__(self): super(vgga, self).__init__() with self.init_scope(): self.conv1 = L.Convolution2D( 3, 64, 3, stride=1, pad=1) self.conv2 = L.Convolution...
= F.max_pooling_2d(F.relu(self.conv2(h)), 2, stride=2) h = F.relu(self.conv3(h)) h = F.max_pooling_2d(F.relu(self.conv4(h)), 2, stride=2) h = F.relu(self.conv5(h)) h = F.max_pooling_2d(F.relu(self.conv6(h)), 2, stride=2)
h = F.relu(self.conv7(h)) h = F.max_pooling_2d(F.relu(self.conv8(h)), 2, stride=2) h = F.relu(self.fc6(h)) h = F.relu(self.fc7(h)) return self.fc8(h)
from django.core.checks.urls import check_url_config from django.test import SimpleTestCase from django.test.utils import override_settings class CheckUrlsTest(SimpleTestCase): @override_settings(ROOT_URLCONF='check_framework.urls_no_warnings') def test_include_no_warnings(self): result = check_url_co...
al(len(result), 1) warning = result[0] self.assertEqual(warning.id, 'urls.W003') expected_msg = "Your URL pattern '^$' [name='name_with:colon'] has a name including a ':'." self.assertIn(expected_msg, wa
rning.msg)
"""Find all models written by user Hut
ton, including the DOI and the source code repository for each model. """ from ask_api_examples import make_query query = '[[Last name::Hutton]]|?DOI model|?Source web address' def main(): r = make_query(query, __file__) return r if __name__ == '__main__': print main()
genet" (pre-training on ImageNet). input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) to use as image input for the model. input_shape: optional shape tuple, only to be specified if `include_top` is False (otherwise the input shape has to be `(299, ...
n your Keras ' 'config located at ~/.keras/keras.json. ' 'The model being returned right now will expect inputs ' 'to follow the "channels_last" data format.') K.set_image_data_format('channels_last') old_data_format = 'channels_first' ...
min_size=71, data_format=K.image_data_format(), include_top=include_top) if input_tensor is None: img_input = Input(shape=input_shape) else: if not K.is_keras_tensor(input_tensor): ...
def f(): try:
a = 1 except:
b = 1
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
pplication process. @param rounding: Totalised monetary value of all errors due to process rounding or truncating that is not reflected in 'amount'. @param note: Free format note relevant to this line. @param amount: Amount for this line item. """ #: Date and time when this l...
cted in 'amount'. self.rounding = rounding #: Free format note relevant to this line. self.note = note #: Amount for this line item. self.amount = amount super(LineDetail, self).__init__(*args, **kw_args) _attrs = ["dateTime", "rounding", "note", "amount"] _at...
#!/usr/bin/env python # This file is part of VoltDB. # Copyright (C) 2008-2010 VoltDB Inc. # # VoltDB 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...
ass Table { int type; Table? buddy1; Table? buddy2; Column* columns; Index* indexes; Constraint* constraints; } class Program { Program* programs; Procedure* procedu
res; Table* tables; } """ def checkeq( a, b ): if a != b: raise Exception( 'test failed: %r != %r' % (a,b) )
# -*- coding: utf-8 -*- # Copyright 2014 OpenMarket Ltd # # 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 la...
, room=None, user=None, expect_code=200, tok=None): yield self.change_membership(room=room, src=user, targ=user, tok=tok, membership=Membership.JOIN, expect_code=expect_code) @defer.inlineCallba
cks def leave(self, room=None, user=None, expect_code=200, tok=None): yield self.change_membership(room=room, src=user, targ=user, tok=tok, membership=Membership.LEAVE, expect_code=expect_code) @defer.inlineCallbacks def chan...
"""Log MAVLink stream.""" import argparse from pymavlink import mavutil import pymavlink.dialects.v10.ceaufmg as mavlink def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verbose", action='store_true', help="print messages to STDOUT") parse...
d=args.baudrate) conn.logfile = args.log while True: msg = conn.recv_msg()
if args.verbose and msg is not None: print(msg) if __name__ == '__main__': main()
if ret > 180: ret -= 360; if ret < -180: ret += 360 return ret average_data = {} def average(var, key, N): '''average over N points''' global average_data if not key in average_data: average_data[key] = [var]*N return var average_data[key].pop(0) average_da...
rz *= mul[2] return lowpass(degrees(asin(rx/sqrt(rx**2+ry**2+rz**2))),'_pitch',smooth) def rotation(ATTITUDE): '''return the current DCM rotation matr
ix''' r = Matrix3() r.from_euler(ATTITUDE.roll, ATTITUDE.pitch, ATTITUDE.yaw) return r def mag_rotation(RAW_IMU, inclination, declination): '''return an attitude rotation matrix that is consistent with the current mag vector''' m_body = Vector3(RAW_IMU.xmag, RAW_IMU.ymag, RAW_IMU.zmag) m...
68, 0) attrs = ua.VariableAttributes() attrs.DisplayName = LocalizedText("ReplaceDataCapability") attrs.DataType = ua.NodeId(ua.ObjectIds.Boolean) attrs.ValueRank = -1 node.NodeAttributes = attrs server.add_nodes([node]) refs = [] ref = ua.AddReferencesItem() ref.IsForward = True ...
node.BrowseName = QualifiedName('DeleteAtTimeCapability',
0) node.NodeClass = NodeClass.Variable node.ParentNodeId = NumericNodeId(11192, 0) node.ReferenceTypeId = NumericNodeId(46, 0) node.TypeDefinition = NumericNodeId(68, 0) attrs = ua.VariableAttributes() attrs.DisplayName = LocalizedText("DeleteAtTimeCapability") attrs.DataType = ua.NodeId(ua....
# Copyright (c) 2014 Rackspace Hosting. # # 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...
ions and # limitations under the License. from openstack_dashboard import exceptions #from solumclient.openstack.common.apiclient import exceptions as solumclient NOT_FOUND = exceptions.NOT_FOUND RECOVERABLE = exceptions.RECOVERABLE # + (solumclient.ClientException,) UNAUTHO
RIZED = exceptions.UNAUTHORIZED
express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ tests for catalog module """ import os import fabric.api from fabric.operations import _AttributeString from mock import patch from prestoadmin import catalog from prestoadmin.util import co...
ch('prestoadmin.catalog.deploy_files') @patch('prestoadmin.cat
alog.os.path.isdir') @patch('prestoadmin.catalog.os.listdir') @patch('prestoadmin.catalog.validate') def test_add_all(self, mock_validate, listdir_mock, isdir_mock, deploy_mock): catalogs = ['tpch.properties', 'another.properties'] listdir_mock.return_value = catalogs ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutDecoratingWithFunctions(Koan): def addcowbell(fn): fn.wow_factor = 'COWBELL BABY!' return fn @addcowbell def
mediocre_song(self): return "o/~ We all live in a broken submarine o/~" def test_decorato
rs_can_modify_a_function(self): self.assertMatch(__, self.mediocre_song()) self.assertEqual(__, self.mediocre_song.wow_factor) # ------------------------------------------------------------------ def xmltag(fn): def func(*args): return '<' + fn(*args) + '/>' return ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Winton Kafka Streams Python documentation build configuration file, created by # sphinx-quickstart on Tue May 16 21:00:14 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are ...
in "default.css". html_static_path = ['_static'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'WintonKafkaStreamsPythondoc' # -- Options for LaTeX output --------------------------------------------- latex_elements =...
# 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual...
""" Project Configuration Importer Handles the importing the project configuration from a separate location and validates the version against the specified expected version. NOTE: If you update this file or any others in scripts and require a NEW variable in project_cfg, then you need to UPDATE THE EXPECTED_CFG...
Returns the project configuration module """ sys.path.append(PROJECT_CFG_DIR) try: project_cfg_module = importlib.import_module(PROJECT_CFG_NAME) except: raise FileNotFoundError("\n\n================================= ERROR ========================================" ...
_DIR + "/" + PROJECT_CFG_NAME + ".py" "\n================================================================================\n") _verify_correct_version(project_cfg_module) return project_cfg_module def _verify_correct_version(project_cfg_module): is_correct_version = False ...
#!/usr/bin/env python import sys import re import os inFilename = sys.argv[1] if os.path.isfile(inFilename): namelength = inFilename.rfind(".") name = inFilename[0:namelength] exten = inFilename[namelength:] outFilename = name+"-cachecmp"+exten print "inFilename:", inFilename print "outFilename:", outFilename fpR...
bwalker1=int(itbwalker1match.group(2)) if dtbwalker2match: dtbwalker2=int(dtbwalker2match.group(2)) if itbwalker2match: itbwalker2=int(itbwalker2match.group(2)) if overallhitsmatch: overallhits=int(overallhitsmatch.group(2)) if cachehitsmatch: cachehits=int(cachehitsmatch.group(2)) if thr...
if gem5hits!=0: ratio=(absval/float(gem5hits))*100 else: ratio=float(0) fpWrite.write("gem5hit %d " % gem5hits) fpWrite.write("cachehit %d " % cachehits) ...
############################################################################### ## ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## "Redistribution and use in source and binary forms, with or without ## modification, ...
OFTWARE, EVEN IF ## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## ############################################################################### import re from lucene import * im
port lucene dir(lucene) class vistrailAnalyzer(PythonAnalyzer): def tokenStream(self, fieldName, reader): result = StandardTokenizer(reader) result = StandardFilter(result) result = vistrailFilter(result) result = LowerCaseFilter(result) result = PorterStemFilter(result) ...
"""Various miscellaneous functions to make code easier to read & write.""" import collections.abc import copy import functools import inspect import logging import urllib.parse import jsonpointer import jsonschema _logger = logging.getLogger("holocron") def resolve_json_references(value, context, keep_unknown=True...
for i in range(len(node)): node[i] = _do_resolve(node[i]) return node return _do_resolve(value) class parameters: def __init__(self, *, fallback=None, jsonschema=None): self._fallback = fallback or {} self._jsonschema = jsonschema def __call__(self, fn): ...
rgs, **kwargs): signature = inspect.signature(fn) arguments = signature.bind_partial(app, *args, **kwargs).arguments # First two arguments always are an application instance and a # stream of items to process. Since they are passed by Holocron # core as posit...
# -*- mode: python -*- from .combinations import STANDARD_METHOD_COMBINATION from .specializers import specializer, ROOT_SPECIALIZER from . import util from .cache import NoCachePolicy, LRU, TypeCachePolicy import threading import inspect import warnings try: from ._py_clos import GenericFunction as GenericFuncti...
Function(GenericFunctionBase): def __init__(self, name): self._name = name self._method_combination = STANDARD_METHOD_COMBINATION self._methods = [] self._specialized_on = [] self._cache_policies = [] self._lock = threading.Lock() self.clear_cache() ...
._method_combination = method_combination self.clear_cache() def get_cache_size(self): return len(self._methods) * 4 def cache_should_grow(self): for i in self._cache_policies: if i != TypeCachePolicy: return False return True def clear_...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 Citrix 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/LICE...
ops.attach_volume( connection_info, 'instance_1', 'mountpoint')
def test_attach_volume_no_hotplug(self): ops = volumeops.VolumeOps('session') self.mox.StubOutWithMock(ops, '_connect_volume') self.mox.StubOutWithMock(volumeops.vm_utils, 'vm_ref_or_raise') self.mox.StubOutWithMock(volumeops.volume_utils, 'get_device_number') connection_info...
#!/usr/bin/env python ## vim:ts=4:et:nowrap """A user-defined wrapper around string objects Note: string objects have grown methods in Python 1.6 This module requires Python 1.6 or later. """ from types import StringType, UnicodeType import sys __all__ = ["UserString","MutableString"] class UserString: def __ini...
h(prefix, start, end) def strip(self): return self.__class__(self.data.strip()) def swapcase(self): return self.__class__(self.data.swapcase()) def title(self): return self.__class__(self.data.title()) def translate(self, *args): return self.__class__(self.data.translate(*args)) def upper(se...
mmutable objects. This has the advantage, that strings may be used as dictionary keys. If this property isn't needed and you insist on changing string values in place instead, you may cheat and use MutableString. But the purpose of this class is an educational one: to prevent people from inventin...
from django.contrib.auth.models import User from djang
o.core.urlresolvers import reverse from django.db import models class Location(models.Model): address = models.CharField(blank=True) latitude = models.DecimalField(max_digits=10, decimal_places=6) longitude = models.DecimalField(max_digits=10, decimal_places=6) created = models.DateTimeField(auto_add_...
: return reverse('location-detail', args=[str(self.id)]) def __str__(self): return '{id: %d, latitude: %d, longitude: %d}' % ( self.id, self.latitude, self.longitude ) class Meta: app_label = 'locations' get_latest_by = 'updated' ...
'''This script demonstrates how to build a variational autoencoder with Keras and deconvolution layers. Reference: "Auto-Encoding Variational Bayes" https://arxiv.org/abs/1312.6114 ''' import numpy as np import matplotlib.pyplot as plt from scipy.stats import norm from keras.layers import Input, Dense, Lambda, Flatte...
an_squash) kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_l
og_var), axis=-1) return K.mean(xent_loss + kl_loss) def call(self, inputs): x = inputs[0] x_decoded_mean_squash = inputs[1] loss = self.vae_loss(x, x_decoded_mean_squash) self.add_loss(loss, inputs=inputs) # We don't use this output. return x y = CustomVar...
f verbose: print("discarding '%s', no digits" % ",".join(refs - tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] ...
it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] """ if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered ...
"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rend...
from __future__ import unicode_literals import logging from django.conf import settings from reviewboard import get_version_string, get_package_version, is_release from reviewboard.admin.server import get_server_url _registered_capabilities = {} _capabilities_defaults = { 'diffs': { 'base_commit_ids': ...
bilities_id in _registered_capabilities: raise KeyError('"%s" is already a registered set of capabilities'
% capabilities_id) if capabilities_id in _capabilities_defaults: raise KeyError('"%s" is reserved for the default set of capabilities' % capabilities_id) _registered_capabilities[capabilities_id] = caps def unregister_webapi_capabilities(capabilities_id): ...
import _plotly_utils.basevalidators class ValueminusValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, p
lotly_name="valueminus", parent_name="scatter3d.error_z", **kwargs ): super(ValueminusValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), min=kwargs.pop("min", 0), role=kwargs.pop(...
"info"), **kwargs )
from httpx import AsyncClient # Runtime import to avoid syntax errors in samples on Python < 3.5 and reach top-dir import os _TOP_DIR = os.path.abspath( os.path.sep.join((
os.path.dirname(__file__), '../', )), ) _SAMPLES_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__file__), '../samples/', )), ) import sys sys.path.append(_TOP_DIR) sys.path.append(_SAMPLES_DIR) from asyncutils import AsyncTestCase from wiringfastapi import we
b class WiringFastAPITest(AsyncTestCase): client: AsyncClient def setUp(self) -> None: super().setUp() self.client = AsyncClient(app=web.app, base_url='http://test') def tearDown(self) -> None: self._run(self.client.aclose()) super().tearDown() def test_depends_mark...
''' :codeauthor: {{full_name}} <{{email}}> ''' from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import TestCase from tests.support.mock import patch import salt.states.{{module_name}} as {{module_name}} class {{
module_name|capitalize}}TestCase(TestCase, LoaderModuleMockMixin): def se
tup_loader_modules(self): return {% raw -%} { {% endraw -%} {{module_name}} {%- raw -%}: { '__env__': 'base' } } {%- endraw %} def test_behaviour(self): # Test inherent behaviours pass
import logging from autotest.client import utils from autotest.client.shared import error from virttest import env_process, utils_test @error.context_aware def run(test, params, env): """ Vhost zero copy test 1) Enable/Disable vhost_net zero copy in host 1) Boot the main vm. 3) Run the ping test, ...
(): """ Check whether host have enabled zero copy, if enabled return True, else return False. """ def_para_path = "/sys/module/vhost_net/parameters/experimental_zcopytx" para_path = params.get("zcp_set_path", def_para_path) cmd_status = utils.system("grep 1 %s" % ...
return True def enable_zerocopytx_in_host(enable=True): """ Enable or disable vhost_net zero copy in host """ cmd = "modprobe -rf vhost_net; " if enable: cmd += "modprobe vhost-net experimental_zcopytx=1" else: cmd += "modprobe vhost-ne...
from __future__ import absolute_import from collections import namedtuple from django.conf import settings from sentry.utils.dates import to_
datetime from sentry.utils.services import LazyServiceWrapper from .backends.base import Backend # NOQA from .backends.dummy import DummyBackend # NOQA backend = LazyServiceWrapper(Backend, settings.SENTRY_DIGESTS, settings.SENTRY_DIGESTS_OPTIONS, (DummyBac...
ry = namedtuple('ScheduleEntry', 'key timestamp') OPTIONS = frozenset(( 'increment_delay', 'maximum_delay', 'minimum_delay', )) def get_option_key(plugin, option): assert option in OPTIONS return 'digests:{}:{}'.format(plugin, option)
""" Handlers to process the responses from the Humble Bundle API """ __author__ = "Joel Pedraza" __copyright__ = "Copyright 2014, Joel Pedraza" __license__ = "MIT" from humblebundle import exceptions from humblebundle import models import itertools import requests # Helper methods def parse_data(response): t...
) raise exceptions.HumbleAuthenticationException( error_msg, request=response.request, response=res
ponse, captcha_required=captcha_required, authy_required=authy_required ) def gamekeys_handler(client, response): """ get_gamekeys response always returns JSON """ data = parse_data(response) if isinstance(data, list): return [v['gamekey'] for v in data] # Let the helper functio...
__author__ = 'Varun Nayyar' from Utils.MFCCArrayGen import emotions, speakers, getCorpus from MCMC import MCMCRun from emailAlerter import alertMe def main2(numRuns = 100000, numMixtures = 8, speakerIndex = 6): import time for emotion in emotions: start = time.ct
ime() Xpoints = getCorpus(emotion, speakers[speakerIndex]) message = MCMCRun(Xpoints, emotion+"-"+speakers[speakerIndex], numRuns, numMixtures) message += "Start time: {}\nEnd Time: {}\n".format(start, time.ctime()) message += "\nNumRuns: {}, numMixtures:{}\n ".format(numRuns, numMi...
if __name__ == "__main__": for i in xrange(len(speakers)): main2(numMixtures=8, speakerIndex=i)
default_app_config = 'user_deletion.ap
ps.UserDeleti
onConfig'
'''GoogLeNet with PyTorch.''' import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable class Inception(nn.Module): def __init__(self, in_planes, n1x1, n3x3red, n3x3, n5x5red, n5x5, pool_planes): super(Inception, self).__init__() # 1x1 conv branch ...
self.
e4(out) out = self.maxpool(out) out = self.a5(out) out = self.b5(out) out = self.avgpool(out) out = out.view(out.size(0), -1) out = self.linear(out) return out # net = GoogLeNet() # x = torch.randn(1,3,32,32) # y = net(Variable(x)) # print(y.size())
on = self.request('/droplets/') return json['droplets'] def new_droplet(self, name, size_id, image_id, region_id, ssh_key_ids=None, virtio=False, private_networking=False, backups_enabled=False): params = { 'name': name, 'size_id': size_id, ...
json = self.request('/droplets/%s/rename/' % id, params) json.pop('status', None) return json def destroy_droplet(self, id, scrub_data=True): params = {'scrub_data': '1' if scrub_data else '0'} json = self.request('/droplets/%s/destroy/' % id, params) json.pop('statu...
def all_regions(self): json = self.request('/regions/') return json['regions'] #images========================================== def all_images(self, filter='global'): params = {'filter': filter} json = self.request('/images/', params) return json['images'] def show...
e(0, 1, 7000) arr[1] = np.random.normal(size=7000) hdu = fits.CompImageHDU(data=arr) hdu.writeto(self.temp('test.fits')) with fits.open(self.temp('test.fits')) as hdul: comp_hdu = hdul[1] # GZIP-compressed tile should compare exactly assert np.all(c...
.count('ZTENSION') == 2 def test_scale_bzero_with_compressed_int_data(self): """ Regression test for https://github.com/astropy/astropy/issues/4600 and https://github.com/astropy/astropy/issues/4588 Identical to test_scale_bzero_with_in
t_data() but uses a compressed image. """ a = np.arange(100, 200, dtype=np.int16) hdu1 = fits.CompImageHDU(data=a.copy()) hdu2 = fits.CompImageHDU(data=a.copy()) # Previously the following line would throw a TypeError, # now it should be identical to the integer...
# -*- coding: utf-8 -*- # Copyright (c)
2017, sathishpy@gmail.com and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest
class TestCMPaperManagement(unittest.TestCase): pass
from collections import defaultdict import colorsys import pg def noise(x, z): a = pg.simplex2(-x * 0.01, -z * 0.01, 4) b = pg.simplex2(x * 0.1, z * 0.1, 4) return (a + 1) * 16 + b / 10 def generate_color(x, z): m = 0.005 h = (pg.simplex2(x * m, z * m, 4) + 1) / 2 s = (pg.simplex2(-x * m, z * ...
[(x, z)] = noise(x, z) colors[(x, z)] = generate
_color(x, z) # generate triangles and track normals for all vertices for x in xrange(-size, size): for z in xrange(-size, size): t1 = [x + 0, z + 0, x + 1, z + 0, x + 0, z + 1] t2 = [x + 0, z + 1, x + 1, z + 0, x + 1, z + 1] for t in [t1, t2]: ...
#!/usr/bin/env python import os import json class TermiteCore: def __init__( self, request, response ): self.request = request self.response = response def GetConfigs( self ): def GetServer(): return self.request.env['HTTP_HOST'] def GetDataset(): return self.request.application def GetModel...
ix', 'DocTopicMatrix', 'TopicCooccurrence' ] elif model == 'corpus': return [ 'DocMeta', 'TermFreqs', 'TermCoFreqs' ] else: return [] server = GetServer() dataset = GetDataset() datasets = GetDatasets( dataset ) model = GetModel() models = GetModels( dataset, ...
ute() attributes = GetAttributes( dataset, model, attribute ) configs = { 'server' : server, 'dataset' : dataset, 'datasets' : datasets, 'model' : model, 'models' : models, 'attribute' : attribute, 'attributes' : attributes } return configs def IsDebugMode( self ): return 'debug' in...
anager.compare( voice, r''' \new Voice \with { \override NoteHead #'color = #red } { c'8 d'8 << \new Voice { e'8 f'8 } \new Voice { ...
c'8 d'8 } e'8 f'8 ''') assert systemtools.TestManager.compa
re( staff, r''' \new Staff { { \time 2/8 c'8 d'8 } e'8 f'8 } ''' ) assert inspect_(staff[0]).get_parentage().logical_voice == \ inspect_(staff[-1]).get_parentage()...
plane = tf.constant( [x for x in range(1, height * width + 1)], shape=(height, width), dtype=dtype ) image = tile_image(plane, image_shape=image_shape) result = filter2d_fn( image, filter_shape=filter_shape, padding=padding, constant_values=constant_values, ) ...
6666665, 3.6666667], ] ) verify_values( mean_filt
er2d, image_shape=image_shape, filter_shape=(3, 3), padding="CONSTANT", constant_values=1, expected_plane=expected_plane, ) @pytest.mark.usefixtures("maybe_run_functions_eagerly") @pytest.mark.parametrize("image_shape", _image_shapes_to_test) def test_symmetric_padding_with...