code
stringlengths
281
23.7M
def _assemble_broker_tas_lookup_records() -> list: base_record = {'created_at': None, 'updated_at': None, 'tas_id': None, 'allocation_transfer_agency': None, 'agency_identifier': None, 'beginning_period_of_availa': None, 'ending_period_of_availabil': None, 'availability_type_code': None, 'main_account_code': None, ...
.integration class TestUpgradeWithEjectAccept(BaseTestUpgradeWithEject): CONFIRM_OUTPUT = [True, True] GENERIC_SELLER = ComponentId(ComponentType.SKILL, PublicId.from_str('fetchai/generic_seller:0.24.0')) EXPECTED_CLICK_ECHO_CALLS = ['Ejecting (skill, fetchai/generic_seller:0.24.0)...', 'Ejecting item skill...
def main(): module_spec = schema_to_module_spec(versioned_schema) mkeyname = 'name' fields = {'access_token': {'required': False, 'type': 'str', 'no_log': True}, 'enable_log': {'required': False, 'type': 'bool', 'default': False}, 'vdom': {'required': False, 'type': 'str', 'default': 'root'}, 'member_path':...
class Solution(): def majorityElement(self, nums: List[int]) -> List[int]: (num1, num2) = (None, None) (c1, c2) = (0, 0) for n in nums: if (n == num1): c1 += 1 elif (n == num2): c2 += 1 elif (c1 == 0): num1 =...
.unit ('fides.api.ui.get_path_to_admin_ui_file') .parametrize('route, expected', [('index.html', True), ('//etc/passwd', False), ('dataset/new.html', True), ('//fides/example.env', False)]) def test_path_is_in_ui_directory(mock_get_path_to_admin_ui_file: Mock, tmp_static: Path, route: str, expected: bool): mock_get...
def _handle_hooks(cls, bases): hooks = [val.__attrs_post_init__ for val in bases if hasattr(val, '__attrs_post_init__')] if (hasattr(cls, '__post_hook__') or hasattr(cls, '__maps__') or (len(hooks) > 0)): if (hasattr(cls, '__post_hook__') and contains_return(cls.__post_hook__)): raise _Spock...
def _add_GSUB_feature_variations(font, axes, internal_axis_supports, rules, featureTags): def normalize(name, value): return models.normalizeLocation({name: value}, internal_axis_supports)[name] log.info('Generating GSUB FeatureVariations') axis_tags = {name: axis.tag for (name, axis) in axes.items(...
.parametrize('asgi', [True, False]) class TestPostQueryParamsDefaultBehavior(): def test_dont_auto_parse_by_default(self, asgi): app = create_app(asgi) resource = testing.SimpleTestResource() app.add_route('/', resource) client = testing.TestClient(app) headers = {'Content-Ty...
def test_fix_reference_namespace_is_working_properly_with_refs_updated_in_a_previous_scene(create_test_data, create_pymel, create_maya_env): data = create_test_data pm = create_pymel maya_env = create_maya_env data['asset2_model_main_v002'].is_published = True data['asset2_lookdev_take1_v001'].is_pu...
def test_tox(cookies, tmp_path): with run_within_dir(tmp_path): result = cookies.bake() assert (result.exit_code == 0) assert file_contains_text(f'{result.project_path}/.github/workflows/main.yml', 'pip install tox tox-gh-actions') assert os.path.isfile(f'{result.project_path}/tox.in...
class AbstractServer(): def __init__(self, host, port, loop=None, **kwargs): if ((sys.version_info > (3, 8)) and sys.platform.startswith('win')): asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) if (loop is None): self._loop = asyncio.get_event_loop() ...
def _check_path_safe_to_write(sql_path: Path, py_path: Path): if sql_path.exists(): with open(sql_path, 'r') as file: contents = file.read() (checksum, found) = _checksum(contents) if ((not found) or (checksum != found)): LOGGER.debug(f'''Existing file cal...
def extractBlackbellyblWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_ty...
def delTransport(snmpEngine, transportDomain): if (not snmpEngine.transportDispatcher): return transport = getTransport(snmpEngine, transportDomain) snmpEngine.transportDispatcher.unregisterTransport(transportDomain) automaticTransportDispatcher = snmpEngine.getUserContext('automaticTransportDis...
def extractZigguratlocalizationsBlogspotCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, nam...
class OptionPlotoptionsArcdiagramSonificationDefaultinstrumentoptionsMappingPan(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text...
def namespace_manifest(namespace: str) -> str: ret = f''' --- apiVersion: v1 kind: Namespace metadata: name: {namespace} ''' if os.environ.get('DEV_USE_IMAGEPULLSECRET', None): dockercfg = {'auths': {os.path.dirname(os.environ['DEV_REGISTRY']): {'auth': b64encode(((os.environ['DOCKER_BUILD_USERNAME'] ...
class OptionSeriesDumbbellDataDatalabels(Options): def align(self): return self._config_get('center') def align(self, text: str): self._config(text, js_type=False) def allowOverlap(self): return self._config_get(False) def allowOverlap(self, flag: bool): self._config(flag...
class Spreadsheet(): def __init__(self, name, title): self.workbook = Workbook(name) self.name = name self.headers = [] try: self.sheet = self.workbook.getSheet(title) except KeyError: self.sheet = self.workbook.addSheet(title) def addTitleRow(self...
def main(page: ft.Page): def on_new_game(settings): page.controls.pop() new_solitaire = Solitaire(settings, on_win) page.add(new_solitaire) page.update() def on_win(): page.add(ft.AlertDialog(title=ft.Text('YOU WIN!'), open=True)) print('You win') page.upd...
def main(): parser = argparse.ArgumentParser(prog='calc_cam16_ucs_jmh_min_m.py', description='Calculate min M for achromatic colors in CAM16 UCS JMh and map current spline against real values.') parser.add_argument('--res', '-r', type=int, default=50000, help='Resolution to use when calculating range, default i...
def extractRbktrtranslationsWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Residence of Monsters', 'Residence of Monsters', 'translated'), ('Jin Xiao Yi Tan', 'Ji...
class RFC6455WebSocket(WebSocket): def __init__(self, sock, environ, version=13, protocol=None, client=False, extensions=None, max_frame_length=DEFAULT_MAX_FRAME_LENGTH): super().__init__(sock, environ, version) self.iterator = self._iter_frames() self.client = client self.protocol =...
def replace_arg(value, resolve_args): result = value re_if = re.compile('\\$\\(arg.(?P<name>.*?)\\)') for arg in re_if.findall(value): if (arg in resolve_args): result = result.replace(('$(arg %s)' % arg), resolve_args[arg]) if value.startswith('$(eval'): re_if = re.compile("...
class NameSuffixTestCase(IdModifyMixin, unittest.TestCase): initial_fasta = '>seq1\nACGT\n>gi|260674|gb|S52561.1| {long terminal repeat} [human immunodeficiency virus type]\nACGT' target_fasta = '>seq1.post\nACGT\n>gi|260674|gb|S52561.1|.post {long terminal repeat} [human immunodeficiency virus type]\nACGT' ...
class IGShoppingReviewStatusReasonWithHelpMessage(AbstractObject): def __init__(self, api=None): super(IGShoppingReviewStatusReasonWithHelpMessage, self).__init__() self._isIGShoppingReviewStatusReasonWithHelpMessage = True self._api = api class Field(AbstractObject.Field): code ...
class AggregateResource(ApiResource): query_args = {} def args(self): return utils.extend(args.paging, self.query_args, self.sort_args) def sort_args(self): return args.make_sort_args(validator=args.IndexValidator(self.model)) def index_column(self): return self.model.idx
.parametrize('name', ('0_starts_with_digit', ' starts_with_space', '$starts_with_dollar', 'has_dollar_$_inside', 'has spaces')) def test_serializable_field_names_must_be_valid_identifiers(name): with pytest.raises(TypeError, match=f'not valid python identifiers: `{re.escape(name)}`'): class Klass(Serializab...
class Render(): def get_selected_shading_nodes(cls): selected_nodes = [] for mat in bpy.data.materials: if mat.node_tree: for node in mat.node_tree.nodes: if node.select: selected_nodes.append(node) return selected_nodes...
class RefreshTokenTests(mixins.RefreshMixin, RelaySchemaTestCase): query = '\n mutation RefreshToken($input: RefreshInput!) {\n refreshToken(input: $input) {\n token\n payload\n refreshToken\n refreshExpiresIn\n clientMutationId\n }\n }' refresh_token_mutations...
def check_vulnerable(fobj, path_chain, stats, has_jndilookup=True): md5sum = md5_digest(fobj) first_path = bold(path_chain.pop(0)) path_chain = ' -> '.join((str(p) for p in ([first_path] + path_chain))) comment = collections.ChainMap(MD5_BAD, MD5_GOOD).get(md5sum, 'Unknown MD5') color_map = {'vulner...
class TickerInfo(): def __init__(self, client): self.exinfo = client.get_exchange_info() self.info = client.get_account() self.tickers = client.get_symbol_ticker() def _list_select(list, key, value): ret = [l for l in list if (l[key] == value)] if (len(ret) == 0): ...
def test_eq(accounts): pub = PublicKeyAccount('0x14b0Ed2a7C4cC60DD8F676AE44D0831d3c9b2a9E') assert (pub == PublicKeyAccount('0x14b0Ed2a7C4cC60DD8F676AE44D0831d3c9b2a9E')) assert (pub == '0x14b0Ed2a7C4cC60DD8F676AE44D0831d3c9b2a9E') assert (pub != 'potato') assert (PublicKeyAccount(accounts[0]) == ac...
def calc_intervals(bins_log2s, weights, func): out_vals_lo = np.repeat(np.nan, len(bins_log2s)) out_vals_hi = np.repeat(np.nan, len(bins_log2s)) for (i, ser) in enumerate(bins_log2s): if len(ser): wt = weights[ser.index] assert (wt.index == ser.index).all() (out_v...
class PlayerServer(Player): def __init__(self, channel: Channel, logger, *args, **kwargs): Player.__init__(self, *args, **kwargs) self._channel: Channel = channel self._connected: bool = True self._logger = (logger if logger else logging) def disconnect(self): if self._co...
def test_set_get_del_providers(): a_p13 = providers.Provider() b_p23 = providers.Provider() ContainerA.p13 = a_p13 ContainerB.p23 = b_p23 assert (ContainerA.providers == dict(p11=ContainerA.p11, p12=ContainerA.p12, p13=a_p13)) assert (ContainerB.providers == dict(p11=ContainerA.p11, p12=Containe...
def main(): args = _get_parser().parse_args() backend = args.backend.lower() updated_packages = get_updated_packages(get_updates_messages(args.delta), backend) log.info('Updated packages per datagrepper %s', len(updated_packages)) for (package, last_build) in PackagesLogic.webhook_package_candidates...
def create_gff(searcher_name, version, annotated_hits, outfile, rm_suffix, gff_ID_field): print(colorify(f'Decorating gff file {outfile}...', 'lgreen'), file=serr) with open(outfile, 'w') as OUT: print('##gff-version 3', file=OUT) print(f'## created with {version}', file=OUT) for (hit, a...
def validate_signature_block(image_content, sig_blk_num): offset = ((- SECTOR_SIZE) + (sig_blk_num * SIG_BLOCK_SIZE)) sig_blk = image_content[offset:(offset + SIG_BLOCK_SIZE)] assert (len(sig_blk) == SIG_BLOCK_SIZE) (magic, version, _, _, _, _, _, _, blk_crc) = struct.unpack('<BBxx32s384sI384sI384sI16x'...
def lab2xyz(lab, axis=(- 1), wp=whitepoints['D65'][(- 1)]): lab = np.asarray(lab) (L, a, b, axis) = separate_colors(lab, axis) fy = ((L + 16) / 116.0) fz = (fy - (b / 200.0)) fx = ((a / 500.0) + fy) def finv(y): eps3 = ((216 / 24389.0) ** 3) kap = (24389 / 27.0) return np...
class Window(QWidget): def __init__(self): super(Window, self).__init__() self.setWindowTitle('GL Waveform Test') self.glWidget = GLWaveformWidget() self.timeSlider = QSlider(Qt.Vertical) self.timeSlider.setRange(0, 300) self.timeSlider.setSingleStep(1) self.t...
def determine_filetype(path): logger = logging.getLogger(__name__) MRbase = os.path.basename(path) if MRbase.endswith('.nii'): if MRbase.endswith('.dtseries.nii'): MR_type = 'cifti' MRbase = MRbase.replace('.dtseries.nii', '') elif MRbase.endswith('.dscalar.nii'): ...
class WorkspaceRepository(BaseRepository[Workspace], UUIDRepositoryMixin[Workspace]): model = Workspace async def get_by_admin_user(self, user_id: uuid.UUID) -> list[Workspace]: statement = select(Workspace).join(Workspace.workspace_users).where((WorkspaceUser.user_id == user_id)) return (await ...
class SymbolPrinter(): def __init__(self, f): self.f = f self.funcs = {} self.operators = {} self.vars = {} def add_symbol(self, key, val): if (key.startswith('_') or key.startswith('_')): return if isinstance(val, fracttypes.Var): self.var...
class JsRowTotal(JsRecFunc): def extendArgs(category, originParams, newCols): originParams[0] += newCols return originParams def extendColumns(jsSchema, params): alias = 'row-total' params = ('seriesNames', 'rowDefinition') value = "\n seriesNames.forEach(function(v){rowDefinition...
class TVDBIDSelectorList(GUIComponent, object): GUI_WIDGET = eListbox def __init__(self): GUIComponent.__init__(self) self.l = eListboxPythonMultiContent() self.l.setFont(0, gFont('Regular', 19)) self.l.setItemHeight(186) self.l.setBuildFunc(self.buildList) def buildL...
class CompoundEdge(BaseEdge): description = 'Compound Edge' def __init__(self, boxes, types, lengths) -> None: super().__init__(boxes, None) self.types = [self.edges.get(edge, edge) for edge in types] self.lengths = lengths self.length = sum(lengths) def startwidth(self) -> f...
def _remap_reserved(field_name): idx = field_name.rfind('.') if (idx > 0): prefix = field_name[:(idx + 1)] sub_field_name = field_name[(idx + 1):] else: prefix = '' sub_field_name = field_name if (sub_field_name in (keyword.kwlist + ['self'])): sub_field_name = (s...
class PSStackParser(PSBaseParser): def __init__(self, fp): PSBaseParser.__init__(self, fp) self.reset() return def reset(self): self.context = [] self.curtype = None self.curstack = [] self.results = [] return def seek(self, pos): PSBas...
() ('-i', 'infile', type=click.File('r'), default='-', help='Input file (Default: stdin)') ('-v', 'verbose', is_flag=True, default=False, help='Verbose output') def cmd_data_enrich(infile, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') lines = infile.read().split('\n...
class OptionSeriesArearangeSonificationDefaultinstrumentoptionsMappingFrequency(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text...
def test_execute_python_workflow_list_of_floats(register): from .workflows.basic.list_float_wf import my_wf remote = FlyteRemote(Config.auto(config_file=CONFIG), PROJECT, DOMAIN) xs: typing.List[float] = [42.24, 999.1, 0.0001] execution = remote.execute(my_wf, name='basic.list_float_wf.my_wf', inputs={'...
class EmmetEvaluateMath(sublime_plugin.TextCommand): def run(self, edit: sublime.Edit): replacements = [] selections = self.view.sel() for sel in selections: if sel.empty(): line = self.view.line(sel.begin()) expr = emmet_sublime.evaluate_math(self...
('gitlabber.git.git') def test_clone_repo_interrupt(mock_git): mock_repo = mock.Mock() mock_git.Repo = mock_repo git.is_git_repo = mock.MagicMock(return_value=False) mock_git.Repo.clone_from.side_effect = KeyboardInterrupt('clone test keyboard interrupt') with pytest.raises(SystemExit): git....
class OptionPlotoptionsTimelineDatalabelsFilter(Options): def operator(self): return self._config_get(None) def operator(self, value: Any): self._config(value, js_type=False) def property(self): return self._config_get(None) def property(self, text: str): self._config(tex...
class TestStatusResource(): (before_hook) def on_get(self, req, resp): resp.status = falcon.HTTP_500 resp.set_header('X-Failed', 'True') resp.text = 'Fail' def on_post(self, req, resp): resp.status = falcon.HTTP_500 resp.set_header('X-Failed', 'True') resp.tex...
def test_ngrams(): ops = get_current_ops() arr1 = numpy.asarray([1, 2, 3, 4, 5], dtype=numpy.uint64) for n in range(1, 10): assert (len(ops.ngrams(n, arr1)) == max(0, (arr1.shape[0] - (n - 1)))) assert (len(ops.ngrams((- 1), arr1)) == 0) assert (len(ops.ngrams((arr1.shape[0] + 1), arr1)) == ...
class OptionPlotoptionsPolygonSonificationDefaultinstrumentoptionsMappingLowpassResonance(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(...
def extractNovelkarimaWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_typ...
def build_distributed_validator(validator_identity: ValidatorIdentity, num_covalidators: int=4) -> DistributedValidator: co_validators = [] for i in range(num_covalidators): co_validators.append(CoValidator(validator_identity=validator_identity, pubkey=BLSPubkey(str(i).zfill((48 * 2))), index=i)) sl...
def toggle_modal(n_clicks, src, is_open, last_ctx): n_clicks = ctx.triggered[0]['value'] trigger_id = ctx.triggered_id['index'] if ((not n_clicks) or ((trigger_id in last_ctx) and (last_ctx[trigger_id] == n_clicks))): raise PreventUpdate new_ctx = Patch() new_ctx[trigger_id] = n_clicks l...
class _IamProjectsServiceAccountsRepository(repository_mixins.GetIamPolicyQueryMixin, repository_mixins.ListQueryMixin, _base_repository.GCPRepository): def __init__(self, **kwargs): super(_IamProjectsServiceAccountsRepository, self).__init__(key_field='name', max_results_field='pageSize', component='projec...
class MaxLengthFilterTestCase(unittest.TestCase): def setUp(self): self.sequences = [SeqRecord(Seq('ACGT')), SeqRecord(Seq('ACTTT'))] def test_none_truncated(self): instance = quality_filter.MaxLengthFilter(6) actual = list(instance.filter_records(self.sequences)) self.assertEqua...
def test_generate_gpu_of_a_look_dev_of_an_environment(create_test_data, store_local_session, create_pymel, create_maya_env): data = create_test_data pm = create_pymel maya_env = create_maya_env gen = RepresentationGenerator(version=data['building1_yapi_model_main_v003']) gen.generate_gpu() gen.v...
def ec2_pipeline_setup(generated=None, project='', settings=None, env='', pipeline_type='', region='', region_subnets=None): data = copy.deepcopy(settings) user_data = generate_encoded_user_data(env=env, region=region, generated=generated, group_name=project, pipeline_type=pipeline_type) instance_security_g...
class OptionSeriesColumnpyramidSonificationContexttracksPointgrouping(Options): def algorithm(self): return self._config_get('minmax') def algorithm(self, text: str): self._config(text, js_type=False) def enabled(self): return self._config_get(True) def enabled(self, flag: bool):...
def _author_affiliation(**kwargs): props = kwargs affiliation = TEI_E.affiliation() if ('key' in props): affiliation.attrib['key'] = props['key'] if ('department' in props): affiliation.append(TEI_E.orgName(props['department'], type='department')) if ('laboratory' in props): ...
def transpile_all(args): project_path = (args.path or os.getcwd()) sys.path.append(project_path) reports_path = utils.get_report_path(project_path) sys.path.append(reports_path) sys.path.append(os.path.join(reports_path, '..')) settings = __import__('ui_settings', fromlist=['object']) result...
class Notices(): def __init__(self, local_config_path: str) -> None: self.local_path = local_config_path self.notices: List[Dict[(str, str)]] = [] def reset(self): local_notices: List[Dict[(str, str)]] = [] local_data = '' try: local_stream = open(self.local_p...
.parametrize('obs_content, match', [(dedent('\n GENERAL_OBSERVATION obs\n {\n DATA = RES;\n DATE = 2023-02-01;\n VALUE = 1;\n };\n '), 'ERROR must also be given...
def main() -> None: robot = Robot.from_parameters(ur10()) tool = Tool() tool.position = np.array([1, 2, 3]) robot.tool = tool world_frame = vector_2_matrix(np.array([100, 200, 300, 0, 0, 0])) robot.world_frame = world_frame print(f'Robot: {robot}') print(f'Kinematic Chain: {robot.kinemat...
class TestFeatureMerger(): .parametrize('data', datas) .parametrize('tickers', [['AAPL', 'TSLA'], ['NVDA', 'TSLA'], ['AAPL', 'NVDA', 'TSLA', 'WORK'], ['AAPL', 'ZLG']]) def test_calculate(self, data, tickers): fc1 = QuarterlyFeatures(data_key='quarterly', columns=['ebit'], quarter_counts=[2], max_bac...
def werkzeug(body, headers): import werkzeug.wrappers as werkzeug from werkzeug.routing import Map, Rule path = '/hello/<account_id>/test' url_map = Map([Rule(path, endpoint='hello')]) .application def hello(request): user_agent = request.headers['User-Agent'] limit = request.arg...
_heads([Minimum, Maximum, ArgMin, ArgMax, ArgMinUnique, ArgMaxUnique, Supremum, Infimum, Zeros, UniqueZero, Solutions, UniqueSolution, Poles]) def tex_std_operator(head, args, **kwargs): argstr = [arg.latex(**kwargs) for arg in args] opname = {Minimum: '\\min', Maximum: '\\max', ArgMin: '\\operatorname{arg\\,mi...
def diag_quadrupole3d_21(ax, da, A, bx, db, B, R): result = numpy.zeros((3, 6, 3), dtype=float) x0 = ((ax + bx) ** (- 1.0)) x1 = (x0 * ((ax * A[0]) + (bx * B[0]))) x2 = (- x1) x3 = (x2 + R[0]) x4 = (x2 + B[0]) x5 = (2.0 * x3) x6 = (x4 * x5) x7 = (x0 + x6) x8 = (x3 * x7) x9 = ...
def test_validate_string_in_int_raises(): records = [{'str_null': 'str', 'str': 'str', 'integ_null': 'str', 'integ': 21}] with pytest.raises(ValidationError) as exc: validation_raise(schema, *records) for error in exc.value.errors: expected_type = error.schema assert (expected_type i...
def from_json_to_html(content: str, page: Rpt=None): if (page is None): page = Page() components = (content['components'] if ('components' in content) else content) for (alias, component) in components.items(): comp_type = component.get('type', alias) comp_category = component.get('c...
class Aria(): def __init__(self, component: primitives.HtmlModel): self.component = component def set(self, arias: dict): for (k, v) in arias.items(): k = k.replace('aria-', '') setattr(self, k, v) def custom(self, key: str, val): self.component.attr[('aria-%s...
def filter_firewall_vendor_mac_data(json): option_list = ['id', 'mac_number', 'name', 'obsolete'] json = remove_invalid_fields(json) dictionary = {} for attribute in option_list: if ((attribute in json) and (json[attribute] is not None)): dictionary[attribute] = json[attribute] r...
def name_exclude(records, filter_regex): logging.info((('Applying _name_exclude generator: excluding IDs matching ' + filter_regex) + ' in results.')) regex = re.compile(filter_regex) for record in records: if ((not regex.search(record.id)) and (not regex.search(record.description))): (y...
class ELFFile(object): def __init__(self, stream, stream_loader=None): self.stream = stream self.stream.seek(0, io.SEEK_END) self.stream_len = self.stream.tell() self._identify_file() self.structs = ELFStructs(little_endian=self.little_endian, elfclass=self.elfclass) ...
def _create_mysql_database(db_name: str, db_url: str, try_to_create_db: bool=False): from sqlalchemy import create_engine, DDL from sqlalchemy.exc import SQLAlchemyError, OperationalError if (not try_to_create_db): logger.info(f'Skipping creation of database {db_name}') return engine = c...
def monitor(session, *args, **kwargs): from evennia.scripts.monitorhandler import MONITOR_HANDLER name = kwargs.get('name', None) outputfunc_name = kwargs.get('outputfunc_name', 'monitor') category = kwargs.get('category', None) if (name and (name in _monitorable) and session.puppet): field_...
class CardsTests(N26TestBase): _requests(method=GET, response_file='cards.json') def test_cards_cli(self): from n26.cli import cards result = self._run_cli_cmd(cards) self.assertIn('MASTERCARD', result.output) self.assertIn('MAESTRO', result.output) self.assertIn('active'...
def _handler1(content_path, model_path, resize_height=None, resize_width=None, save_path=None, prefix=None, suffix=None): content_target = get_images(content_path, resize_height, resize_width) with tf.Graph().as_default(), tf.Session() as sess: content_image = tf.placeholder(tf.float32, shape=content_ta...
() def search_packages(search_term: str, channel: Optional[str]=None, shipper: Optional[str]=None): filters = {CHANNEL_ID_FIELD: channel, SHIPPING_PROVIDER_CODE: shipper, MANIFEST_GENERATED_CHECK: 0} filters = {k: v for (k, v) in filters.items() if (v is not None)} or_filters = {TRACKING_CODE_FIELD: search_...
_type(OSPF_OPAQUE_TYPE_EXTENDED_PREFIX_LSA) class ExtendedPrefixOpaqueBody(OpaqueBody): def parser(cls, buf): buf = six.binary_type(buf) tlvs = [] while buf: (type_, length) = struct.unpack_from('!HH', buf) if (len(buf[struct.calcsize('!HH'):]) < length): ...
def gethtml(url, times=3): try: ua = get_UserAgent() session = get_request_session(url) response = session.get(url, headers={'User-Agent': ua}, timeout=8, verify=False) response.encoding = 'utf-8' if (response.status_code == 200): return response.text except E...
class GradientEditorWidget(AbstractGradientEditor): def __init__(self, master=None, vtk_table=None, on_change_color_table=None, colors=None): if (colors is None): colors = ['rgb', 'hsv', 'a'] self.colors = colors self.gradient_preview_width = 300 self.gradient_preview_hei...
def update_css_js(app: Sphinx): app.env.sphinx_design_css_changed = False static_path = (Path(app.outdir) / '_sphinx_design_static').absolute() static_existed = static_path.exists() static_path.mkdir(exist_ok=True) app.config.html_static_path.append(str(static_path)) js_path = (static_path / 'de...
class OptionSeriesErrorbarSonificationContexttracksMappingTremoloSpeed(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
class TestDeleteDirectoryContents(): def setup(self): self.root = Path(tempfile.mkdtemp()) file_1 = (self.root / 'file_1') file_1.touch() (self.root / 'symlink_1').symlink_to(file_1) subdir = (self.root / 'directory') subdir.mkdir() (subdir / 'file').touch() ...
class ChannelSpatialSqueezeExcitation(nn.Module): def __init__(self, num_channels: int, num_channels_reduced: Optional[int]=None, reduction_ratio: float=16.0, is_3d: bool=False, activation: Optional[nn.Module]=None) -> None: super().__init__() self.channel = SqueezeExcitation(num_channels=num_channe...
def code_command(argv) -> CommandResult: if (not argv): return (ExitCode.NO_PLUGIN_NAME, 'no plugin name provided') if (argv[0] == '--help'): print(code_command.__doc__) return (ExitCode.OK, '') if (len(argv) > 1): return (ExitCode.TOO_MANY_ARGS, 'the command accept only one ...
class ChainContext(ChainContextAPI): __slots__ = ['_chain_id'] def __init__(self, chain_id: Optional[int]) -> None: if (chain_id is None): chain_id = 0 validate_uint256(chain_id) self._chain_id = chain_id def chain_id(self) -> int: return self._chain_id
class RegisterPairHandling(PipelineStage): name = 'register-pair-handling' instruction_location = namedtuple('InstructionLocation', ['basic_block', 'index']) def __init__(self): self.cfg = None self._def_map = None self._use_map = None self._locations = None self._dom...
def reset_schema(): for schema in ['aouser', 'auditsearch', 'disclosure', 'fecapp', 'fecmur', 'public', 'rad_pri_user', 'real_efile', 'real_pfile', 'rohan', 'staging']: rest.db.engine.execute(('drop schema if exists %s cascade;' % schema)) rest.db.engine.execute('create schema public;')
def test_max_geometry_validation(): too_many = [td.Box(size=(1, 1, 1)) for _ in range((MAX_GEOMETRY_COUNT + 1))] fine = [td.Structure(geometry=td.ClipOperation(operation='union', geometry_a=td.Box(size=(1, 1, 1)), geometry_b=td.GeometryGroup(geometries=too_many)), medium=td.Medium(permittivity=2.0)), td.Structu...
def extractArunamettaAsia(item): badwords = ['Menantu Sang Raja Naga', 'Lembayung Ema'] if any([(bad in item['tags']) for bad in badwords]): return None (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): ...
def _get_atf_vector(atf_type, target_psd_matrix, noise_psd_matrix, **atf_kwargs): if (atf_type == 'pca'): return get_pca_vector(target_psd_matrix, **atf_kwargs) elif (atf_type == 'scaled_gev_atf'): return _get_gev_atf_vector(target_psd_matrix, noise_psd_matrix, **atf_kwargs) else: ra...