repo_name
stringlengths
5
100
path
stringlengths
4
231
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
6
947k
score
float64
0
0.34
prefix
stringlengths
0
8.16k
middle
stringlengths
3
512
suffix
stringlengths
0
8.17k
ProjectSWGCore/NGECore2
scripts/mobiles/generic/faction/rebel/battle_droid_rebel.py
Python
lgpl-3.0
1,397
0.029349
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...
onType.CARBINE, 1.0, 15, 'energy') weaponTemplates.add(weapontemplate) mobileTe
mplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() mobileTemplate.setDefaultAttack('rangedShot') mobileTemplate.setAttacks(attacks) core.spawnService.addMobileTemplate('battle_droid_rebel', mobileTemplate) return
muravjov/ansible
lib/ansible/utils/__init__.py
Python
gpl-3.0
60,718
0.004957
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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) an...
Loader exce
pt ImportError: from yaml import SafeLoader as Loader PASSLIB_AVAILABLE = False try: import passlib.hash PASSLIB_AVAILABLE = True except: pass try: import builtin except ImportError: import __builtin__ as builtin KEYCZAR_AVAILABLE=False try: try: # some versions of pycrypto may no...
Diptanshu8/zulip
zerver/views/webhooks/taiga.py
Python
apache-2.0
11,660
0.00446
""" Taiga integration for Zulip. Tips for notification output: *Emojis*: most of the events have specific emojis e.g. - :notebook: - change of subject/name/description - :chart_with_upwards_trend: - change of status etc. If no there's no meaningful emoji for certain event, the defaults are used: - :thought_balloon: -...
' from %(old)s to %(new)s.', 'delete': u':x: %(user)s deleted sprint **%(subject)s**.' }, 'task': { 'create': u':clipboard: %(user)s created task **%(subject)s**.', 'set_assigned_to': u':busts_in_silhouette: %(user)s assigned task **%(subject)s** to %(new)s.', 'unset_ass...
ask **%(subject)s**' ' from %(old)s to %(new)s.', 'blocked': u':lock: %(user)s blocked task **%(subject)s**.', 'unblocked': u':unlock: %(user)s unblocked task **%(subject)s**.', 'set_milestone': u':calendar: %(user)s added task **%(subject)s** to sprint %(new)s.', 'changed_milest...
rht/universe
universe/remotes/compose/colors.py
Python
mit
860
0
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 + i) + ';1') def ansi(code): return '\0...
s, ansi(0)) def make_color_fn(code): return lambda s: ansi_color(code, s) 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_ma...
DTUWindEnergy/Python4WindEnergy
py4we/fortran_namelist_io.py
Python
apache-2.0
8,294
0.01278
""" IO classes 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...
f.data[nml][param]['val'])) if len(self.data[nml][param]['com']) >0: f.write(' !'+self.data[nml][param]['com']) f.write('\n') f.write('/\n') def _read(self): """ Read the file (overrided) """ with open(self.file...
nt = re.compile(r'[+-]?[0-9]+') valueReal = re.compile(r'[+-]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)') valueNumber = re.compile(r'\b(([\+\-]?[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) spac...
jawilson/home-assistant
tests/components/nws/test_config_flow.py
Python
apache-2.0
3,482
0
"""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 ...
{"api_key": "test"}, ) await hass.async_bloc
k_till_done() assert result2["type"] == "create_entry" assert len(mock_setup_entry.mock_calls) == 1 result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.nws.async_setup_entry", re...
gems-uff/noworkflow
tests/test_disasm.py
Python
mit
831
0.002407
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_funct
ion_var_kw class C(object): # call_function def __enter__(self): x = 1 return x def __exit__(self, *args, **kwargs): pass def fn_dec(*args): def dec(fn): return fn
return dec dec1 = 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_...
apache/incubator-systemml
src/main/python/systemds/operator/algorithm/builtin/getAccuracy.py
Python
apache-2.0
1,549
0.002582
# ------------------------------------------------------------- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you unde...
with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or imp...
ing permissions and limitations # under the License. # # ------------------------------------------------------------- # Autogenerated By : src/main/python/generator/generator.py # Autogenerated From : scripts/builtin/getAccuracy.dml from typing import Dict, Iterable from systemds.operator import OperationNode, Ma...
guineawheek/Dozer
dozer/utils.py
Python
gpl-3.0
2,868
0.003138
"""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+)>')
def clean(ctx, text=None, *, mass=True, member=True, role=True, channel=True): """Cleans the message of anything specified in the parameters passed.""" if text is None: text = ctx.mess
age.content if mass: 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 mat...
armab/st2contrib
packs/jira/actions/transition_issue.py
Python
apache-2.0
269
0
from lib.base import BaseJiraAction __all__ = [ 'TransitionJiraIssueAc
tion' ] class TransitionJiraIssueAction(BaseJiraActi
on): def run(self, issue_key, transition): result = self._client.transition_issue(issue_key, transition) return result
jacksarick/My-Code
Python/python challenges/euler/017_number_letter_counts.py
Python
mit
25
0.08
## Nee
d to find a library
melvyn-sopacua/kdelibs
cmake/modules/FindPyQt.py
Python
gpl-2.0
1,768
0.001697
# 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...
# This is based on QScintilla's configure.py, and only works for the # default case where installation paths have not been changed in PyQt's # configuration process. if sys.platform == 'win32': pyqt_sip_dir = os.path.join(sys.prefix, 'sip', 'PyQt4') else: pyqt_sip_dir = os.path.join(sys...
alse for item in sip_flags.split(' '): if item == '-t': in_t = 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__': t...
lilulu/openmc
openmc/material.py
Python
mit
18,937
0.000422
from collections import Iterable from copy 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_xm...
self._id = AUTO_MATERIAL_ID MATERIAL_IDS.append(AUTO_MATERIAL_ID) AUTO_MATERIAL_ID += 1 else: check_type('material ID', material_id, Integral) if material_id in MATERIAL_IDS: msg = 'Unable to set Material ID to {0} since a Material with ...
ialized'.format(material_id) raise ValueError(msg) check_greater_than('material ID', material_id, 0) self._id = material_id MATERIAL_IDS.append(material_id) @name.setter def name(self, name): check_type('name for Material ID={0}'.format(self._id), ...
tempbottle/mcrouter
mcrouter/test/test_mcrouter.py
Python
bsd-3-clause
13,301
0.001579
# Copyright (c) 2015, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. from __future__ import absolute_...
elf.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 old but not new self.assertEqual(self.wild_old.get("get-key-1"), None) self.assertEqual(self.wild_new.get("get-key...
cr.set("set-key-2", str(4242)) self.assertEqual(self.wild_old.get("set-key-2"), str(4242)) self.assertEqual(self.wild_new.get("set-key-2"), None) mcr.delete("get-key-2") #make sure the delete went to both places self.assertEqual(self.wild_old.get("get-key-2"), None) self...
christianurich/VIBe2UrbanSim
3rdparty/opus/src/psrc/config/workplace_zone_choice_model_config.py
Python
gpl-2.0
13,587
0.011261
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE from urbansim.configs.base_configuration import AbstractUrbansimConfiguration from opus_core.resources import merge_resources_if_not_None import copy """this configuration file specifying work...
"agents_index": None, "agents_filter":"'psrc.person.is_non_home_based_worker_without_workplace_zone'", "data_objects": "datasets", "chunk_specification":"{'records_per_chunk':5000}", "debuglevel": run_configuration['d...
imate": { "name": "prepare_for_estimate", "arguments": { "agent_set":"person", "join_datasets": "False", "agents_for_estimation_storage": "base_cache_storage", "agents_for_estimation_table": "'workers_for_estim...
perlang/bv9arm-chinese
branches/9.16.18/arm/conf.py
Python
mpl-2.0
5,717
0.000352
############################################################################ # 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...
rter.error(error_text, line=self.lineno) prb = self.inliner.problematic(self.rawtext, self.rawtext, msg) return [prb], [msg] return [index, target, reference], [] def build_uri(self): if self.target[0] == '#': return self.base_url + 'issues/%d' % int(self.target...
'!': return self.base_url + 'merge_requests/%d' % int(self.target[1:]) raise ValueError def setup(_): roles.register_local_role('gl', GitLabRefRole(GITLAB_BASE_URL)) # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options....
danrg/RGT-tool
src/RGT/XML/SVG/Animation/baseAnimationNode.py
Python
mit
1,499
0.004003
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...
BasicSvgNode.__init__(self, ownerDoc, tagName) ConditionalProcessingAttributes.__init__(self) XlinkAttributes.__init__(self) AnimationTimingAttributes.__init__(self) self._allowedSvgChildNodes.update(self.SVG_GROUP_DESCRIPTIVE_ELEMENTS) def setExternalResourcesRequired(self,...
for value in allowedValues: values += value + ', ' values = values[0: len(values) - 2] raise ValueError('Value not allowed, only ' + values + 'are allowed') else: self._setNodeAttribute(self.ATTRIBUTE_EXTERNAL_RESOURCES_REQUIRED, data)...
odlgroup/odl-examples
tomography_wavelet_split_bregman.py
Python
gpl-3.0
2,070
0.002415
# -*- 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...
* Atf + la * Phi.adjoint(d-b) odl.solvers.conjugate_gradient(op, x, rhs, niter=2) # d = sign(Phi(x)+b) * max(|Ph
i(x)+b|-la^-1,0) s = Phi(x) + b d = s.ufunc.sign() * (s.ufunc.absolute(). 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...
snelis/snelis
snelis/management/commands/__init__.py
Python
bsd-3-clause
1,601
0.001874
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 """ ...
g(self, key): """ Retrieve a single argument """ return self._args.get(key) def args(self, *keys): """ Retrieve a set of argument """ if keys: return [self.arg(k) for k in keys] else: return self._args def value(se...
ey = '<{0}>'.format(key) return self.arg(key) def option(self, key, value=None): """ Retrieve a single argument """ key = '--'+key if value: return self.arg(key) == value return self.arg(key) def args_context(self): """ Conv...
PythonRails/examples
blog/config.py
Python
mit
218
0
""" Configurati
on for a project. """ rails = { 'models.engine': 'sqlalchemy', 'models.db.type': 'postgres', 'models.db.user': 'rails', 'models.db.password': 'rails
', 'views.engine': 'jinja', }
jklaiho/django-class-fixtures
class_fixtures/utils/__init__.py
Python
bsd-3-clause
214
0.004673
import sys from contextlib import contextm
anager
from StringIO import StringIO @contextmanager def string_stdout(): output = StringIO() sys.stdout = output yield output sys.stdout = sys.__stdout__
LeXuZZ/localway_tests
wtframework/wtf/tests/test_config_reader.py
Python
gpl-3.0
3,596
0.003337
########################################################################## #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...
"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, "setting_that_doesnt_exist") def test_spe
cifying_bad_config_file(self): "Test error is thrown when invalid config file is specified." self.assertRaises(ConfigFileReadError, ConfigReader, "tests/TestConfig1,NOSUCHFILE") if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
unreal666/outwiker
src/outwiker/gui/searchreplacepanel.py
Python
gpl-3.0
6,309
0
# -*- 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 =...
# Поле для ввода искомой фразы self._searchText = wx.TextCtrl(self, -1, u"", style=wx.TE_PROCESS_ENTER) # Текст для замены self._replaceText = wx.TextCtrl(self, -1, u"",
style=wx.TE_PROCESS_ENTER) # Элементы интерфейса, связанные с поиском self._findLabel = wx.StaticText(self, -1, _(u"Find what: ")) # Кнопка "Найти далее" self._nextSearchBtn = wx.Button(self, -1, _(u"Next")) # Кнопка "Найти выше" self._...
MichalKononenko/MrFreeze
mr_freeze/devices/lakeshore_475.py
Python
agpl-3.0
2,013
0.000497
""" 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 """ ...
:return: The instance of
the magnetometer that this adapter manages, or None if there is no instance. .. note:: The 1 second delay is required for the gaussmeter to reset itself and accept commands """ if self._managed_instance is None: self._managed_instance = self._cons...
Alberto-Beralix/Beralix
i386-squashfs-root/usr/lib/python2.7/dist-packages/orca/scripts/apps/packagemanager/script_settings.py
Python
gpl-3.0
87
0.022989
../../../../../../.
./share/pyshared/orca/scripts/apps/packagemanager
/script_settings.py
googleapis/python-compute
google/cloud/compute_v1/services/target_tcp_proxies/client.py
Python
apache-2.0
42,291
0.001537
# -*- coding: utf-8 -*- # Copyright 2022 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # ty...
utualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.compute_v1.services...
demisto/content
Packs/QRadar/Integrations/QRadar_v3/QRadar_v3.py
Python
mit
164,136
0.003649
import concurrent.futures import secrets from enum import Enum from ipaddress import ip_address from typing import Tuple, Set, Dict, Callable from urllib import parse import pytz import urllib3 from CommonServerUserPython import * # noqa from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-impo...
hes BATCH_SIZE = 100 # batch size used for offense ip enrichment OFF_ENRCH_LIMIT = BATCH_SIZE * 10 # max amount of IPs to enrich per offense MAX_WORKERS = 8 # max concurrent workers used for events enriching DOMAIN_ENRCH_FLG = 'true' # when set to true, will try to enrich offense and assets with domain names RULES_...
true, will try to enrich offense with rule names MAX_FETCH_EVENT_RETIRES = 3 # max iteration to try search the events of an offense SLEEP_FETCH_EVENT_RETIRES = 10 # sleep between iteration to try search the events of an offense MAX_NUMBER_OF_OFFENSES_TO_CHECK_SEARCH = 5 # Number of offenses to check during mirroring...
comic/comic-django
app/tests/cases_tests/test_dicom.py
Python
apache-2.0
5,037
0
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...
s[1:], "file": "bar", "index": 1}, }, ): errors = defaultdict(list) studies = _validate_dicom_files(files, errors) assert len(studies) == 0 for header in headers[1:]: assert errors[header["file"]] == [ format_error("Number of slices per time point ...
def test_image_builder_dicom_4dct(tmpdir): files = {Path(d[0]).joinpath(f) for d in os.walk(DICOM_DIR) for f in d[2]} result = _build_files( builder=image_builder_dicom, files=files, output_directory=tmpdir ) assert result.consumed_files == { Path(DICOM_DIR).joinpath(f"{x}.dcm") for x ...
cmantas/tiramola_v3
new_decision_module.py
Python
apache-2.0
36,005
0.007055
__author__ = 'tiramola group' import os, datetime, operator, math, random, itertools, time import numpy as np from lib.fuzz import fgraph, fset from scipy.cluster.vq import kmeans2 from lib.persistance_module import env_vars from scipy.stats import linregress from collections import deque from lib.tiramola_logging imp...
self.sumMetrics[state]['divide_by']) + " av. throughput: " + str(averages['throughput']) + " av. latency: " + str(averages['latency'])) return averages def doKmeans(self, state, from_inlambda, to_inlambda): # Run kmeans fo...
oid point (throughput, latency) ctd = {} label = [] centroids = {} if self.memory[state]['arrayMeas'] != None: count_state_measurements = len(self.memory[state]['arrayMeas']) # self.log.debug("DOKMEANS " + str(len(self.memory[state]['arrayMeas'])) + # ...
moshthepitt/product.co.ke
core/admin.py
Python
mit
458
0.004367
from django.contrib import admin from django.contrib.flatpages.admin import FlatPageAdmin from django.contrib.flatpages.models import FlatPage from django.db import models from suit_redactor.widgets import Red
actorWidget class FlatPageCustom(FlatPageAdmin): formfield_overrides = { models.TextField: {'widget': RedactorWidget(editor_opti
ons={'lang': 'en'})} } admin.site.unregister(FlatPage) admin.site.register(FlatPage, FlatPageCustom)
cbrunker/quip
lib/Utils.py
Python
gpl-3.0
4,795
0.003337
# # 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...
# 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 with ZipFile(path.join(resDir, ofile), 'r') as ozip: newDir = path.join(resDir, path.splitext(ofile)[0]) ozip.extrac...
tdimiduk/groupeng
src/input_parser.py
Python
agpl-3.0
2,845
0.002109
# 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...
ad 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(',')]) vals = [] for v in val: vals.append(union_group(v)) if len(vals) == 1: vals = vals[0] rule[key] = vals rules.append(rule) else: raise GroupEngFileError(line, i+1,...
austinban/aima-python
submissions/Porter/vacuum2Runner.py
Python
mit
6,343
0.006779
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...
umAgent, ModelBa
sedVacuumAgent ] def percept(self, agent): """The percept is a tuple of ('Dirty' or 'Clean', 'Bump' or 'None'). Unlike the TrivialVacuumEnvironment, location is NOT perceived.""" status = ('Dirty' if self.some_things_at( agent.location, Dirt) else 'Clean') ...
codercold/Veil-Evasion
tools/backdoor/intel/LinuxIntelELF32.py
Python
gpl-3.0
5,166
0.00542
''' 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...
sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80
\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\xb0\x66\x89\xe1\xcd\x80" "\x97\x5b\x68"...
rsalmaso/django-cms
cms/migrations/0015_auto_20160421_0000.py
Python
bsd-3-clause
391
0.002558
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cms', '0014_auto_20160404_1908'), ] operations = [ migrations.AlterField( model_name='cmsplugin', name='position', field=models.PositiveSma
llInte
gerField(default=0, verbose_name='position', editable=False), ), ]
rbmj/pyflightcontrol
pyflightcontrol/base/__init__.py
Python
apache-2.0
305
0
from . import font from .i
ndicator import Indicator, IndicatorOptions from .airspeed import AirspeedIndicator from .altitude import AltitudeIndicator from .attitude import AttitudeIndicator from .compass import CompassIndicator from .pfd import PFD from .joystic
k import Joystick from . import base_test
MarxMustermann/OfMiceAndMechs
src/itemFolder/military/bomb.py
Python
gpl-3.0
1,990
0.009045
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 trig...
unCallbackEvent( #src.gamestate.gamestate.tick+random.randint(1,4)+delay src.gamestate.gamestate.tick+1 ) event.setCallback({"container": self, "method": "destroy"}) self.container.addEvent(event) def destroy(self, generateScrap=True): """ destroy the...
offsets = [(0,0),(1,0),(-1,0),(0,1),(0,-1)] random.shuffle(offsets) delay = 1 if isinstance(self.container,src.rooms.Room): delay = 2 for offset in offsets[:-1]: new = src.items.itemMap["Explosion"]() self.container.addItem(new,(self.xPositi...
huaiping/pandora
salary/models.py
Python
mit
332
0.03012
from django.db import models class Salary(models.Model): id = models.AutoField(prim
ary_key = True) bh = models.CharField(max_length = 10) xm = models.CharField(max_length = 12) status = models.CharField(max_length = 8) class Meta: db_table = 'swan_salary'
def __str__(self): return self.id
PeterDowdy/py-paradox-convert
tests/serialization_tests.py
Python
mit
2,040
0.007353
import unittest import serializer __author__ = 'peter' class SerializationTests(unittest.TestCase): def test_serialize_single_key_value_pair(self): input = [{ 'name': 'value' }] expected_output = "name=value" output = serializer.serialize(input) self.assertEquals(cmp(expected_outp...
t', 'second']}] expected_output = 'name={\r\n\tfirst\r\n\tsecond\r\n}' output = serializer.serialize(input) self.assertEquals(cmp(expected_output, output), 0) def test_serialize_nested_key(self): input = [{ 'name': [{'sub_name': 'derp'}]}] expected_output = 'name={\r\n\tsub_...
pected_output, output), 0) def test_serialize_array_of_kvps(self): input = [{'name one': 'value one'},{'name two':'value two'}] expected_output = 'name one=value one\r\nname two=value two' output = serializer.serialize(input) self.assertEquals(cmp(expected_output, output), 0) d...
xbmcmegapack/plugin.video.megapack.dev
resources/lib/menus/home_countries_virgin_islands_us.py
Python
gpl-3.0
1,134
0.00265
#!/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 Softwar...
ot, see http://www.gnu.org/licenses/gpl-3.0.html """ class Countries_Virgin_islands_us(): '''Class that manages this specific menu context.''' def open(self, plugin, menu): menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels", "Events", "Li
ve", "Movies", "Sports", "TVShows"], countries=["Virgin Islands, U.S."]))
willthames/ansible-lint
lib/ansiblelint/rules/GitHasVersionRule.py
Python
mit
1,699
0
# 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 Software without restriction, including without limitation the rights # to use, copy, modify...
E SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDIN
G BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH TH...
luci/luci-py
client/third_party/depot_tools/fix_encoding.py
Python
apache-2.0
12,497
0.009842
# Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Collection of functions and classes to fix various encoding problems on multi
ple platforms with p
ython. """ from __future__ import print_function import codecs import locale import os import sys # Prevents initializing multiple times. _SYS_ARGV_PROCESSED = False def complain(message): """If any exception occurs in this file, we'll probably try to print it on stderr, which makes for frustrating debugging ...
kleptog/saautopool
saautopool.py
Python
mit
3,786
0.002905
import sqlalchemy.pool import time import math class SAAutoPool(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 m...
r testing. return time.time() def _update_qsize(self, ts, checkout): # An weighted average, where one minute ago counts half as much. w = math.exp( (ts-self.last_ts)*self.decay_rate ) self.last_ts = ts self.rate = w*self.rate if checkout: self.rate += (1...
cay_rate)) level = self.checkedout() self.mean = w*self.mean + (1-w)*level if ts > self.next_update: # The idea is that if we know there are 20 checkouts per second, # then we want to aim that only 5% of checkouts lead to an # actual new connection. The num...
ritashugisha/neat
neat/pipe/__init__.py
Python
gpl-3.0
255
0
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright (c) 2017 Stephen Bunn (stephen@bunn.io) # G
NU GPLv3 <https://www.gnu.org/licenses/gpl-3.
0.en.html> from ._common import * from .rethinkdb import RethinkDBPipe from .mongodb import MongoDBPipe
vmax-feihu/hue
apps/useradmin/src/useradmin/ldap_access.py
Python
apache-2.0
14,369
0.009326
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
import desktop.conf from desktop.lib.python_
util import CaseInsensitiveDict LOG = logging.getLogger(__name__) CACHED_LDAP_CONN = None class LdapBindException(Exception): pass class LdapSearchException(Exception): pass def get_connection_from_server(server=None): ldap_servers = desktop.conf.LDAP.LDAP_SERVERS.get() if server and ldap_servers: ...
colloquium/spacewalk
backend/server/rhnUser.py
Python
gpl-2.0
28,422
0.004398
# # Copyright (c) 2008--2010 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a c...
Mr." changed = 1 # fields in site if name in ["phone", "fa
x", "zip"]: self.site[name] = value[:32] changed = 1 elif name in ["city", "country", "alt_first_names", "alt_last_name", "address1", "address2", "email", "last_name", "first_names"]: if name == "last_name": self.si...
michaelhkw/incubator-impala
testdata/bin/random_avro_schema.py
Python
apache-2.0
6,014
0.00981
#!/usr/bin/env impala-python # # Lice
nsed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use thi...
file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # ...
johnreswebpro/CoilSnake
coilsnake/util/eb/text.py
Python
gpl-3.0
1,914
0.002612
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...
try: bracket_byte_value = int(bracket_byte, 16) except ValueError as e: raise ValueError("String contains invalid hex number '{}': {}".format( bracket_byte, text ), e) byte_list.append(brack...
et_pos + 1 else: byte_list.append(ord(c) + 0x30) text_pos += 1 num_bytes = len(byte_list) if num_bytes > max_length: raise ValueError("String cannot be written in {} bytes or less: {}".format( max_length, text )) elif num_bytes < max_length: ...
fredmorcos/attic
projects/grafeo/attic/grafeo_20100227_python/grafeo/config/Config.py
Python
isc
46
0
INST
ALL_PATH = '/home/fred/
workspace/grafeo/'
leppa/home-assistant
homeassistant/util/location.py
Python
apache-2.0
6,274
0.000956
""" 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...
ne 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"), "city": raw_info.get("city"), "zip_code": raw_info.get("postal"), ...
jmakov/ggrc-core
test/selenium/src/lib/page/widget/admin_people.py
Python
apache-2.0
457
0.002188
# Copyright (C) 2015 Google Inc., authors, and contributors <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.const
ants import url from lib.page.widget.base import Widget class AdminPeople(Widget): URL = environment.APP_URL \ + url.ADMIN_DASHBOARD \ + url.Widget.
PEOPLE
wood-galaxy/FreeCAD
src/Mod/Fem/FemInputWriter.py
Python
lgpl-2.1
9,277
0.003557
# *************************************************************************** # * * # * Copyright (c) 2016 - Bernd Hahnebach <bernd@bimstatik.org> * # * * # * Th...
: # get nodes for femobj in self.planerotation_objects: # femobj --> dict, FreeCAD document object is femobj['Object'] femobj['Nodes'] = FemMeshTools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) def get_constraints_transform_nodes(self): # get nodes f
or femobj in self.transform_objects: # femobj --> dict, FreeCAD document object is femobj['Object'] femobj['Nodes'] = FemMeshTools.get_femnodes_by_femobj_with_references(self.femmesh, femobj) def get_constraints_temperature_nodes(self): # get nodes for femobj in self.temperature_object...
chebee7i/dit
dit/other/extropy.py
Python
bsd-3-clause
2,122
0.000471
""" 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...
d to calculate the extropy. If None, then the extropy is calculated over all random variables. This should remain `None` for ScalarDistributions. rv_mode : str, None Specifies how to interpret the elements of `rvs`. Valid options are: {'indices', 'names'}. If equal to 'indices', then...
to 'names', the the elements are interpreted as random variable names. If `None`, then the value of `dist._rv_mode` is consulted. Returns ------- J : float The extropy of the distribution. """ try: # Handle binary extropy. float(dist) except TypeError: ...
czchen/debian-lxc
config/yum/lxc-patch.py
Python
lgpl-2.1
1,850
0.000541
# Yum plugin to re-patch container rootfs after a yum update is done # # Copyright (C) 2012 O
racle # # 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 Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Library General ...
heilaaks/snippy
snippy/server/rest/api_fields.py
Python
agpl-3.0
3,524
0.000568
# -*- 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 ...
ttp_status() Cause.reset() self._logger.debug('end: %s %s', request.method, request.uri) @staticmethod @Logger.
timeit(refresh_oid=True) def on_post(request, response): """Create new field.""" ApiNotImplemented.send(request, response) @staticmethod @Logger.timeit(refresh_oid=True) def on_put(request, response): """Change field.""" ApiNotImplemented.send(request, response) @...
oliver-sanders/cylc
tests/unit/parsec/test_validate.py
Python
gpl-3.0
21,599
0
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # 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 Licen...
IST, default=1, options=[1, 2, 3, 4]) cfg = OrderedDictWithDefaults() cfg['value'] = "1, 2, 3" msg = None values.append((spec, cfg, msg)) # set 2 (t, t, f, t) with Conf('base') as spec:
Conf('value', VDR.V_INTEGER_LIST, default=1, options=[1, 2, 3, 4]) cfg = OrderedDictWithDefaults() cfg['value'] = "1, 2, 5" msg = '(type=option) value = [1, 2, 5]' values.append((spec, cfg, msg)) # set 3 (f, f, t, f) with Conf('base') as spec: Conf('value', VDR.V_INTEGER, default=1...
erasche/python-apollo
arrow/commands/annotations/get_comments.py
Python
mit
652
0.001534
import click from arrow.cli import pass_context, json_loads from arrow.decorators im
port custom_exception, dict_output @click.command('get_comments') @click.argument("feature_id", type=str) @click.option( "--organism", help="Organism Common Name", type=str ) @click.option( "--sequence", help="Sequence Name", type=str ) @pass_context @custom_exception @dict_output def cli(ctx,...
dard apollo feature dictionary ({"features": [{...}]}) """ return ctx.gi.annotations.get_comments(feature_id, organism=organism, sequence=sequence)
nirvn/QGIS
python/plugins/processing/algs/qgis/SelectByAttribute.py
Python
gpl-2.0
5,528
0.001447
# -*- coding: utf-8 -*- """ *************************************************************************** SelectByAttribute.py --------------------- Date : May 2010 Copyright : (C) 2010 by Michael Minn Email : pyqgis at michaelminn dot com *******************...
self.tr('Selected (attribute)'))) def name(self): return 'selectbyattribute' def displayName(self): return self.tr('Select by attribute') def processAlgorithm(self, parameters, context, feedback): layer = self.parameterAsVectorLayer(parameters, self.INPUT, context) field...
me = self.parameterAsString(parameters, self.FIELD, context) operator = self.OPERATORS[self.parameterAsEnum(parameters, self.OPERATOR, context)] value = self.parameterAsString(parameters, self.VALUE, context) fields = layer.fields() idx = layer.fields().lookupField(fieldName) f...
soumith/convnet-benchmarks
chainer/vgga.py
Python
mit
1,463
0.001367
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.Convolution2D( 64, 128, 3, stride=1, pad=1) self.conv3 = L.Convolution2D(128, 256, 3, stride=1, pad=1) sel
f.conv4 = L.Convolution2D(256, 256, 3, stride=1, pad=1) self.conv5 = L.Convolution2D(256, 512, 3, stride=1, pad=1) self.conv6 = L.Convolution2D(512, 512, 3, stride=1, pad=1) self.conv7 = L.Convolution2D(512, 512, 3, stride=1, pad=1) self.conv8 = L.Convolution2D(512, 512, ...
cainmatt/django
tests/check_framework/test_urls.py
Python
bsd-3-clause
1,638
0.001832
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...
t = check_url_config(None) self.assertEqual(len(
result), 1) warning = result[0] self.assertEqual(warning.id, 'urls.W002') expected_msg = "Your URL pattern '/starting-with-slash/$' has a regex beginning with a '/'" self.assertIn(expected_msg, warning.msg) @override_settings(ROOT_URLCONF='check_framework.urls_name') def test_ur...
mdpiper/csdms-wiki-api-examples
ask_api_examples/list_model_repo_doi.py
Python
mit
327
0
"""Find all models written by user Hutton, including the DOI and the source code repository f
or each model. """ from ask_api_examples import make_query query = '[[Last name::Hutton]]|?DOI model|?Source web address' def main(): r = make_query(query, __fi
le__) return r if __name__ == '__main__': print main()
bbenligiray/keras_models
not_used/xception.py
Python
mit
11,593
0.002156
# -*- coding: utf-8 -*- """Xception V1 model for Keras. On ImageNet, this model gets to a top-1 validation accuracy of 0.790 and a top-5 validation accuracy of 0.945. Do note that the input image format for this model is different than for the VGG16 and ResNet models (299x299 instead of 224x224), and that the input p...
ides=(2, 2), padding='same', use_bias=False)(x) residual = BatchNormalization()(residual) x = Activation('relu', name='block3_sepconv1_act')(x) x = SeparableConv2D(256, (3, 3), padding='same',
use_bias=False, name='block3_sepconv1')(x) x = BatchNormalization(name='block3_sepconv1_bn')(x) x = Activation('relu', name='block3_sepconv2_act')(x) x = SeparableConv2D(256, (3, 3), padding='same', use_bias=False, name='block3_sepconv2')(x) x = BatchNormalization(name='block3_sepconv2_bn')(x) x = ...
idea4bsd/idea4bsd
python/testData/copyPaste/Whitespace.after.py
Python
apache-2.0
59
0.016949
def
f(): try: a = 1 except: b = 1
rwl/PyCIM
CIM14/IEC61968/PaymentMetering/LineDetail.py
Python
mit
2,482
0.004432
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associate
d documentation files (the "Software"), to # deal in the Software 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 followin...
s of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OT...
apavlo/h-store
src/catgen/catalog_utils/testdata.py
Python
gpl-3.0
1,429
0.004899
#!/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...
Database { /** test comment */ // more comments Partition* partitions; // more comments Table* tables; Program* programs; Procedure* procedures; } /* class Garbage { Garbage garbage; } */ class Partition { bool isActive; Range* ranges; Replica* re...
Table? buddy1; Table? buddy2; Column* columns; Index* indexes; Constraint* constraints; } class Program { Program* programs; Procedure* procedures; Table* tables; } """ def checkeq( a, b ): if a != b: raise Exception( 'test failed: %r != %r' % (a,b) ...
rzr/synapse
tests/rest/client/v1/utils.py
Python
apache-2.0
4,828
0.000829
# -*- 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...
tations under the License. # twisted imports from twisted.internet import defer # trial imports from tests im
port unittest from synapse.api.constants import Membership import json import time class RestTestCase(unittest.TestCase): """Contains extra helper functions to quickly and clearly perform a given REST action, which isn't the focus of the test. This subclass assumes there are mock_resource and auth_user...
cea-ufmg/pyfdas
pyfdas/mavlog.py
Python
mit
891
0.001122
"""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")
parser.add_argument("--device", required=True, help="serial port") parser.add_argument("--log", type=argparse.FileType('w'), help="Log file") parser.add_argument("--baudrate", type=int, help="serial port baud rate", default=57600) args = parser.parse_args() ...
s.verbose and msg is not None: print(msg) if __name__ == '__main__': main()
trunetcopter/trunetcopter
gui/pymavlink/mavextra.py
Python
gpl-3.0
16,655
0.005344
#!/usr/bin/env python ''' useful extra functions for use by mavlink clients Copyright Andrew Tridgell 2011 Released under GNU GPL version 3 or later ''' import os, sys from math import * sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'examples')) try: # rotmat doesn't work on Python...
values''' global last_diff ret = 0 if not key in last_diff: last_diff[key] = var return 0 ret = var - last_diff[key] last_diff[key] = var return ret last_delta = {} def delta(var, key, tusec=None): '''calculate slope''' global last_delta if tusec is not None: ...
tnow = mavutil.mavfile_global.timestamp dv = 0 ret = 0 if key in last_delta: (last_v, last_t, last_ret) = last_delta[key] if last_t == tnow: return last_ret if tnow == last_t: ret = 0 else: ret = (var - last_v) / (tnow - last_t) ...
iirob/python-opcua
opcua/server/standard_address_space/standard_address_space_part11.py
Python
lgpl-3.0
125,106
0.000767
# -*- coding: utf-8 -*- """ DO NOT EDIT THIS FILE! It is automatically generated from opcfoundation.org schemas. """ from opcua import ua from opcua.ua import NodeId, QualifiedName, NumericNodeId, StringNodeId, GuidNodeId from opcua.ua import NodeClass, LocalizedText def create_standard_address_space_Part11(server)...
erver.add_references(refs) node = ua.AddNodesItem() node.RequestedNewNodeId = NumericNodeId(11193, 0) node.BrowseName = QualifiedName('AccessHistoryDataCapability', 0) node.NodeClass = NodeClass.Variable node.ParentNodeId = NumericNodeId(11192, 0) node.ReferenceTypeId = NumericNodeId(46, 0) ...
edText("AccessHistoryDataCapability") attrs.DataType = ua.NodeId(ua.ObjectIds.Boolean) attrs.ValueRank = -1 node.NodeAttributes = attrs server.add_nodes([node]) refs = [] ref = ua.AddReferencesItem() ref.IsForward = True ref.ReferenceTypeId = NumericNodeId(40, 0) ref.SourceNodeId = N...
rackerlabs/solum-horizon
solumdashboard/exceptions.py
Python
apache-2.0
854
0.001171
# 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...
Y KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from openstack_dashboard import exceptions #fr
om solumclient.openstack.common.apiclient import exceptions as solumclient NOT_FOUND = exceptions.NOT_FOUND RECOVERABLE = exceptions.RECOVERABLE # + (solumclient.ClientException,) UNAUTHORIZED = exceptions.UNAUTHORIZED
prestodb/presto-admin
tests/unit/test_catalog.py
Python
apache-2.0
9,157
0.000655
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
p(ConfigurationError, 'Catalog configuration example.properties ' 'does not contain connector.name', catalog.add, 'example
') @patch('prestoadmin.catalog.os.path.isfile') def test_validate_fail(self, is_file_mock): is_file_mock.return_value = True self.assertRaisesRegexp( SystemExit, 'Error validating ' + os.path.join(get_catalog_directory(), 'example.properties') + '\n\n' 'Unde...
Krakn/learning
src/python/python_koans/python2/about_decorating_with_functions.py
Python
isc
832
0
#!/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_de...
tor) # ------------------------------------------------------------------ def xmltag(fn): def func(*args): return '<' + fn(*args) + '/>' return func @xmltag def render_tag(self, name): return name def test_decorators_can_change_a_function_o
utput(self): self.assertEqual(__, self.render_tag('llama'))
wintoncode/winton-kafka-streams
docs/conf.py
Python
apache-2.0
5,443
0.002021
#!/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 ...
) for mod_name in MOCK_MODULES) # -- General configuration ------------------------------------------------ # If your documentati
on needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ['sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to th...
Avantol13/mgen
dev/scripts/_project_cfg_importer.py
Python
gpl-3.0
1,937
0.005163
""" 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...
========== ERROR ========================================" "\nUnable to import project configuration: " + PROJECT_CFG_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 if project_cfg_module.__CFG_VERSION__ == EXPECTED_CFG_VERSION: is_correct_version = True else: ...
bcheung92/Paperproject
gem5/pyscript/cachecmp.py
Python
mit
2,915
0.026072
#!/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...
.search(threadlines) threadendmatch = threadendPatte
rn.match(threadlines) if dtbwalker1match: dtbwalker1=int(dtbwalker1match.group(2)) if itbwalker1match: itbwalker1=int(itbwalker1match.group(2)) if dtbwalker2match: dtbwalker2=int(dtbwalker2match.group(2)) if itbwalker2match: itbwalker2=int(itbwalker2match.group(2)) if overallhitsmatch: ...
CMUSV-VisTrails/WorkflowRecommendation
vistrails/index/vistrailanalyzer.py
Python
bsd-3-clause
4,209
0.012354
############################################################################### ## ## 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, ...
# 32 char md5 sums "[a-f0-9]{32}", # '2D', '3D' "2D", "3D", # words beginning with capital letters "[A-Z][a-z]+"
, # capital letter sequence ending with a word that begins with a capital letter "[A-Z]*(?=[A-Z][a-z])", # capital letter sequence "[A-Z]{2,}", # non-capital letter sequence "[a-z]{2,}" ] splitPattern = re.compile("|".join(patterns)) class vistrailFilter(PythonTokenFilter): TOKEN_TYPE_PAR...
ikalnytskyi/holocron
src/holocron/_processors/_misc.py
Python
bsd-3-clause
4,296
0.000466
"""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...
need to save resolved value in both arguments and # kwargs mappings, because the former is used to *validate* # passed arguments, and the latter to supply a value from a # fallback. arguments[param] = kwargs[param] = value if ...
def is_encoding(value): if isinstance(value, str): import codecs return codecs.lookup(value) @format_checker.checks("timezone", ()) def is_timezone(value): if isinst...
adh/py-clos
py_clos/base.py
Python
mit
7,245
0.003313
# -*- 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...
ifiers=[], next_method_arg=None): self.proc = proc self.specializers = specializers self.qualifiers = qualifier
s self.next_method_arg = next_method_arg @property def specialized_on(self): return [idx for idx, i in enumerate(self.specializers) if i != None] def matches(self, args): for idx, i in enumerate(self.specializers): if i is None: continue if n...
sridevikoushik31/nova
nova/tests/virt/xenapi/test_volumeops.py
Python
apache-2.0
8,108
0
# 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...
ect_volume(connection_info, dev_number, instance_name, vm_ref, hotplug=False) self.assertEquals(False, called['VBD.plug']) def test_connect_volume(self): session = stubs.FakeSessionForVolumeTests('fake_uri') ops = volume
ops.VolumeOps(session) sr_uuid = '1' sr_label = 'Disk-for:None' sr_params = '' sr_ref = 'sr_ref' vdi_uuid = '2' vdi_ref = 'vdi_ref' vbd_ref = 'vbd_ref' connection_data = {'vdi_uuid': vdi_uuid} connection_info = {'data': connection_data, ...
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.1/Lib/UserString.py
Python
mit
7,530
0.00571
#!/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...
def isalpha(self): return self.data.isalpha() def isalnum(self): return self.data.isalnum() def isdecimal(self): return self.data.isdecimal() def isdigit(sel
f): return self.data.isdigit() def islower(self): return self.data.islower() def isnumeric(self): return self.data.isnumeric() def isspace(self): return self.data.isspace() def istitle(self): return self.data.istitle() def isupper(self): return self.data.isupper() def join(self, seq): return sel...
derrickyoo/serve-tucson
serve_tucson/locations/models.py
Python
bsd-3-clause
956
0
from django.contrib.auth.models import User from django.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_...
elf.id)]) def __str__(self): return '{id: %d, latitude: %d, longitude: %d}' % ( self.id, self.latitude, self.longitude ) class Meta: app_label = 'location
s' get_latest_by = 'updated' ordering = ['updated'] verbose_name = 'location' verbose_name_plural = 'Locations'
baojianzhou/DLReadingGroup
keras/examples/variational_autoencoder_deconv.py
Python
apache-2.0
7,159
0.000698
'''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...
vae.compil
e(optimizer='rmsprop', loss=None) vae.summary() # train the VAE on MNIST digits (x_train, _), (x_test, y_test) = mnist.load_data() x_train = x_train.astype('float32') / 255. x_train = x_train.reshape((x_train.shape[0],) + original_img_size) x_test = x_test.astype('float32') / 255. x_test = x_test.reshape((x_test.shap...
wheeler-microfluidics/dmf_control_board_plugin
_version.py
Python
bsd-3-clause
18,441
0
# This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # d
irectories (produced by setup.py build) will contain a much shorte
r file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.17 (https://github.com/warner/python-versioneer) """Git implementation of _version.py.""" import errno import os import re import subprocess import sys def get_keywords(): """Get...
KnowNo/reviewboard
reviewboard/webapi/server_info.py
Python
mit
3,158
0
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': ...
gistered set of web API capabilities.""" try: del _registered_capabilities[capabilities_id] except KeyError: logging.error('Failed to unregister unknown web API capabilities ' '"%s".', capabilities_id)
raise KeyError('"%s" is not a registered web API capabilities set' % capabilities_id)
plotly/python-api
packages/python/plotly/plotly/validators/scatter3d/error_z/_valueminus.py
Python
mit
512
0.001953
import _plotly_utils.basevalidators class ValueminusValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="valueminus", parent_
name="scatter3d.error_z", **kwar
gs ): 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("role", "info"), **kwargs )
rmk135/objects
tests/unit/wiring/test_wiringfastapi_py36.py
Python
bsd-3-clause
1,426
0.004208
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(__fi...
OP_DIR) sys.path.append(_SAMPLES_DIR) from asyncutils import AsyncTestCase from wiringfastapi import web class WiringFastAPITest(AsyncTestCase): client: AsyncClient def setUp(self) -> None: super().setUp() self.client = AsyncClient(app=web.app, base_url='http://test') def tearDown(sel...
().tearDown() def test_depends_marker_injection(self): class ServiceMock: async def process(self): return 'Foo' with web.container.service.override(ServiceMock()): response = self._run(self.client.get('/')) self.assertEqual(response.status_code, 200...
saltstack/salt
templates/test_state/tests/unit/states/test_{{module_name}}.py
Python
apache-2.0
590
0.015254
''' :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|capital
ize}}TestCase(TestCase, LoaderModuleMockMixin): def setup_loader_modules(self): return {% raw -%} { {% endraw -%} {{module_name}} {%- raw -%}: { '__env__': 'base' } } {%- endraw %} def test_behaviour(self): # Test inherent behaviours pas...
ehabkost/tp-qemu
qemu/tests/zero_copy.py
Python
gpl-2.0
2,659
0
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 guest nic works. 4) check vm is alive have no crash :param test: QEMU test object. :param params: Dictionary with the test parameters. :param env: Dictionary with test environment. """ def zerocp_enable_status(): """ Check whether host have enabled zero...
st_net/parameters/experimental_zcopytx" para_path = params.get("zcp_set_path", def_para_path) cmd_status = utils.system("grep 1 %s" % para_path, ignore_status=True) if cmd_status: return False else: return True def enable_zerocopytx_in_host(enable=True): ...
JackDanger/sentry
src/sentry/digests/__init__.py
Python
bsd-3-clause
910
0
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 = LazyServic...
settings.SENTRY_DIGESTS_OPTIONS, (DummyBackend,)) backend.expose(locals()) class Record(namedtuple('Record', 'key value timestamp')): @property def datetime(self): return to_datetime(self.timestamp) ScheduleEntry = namedtuple('ScheduleEntry', 'key times...
delay', 'minimum_delay', )) def get_option_key(plugin, option): assert option in OPTIONS return 'digests:{}:{}'.format(plugin, option)
lutris/humblebundle-python
humblebundle/handlers.py
Python
mit
5,985
0.000668
""" 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...
response_helper(response, data) # We didn't get a list, or an error message raise exceptions.HumbleResponseException( "Unexpected response body", request=response.request, response=response ) def order_list_handler(client, response): """ order_list response always returns JSON """ data =...
authenticated_response_helper(response, data) # We didn't get a list, or an error message raise exceptions.HumbleResponseException( "Unexpected response body", request=response.request, response=response ) def order_handler(client, response): """ order response might be 404 with no body if no...
nayyarv/MonteGMM
Inference/BayesInference.py
Python
mit
844
0.016588
__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 = t
ime.ctime() Xpoints = getCorpus(emotion, speakers[speakerIndex]) message = MCMCRun(Xpoints, emotion+"-"+speakers[speakerInde
x], numRuns, numMixtures) message += "Start time: {}\nEnd Time: {}\n".format(start, time.ctime()) message += "\nNumRuns: {}, numMixtures:{}\n ".format(numRuns, numMixtures) message += "\nEmotion: {}, speaker:{}\n".format(emotion, speakers[speakerIndex]) alertMe(message) if __name...
incuna/django-user-deletion
user_deletion/__init__.py
Python
bsd-2-clause
61
0
default_a
pp_config = 'user_deletion.apps.
UserDeletionConfig'
2prime/DeepLab
ResNet/models/googlenet.py
Python
mit
3,237
0.001236
'''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.d4 = Inception(512, 112, 144, 288, 32, 64, 64) self.e4 = Inception(528, 256, 160, 320, 32, 128, 128) self.a5 = Inception(832, 256, 160, 320, 32, 128, 128) self.b5 = Inception(832, 384, 192, 384, 48, 128, 128) self.avgpool = nn.AvgPool2d(8, stride=1) self.linear = nn.Li...
4(out) out = self.b4(out) out = self.c4(out) out = self.d4(out) out = 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 o...
chuwy/dopy
dopy/manager.py
Python
mit
9,514
0.003363
#!/usr/bin/env python #coding: utf-8 """ This module simply sends request to the Digital Ocean API, and returns their response as a dict. """ import requests API_ENDPOINT = 'https://api.digitalocean.com' class DoError(RuntimeError): pass class DoManager(object): def __init__(self, client_id, api_key): ...
) return json def snapshot_droplet(self, id, name): params = {'name': name} json = self.request('/droplets/%s/snapshot/' % id, params) json.pop('status', None) return json de
f restore_droplet(self, id, image_id): params = {'image_id': image_id} json = self.request('/droplets/%s/restore/' % id, params) json.pop('status', None) return json def rebuild_droplet(self, id, image_id): params = {'image_id': image_id} json = self.request('/drople...
MSeifert04/astropy
astropy/io/fits/tests/test_image.py
Python
bsd-3-clause
76,391
0.000406
# Licensed under a 3-clause BSD style license - see PYFITS.rst import math import os import re import time import warnings import pytest import numpy as np from numpy.testing import assert_equal from astropy.io import fits from astropy.tests.helper import catch_warnings, ignore_warnings from astropy.io.fits.hdu.comp...
== 'list index out of range' # And the same with the global config item assert fits.conf.lazy_load_hdus # True by default fits.conf.lazy_load_hdus = False try: r = fits.open(self.data('test0.fits')) r.close() assert isinstance(r[1], fits.ImageHDU) ...
ts.conf.lazy_load_hdus = True def test_fortran_array(self): # Test that files are being correctly written+read for "C" and "F" order arrays a = np.arange(21).reshape(3,7) b = np.asfortranarray(a) afits = self.temp('a_str.fits') bfits = self.temp('b_str.fits') # writ...
sathishpy/corrugation
corrugation/corrugation/doctype/cm_paper_management/test_cm_paper_management.py
Python
gpl-3.0
227
0.008811
# -*- coding: utf-8 -*- # Copyright
(c) 2017, sathishpy@gmail.com and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest class TestCMPaperManage
ment(unittest.TestCase): pass
kbrafford/pg
examples/terrain.py
Python
mit
2,927
0.00205
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 * ...
normals[(x3, z3)].append(n) # compute average normal for all vertices for key, value in normals.items(): normals[key] = pg.normalize(reduce(pg.add, value)) for x, y, z in position: normal.append(normals[(x, z)]) # generate vertex buffer vb = ...
(pg.interleave(position, normal, color)) self.context.position, self.context.normal, self.context.color = ( vb.slices(3, 3, 3)) def update(self, t, dt): matrix = pg.Matrix() matrix = self.wasd.get_matrix(matrix) matrix = matrix.perspective(65, self.aspect, 0.1, 1000) ...
jyt109/termite-data-server
server_src/modules/core.py
Python
bsd-3-clause
4,206
0.07204
#!/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...
a = {} for key in env: value = env[key] if isinstance( value, dict ) or \ isinstance(
value, list ) or isinstance( value, tuple ) or \ isinstance( value, str ) or isinstance( value, unicode ) or \ isinstance( value, int ) or isinstance( value, long ) or isinstance( value, float ) or \ value is None or value is True or value is False: data[ key ] = value else: data[ key...
mscuthbert/abjad
abjad/tools/selectiontools/test/test_selectiontools_Parentage_logical_voice.py
Python
gpl-3.0
10,702
0.000748
# -*- encoding: utf-8 -*- from abjad import * import pytest def test_selectiontools_Parentage_logical_voice_01(): r'''An anonymous staff and its contained unvoiced leaves share the same signature. ''' staff = Staff("c'8 d'8 e'8 f'8") containment = inspect_(staff).get_parentage().logical_voice ...
def test_selectiontools_Parentage_logical_voice_02(): r'''A named staff and its contained unvoiced leaves share the same signature. ''' staff = Staff("c'8 d'8 e'8 f'8") staff.name = 'foo' containment = inspect_(staff).get_parentage().logical_voice for com
ponent in iterate(staff).by_class(): assert inspect_(component).get_parentage().logical_voice == containment def test_selectiontools_Parentage_logical_voice_03(): r'''Leaves inside equally named sequential voices inside a staff share the same signature. ''' staff = Staff(Voice("c'8 d'8 e'8 f'8...
tensorflow/addons
tensorflow_addons/image/tests/filters_test.py
Python
apache-2.0
11,712
0.000256
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may noa 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...
_test) def test_symmetric_padding_with_3x3_filter_mean(image_shape): expected_plane = tf.constant( [ [2.3333333, 3.0, 3.6666667], [4.3333335, 5.0, 5.6666665],
[6.3333335, 7.0, 7.6666665], ] ) verify_values( mean_filter2d, image_shape=image_shape, filter_shape=(3, 3), padding="SYMMETRIC", constant_values=0, expected_plane=expected_plane, ) @pytest.mark.parametrize("image_shape", [(1,), (16, 28, 28,...