code
stringlengths
281
23.7M
def run(options): time_start = time.time() if options.psk_file: assert options.bridge, 'PSK is only supported with bridging due to python limitations, sorry about that' auth_pairs = options.psk_file.readlines() assert ((options.thread_ratio * options.processes) <= len(auth_pairs)), "can'...
def _install_plugins(distribution, skip_docker, only_docker=False): installer_paths = Path((get_src_dir() + '/plugins/')).glob('*/*/install.py') for install_script in installer_paths: plugin_name = install_script.parent.name plugin_type = install_script.parent.parent.name plugin = import...
def xml_encode(value, key=None, quote=True): if hasattr(value, '__xml__'): return value.__xml__(key, quote) if isinstance(value, dict): return tag[key](*[tag[k](xml_encode(v, None, quote)) for (k, v) in value.items()]) if isinstance(value, list): return tag[key](*[tag[item](xml_encod...
class op_popup(bpy.types.Operator): bl_idname = 'ui.textools_popup' bl_label = 'Message' message: StringProperty() def execute(self, context): self.report({'INFO'}, self.message) print(self.message) return {'FINISHED'} def invoke(self, context, event): wm = context.wi...
def diff(path_to_new, path_to_old): output = '' new = esptool.loader.StubFlasher(path_to_new) old = esptool.loader.StubFlasher(path_to_old) if (new.data_start != old.data_start): output += ' Data start: New {:#x}, old {:#x} \n'.format(new.data_start, old.data_start) if (new.text_start != ol...
class bsn_time_reply(bsn_header): version = 6 type = 4 experimenter = 6035143 subtype = 45 def __init__(self, xid=None, time_ms=None): if (xid != None): self.xid = xid else: self.xid = None if (time_ms != None): self.time_ms = time_ms ...
class Cleanup(Validator): rule = re.compile('[^\\x09\\x0a\\x0d\\x20-\\x7e]') def __init__(self, regex=None, message=None): super().__init__(message=message) self.regex = (self.rule if (regex is None) else re.compile(regex)) def __call__(self, value): v = self.regex.sub('', (to_unicod...
def infer(text, sdp_ratio, noise_scale, noise_scale_w, length_scale, sid, language, hps, net_g, device): (bert, ja_bert, phones, tones, lang_ids) = get_text(text, language, hps, device) with torch.no_grad(): x_tst = phones.to(device).unsqueeze(0) tones = tones.to(device).unsqueeze(0) lan...
class BlockedDofOrderType(DofOrderInfo): def __init__(self, n_DOF_pressure, model_info='no model info set'): DofOrderInfo.__init__(self, 'blocked', model_info='no model info set') self.n_DOF_pressure = n_DOF_pressure def create_DOF_lists(self, ownership_range, num_equations, num_components): ...
class OptionSeriesTilemapSonificationTracksMappingFrequency(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): self...
class TestRestCompareFirmware(): def _rest_upload_firmware(self, test_client, fw): testfile_path = (Path(get_test_data_dir()) / fw.path) file_content = testfile_path.read_bytes() data = {'binary': standard_b64encode(file_content).decode(), 'file_name': 'test.zip', 'device_name': 'test_device...
class OptionSeriesVectorData(Options): def accessibility(self) -> 'OptionSeriesVectorDataAccessibility': return self._config_sub_data('accessibility', OptionSeriesVectorDataAccessibility) def className(self): return self._config_get(None) def className(self, text: str): self._config(...
.parametrize('_estimator, _scoring, _distribution, _cv, _n_probes, _random_state', _input_params) def test_input_params_assignment(_estimator, _scoring, _distribution, _cv, _n_probes, _random_state): sel = ProbeFeatureSelection(estimator=_estimator, scoring=_scoring, distribution=_distribution, cv=_cv, n_probes=_n_...
class AsymptoteLexer(RegexLexer): name = 'Asymptote' aliases = ['asy', 'asymptote'] filenames = ['*.asy'] mimetypes = ['text/x-asymptote'] _ws = '(?:\\s|//.*?\\n|/\\*.*?\\*/)+' tokens = {'whitespace': [('\\n', Text), ('\\s+', Text), ('\\\\\\n', Text), ('//(\\n|(.|\\n)*?[^\\\\]\\n)', Comment), ('...
class JsTop(): def extendColumns(jsSchema, params): pass alias = 'top' params = ('countItems', 'value', 'sortType') value = "\n var tmpRec = {};\n data.forEach(function(rec){\n if(tmpRec[rec[value]] === undefined){ tmpRec[rec[value]] = [rec] } else {tmpRec[rec[value]].push(rec)}});\n ...
class EchoNestPlaylist(WebPlaylist): def __init__(self, shell, source): WebPlaylist.__init__(self, shell, source, 'echonest_playlist') def search_website(self): apikey = 'N685TONJGZSHBDZMP' url = ' artist = self.search_entry.get_string(RB.RhythmDBPropType.ARTIST) artist =...
def get_sink_callers(ghidra_analysis, sink_functions): sink_callers = [] for func in sink_functions: sink_references = ghidra_analysis.flat_api.getReferencesTo(func.getEntryPoint()) for sink_ref in sink_references: calling_function = ghidra_analysis.flat_api.getFunctionContaining(sin...
class BillingStatus(ModelNormal): allowed_values = {('status',): {'PENDING': 'Pending', 'OUTSTANDING': 'Outstanding', 'PAID': 'Paid', 'MTD': 'MTD'}} validations = {} _property def additional_properties_type(): return (bool, date, datetime, dict, float, int, list, str, none_type) _nullable = ...
def call_pip(pip_args: List[str], timeout: float=300, retry: bool=False) -> None: command = [sys.executable, '-m', 'pip', *pip_args] result = subprocess.run(command, stdout=PIPE, stderr=PIPE, timeout=timeout, check=False) if ((result.returncode == 1) and retry): result = subprocess.run(command, stdo...
class CmdBoot(COMMAND_DEFAULT_CLASS): key = 'boot' switch_options = ('quiet', 'sid') locks = 'cmd:perm(boot) or perm(Admin)' help_category = 'Admin' def func(self): caller = self.caller args = self.args if (not args): caller.msg('Usage: boot[/switches] <account> [...
def build_ait_module_gemm_rcr(*, ms, n, k, split_k, test_name): target = detect_target(use_fp16_acc=True) input_params = {'dtype': 'float16', 'is_input': True} a = Tensor(shape=[shape_utils.gen_int_var_min_max(ms), k], name='a', **input_params) b = Tensor(shape=[n, k], name='b', **input_params) bias...
class AllListMembers(Rule): rule: Rule def __init__(self, rule: Rule, name: str='all_list_members') -> None: Rule.__init__(self, name) self.rule = rule def apply(self, test: Any) -> RuleResult: if (not isinstance(test, list)): return Fail(test) if (len(test) == 0)...
class TestLinkCont(unittest.TestCase): def test_link_cont(self): def generator(dut): test_packet = ContPacket(([primitives['SYNC'], primitives['SYNC'], primitives['SYNC'], primitives['SYNC'], primitives['SYNC'], primitives['SYNC'], primitives['ALIGN'], primitives['ALIGN'], primitives['SYNC'], pr...
def logarithmic_utility(utility_params_by_good_id: Dict[(str, float)], quantities_by_good_id: Dict[(str, int)], quantity_shift: int=100) -> float: enforce((quantity_shift >= 0), 'The quantity_shift argument must be a non-negative integer.') goodwise_utility = [((utility_params_by_good_id[good_id] * math.log((qu...
class AttributeDictTranslator(): def _remove_hexbytes(cls, value: Any) -> Any: if (value is None): return value if isinstance(value, HexBytes): return value.hex() if isinstance(value, list): return cls._process_list(value, cls._remove_hexbytes) if ...
class OptionSeriesNetworkgraphNodesMarkerStatesInactive(Options): def animation(self) -> 'OptionSeriesNetworkgraphNodesMarkerStatesInactiveAnimation': return self._config_sub_data('animation', OptionSeriesNetworkgraphNodesMarkerStatesInactiveAnimation) def opacity(self): return self._config_get(...
def test_send_multicast(): multicast = messaging.MulticastMessage(notification=messaging.Notification('Title', 'Body'), tokens=['not-a-token', 'also-not-a-token']) batch_response = messaging.send_multicast(multicast) assert (batch_response.success_count == 0) assert (batch_response.failure_count == 2) ...
_tag def generate_tag_html(): tag_list = Tags.objects.all()[:15] tag_html = [] for tag in tag_list: if tag.articles_set.all(): tag_html.append(f'<li>{tag.title} <i>{tag.articles_set.count()}</i></li>') else: tag_html.append(f'<li>{tag.title}</li>') return mark_saf...
def get_suggested(form: FlowResult, key: str) -> Any: for schema_key in form['data_schema'].schema: if (schema_key == key): if ((schema_key.description is None) or ('suggested_value' not in schema_key.description)): return None return schema_key.description['suggested...
def _maybe_add_data_augmentations_for_example(training_example: TrainingExample, formatted_examples_being_built: List[str], indices_of_all_categories: range, formatter_configs: FormatterConfigs) -> None: violated_category_indices = _convert_category_codes_to_indices(training_example.violated_category_codes, formatt...
class BaseMessage(BaseModel, ABC): content: str index: int = 0 round_index: int = 0 additional_kwargs: dict = Field(default_factory=dict) def type(self) -> str: def pass_to_model(self) -> bool: return True def to_dict(self) -> Dict: return {'type': self.type, 'data': self.dic...
class TreeLayout(): def __init__(self, name, ts=None, ns=None, aligned_faces=False, active=True, legend=True): self.name = name self.active = active self.aligned_faces = aligned_faces self.description = '' self.legend = legend self.always_render = False self.t...
def cache_generate_code(kernel, comm): _cachedir = os.environ.get('PYOP2_CACHE_DIR', os.path.join(tempfile.gettempdir(), ('pyop2-cache-uid%d' % os.getuid()))) key = kernel.cache_key[0] (shard, disk_key) = (key[:2], key[2:]) filepath = os.path.join(_cachedir, shard, disk_key) if os.path.exists(filepa...
class StreamPacket(): def __init__(self, data, params={}): assert (type(data) == list) for b in data: assert ((type(b) == int) and (b >= 0) and (b < 256)) assert (type(params) == dict) for (param_key, param_value) in params.items(): assert (type(param_key) == ...
def execute(cmd, no_except=True, inline=False, init='', g=None): console = '' colors = [] if (g is None): g = {'Ramp': Ramp, 'Steps': Steps, 'Row': Row, 'HtmlRow': HtmlRow, 'HtmlSteps': HtmlSteps, 'HtmlGradient': HtmlGradient} if init: execute(init.strip(), g=g) m = RE_INIT.match(cmd...
def downgrade(): op.alter_column('flicket_topic', 'hours', existing_type=sa.Numeric(precision=10, scale=2), type_=sa.Numeric(precision=10, scale=0), existing_nullable=True, existing_server_default=sa.text("'0'")) op.alter_column('flicket_post', 'hours', existing_type=sa.Numeric(precision=10, scale=2), type_=sa....
class TestSerializer(TestCase): def setUp(self): class SimpleSerializer(Serializer): username = serializers.CharField() password = serializers.CharField() age = serializers.IntegerField() class CrudSerializer(Serializer): username = serializers.CharFie...
def gas_buffer(*args: Tuple[(float, None)]) -> Union[(float, None)]: if (not is_connected()): raise ConnectionError('Not connected to any network') if args: if (args[0] is None): CONFIG.active_network['settings']['gas_buffer'] = 1 elif isinstance(args[0], (float, int)): ...
def pack_A1_0(data): min_max_ratio = (min(data) / max(data)) if (min_max_ratio < _eps): log.warning('min to max ratio is too low at %f and it could cause algorithm stability issues. Try to remove insignificant data', min_max_ratio) assert (data == sorted(data, reverse=True)), 'data must be sorted (d...
class ClassificationPreset(MetricPreset): columns: Optional[List[str]] probas_threshold: Optional[float] k: Optional[int] def __init__(self, columns: Optional[List[str]]=None, probas_threshold: Optional[float]=None, k: Optional[int]=None): super().__init__() self.columns = columns ...
class Websocket(RSGIIngressMixin, _Websocket): __slots__ = ['_scope', '_proto'] def __init__(self, scope: Scope, path: str, protocol: WSTransport): super().__init__(scope, path, protocol) self._flow_receive = None self._flow_send = None self.receive = self._accept_and_receive ...
class OptionSeriesHeatmapDatalabelsFilter(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(text, js_...
_recovery_question.command() _context def execute(ctx): error = MODULE.check_options() if error: return msg = f"Attempting to set the recovery question and answer for user ID {MODULE_OPTIONS['id']['value']}" LOGGER.info(msg) index_event(ctx.obj.es, module=__name__, event_type='INFO', event=m...
def make_list_for_entry(center, data, list_for_entry, error_logs): for entry in data['list']: if (entry['total_quantity'] > 0): warehouse = center.get('erpnext_warehouse') if (not warehouse): err_msg = _('Center {0} is not linked to any ERPNext Warehouse.').format(fra...
def data_processer(json_data, logger: Logger): generation = json_data['Fuel']['Type'] production = {} for fuel in generation: try: k = mapping[fuel['CATEGORY']] except KeyError: logger.warning("Key '{}' is missing from the MISO fuel mapping.".format(fuel['CATEGORY']))...
class CamLoadMode(BaseMode): name = Mode.cam_load keymap = {Action.quit: False, Action.cam_load: True} def enter(self): if (Global.mode_mgr.last_mode == Mode.aim): Global.mode_mgr.last_mode = Mode.view mouse.mode(MouseMode.ABSOLUTE) self.selection = None self.regi...
def test_trigger_transform(dash_duo): app = DashProxy(prevent_initial_callbacks=True, transforms=[TriggerTransform()]) app.layout = html.Div([html.Button(id='btn1'), html.Button(id='btn2'), html.Button(id='btn3'), html.Button(id='btn4'), html.Div(id='log')]) (Output('log', 'children'), Trigger('btn1', 'n_cl...
class Draw_grab_width(QLabel): def __init__(self, parent): super(Draw_grab_width, self).__init__(parent) self.h = 18 self.painter = QPainter(self) def paintEvent(self, event): self.painter.setPen(QPen(Qt.green, 1, Qt.SolidLine)) self.painter.drawLine(0, 0, self.width(), 0...
def parse_obj_with_group(obj_name): vlines = [] vnlines = [] glines = {} with open(obj_name) as f: for line in f: if line.startswith('v '): vlines.append(line) if line.startswith('vn '): vnlines.append(line) if line.startswith('...
def extractChibitranslationWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('Food Chain', 'The Man Standing on Top of the Food Chain', 'translated')] for (tagnam...
def get_flet_server_job_ids(): account_name = os.environ.get('APPVEYOR_ACCOUNT_NAME') project_slug = os.environ.get('APPVEYOR_PROJECT_SLUG') build_id = os.environ.get('APPVEYOR_BUILD_ID') url = f' print(f'Fetching build details at {url}') req = urllib.request.Request(url) req.add_header('Con...
def test_cli_record_output(): given_avro_input = os.path.join(data_dir, 'weather.avro') given_cmd_args = [sys.executable, '-m', 'fastavro', given_avro_input] expected_data = [{'station': '011990-99999', 'time': (- ), 'temp': 0}, {'station': '011990-99999', 'time': (- ), 'temp': 22}, {'station': '011990-9999...
def get_sha_functions(bv_size_in, bv_size_out=256): label = 'sha{}'.format(bv_size_in) label_inv = (label + '_inv') sha_func = z3.Function(label, z3.BitVecSort(bv_size_in), z3.BitVecSort(bv_size_out)) sha_func_inv = z3.Function(label_inv, z3.BitVecSort(bv_size_out), z3.BitVecSort(bv_size_in)) return...
def test_should_generate_simple_policy(): records = [Record('autoscaling.amazonaws.com', 'DescribeLaunchConfigurations'), Record('sts.amazonaws.com', 'AssumeRole')] assert (generate_policy(records) == PolicyDocument(Version='2012-10-17', Statement=[Statement(Effect='Allow', Action=[Action('autoscaling', 'Descri...
(scope='function') def custom_fields_system(db, system, system_third_party_sharing, custom_field_definition_system, custom_field_definition_system_2, custom_field_definition_system_disabled): field_1 = sql_models.CustomField.create(db=db, data={'resource_type': custom_field_definition_system.resource_type, 'resourc...
class Recursion(TestCase): def test_nocache(self): untouched = object() class R(cache.Recursion, length=1): def resume(R_self, history): nonlocal received_history received_history = tuple(history) (yield from range((0 if (not history) else ...
class ImageSerializer(s.ConditionalDCBoundSerializer): _backup_attrs_map_ = {'owner': 'owner_id', 'dc_bound': 'dc_bound_id'} _model_ = Image _update_fields_ = ('alias', 'version', 'dc_bound', 'owner', 'access', 'desc', 'resize', 'deploy', 'tags') _default_fields_ = ('name', 'alias', 'owner') name = ...
def main(argv=sys.argv): try: print_help = True (options, args) = parse_options(argv) if options['show_screen_log']: logfile = screen.get_logfile(node=options['show_screen_log']) if (not os.path.isfile(logfile)): raise Exception(('screen logfile not fo...
class DrillStand(Boxes): description = 'Note: `sh` gives the height of the rows front to back. It though should have the same number of entries as `sy`. These heights are the one on the left side and increase throughout the row. To have each compartment a bit higher than the previous one the steps in `sh` should be...
.parametrize('model,full_refresh,dbt_vars', [('m1', True, None), ('m1', False, {'key1': 'x', 'key2': 'y', 'key3': 'z'}), (None, True, {'key1': 'x', 'key2': 'y', 'key3': 'z'}), (None, False, None)]) ('subprocess.run') def test_dbt_runner_run(mock_subprocess_run, model, full_refresh, dbt_vars): project_dir = 'proj_di...
class OptionSeriesBulletSonification(Options): def contextTracks(self) -> 'OptionSeriesBulletSonificationContexttracks': return self._config_sub_data('contextTracks', OptionSeriesBulletSonificationContexttracks) def defaultInstrumentOptions(self) -> 'OptionSeriesBulletSonificationDefaultinstrumentoption...
.parametrize('xml', ['<root><element key="value">text</element><element>text</element>tail<empty-element/></root>', '<root>\n <element key="value">text</element>\n <element>text</element>tail\n <empty-element/>\n</root>', '<axis default="400" maximum="1000" minimum="1" name="weight" tag="wght"><labelname xml:lang="f...
.usefixtures('prepare_shared_client_config') class TestAsyncClientDeviceGeneration(): def _verify_event(self, client: AsyncClientDevice, expected_start_time: int, expected_end_time: int) -> None: assertEqual(client.training_schedule.start_time, expected_start_time) assertEqual(client.training_schedu...
class TestPCPreValidationCLI(TestCase): ('fbpcs.pc_pre_validation.pc_pre_validation_cli.print') ('fbpcs.pc_pre_validation.pc_pre_validation_cli.InputDataValidator') ('fbpcs.pc_pre_validation.pc_pre_validation_cli.BinaryFileValidator') ('fbpcs.pc_pre_validation.pc_pre_validation_cli.run_validators') ...
def faba_with_toptier_agencies(award_count_sub_schedule, award_count_submission, defc_codes): toptier_agency(1) award1 = award_with_toptier_agency(1, 8, 0) toptier_agency(2) award2 = award_with_toptier_agency(2, 0, 7) award3 = baker.make('search.AwardSearch', award_id=1, type='A', funding_agency_id=...
def uploaded(textpath): if (not (textpath is None)): print(textpath) file_paths = textpath.name print(file_paths) links = [] with open(file_paths, 'r') as file: for line in file: if line.startswith(tuple(supportedlinks)): links....
class Bed2SidesEdge(edges.BaseEdge): def __init__(self, boxes, bed_length, full_head_length, full_foot_height) -> None: super().__init__(boxes, None) self.bed_length = bed_length self.full_head_length = full_head_length self.full_foot_height = full_foot_height def __call__(self, ...
def check_password_match(moderator: ModeratorModel, password: str): if (not validation.check_password_validity(password)): raise ArgumentError(MESSAGE_INVALID_PASSWORD) with session() as s: moderator_orm_model = s.query(ModeratorOrmModel).filter_by(id=moderator.id).one() moderator_hashed...
def print_perf_results(results): pal_avgs = dict() pal_min = for (i, (key, tds)) in enumerate(sorted(results.items())): (pal, mem) = key pal_min = min(pal, pal_min) print(highlight_text(f'{i:03d}: pal={pal}, mem={mem} MB')) for (j, td) in enumerate(tds): print(f'...
def test(): assert ('from spacy.tokens import Doc' in __solution__), 'Estas importando la clase Doc correctamente?' assert (len(spaces) == 5), 'Parece que el numero de espacios no concuerda con el numero de palabras.' assert all((isinstance(s, bool) for s in spaces)), 'Los espacios tienen que ser booleanos....
.usefixtures('use_tmpdir') def test_copy_directory_error(shell): assert (b'existing directory' in shell.copy_directory('does/not/exist', 'target').stderr) with open('file', 'w', encoding='utf-8') as f: f.write('hei') assert (b'existing directory' in shell.copy_directory('hei', 'target').stderr)
class DiagResult(): def __init__(self, diag: 'Diagnostics', estat: EnvoyStats, request) -> None: self.diag = diag self.logger = self.diag.logger self.estat = estat self.cstats = {cluster.name: self.estat.cluster_stats(cluster.stats_name) for cluster in self.diag.clusters.values()} ...
.external .skipif((has_openai_key is False), reason='OpenAI API key not available') def test_add_label(): nlp = spacy.blank('en') llm = nlp.add_pipe('llm', config={'task': {'_tasks': 'spacy.TextCat.v3'}, 'model': {'_models': 'spacy.GPT-3-5.v1'}}) nlp.initialize() text = 'I am feeling great.' doc = n...
def generate_training_data_for_source_filename(source_filename: str, output_path: str, sciencebeam_parser: ScienceBeamParser, use_model: bool, use_directory_structure: bool, gzip_enabled: bool): LOGGER.debug('use_model: %r', use_model) layout_document = get_layout_document_for_source_filename(source_filename, s...
def test_arg_range6(): val = (2 ** 32) def foo(N: size, K: size): assert (N > val) assert (K < val) pass assert (arg_range_analysis(foo._loopir_proc, foo._loopir_proc.args[0], fast=False) == ((2 ** 15), None)) assert (arg_range_analysis(foo._loopir_proc, foo._loopir_proc.args[1],...
def _remove_empty_fields(initial: Dict) -> Dict: result = {} for (key, value) in initial.items(): if isinstance(initial[key], dict): value = _remove_empty_fields(value) if isinstance(initial[key], list): value = [i for i in initial[key] if (i is not None)] if (val...
_only_with_numba def test_equivalent_sources_spherical_parallel(): region = ((- 70), (- 60), (- 40), (- 30)) radius = 6400000.0 points = vd.grid_coordinates(region=region, shape=(6, 6), extra_coords=(radius - 500000.0)) masses = vd.synthetic.CheckerBoard(amplitude=.0, region=region).predict(points) ...
.skip(reason='Global index not supported.') .long_test .download .parametrize('baseurl', CML_BASEURLS) .parametrize('source_name', ['indexed-url', 'indexed-url-with-json-index']) def test_global_index(source_name, baseurl): print(f'{baseurl}/test-data/input/indexed-urls/global_index.index') s = cml.load_source(...
class MatchRequest(): status_code = 200 error = False def __init__(self, url): self.url = url if self.error: raise requests.exceptions.ConnectionError def json(self): if (('chelsea' in self.url) or ('burnley' in self.url)): return lfs_data.CHELSEA ...
(scope='function') def privacy_notice_us_co_provide_service_operations(db: Session) -> Generator: privacy_notice = PrivacyNotice.create(db=db, data={'name': 'example privacy notice us_co provide.service.operations', 'notice_key': 'example_privacy_notice_us_co_provide.service.operations', 'description': 'a sample pr...
def get_audio_length(file_path) -> int: try: if file_path.casefold().endswith('.wav'): a = WavInfoReader(file_path) length = (a.data.frame_count / a.fmt.sample_rate) elif file_path.casefold().endswith('.wma'): try: audio_info = mutagen.File(file_pa...
class FaucetTaggedIPv4RouteTest(FaucetTaggedTest): CONFIG_GLOBAL = '\nvlans:\n 100:\n description: "tagged"\n faucet_vips: ["10.0.0.254/24"]\n routes:\n - route:\n ip_dst: "10.0.1.0/24"\n ip_gw: "10.0.0.1"\n - route:\n ip_dst...
('/search/', methods=['GET']) ('/search/<int:page>', methods=['GET']) _required def search(page=1): scope = request.args.get('scope') query = request.args.get('query') if (not (scope and query)): return render_search_page() if ('source-site' in request.args): try: request_str...
class ServiceObj(metaclass=ServiceObjMeta): def __init__(self, service, name=None): self._service = service self._loop = (service.loop if service else asyncio.get_event_loop()) self._objname = (name or self.__class__.__name__) self._logger = self.create_logger() def loop(self): ...
class DockableListElement(DockableViewElement): editor = Instance(NotebookEditor) def dockable_close(self, dock_control, force): return self.close_dock_control(dock_control, force) def close_dock_control(self, dock_control, abort): if abort: return super().close_dock_control(dock...
class TestComposerThread_send_testing_digest(ComposerThreadBaseTestCase): ('bodhi.server.mail.smtplib.SMTP') def test_critpath_updates(self, SMTP): t = ComposerThread(self.semmock, self._make_task()['composes'][0], 'bowlofeggs', self.Session, self.tempdir) t.compose = self.db.query(Compose).one(...
class USDDRPHY(Module, AutoCSR): def __init__(self, pads, memtype='DDR3', sys_clk_freq=.0, iodelay_clk_freq=.0, cl=None, cwl=None, cmd_latency=0, cmd_delay=None, is_rdimm=False, is_clam_shell=False): phytype = self.__class__.__name__ device = {'USDDRPHY': 'ULTRASCALE', 'USPDDRPHY': 'ULTRASCALE_PLUS'...
def _chunk_actions(actions: Iterable[_TYPE_BULK_ACTION_HEADER_AND_BODY], chunk_size: int, max_chunk_bytes: int, serializer: Serializer) -> Iterable[Tuple[(List[Union[(Tuple[_TYPE_BULK_ACTION_HEADER], Tuple[(_TYPE_BULK_ACTION_HEADER, _TYPE_BULK_ACTION_BODY)])]], List[bytes])]]: chunker = _ActionChunker(chunk_size=ch...
class TestRegistry(unittest.TestCase): def test_registry(self) -> None: OBJECT_REGISTRY = Registry('OBJECT') _REGISTRY.register() class Object1(): pass with self.assertRaises(AssertionError) as err: OBJECT_REGISTRY.register(Object1) self.assertTrue(("A...
def test_observation_normalization_manual_stats(): env = GymMazeEnv('CartPole-v0') normalization_config_1 = {'default_strategy': 'maze.normalization_strategies.MeanZeroStdOneObservationNormalizationStrategy', 'default_strategy_config': {'clip_range': (None, None), 'axis': None}, 'default_statistics': None, 'sta...
def marshal(data, fields, envelope=None): def make(cls): if isinstance(cls, type): return cls() return cls if isinstance(data, (list, tuple)): return (OrderedDict([(envelope, [marshal(d, fields) for d in data])]) if envelope else [marshal(d, fields) for d in data]) items ...
class Vars(_coconut.object): def items(cls): for name in dir(cls): if (not name.startswith('_')): var = getattr(cls, name) (yield (name, var)) def add_to(cls, globs): for (name, var) in cls.items(): globs[name] = var use = add_to de...
class ModelBasedAgent(core.Actor): def __init__(self, actor: core.Actor, learner: core.Learner): self._actor = actor self._learner = learner self._last_timestep = None def select_action(self, observation: np.ndarray): return self._actor.select_action(observation) def observe_...
class AggregatableEvent(Event): def _unique_zone_key(df_view: pd.DataFrame) -> ZoneKey: zone_key = df_view['zoneKey'].unique() if (len(zone_key) > 1): raise ValueError(f'Cannot merge events from different zones: {zone_key}') return zone_key[0] def _sources(df_view: pd.DataFra...
_deserializable class JinaLlm(BaseLlm): def __init__(self, config: Optional[BaseLlmConfig]=None): if ('JINACHAT_API_KEY' not in os.environ): raise ValueError('Please set the JINACHAT_API_KEY environment variable.') super().__init__(config=config) def get_llm_model_answer(self, prompt...
class BaseEmbeddingProvider(): def get(self, text: str) -> np.ndarray: raise NotImplementedError() def __call__(self, text: str): return self.get(text) def config(self): return {'class': self.__class__.__name__, 'type': 'embedding_provider'} def from_config(cls, config): ...
def verify_required_paths(volume_map, output_dir): assert (constants.DOCKER_SOCKET_PATH in volume_map) docker_map = volume_map[constants.DOCKER_SOCKET_PATH] assert ('bind' in docker_map) assert (docker_map['bind'] == constants.DOCKER_SOCKET_PATH) assert (docker_map['mode'] == constants.MOUNT_READ_WR...
class SynchronousLogstashHandler(Handler): def __init__(self, host, port, transport='logstash_async.transport.TcpTransport', ssl_enable=False, ssl_verify=True, keyfile=None, certfile=None, ca_certs=None, enable=True, encoding='utf-8', **kwargs): super().__init__() self._host = host self._por...
class ZipFileReference(ResourceReference): zip_file = Instance(FastZipFile) volume_name = Str() file_name = Str() cache_file = File() filename = Property def load(self): cache_file = self.cache_file if (cache_file == ''): data = self.zip_file.read(self.file_name) ...
class ONFFlowMonitorRequest(StringifyMixin): def __init__(self, id_, flags, match=OFPMatch(), out_port=ofproto.OFPP_ANY, table_id=ofproto.OFPTT_ALL, match_len=None): self.id = id_ self.flags = flags self.match_len = match_len self.out_port = out_port self.table_id = table_id ...