content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def oo_selector_to_string_list(user_dict): """Convert a dict of selectors to a key=value list of strings Given input of {'region': 'infra', 'zone': 'primary'} returns a list of items as ['region=infra', 'zone=primary'] """ selectors = [] for key in user_dict: selectors.append("{}={}".format(key...
6c46d87d57c63869a2c4caf980fd064b37bd71b0
662,642
import random def randomseq(length, letters): """ Returns a sequence of a certain length with a composition of letters given as input. Args: length (int): Length of the sequence letters (string): A string containing all the possible letters Returns: Sequence (string): A seque...
c744ca81ae23c53a381cfd157447310118fef6bb
662,646
from typing import Dict def split_entry(entry: str) -> Dict[str, str]: """ Splits a given entry into a dictionary of parameters :param entry: An entry as a formatted string :return: A dictionary of key value pairs """ entries = entry.split(" ") return {key: value for key, value in [entry....
4dfe41869a5a8b3191a17d9140f0b0da450823d7
662,650
def free_slots(slots): """With planned slots as 18 return available slots""" return 18 - slots
465cf74e6599d9b4beedce15e6042f935f0373b5
662,652
import math def lonlat_to_mercator_tile_indices( longitude: float, latitude: float, zoom: int, tile_size: int = 512, flip_y: bool = False ): """ Conversion of lon-lat coordinates to (web)Mercator tile indices :param longitude: :param latitude: :param zoom: zoom level (0, 1, ...) ...
51ecc212ca50cc47aedd1a94a3e4f04454b75e52
662,660
def within_tolerance(value, expected): """ Verify that all values of the color tuple are within a range of tolerance. """ t = 0.01 return ((expected[0] - t) <= value[0] <= (expected[0] + t) and (expected[1] - t) <= value[1] <= (expected[1] + t) and (expected[2] - t) <= value[...
845960ee673319030ec65f0f13c206f337f687a2
662,664
def node2geoff(node_name, properties, encoder): """converts a NetworkX node into a Geoff string. Parameters ---------- node_name : str or int the ID of a NetworkX node properties : dict a dictionary of node attributes encoder : json.JSONEncoder an instance of a JSON enco...
461b2f8c3df9f6db8ba0161765f72f8cb77d8f38
662,666
def fix_filename(filename): """Latex has problems if there are one or more points in the filename, thus 'abc.def.jpg' will be changed to '{abc.def}.jpg :param filename: :type filename: str :return: :rtype: str """ parts = filename.split('.') ...
7453ef5e2bc57258ae3056ac78ab9729c4d1bd02
662,667
import re def compare_no_whitespace(a, b): """Compare two base strings, disregarding whitespace.""" return re.sub('\s*"*', '', a) == re.sub('\s*"*', '', b)
ce1672ee9244e1cfc37914184cc42e13dbe57652
662,669
import logging def make_log_record_output(category, level, message, format=None, datefmt=None, **kwargs): """ Create the output for a log record, like performed by :mod:`logging` module. :param category: Name of the logger (as string or None). :param level: Log lev...
7bf1ea588c6bb7374218def8edf40c7c5753931a
662,670
import base64 def _decode_endpoints(crypt: str) -> str: """Decode a GE endpoint.""" return base64.b64decode(crypt).decode('ascii')
c98378cb639948207fcaa22e63f7a15d01943b52
662,671
def get_center(im): """ Given image, returns the location of center pixel Returns ------- (int, int): center of the image """ center_x = float(im.size[0]) / 2 center_y = float(im.size[1]) / 2 return int(center_x), int(center_y)
ee4f445cc9fab709c9c713e0c71380d26532c800
662,680
import json def captureCardTransactionPayload(amount, capture_reference): """ Create JSON payload for capture transaction API call :param amount: Integer - Amount of currency's smallest denomination to be moved :param capture_reference: String - A reference specified by the merchant to identify the tr...
690a59f4d18fb1218bbbd34853b6809357d146e2
662,682
def get_team_player_links(league_soup): """NPBのsoupを解いてリンク集を取り出す関数 Args: league_soup(BeautifulSoup): NPB leagueの一覧表 Return: Dict: { 2019:{ chunichi dragons: URL, yokohama ba...
9ae9e614934d3d5fb9550ef38d973d5c3a277b73
662,683
def get_chunks(t_start, t_stop, n_chunks): """Group frame indices into given number of 'chunks'. Args: t_start (int): Frame index to start at (inclusive) t_stop (int): Frame index to stop at (exclusive) n_chunks (int): Number of chunks Returns: List of 2-tuples containing (...
b7477723cd35753699fce913f966618b882cdf21
662,686
from datetime import datetime def dt(txt, fmt='%Y-%m-%d'): """ Parse a text in YYYY-mm-dd format and returns a datetime.date. """ return datetime.strptime(txt, fmt).date()
3f1e8aa04dd1bbc86e937c11409495f295483725
662,687
import re def _at_notification(username, _sub=re.compile(r"[^\w'.-]*").sub): """Produce the @DisplayName notification normazilation form""" return "@" + _sub("", username)
ded3bf46a1b95dc0c7840aad324276b794d0ccd1
662,691
def update_particle(position_update, velocity_update, state, nbest_topology, idx_particle): """ Update function for a particle. Calculates and updates the velocity and position of a particle for a single iteration of the PSO algorithm. Social best particle is determined by the state...
6512c5ef337dbf411b7bd84987b52abba991a075
662,693
import re def parse_graphicspath(fname): """Parse "\grapchicspath" and return the result as a list object.""" with open(fname) as f: s = f.read() l = re.findall('.*graphicspath.*', s) graphicspath = ['./'] if l: for i in re.sub('(^.*?{)|(\s*}$)', '', l[-1]).split(','): ...
6e91d6fbbedd50d1cdc17e3c17b71656044ee12b
662,694
import math def hard_negative_mining(loss, labels, neg_pos_ratio): """ It used to suppress the presence of a large number of negative prediction. It works on image level not batch level. For any example/image, it keeps all the positive predictions and cut the number of negative predictions to mak...
a05f5f8614936e4860a11d4a16b7f0d37fe756d3
662,696
import pathlib def list_dirs(directory): """Returns all directories in a train directory """ return [folder for folder in pathlib.Path(directory).iterdir() if folder.is_dir()]
181861ce01583149e7479109d14963dfff50c871
662,699
def nofirst(l): """ Returns a collection without its first element. Examples -------- >>> nofirst([0, 1, 2]) [1, 2] >>> nofirst([]) [] """ return l[1:]
adf86fe85f8173be173ee94479dac1ceb7a38813
662,704
def clean_code(code): """Escape newlines.""" return code.replace('\n', '\\n')
2535cb97d9c42391fb43d7b8cca4281742f39526
662,705
def find_first1(l, pred): """ Find first occurrence in list satisfying predicate. :param l: list. :param pred: predicate on the list elements. :return: index of first occurrence in list satisfying predicate; length of the list if not found. """ length = len(l) index = length for i in...
c02823d9f27f79e714cfa2f8237363f96927189e
662,707
def pack(x: int, y: int, z: int) -> int: """ Pack x, y, and z into fields of an 8-bit unsigned integer. x: bits 4..7 (4 bits) y: bits 2..3 (2 bits) z: bits 0..1 (2 bits) """ word = (x << 4) | (y << 2) | z return word
88ec4e3940a55bd10f0f1f12c968000ea945a529
662,708
def no_replace(f): """ Method decorator to indicate that a method definition shall silently be ignored if it already exists in the target class. """ f.__no_replace = True return f
d9a0f8caaf6b05542c98f66a9e863f5470441b2a
662,718
def read_centers(file='year_centers.txt'): """ Read text file of array centers. three numbers per line: year of coverage, longitude, latitude. Returns dict of lon,lat pairs (list) indexed by integer year. """ centers={} # More elegant method is to use with, but not necessary # for ...
b1b5a87953a869fd46ae55dfb8bdd3e68ff51335
662,721
from typing import Tuple def interval_overlap(a: Tuple[int, int], b: Tuple[int, int]) -> int: """ Calculate the overlap between two intervals Example: a=(10, 30) and b=(20, 40) gives an overlap of 10 """ return max(0, min(a[1], b[1]) - max(a[0], b[0]))
ba27c08344ac8990bae208bed63d74bb7051019b
662,723
def update_config(original, update, override=True): """ Recursively update a dict. Subdict's won't be overwritten but also updated. """ for key, value in update.items(): if key not in original or (not isinstance(value, dict) and override): original[key] = value else: ...
40229801ee6fd974a874b9e83d66dc201b50c812
662,724
from datetime import datetime def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'): """Converts a unix timestamp into a formatted string.""" return datetime.fromtimestamp(t).strftime(fmt)
8d299125fb9ed6611f047c5c65b97685ea7d994f
662,725
from typing import Iterable import math from functools import reduce def least_common_multiple(seq: Iterable[int]) -> int: """ Least common multiple of positive integers. :param seq: sequence of numbers :return: LCM """ def lcm(num1: int, num2: int) -> int: return num1 * num2 // math....
89db10dc1f0ed8ea618a8a61e09056622c86c157
662,726
def generate_flake8_command(file: str) -> str: """ Generate the flake8 command for a file. Parameters ---------- file : str The file to fix. Returns ------- str The flake8 command. """ cmd = f"flake8 {file}" return cmd
d5358d30e27c54ae9e38110c63497755e223826a
662,729
def decomp(val): """ Returns the absolute value of a one's complement negative number """ c = 1 while val * 2 > c: val = val ^ c c = c << 1 return val
117b84a83671e9a19af59617bfb0cfba78773c57
662,734
def extract_id(object_or_id): """Return an id given either an object with an id or an id.""" try: id = object_or_id.id except AttributeError: id = object_or_id return id
db25673515fda0f98bf42f14f4da676c5ff2fec7
662,735
def validate_header(fields, required): """ Validate the header line in a source file. Parameters ---------- fields : list of str Each element is the name of a field from a header line required : set of str Each element is the name of a required field Returns --...
c8c1bf28aeb691f5fd414d32120561a4914d4d53
662,738
def fill_with_neg_inf(t): """FP16-compatible function that fills a tensor with -inf.""" return t.float().fill_(float('-inf')).type_as(t)
a1f1c6abb6f7e3cc2db6eb4cf3499b64bf5fdbe0
662,748
import jinja2 def make_jinja_env(templates_dir): """ Create the default Jinja environment given the template folder. Parameters ---------- templates_dir : str or pathlib.Path The path to the templates. Returns ------- env : jinja2.Environment The environment used to r...
79d03ae0aeaf7dafed04001e44b2446756313444
662,749
def p_test_loc_uty(α_spt, p_lt, p_li, p_e): """Local test pressure unity check. Reference: DNVGL-ST-F101 (2017-12) sec:5.4.2.1 eq:5.6 p:93 (local_test_press_unity) """ p_lt_uty = (p_li - p_e) * α_spt / p_lt return p_lt_uty
eb3f7886422e666381646181c10858d6db68d16b
662,751
def _generator_transfer(m, t): """ Constraint rule for electricity generation in generator @ In, m, pyo.ConcreteModel, model containing problem @ In, t, int, time indexer @ Out, constraint, bool, constraining evaluation """ return - m.elec_generator_production[0, t] == 2.0 * m.elec_generator_produ...
892e19da1a01b5118e183914aa9c1f15ea2ef78f
662,753
def getSparkFrameFromCSV(sparkSession, localFileSystemPath, selectionColumns=None): """ This function returns a sparkSession dataframe from the provided csv file path Syntax: status, message, df = getSparkFrameFromCSV(sparkSession, "/path/to/data/dataset.csv") Args: sparkSessio...
813cebcb040448776c9466bce7de56ffd13c65c9
662,754
from typing import List import pathlib from typing import Dict from typing import Any import pickle def _open_hydra_pickles(paths: List[pathlib.Path]) -> Dict[str, Any]: """Open pickles in directory of Hydra log and return dict of data. Parameters ---------- paths : List[pathlib.Path] Paths t...
fc5b187549251fc7aba7e711b64551e254bfde8d
662,755
def jaccard_distance(context_tokens: list[str], category_tokens: list[str]): """Simple function for calculating Jaccard Distance Args: context_tokens (list[str]): List of context words (i.e. target words) category_tokens (list[str]): List of words in category Returns: [float]: Valu...
490c516f6e3136a736d3e420d2061c6c221d1730
662,756
def get_vars(varstr): """Gets 2d variable labels from a single string""" variables = ['x', 'y', 'z', 'px', 'py', 'pz', 't'] #all_2d_vars = {} for var1 in variables: for var2 in variables: if(varstr == f'{var1}{var2}'): return [var1,var2]
22afb8040276879bd7b468bcdd84633b5ef9a0d5
662,760
def query(port, prop, repo=False): """Query q property of a package.""" args = ("pkg", "rquery" if repo else "query", port.attr["pkgname"]) if prop == "config": args += ("%Ok %Ov",) else: assert not "unknown package property '%s'" % prop return args
0d7d7a7f58d7d207d26b5e876c95efda35f1b70f
662,761
def next_event_name(trace: list, prefix_length: int): """Return the event event_name at prefix length or 0 if out of range. """ if prefix_length < len(trace): next_event = trace[prefix_length] name = next_event['concept:name'] return name else: return 0
f8e01a7ad8795c97ac4909f0996c70a8236916b4
662,765
def is_xlsx(filename: str) -> bool: """Checks if a filename suggests a file is an .xlsx file""" return filename.endswith(".xlsx")
4265f1c2743c9d0dc609d29ccafdcab273f034ae
662,766
def update_mean(mean, n, x, remove=False): """Calculates the updated mean of a collection on adding or removing an element. Returns 0 mean if updated number of elements become 0. Args: mean (float): current mean of the collection n (int): current number of elements in the collection x (...
3e4f44638c5b3f393b361241558058b95d377987
662,767
def rule_nr_to_rule_arr(number, digits, base=2): """Given a rule `number`, the number of cells the neighbourhood has (as `digits`) and the `base` of the cells, this function calculates the lookup array for computing that rule. >>> rule_nr_to_rule_arr(110, 3) [0, 1, 1, 1, 0, 1, 1, 0] >>> rule_nr...
6b9bff8b9c038bd8a397b1b99841cde469fe3665
662,768
def int_enum(cls, val): """Get int enum value. Parameters ---------- cls : `type` Int enum class. val : `int` or `str` Name or value. Returns ------- `IntEnum` Raises ------ ValueError """ if isinstance(val, str): val = val.upper() t...
d2a53e12a21749589e23b6688241600baed8450e
662,769
def cummulative_sum(x): """Returns the cummulative sum of elements of a list.""" # Create a copy of list x. output = x[:] for i in range(len(output) - 1): output[i + 1] += output[i] return output
63a571720bf13e9e3ed78b1a94e3527d16f70c55
662,770
def rivers_with_station(stations): """Returns a set with the names of rivers that have a monitoring station """ rivers = set() for station in stations: if station.river != None: rivers.add(station.river) return rivers
2efb43270f8401c773eefbf7621fb7355f795848
662,771
def author_media_location(instance, filename): """Return the location of a stored media file for an Author.""" author_id = instance.id image_type = filename.rpartition(".")[2] return f"workflow_system/authors/{author_id}/profileImage.{image_type}"
2484b33cd1535d103bc7f711573a8ca7ff551a8c
662,773
def get_sub_image_coords(coords, region_size, x_parts, y_parts): """ If an image is divided into sub_images, return a list of coordinates for all the sub-images. Parameters ========== coords: list of floats, [long,lat] region_size: float, size of square image in degrees long,loat x_part...
8dbb30a11772e9e62c521f36170e3ddbd4a2c6ab
662,776
def p() -> float: """``p`` in the top-.""" return 0.9
bb83d4a5793f0322d37a94dc5ee8655d4c035761
662,783
def validate_attr(attr, table_cols, attr_label, table_label): """Check if the attribute exists in the table.""" if attr not in table_cols: raise AssertionError(attr_label + ' \'' + attr + '\' not found in ' + \ table_label) return True
7d9b7d87098908754e4301b42900a8cbd80384cd
662,784
def updated_dict(d, only_existing=True, **updates): """ Update dictionary `d` with `updates`, optionally changing `only_existing` keys. * d: dict * only_existing: do not add new keys, update existing ones only * updates: dict :return: updated dictionary """ d = d.copy() if only_exis...
e33e77cf5cc1b626ea88ed831726265f4f4423b3
662,785
def filter_irr(df, irr_col, low, high, ref_val=None): """ Top level filter on irradiance values. Parameters ---------- df : DataFrame Dataframe to be filtered. irr_col : str String that is the name of the column with the irradiance data. low : float or int Minimum va...
01c631ff14bd35d0377513910542fce907328551
662,789
def break_camelcase_pythonic(string: str) -> str: """Breaks camelcase string (pythonic). Args: string (str): as string Examples: >>> assert break_camelcase_pythonic("helloWorld") == "hello World" """ return "".join(f" {item}" if item.isupper() else item for item in string)
5eb171187ea1b8d7c676e0c8194922e9f545a8bd
662,793
import pickle def load_results_dict(pickle_filename): """ Load results in a dict that have been pickled. Parameters ---------- pickle_filename : str DESCRIPTION. String with the filename we are loading results from Returns ------- results_dict : dict DESCRIPTION. Dict...
bdc6c11b8507266a28e7f0562e9bc8155ffdf3e3
662,795
def get_clean_block(block): """Clean up unicode characters and common OCR errors in blocks""" replacements = {'fi': 'fi', 'fl': 'fi', '—': '-', "’": "'", "‘": "'", '”': '"', '“': '"', ...
7a769ebeb1992070286e1d57bb93421c68c79afc
662,796
def read_diff_file(filename): """Read the diff file in its entirety.""" with open(filename) as fd: content = fd.read() return content
f2d22ba3e69870e2e588fc1df81cd061253e5663
662,797
def remove_multicollinearity_by_coefficient_threshold(df, method = 'spearman', coefficient_threshold = 0.7): """ Uses the correlation between features and a specified threshold to identify and remove collinear/multicollinear features. Args: df ([pandas.DataFrame]): A dataframe tha...
3de2fcb1ffe2c1d41af5ee62aa2a437e5c7baf41
662,799
def get_dir_edges_from_c_to_tars(c_to_tars): """ Returns tuple of all allowed directed edges (c, t) where c control and t target. Parameters ---------- c_to_tars : dict[int, list[int]] a dictionary mapping j in range(num_qbits) to a list, possibly empty, of the physically allowe...
8df730c2b5380989ca19bba9928a7051eead0b60
662,801
import torch def initial_state(hparams): """ Samples a random initial state. """ B = hparams.batch_size L = hparams.lattice_size num_particles = round(hparams.concentration * L**2) # choose sites that get a particle. Bose-Hubbard allows multiple particles per site. if hparams.potential.starts...
3b2547e87fe0898692957b426e175e223321f225
662,802
def seconds_to_str(s: int) -> str: """ Returns a string describing the given number of seconds in a human-readable form. """ s = abs(s) result = [] days = s // 86400 if days: result.append('{} day{}'.format(days, '' if days == 1 else 's')) hours = s // 3600 % 24 if hours: ...
0ee56882c80082a8621aeced9ba8364a6addc631
662,804
import collections import re def key_assignments_from_file(file_path): """ Return the key assignments found in the given file, as a collections.OrderedDict mapping each key to its text meaning. The file syntax and semantics are detailed in AnnotateShell.do_load_keys(). This function is meant...
517afa474b8fae53b650b7f48ff392714bd0ff1f
662,805
def _dec_out_formatter(out): """Converts PyTorch int sequences (word ids) to Python integers.""" res = [] for seq in out: tmp = [] for elem in seq: elem = elem.to('cpu').numpy() if len(elem.shape) == 0: elem = elem.item() tmp.append(elem) ...
20459c5549426601713374ebbca1fcfe6aa95e27
662,809
import json def load_map(map_path): """Load map in json format and return a dic Args: map_path (str): Path to json file Returns: map_dict: Map as dictionary. """ with open(map_path) as map_handle: map_dict = json.load(map_handle) return map_dict
208b4380912c832d8742648c5b0169c9b31a26dc
662,812
import re def __capitalize_hexadecimals(source): """ Capitalize all hexadecimal strings :param source: The source CSS string :return: The CSS string with all hexadecimal values capitalized """ def found(match): return match[0].replace(match[1], match[1].lower()) return re.sub(r'...
5811aa6347cfe945f5d0b4aa1f841eb7cd5ed16c
662,814
def squash_to_unit_interval(x: float, constant: float) -> float: """Scales non-negative x to be in range [0, 1], with a squash.""" if constant <= 0: raise ValueError('Squash constant must be greater than zero.') if x < 0: raise ValueError('Squash can only be performed on a positive value.') return x / (...
0a99803cfad0b82f15ebefe1a59ef24cfd8bbd33
662,815
import random def uniformFloat(lo, hi): """ Return a number chosen uniformly from the range [lo, hi). """ return random.uniform(lo, hi)
5712a90409df6ad269a5e61869d6cadfbf672225
662,823
def levenshtein(s, t): """ Computes the levenschtein distance between two strings of text This is borrowed code and has been checked, but stay careful :param s: first string of text :param t: second string of text :return: a distance measure, not normalized """ if s == "": return...
0acfbad0fcbc4bde79bc8d9fc379655c40b6e466
662,824
import random import time def get_pick(pick_status): """ This function takes one argument of variable type and returns an intger. It checks to see if it's the first round and randomly chooses a starting player if it is the first round. Otherwise, it simply returns the argument passed (an integer determining whose...
f976edae49e76250a996a2647133588ffa728faf
662,827
def func_name(func): """ Return the name of the function, or None if `func` is None. """ return None if func is None else func.__name__
4d33cdaf788101de2d5e2dfecde66cebbc589e95
662,833
def find_short(s): """ Given a string of words, return the length of the shortest word(s).""" return min(len(x) for x in s.split())
391e4af606f3ce7b1c16d3174b489baac256d7ce
662,840
def arraytize(v): """ convenience function that "transforms" its arguments into a list. If the argument is already a list, returns it. If the argument is None, returns an empty list. Otherwise returns [argument]. """ if v is None: return [] try : return list(v) excep...
38810e67cc10a14fe27dc4991d736b8a77fe6843
662,843
def sort_freqs(freqs): """Sort a word frequency histogram represented as a dictionary. Parameters ---------- freqs : dict A dict with string keys and integer values. Return ------ items : list A list of (count, word) pairs. """ items = freqs.items() items.sort(key =...
74962857ba48cfdb19bae2d584212b305be439f8
662,845
def get_precision(n): """ Get precision. Parameters ---------- n : dict Confusion matrix which has integer keys 0, ..., nb_classes - 1; an entry n[i][j] is the count how often class i was classified as class j. Returns ------- float precision (in [0, 1])...
a671394a7b388f7c47a56e8b8a0f726d143e2351
662,846
def get_clean_name(name): """ A convenience function for naming the output files. :param name: A name of the target file. :returns: The name suffixed with "_clean" and the file extension. """ name = name.split(".") name = name[0] + "_clean." + name[1] return name
d9bd9d1222edb033d3108c4a9365addeaca5aacb
662,847
def add_unary_magic_methods(np_funcs, translate_func): """Class decorator to add unary magic methods using NumPy to the class.""" def wrapper(cls): for fname, np_func in np_funcs: def magic_func(self, np_func=np_func): return translate_func(self, np_func) setatt...
d70f5bc2b619ab5e0fe49cc3855321b3846b0f39
662,849
def reformat_trademarks(data): """ Reformats the trademarks data to global standard. :param data: unformatted data :return: Formatted data """ for key,val in data.items(): if val == ["-"]: new_val = [] else: new_val = [{ "Name": ele[0], ...
79a17a56800bf41a40bbb5fabaf39188d48e03ba
662,850
def quality_score_to_string(score: int) -> str: """Returns the string representation for the given quality score. We add 33 to the score because this is how the quality score encoding is defined. Source: https://support.illumina.com/help/BaseSpace_OLH_009008/Content/Source/Informatics/BS/QualityScoreEncoding_s...
631c5742c9c111b3f2da41c77e23b60843121aee
662,853
from typing import List def octet_list_to_int(octet_list: List[int]) -> int: """ Convert octet list to integer. :param octet_list: Octet list to convert. :returns: Converted integer. """ result = 0 for octet in octet_list: result <<= 8 result += octet return result
f6c42461843b66c9cbc0026c1e242a72e1d95ae8
662,856
def get_host_replica(volume, host_id): """ Get the replica of the volume that is running on the test host. Trigger a failed assertion if it can't be found. :param volume: The volume to get the replica from. :param host_id: The ID of the test host. :return: The replica hosted on the test host. ...
efa06107afd39d81a7cb1e1f41724ba9e5310227
662,857
def delete_border_detections(chip_detections, chip_w, border_delete_amount): """Deletes detections near borders. This is to make merging of several slided inference patches easier. The function is implemented vectorized and is therefore lightning fast. Args: chip_detections (list): List of np.array...
0d1a7c56c27d4d0c0c57878dbc1ba3645c56d3ec
662,858
def mosaic_name(pairs_param): """ Generates a filename for the mosaic. Concatenating the pair names would be very long so instead we combine the last four numbers of the product_id's. """ return ''.join( [ f'{pair["left"][-5:-1]}-{pair["right"][-5:-1]}_' for pair in p...
c8ec322e0f7069261068e2dbd220822ed227e903
662,860
def add(x, y): """ Returns x+y Parameter x: The first number to add Precondition: x is an int or float Parameter y: The second number to add Precondition: y is an int or float """ return x+y
4d9cdc4ad3e41e74ffecece68b9cccd32440c664
662,862
def strip_uri_host_and_path(concept_uri): """remotes the host and path from a URI, returning only the final resource name """ if concept_uri is None: return None rightmost_slash_position = concept_uri.rfind('/') rightmost_colon_position = concept_uri.rfind(':') simplified_start = max(0, ...
bbbdda1cfeebf462f69dc9e75bcc63b8f5e51899
662,863
def extra(request): """ Add information to the json response """ return {'one': 123}
599be1cf18bed6b622c9a55aca73b62a7a1cb04e
662,865
def parseDockerAppliance(appliance): """ Takes string describing a docker image and returns the parsed registry, image reference, and tag for that image. Example: "quay.io/ucsc_cgl/toil:latest" Should return: "quay.io", "ucsc_cgl/toil", "latest" If a registry is not defined, the default is: "d...
73d75fcbe504c2404e24958db1d67b0880abdf4c
662,866
def getFilename(f): """Get the filename from an open file handle or filename string.""" if isinstance(f, str): return f return f.name
62a0e4301ee5284bac569134f3cf89edec7762a4
662,874
def coordinates(location): """Return a (lat, lng) tuple from an OpenCage location result location: a dict (from opencage.geocoder.OpenCageGeocode.geocode) """ geometry = location['geometry'] return geometry['lat'], geometry['lng']
201216a53194842aba102fe8e5c1d8609f5b197c
662,879
def m_seq_inx0_sort_in_list(seq, args=False): """ 对列表中单个列表按第一个元素排序,返回新的列表 :param seq: 列表形成的列表 :param args: 是否倒序 True or False :return: 排序后的列表 example: :seq [['20160708', 'gyf'], ['20180505', 'zme'], ['20170101', 'zkp']] :args True ...
27521ee6fff748c96f4e1ba00016662d8d6d4808
662,880
def cubes(l=[1, 2, 3]): """ task 0.5.29 implement one line procedure taking list of integers 'l' output should be a list of numbers whose 'i'th element is the cube of the 'i'th element of 'l' e.g. input[1, 2, 3] output[1, 8, 27] def cubes(l=[1, 2, 3]): return [i ** 3 for i in l] """ ...
a7143f5efd86a4b21e75a7a7fc7f93309840d156
662,882
import re def validate_date(date: str) -> dict: """ Validate provided date data. Desired format: YYYY or YYYY-MM (2021 or 2021-12). """ # regex patters rp_year_month = re.compile('^(20[0-9]{2})-((0[1-9])|(1[0-2]))$') rp_year = re.compile('^(20[0-9]{2})$') # Match year-month object ...
86ed53dc1a7a1b7e060fc1acf8762e3f447ff279
662,883
def has_material(obj, name): """check if obj has a material with name""" return name in obj.data.materials.keys()
3c8ce0daaacf59b49e486d09266d6bc94f805590
662,885
from functools import reduce def fuseDotAl(dotAl): """Given input [ (2, "3"), (4, "5"), (2,"6") ], d will be a dict { 2: {"3","6"}, 4: {"5"} } and return value { 2: {"3 \n 6"}, 4: {"5"} } """ d = dict([(x, {y for (z,y) in dotAl if z==x}) for (x,w) in dotAl]) # sets of y for the same x ...
b93ec0a30dcc69ef5b0561191ba543459e6f7801
662,888
def outline_az_sub(sub_index, sub, tenant): """Return a summary of an Azure subscription for logging purpose. Arguments: sub_index (int): Subscription index. sub (Subscription): Azure subscription model object. tenant (str): Azure Tenant ID. Returns: str: Return a string th...
e947598b16e44d1bd3e86e65c31f5b933d256a11
662,889
def lowercase_set(sequence): """ Create a set from sequence, with all entries converted to lower case. """ return set((x.lower() for x in sequence))
23f55bd4ad1c9ec19b9d360f87a3b310ad619114
662,890
import requests def _get_token(ZC, username, password): """Gets the client's token using a username and password.""" url = '{}/oauth/token/'.format(ZC.HOME) data = {'username': username, 'password': password, 'noexpire': True} r = requests.post(url, json=data) if r.status_code != 200: r...
192c113d6e904f6d7756e28e7a80147b9d20cb54
662,891