content
stringlengths
22
815k
id
int64
0
4.91M
def callit(callback, *args, **kargs): """Inspect argspec of `callback` function and only pass the supported arguments when calling it. """ maxargs = len(args) argcount = (kargs['argcount'] if 'argcount' in kargs else getargcount(callback, maxargs)) argstop = min([maxargs, argcoun...
53,300
def drop_nan_columns(data, settings): """ :param data: A list with pandas's DataFrame. :param settings: A dictionary with: * subset: optional list of column names to consider. * thresh: int, default None If specified, drop rows that have less than thresh non-null values. This overwrites th...
53,301
def iree_vision_test_suite( name, models, datasets, backends, reference_backend, failing_configurations = None, external_weights = None, tags = None, deps = None, size = "large", python_version = "PY3", **kwargs): """Cre...
53,302
def registerCallbacks(reg): """ Register our callbacks. :param reg: A Registrar instance provided by the event loop handler. """ # Grab authentication env vars for this plugin. Install these into the env # if they don't already exist. server = os.environ["SG_SERVER"] script_name = os.e...
53,303
def crf_log_likelihood( inputs: Tensors, tag_indices: Tensors, sequence_lengths: Tensors, transition_params: Optional[Tensors] = None, ) -> tf.Tensor: """Computes the log-likelihood of tag sequences in a CRF. Args: inputs: A [batch_size, max_seq_len, num_tags] tensor of unary potentials ...
53,304
def memory_monitor(slot=0.1): """ Decorator: memory monitor. Args: slot(float): sampling frequency. Returns: func, memory: function output and memory usage. """ def _get_memory(monitor): """ Get memory usage. """ info = monitor.memory_full_info()...
53,305
def t_POUND(t): """header token""" # 如果header前面有换行 if t.value[0] == '\n': t.value = str(len(t.value) - 1) else: t.value = str(len(t.value)) return t
53,306
def nearby_difference(x): """Compute L2 norms for nearby entries in a batch.""" # This is a very rough measure of diversity. with tf.device('cpu'): x1 = tf.reshape(x, shape=[int(x.shape[0]), -1]) x2 = tf.roll(x1, shift=1, axis=0) return tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x1, x2))))
53,307
def _split_article_sentences(article_text): """ Recieves a string containing the plain text of a wikipedia article Returns a list containing the sentences of the recieved article text """ def not_image_thumb(paragraph): """ True if the paragraph is wikitext for displaying an image t...
53,308
def get_metric(fn, tags): """ Wraps the metric function to decorate with additional tags """ @functools.wraps(fn) def wrapper(name, *args, **kwargs): # the metric name starts as the name of the function itself metric = fn.__func__.__name__ _tags = tags.copy() _tags.u...
53,309
def run_NEMO_hindcast(parsed_args, config, *args): """ :param :py:class:`argparse.Namespace` parsed_args: :param :py:class:`nemo_nowcast.Config` config: :return: Nowcast system checklist items :rtype: dict """ host_name = parsed_args.host_name ssh_key = Path( os.environ["HOME"],...
53,310
def equation_plot(): """ Plot the "christmas equation" and some christmas background. """ def format_plot(sx, sy, st_x, st_y): # change plot style plt.xkcd() # switch off all labels plt.tick_params( axis='both', which='both', bottom='o...
53,311
def import_data(table: List[str] | None = None, url: str | dict | None = None, chunksize: int | None = None) -> tuple[DataFrame | Series, ...]: """ Importing data from database as a pandas DataFrame. :param table: List of table name that needs to be imported from dat...
53,312
def xrate_interval_iterator(b_orders, s_orders, fee, optimal_trivial_xrate=None): """Exchange rate interval iterator. Iterates through intervals [xrate_lb, xrate_ub] of possible values for xrate, where xrate_lb, xrate_ub are defined by the max_xrate's of two orders that are consecutive in the optimal e...
53,313
def accuracy_plot(a, b, z, ref, func): """Plot the relative error in using func to approximate hyp1f1. Parameters ---------- a, b: array_like Meshgrid of a and b values. z : float Value of the argument. ref : array_like An array of reference values, of the same shape as ...
53,314
def plot_zero_check(amplitudes, properties, vars=['polar_angle', 'eccentricity'], hue='hemi', sum_idx=1, nan_check=False): """plot properties of voxels with zero or NaN amplitude after interpolation, some voxels may end up with zero amplitude for some reason, including because their coo...
53,315
def version(client_only: bool, **kwargs): """ Displays version and connectivity information """ try: feast_versions_dict = { "sdk": {"version": str(pkg_resources.get_distribution("feast"))} } if not client_only: feast_client = Client(**kwargs) ...
53,316
def cum_sound_chunks(audio_frames: List) -> AudioSegment: """cummulate sound frames""" sound_chunk = pydub.AudioSegment.empty() for audio_frame in audio_frames: sound = pydub.AudioSegment( data=audio_frame.to_ndarray().tobytes(), sample_width=audio_frame.format.bytes, ...
53,317
def _nowiki_sub_fn(m): """This function escapes the contents of a <nowiki> ... </nowiki> pair.""" text = m.group(1) text = re.sub(_nowiki_re, _nowiki_repl, text) text = re.sub(r"\s+", " ", text) return text
53,318
def ext(f): """Changes the extension of the a give file to jpeg""" return os.path.splitext(f)[0] + '.jpg'
53,319
def main(): """Top-level main function.""" wiki_dump = WikiDump() for _wiki_name, _job_name, file_name in wiki_dump.iter_files(): print(file_name)
53,320
async def test_block_device_services(hass, coap_wrapper): """Test block device turn on/off services.""" assert coap_wrapper hass.async_create_task( hass.config_entries.async_forward_entry_setup(coap_wrapper.entry, SWITCH_DOMAIN) ) await hass.async_block_till_done() await hass.services....
53,321
def display_timezone(): """Displays the dialog for all""" tzlist = pytz.common_timezones tzlist.sort() tag = tzlist desc = [] for item in tag: desc.append(item.split("/")[-1]) mytzlist = zip(tag, desc) return DISPLAY.menu( "Please select the system timezone.", width=80,...
53,322
def test_integration_git_noglob_pathspecs(tmpdir): """see #47""" with mock.patch.dict(os.environ, {'GIT_NOGLOB_PATHSPECS': '1'}): test_integration_isort_cfg(tmpdir)
53,323
def operate_favorite(rid: int, type_: str, add_media_ids: list = None, del_media_ids: list = None, verify: utils.Verify = None): """ 操作收藏夹 :param rid: :param type_: :param add_media_ids: 要添加的收藏夹内容列表 :param del_media_ids: 要删除的收藏夹内容列表 :param verify: :return: """ ...
53,324
def test_maxwells_equations_source_near_field(source): """ Verify Maxwell's equations for a source at a point in the near field """ x0, y0, z0 = 50*nm, 100*nm, 150*nm eps = .1*nm x = np.linspace(x0, x0 + eps, 2) y = np.linspace(y0, y0 + eps, 2) z = np.linspace(z0, z0 + eps, 2) X, Y,...
53,325
def consume(q, woker_id=0, finished=None, head=None, save_path='./', display=1000): """多进程,有时间瓶颈""" count = 0 save_file = osp.join(save_path, 'split{}.tsv'.format(woker_id)) with open(save_file, 'w') as writer: writer.write(head) while finished.value == 0: try: ...
53,326
def mask_3D(hPa, sect, MBL=True, res='4x5', extra_mask=None, M_all=False, use_multiply_method=True, trop_limit=False, verbose=True, debug=False): """ Creates Maskes by pressure array (required shape: 72,46,47), with conditions (lower and upper bounds) set by given cases for MBL,...
53,327
def kmeans_rand_centroids_1_d(data, k, max_error, max_iters): """Performs K-Means analysis on a one dimensional array, starting with centroids that are randomly distributed across the range of the input set.""" # Sanity check. data_len = len(data) if data_len <= 1: return [] if k > data_len...
53,328
def _compute_fscores(a_stat, a_fscore_stat): """ Compute macro- and micro-averaged F-scores @param a_stat - statistics disctionary on single classes @param a_fscore_stat - verbose statistics with F-scores for each particular class (will be updated in this method) @return 6-tu...
53,329
def pseudonymize(collection, entry, pseudonymizer, config): """Pseudonymize an entry in the database.""" entry_out = entry if collection in config['pseudonymize']: entry_out = deepcopy(entry) config_keys = config['pseudonymize'][collection] entry_keys = entry_out.keys() #...
53,330
def info( request ): """ Returns info page. """ log.debug( 'request.__dict__, ```%s```' % request.__dict__ ) context = { u'email_general_help': os.environ[u'EZSCAN__EMAIL_GENERAL_HELP'], u'phone_general_help': os.environ[u'EZSCAN__PHONE_GENERAL_HELP'] } return render( request, u'...
53,331
def vector_layer_db(map, layer): """Return the database connection details for a vector map layer. If db connection for given layer is not defined, fatal() is called. :param str map: map name :param layer: layer number :return: parsed output """ try: f = vector_db(map)[int(layer)] ...
53,332
def _Flatten(nmap_list): """Flattens every `.NestedMap` in nmap_list and concatenate them.""" ret = [] for x in nmap_list: ret += x.Flatten() return ret
53,333
def get_all_subscription_request( from_position: Union[Dict[str, int], str] = constants.START, resolve_link_to_s: bool = False, filters: Dict = None, ) -> streams_pb2.ReadReq: """Returns a streams_pb2.ReadReq configured for subscription operations for the "$all" stream.""" request = streams_pb2.Read...
53,334
def text_person(person, text): """Text a specific person the given text""" run_applescript( 'tell application "Messages" to send "{text}" to buddy "{person}"', text=text, person=person)
53,335
def gunzip(filename: str) -> None: """Decompress a GZ file.""" decompressed_filename = filename[:-3] with open(decompressed_filename, "wb") as out_fd, gz.open(filename, "rb") as in_fd: shutil.copyfileobj(in_fd, out_fd) os.unlink(filename)
53,336
def us2en(edate, **kwargs): """ Wrapper function for :func:`date2date` with English date format output That means `date2date(edate, format='en', **kwargs)`; but *format* given in call will overwrite *format='en'*. Examples -------- >>> edate = ['11/12/2014 12:00', '01.03.2015 17:56:00', ...
53,337
def test_cray_hsmV2_state_components_list(cli_runner, rest_mock): """ Test `cray hsm state components list` with valid params """ runner, cli, config = cli_runner url_template = '/apis/smd/hsm/v2/State/Components' result = runner.invoke(cli, ['hsm', 'state', 'components', 'list']) assert result.exi...
53,338
def autosave_info(user, namespace_project): """Information about all autosaves for a project.""" if user.get_renku_project(namespace_project) is None: return make_response( jsonify( {"messages": {"error": f"Cannot find project {namespace_project}"}} ), ...
53,339
def get_anchor_gt(all_img_data, C, img_length_calc_function, mode='train'): """ Yield the ground-truth anchors as Y (labels) Args: all_img_data: list(filepath, width, height, list(bboxes)) C: config img_length_calc_function: function to calculate final layer's feature map (of base model)...
53,340
def assert_transform(pattern, text, transformed_tokens): """Assert grammar parses text to expected transformed tokens.""" assert not hasattr(pattern, "patterns"), "assert_transform only works with basic style patterns" find_and_replace = create_find_and_replace(pattern.grammar, pattern.replace) results ...
53,341
def per_subgroup_fnr_diff_from_overall(df, subgroups, model_families, threshold, squared_error): """Calculates the sum of differences between the per-subgroup false negative rate and the overall FNR.""" d = per_subgroup_nr_diff_from_overall(df, subgroups, model_families, ...
53,342
def load_data(file_path=FILE_PATH): """If the data exist load the data from a db (represented by a dict(str[name] -> int[quantity])). If not, return an empty dict.""" try: with open(os.path.join(file_path, 'data.pk'),'rb') as fh: data = pickle.load(fh) except FileNotFoundError: ...
53,343
def DoneWithResults(output: TextIO): """Final formatting for the results. Once the results of an experiment have been written to `output`, this function removes the last comma, adds a new line, and flushes the stream. Args: output: The stream that this function accesses. """ # Remove the comma at the ...
53,344
def scaffold_split_from_smiles( smiles_list, frac_train=0.8, frac_valid=0.1, frac_test=0.1, ): """ The same algorithm as scaffold_split. Only take SMILES list as input and return indices of the train, validation, and test samples. Args: smiles_list (list): list of SMILES to be splitted. ...
53,345
def _get_transitive_values(values, deps, deps_accessor): """Returns the transitive values from "values" added to values from deps. Args: values: the values of to be added to the transitive values from deps. deps: list of dependencies with GLSLInfo providers to add to the transitive ...
53,346
def get_common_config( io_conf: ConfigType, mqtt_conf: ConfigType, mqtt_options: MQTTClientOptions ) -> Dict[str, Any]: """ Return config that's common across all HQ discovery announcements. """ disco_conf: ConfigType = mqtt_conf["ha_discovery"] config = dict(name=io_conf["name"]) config.upd...
53,347
def handle_deposit_confirmation(*, deposit): """ Update confirmation status of deposit Increase users balance or create new user if they don't already exist """ DEPOSITS.update_one( {'_id': deposit['_id']}, { '$set': { 'is_confirmed': True } ...
53,348
def activate_cmd(s3_path, target, force, bucket_url): """Activate a version at the root of a bucket (by copying index.html and co to the root)""" global s3, s3client, bucket bucket_name = get_bucket_name(target) s3, s3client, bucket = init_connection(bucket_name) s3_path = parse_s3_path(s3_path, 'ac...
53,349
def compute_sampled_logits_css( weights, # [V, d] biases, # [V] probable, # [B, P] inputs, # [B, T, d] num_sampled, num_classes, minval=1, # use this to control what's the first valid class bias_correction=True ): """ :param weights: class...
53,350
def interp_weights(xyz, uvw, d=2): """ Fast interpolation of multiple datasets over the same grid from: https://stackoverflow.com/a/20930910/2197375 Parameters: --- xyz: ndarray, array of starting irregular grid coordinates uvw: ndarray, array of target regular grid coordinates d: int, ...
53,351
def add_shopping_list_items(create_client_shopping_list, client, generate_token): # noqa """ add items to a shopping list """ shopping_list_id = create_client_shopping_list.data['data']['id'] token, _ = generate_token url = reverse('shoppingItem:get shopping list items', args=[shopping_list_id]...
53,352
def _get_mode(): """Get the current mode (0 is Graph mode, 1 is PyNative mode)""" return context.get_context('mode')
53,353
def parse_xml(text:str): """Parse the given string as XML.""" return etree.fromstring(text)
53,354
def crop_anno(img_path, crop_position, df, im_w=None, im_h=None, filesystem:FileMan=None): """Calculate annos for a crop-position in an image Args: img_path (str): image to calculate the crop-annos crop_position (list): crop-position like: [xmin, ymin, xmax, ymax] ...
53,355
def tab_listtable_details(p_engine, p_format, rulesetname, envname, metaname): """ List details of tables/file from ruleset param1: p_engine: engine name from configuration param2: p_format: output format param3: rulesetname: ruleset name to display metadata from param4: envname: environemnt nam...
53,356
def setup_system_tomograph(n_shots: np.int, n_rays: np.int, n_grid: np.int) -> (np.ndarray, np.ndarray): """ Set up the linear system describing the tomographic reconstruction Arguments: n_shots : number of different shot directions n_rays : number of parallel rays per direction n_grid : n...
53,357
def parse_markdown_to_html_table(): """ Parse README.md, convert to HTML, return table """ readme = open("README.md", 'r').read() html = markdown2.markdown(readme, extras=['tables']) soup = BeautifulSoup(html, 'html.parser') table = soup.find("table") return table
53,358
def get_relation_priority(relation: Relation) -> int: """This function helps resolve conflicts when multiple conditions apply to the same factor transition. """ if isinstance(relation, And): priorities = [get_relation_priority(rel) for rel in relation.relations] priority = sum(prior...
53,359
def jsonunpipe(stdin, *args, **kwargs): """Calabash wrapper for :func:`jsonpipe.jsonunpipe`.""" yield jp.jsonunpipe(stdin, *args, **kwargs)
53,360
def _int_size_to_type(size): """ Return the Catalyst datatype from the size of integers. """ if size <= 8: return ByteType if size <= 16: return ShortType if size <= 32: return IntegerType if size <= 64: return LongType return None
53,361
def Coordinate(coord: str) -> Coord: """Converts a coordinate string into float tuple""" try: split = coord.split(",") return Coord(lat=Latitude(split[0]), lon=Longitude(split[1]), repr=coord) except Exception as exc: raise Invalid(f"{coord} is not a valid coordinate pair") from exc
53,362
def getCollateralRepayQuote(coin, collateralCoin, amount, recvWindow=""): """# Get Collateral Repay Quote (USER_DATA) #### `GET /sapi/v1/futures/loan/collateralRepay (HMAC SHA256)` Get quote before repay with collateral is mandatory, the quote will be valid within 25 seconds. ### ### Parameters: Name |Type |Manda...
53,363
def check_alpha(alpha): """Check whether given alpha is valid or not. Parameters ---------- alpha : float [scalar] Frequency warping factor. """ if np.abs(alpha) >= 1.0: raise ValueError('|alpha| must be less than 1.0')
53,364
def load_records(es, records, index): """Load batch of records""" if not es.indices.exists(index): es.indices.create(index=index, body=MAPPING) for success, info in helpers.parallel_bulk(es, records, index=index): if not success: print('Doc failed in parallel loading', fg="red")...
53,365
def _remove_duplicate_punctuation(text: str) -> str: """ Remove duplicate punctuation, which may have been a feature of gazette design. """ pattern = f"([{string.punctuation}])" + "{1,}" pattern = re.compile(pattern) text = re.sub(pattern, r"\1", text) return text
53,366
def forwarded(logLine, blinkTime=0.2) -> None: """Blink on forwarded quary.""" print("Forwarded ==> " + logLine) yellow.high() sleep(blinkTime) yellow.low()
53,367
def cprint(msg, color=None, style=None): """Coloured printing""" print(colored(msg, color=color, style=style))
53,368
def coeffs_mydft(x, order): """Use DFT.""" coeffs = [my_dft(x, 0)] for k in range(1, order+1): coeffs.extend([my_dft(x, k), my_dft(x, -k)]) coeffs = np.array(coeffs) / len(coeffs) return coeffs
53,369
def write_edits(f, edits): """Write EDITS to file-like object f as an RCS diff.""" for (command, input_position, arg) in edits: if command == 'd': f.write('d%d %d\n' % (input_position + 1, arg,)) elif command == 'a': lines = arg f.write('a%d %d\n' % (input_position, len(lines),)) f....
53,370
def _trim_log(file_name): """ if log is over the maximum we trim 10% old logs """ max_log_size = storage.get_leaf('logging').get('max_logsize', 4096) file_size_in_bytes = os.stat(file_name)[6] if file_size_in_bytes <= max_log_size: return # trim log os.rename(file_name, "temp.log...
53,371
def append_buttons(doc: BeautifulSoup) -> None: """Add buttons""" elems = doc.find_all("div", {"class": "cell tag_hide-input docutils"}) if len(elems) > 0: for element in elems: print(action_log(Fore.GREEN, "[APPEND]", "Adding hidden input button")) tag = BeautifulSoup( ...
53,372
def versionCompare(sVer1, sVer2): """ Compares to version strings in a fashion similar to RTStrVersionCompare. """ ## @todo implement me!! if sVer1 == sVer2: return 0; if sVer1 < sVer2: return -1; return 1;
53,373
def list_languages(request): """ Lists the languages for the current project, the gettext catalog files that can be translated and their translation progress """ languages = [] do_django = 'django' in request.GET do_rosetta = 'rosetta' in request.GET has_pos = False for language in s...
53,374
def test_genome_level_3(BTO): """ Test running on the mm level """ # Run the dereplicated version location = os.path.join(BTO.test_dir, os.path.basename(BTO.IS_nogenes)) shutil.copytree(BTO.IS_nogenes, location) for f in glob.glob(location + '/output/*.tsv'): os.remove(f) cmd = ...
53,375
def parse_employee_info(record_list): """ Parses the employee record information Example input: [('3c7ca263-9383-4d61-b507-2c8bd367567f', 123456, 'Austin', 'Grover', <memory at 0x11059def0>, True, 1, '00000000-0000-0000-0000-000000000000', datetime.datetime(2020, 2, 23, 16, 53, 25, 531305))] Args...
53,376
def define_struct(name, values, pack_attributes=True, skip_conversions=False): """Defines a collection of structs and their properties. Args: name: Name of the struct. This should be the same as the struct name used in newlib/libc libraries for the system calls. Eg. 'stat', 'timeval' values: List con...
53,377
def make_request( schema: Schema, request_url: str, endpoint_name: str, method: str, body: Union[Tuple[str, str], None], after_error_occurred: Callable[[ErrorMessage], None] = None, before_request_send: Union[Callable[[any], any], None] = None, ): """ Combine `prepared_request` and `...
53,378
def validate_options(*, options: Dict) -> None: """ Raises an Exception if the options do not contain resource_path or resource_name """ if options.get('resource_path') is None: raise Exception('resource_path was not provided in the notification options') if options.get('resource_name')is No...
53,379
def process_file(src, dst, file, language): """Process single wav file by creating transcription according to diarization in .rttm file""" file_path = join(src, file) # Create temp files tmp_dir = tempfile.mkdtemp() extract_channels(file, src, tmp_dir) # Init ASR r = sr.Recognizer() w...
53,380
def gas_release_rate(P1, P2, rho, k, CD, area): """ Gas massflow (kg/s) trough a hole at critical (sonic) or subcritical flow conditions. The formula is based on Yellow Book equation 2.22. Methods for the calculation of physical effects, CPR 14E, van den Bosch and Weterings (Eds.), 1996 Parameters...
53,381
def kube_rootca_update_start(token, force=False, alarm_ignore_list=None): """ Ask System Inventory to start a kube rootca update """ api_cmd_payload = dict() api_cmd_payload['force'] = force if alarm_ignore_list is not None: api_cmd_payload['alarm_ignore_list'] = copy.copy(alarm_ignore_l...
53,382
def email2words(email): """Return a slightly obfuscated version of the email address. Replaces @ with ' at ', and . with ' dot '. """ return email.replace('@', ' at ').replace('.', ' dot ')
53,383
def extract_zip_archive(archive, dest, delete_archive=True): """ Extracts a zip archive to `dest` :param export_archive: :param dest: :param delete_archive: delete the archive after extracting :return dest: """ try: logging.debug('Extracting archive to {}'.format(dest)) w...
53,384
def availPorts(): """ Returns a generator for all available serial ports """ try: import serial except ImportError as e: raise IOError("Could not import serial functions. Make sure pyserial is installed.") if os.name == 'nt': # windows for i in range(256): ...
53,385
def read_response_body(response: requests.Response) -> Union[dict[str, Any], str]: """ Read response body as a ``dict`` if possible, else as a ``str`` """ body = response.content.decode('utf-8') try: body = json.loads(body) if response.content else None except json.decoder.JSONDecodeError: ...
53,386
def mmid_data_generator_rnd(config, augment=False, augmentation=None, batch_size=1, no_augmentation_sources=None, mode='train'): """A generator that returns anchor and positive images config: The model config object augment: (deprecated. Use augmentation instead). If true, apply random...
53,387
def _augment_gain(audio, low=0.25, high=1.25): """Applies a random gain between `low` and `high`""" g = random.uniform(0.25, 1.25) return audio * g
53,388
def gaussfit(data, err=None, params=(), autoderiv=True, return_error=False, circle=False, fixed=np.repeat(False, 7), limitedmin=[False, False, False, False, True, True, True], limitedmax=[False, False, False, False, False, False, True], usemoment=np.array([], dtype='b...
53,389
def check_level_number(tags: Tags, level: float) -> bool: """Check if element described by tags is no the specified level.""" if "level" in tags: if level not in parse_levels(tags["level"]): return False else: return False return True
53,390
def setup(): """ setup any state specific to the execution of the given module.""" global couch couch = CouchDB(username="test", password="test", host="http://127.0.0.1", port=8000) yield
53,391
def fill_molecules_reactions(session): """Fills the reactionsequence column in the molecules table with info from reactions table. The molecules query will become to complex when reactionsequence is queried from reactions table. So we fill reaction sequence with a json serialized struct which c...
53,392
def read_eof_file(file): """wrapper for parse_eof to return a dictionary""" D = dict() potc,rforcec,zforcec,densc,potS,rforces,zforces,denss = parse_eof(file) D['potC'] = potc D['rforceC'] = rforcec D['zforceC'] = zforcec D['densC'] = densc D['potS'] = pots D['rforceS'] = rforces ...
53,393
def seed(seed): """Sets the seed for parcels internal RNG""" parcels_random.lib.pcls_seed(c_int(seed))
53,394
def test_train(args): """Trains the model.""" if args.verbose: tf.logging.set_verbosity(tf.logging.INFO) # Create input data pipeline. with tf.device("/cpu:0"): train_files = glob.glob(args.train_glob) if not train_files: raise RuntimeError( "No training images found with glob '{}'...
53,395
def protocol_store(sql_engine: SQLEngine) -> ProtocolStore: """Return a `ProtocolStore` linked to the same database as the subject under test. `ProtocolStore` is tested elsewhere. We only need it here to prepare the database for our `AnalysisStore` tests. An analysis always needs a protocol to link to....
53,396
def session_wrapper(addressed=True): """Allow to differentiate between addressed commands and all messages.""" def real_session_wrapper(func): """Wrap a telethon event to create a session and handle exceptions.""" async def wrapper(event): if addressed: # Check if t...
53,397
def _get_callable_str(*, callable_: Union[Callable, str]) -> str: """ Get a callable string (label). Parameters ---------- callable_ : Callable or str Target function or method or property or dunder method name. Returns ------- callable_str : str A callable ...
53,398
def pad_lr(x, fsize, fshift): """Compute left and right padding """ m = num_frames(len(x), fsize, fshift) pad = (fsize - fshift) t = len(x) + 2 * pad r = (m - 1) * fshift + fsize - t return pad, pad + r
53,399