content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def split_str_avoiding_square_brackets(s: str) -> list: """ Splits a string by comma, but skips commas inside square brackets. :param s: string to split :return: list of strings split by comma """ res = list() skipping = 0 last_idx = 0 for i, c in enumerate(s): if c == '[': ...
29dad952d9b8151bb2bad0f5c7338436251792b7
16,686
def sizeToTeam(size): """Given a size in kilobytes, returns the 512kb.club team (green/orange/blue), or "N/A" if size is too big for 512kb.club""" if size<100: return "green" elif size<250: return "orange" elif size<=512: return "blue" else: return "N/A"
a61f6a28f8f00cd05271684f715345b7fac4ed54
16,689
def product_consumption_rate(total_items, total_orders): """Returns the average number of units per order. Args: total_items (int): Total number of items of a SKU sold during a period. total_orders (int): Total number of orders during a period. Returns: Average number of units per ...
e5645a4703d0d9335abc6832da24b8a6b53c0c17
16,693
import json def read_cjson(path): """ Read a json file with #-comment lines """ with open(path) as f: lines = [line for line in f if not line.strip().startswith('#')] data = json.loads('\n'.join(lines)) return data
f0585820e56c5fa8ccbf9894a70b780b4ce00018
16,694
def getSelectRedirect(params): """Returns the pick redirect for the specified entity. """ if params.get('args'): return '/%(url_name)s/pick?%(args)s' % params else: return '/%(url_name)s/pick' % params
1eae1150f180986b74ac2ec9bc31c3d3d1f566e1
16,698
def wrap(char, wrapper): """Wrap a sequence in a custom string.""" return wrapper.format(char=char)
a86bbfb5f1b4ea373eb0a23b365c63ceed106159
16,708
def x2bool(s): """Helper function to convert strings from the config to bool""" if isinstance(s, bool): return s elif isinstance(s, str): return s.lower() in ["1", "true"] raise ValueError()
2850c3ab0421619a087d88181f3b6e2c6ffa9e9a
16,718
def round_down(rounded, divider): """Round down an integer to a multiple of divider.""" return int(rounded) // divider * divider
cf9ea0a437d3246776bd80e03ed19f06827f68ce
16,719
import json import base64 import binascii def validate(arg): """ Validate input parameters for `left` and `right` :param arg: input from request :return: dictionary of {'data': base64encoded_stirng} if valid or False if not valid """ if not arg: return False if isinstan...
c10634020e402ffd7b39f657c405e6bcc7283031
16,721
import json def read_json_config(cfg): """Read a JSON configuration. First attempt to read as a JSON string. If that fails, assume that it is a JSON file and attempt to read contents from the file. Args: res: a config string or file path Returns: dict of config options """ ...
2268297273dbfb468e0a8391981b4795702ba0b7
16,723
import string def idx_to_label(n: int) -> str: """Convert a number to a corresponding letter in the alphabet. In case the number is higher than the number of letters in the english alphabet, then a second character is appended. >>> For instance: >>>idx_to_label(0) >>> 'a' >>> idx_to_label...
67e4bba437016dddb6d90f286e1d65f2bfec8caf
16,728
def dict_contains(subdict, maindict): """ return True if the subdict is present with the sames values in dict. can be recursive. if maindict contains some key not in subdict it's ok. but if subdict has a key not in maindict or the value are not the same, it's a failure. >>> dict_contains(dict(a=1, ...
3c02145c7572f4c2d815213527effbfd7df93496
16,729
from typing import Any def cast_numeric_greater_than_zero( value: Any, value_name: str, required_type: type ) -> None: """ Checks that `value` is greater than zero and casts it to `required_type`. Raises an exception `value` not greater than zero. Args: value: numeric value to check ...
27f3b26d824863f1a94d4efe8c902cb84bc26c59
16,730
from typing import Iterable def filter_duplicate_key( line: bytes, line_number: int, marked_line_numbers: Iterable[int], ) -> bytes: """Return '' if first occurrence of the key otherwise return `line`.""" if marked_line_numbers and line_number == sorted(marked_line_numbers)[0]: return b"" ...
d592e718832f6d0c4718989d1a0fb96783c1508c
16,732
import re def clean_text(text, *, replace='_'): """ Ensure input contains ONLY ASCII characters valid in filenames. Any other character will be replaced with 'replace'. Characters added in extras will be whitelisted in addiction to normal ASCII. Args: text: The text to clean. repl...
92d305e78d4883cea2e0a1c3da218284ad783b72
16,741
from pathlib import Path def label_malformed(path: Path) -> Path: """ Renames the file at the given location to <original_filename>_MALFORMED. If such a file already exists, an incremented number is appended to the name until it can be created. The new file name is returned. Raises: `OSError` ...
12ca5ec240803127dd8aed7d13502c71a12f08ae
16,749
def get_child_parents(edges): """Puts each non-parent node together with its parents Parameters ---------- edges : list A list of tuples corresponding to the Bayesian network structure as described in the input file Returns ------- child_parents A dictionary with non-paren...
4b01a264ee1e2498c37f1fa0695f9430c207f04d
16,750
import random def get_random_from_distribution(minimum_value, distribution, increment=1): """Returns an integer from minimum_value to len(distribution)*increment, where the probability of any specific integer is determined by the probability distribution. """ x = random.random() result = minim...
0d3cde30c86ea8e230e3740123810d1e2d73d7ee
16,751
def get_divisable(row): """Get numbers from row where one divides another without rest.""" for index, num in enumerate(row[:-1]): for other_num in row[index + 1:]: if num % other_num == 0 or other_num % num == 0: return sorted([num, other_num], reverse=True)
e7e6cb9936cd54df7cd0594168e53b8821cfbae6
16,755
def dms(degrees): """ Calculate degrees, minutes, seconds representation from decimal degrees. Parameters ---------- degrees : float Returns ------- (int, int, float) """ degrees_int = int(abs(degrees)) # integer degrees degrees_frac = abs(degrees) - degrees_int # fracti...
ef062ddc4d313c0e8376096952d0011c01d27825
16,756
def parenthesise(s, parens = True): """ Put parentheses around a string if requested. """ if parens: return '(%s)' % s else: return s
37a1abbb4a511eff9b9c63a79fafcc60331bee67
16,762
def delta_sr(processor_sr, aeronet_sr): """ Convention in ACIX I paper :param processor_sr: surface reflectance of the processor :param aeronet_sr: surface reflectance of the reference (aeronet based) :return: """ return processor_sr - aeronet_sr
60b3a69fd986044126cf95b8d87425334e472abe
16,763
from typing import Tuple import math def uniform_divide(total: float, mpp: float) -> Tuple[int, float]: """Return the minimum number of partitions and the quantity per partition that uniformly divide a given quantity :param total: The total quantity to divide :param mpp: Maximum quantity per partition ...
2cccebd710975b34ab7f3538516d8f4c60b18c87
16,764
def matrix_wrapper(input_tuple): """ Parallel wrapper for matrix formation. This wrapper is used whenever a pmap/map-type function is used to make matrices for each cell in parallel. Parameters ---------- input_tuple : Tuple Index 0 is the chain (depletion_chain.DepletionChain), index ...
4a594e6fda9b4916f644a422d1b51969b86fb44e
16,771
def short_msg(msg, chars=75): """ Truncates the message to {chars} characters and adds three dots at the end """ return (str(msg)[:chars] + '..') if len(str(msg)) > chars else str(msg)
f807c4e2a032bb05ba5736e955af7c03653bcf80
16,773
import torch def accumarray(I, V, size=None, default_value=0): """ Returns a Tensor by accumulating elements of tensor V using the subscripts I The output tensor number of dimensions is/should be equal to the number of subscripts rows plus the values tensor number of dimensions minus one. Parame...
5e5acb0490f305a4498825260d5852a2fd15ea90
16,776
def _AsInt(x): """Converts text to int. Args: x: input value. Returns: Integer value of x, or None. """ try: i = int(x) return i except (ValueError, TypeError): return None
393b88a0cc317b34fee1c0748e508ddac9ce5534
16,778
def coerce_entity_dict(v): """Coerce entity ID strings to a dictionary with key "entity".""" if isinstance(v, str): return {"entity": v} return v
6f8265d08bde871b9379fb693cfb385bff0783ce
16,779
from typing import List def cut_on_stop(text: str, stop: List[str]) -> str: """Cuts a text to the first stop sequences. :param text: Text to cut. :type text: str :param stop: List of stop sequences. :type stop: List[str] :return: Cut text. :rtype: str """ items = [text] for ...
b25d4c4172b171ea126dfaa77203691c935001ac
16,789
def datetime_to_str(time): """convert python datetime object to a {hour}:{min}:{second}:{millisecond} string format """ return '{hour}:{min}:{second}:{millisecond}'.format( hour=time.hour, min=time.minute, second=time.second, millisecond=str(int(round(time.microsecond ...
8d7c5a7b08c32718cb5e284b30ee9cd57b3c2e2e
16,790
def extract_header_spki_hash(cert): """ Extract the sha256 hash of the public key in the header, for cross-checking. """ line = [ll for ll in cert.splitlines() if ll.startswith('# SHA256 Fingerprint: ')][0] return line.replace('# SHA256 Fingerprint: ', '').replace(':', '').lower()
7cd9f38855be4877e14761ab87994df79d251e4e
16,792
def backend_listener_url(testconfig): """ Returns the url of the backend listener """ return f'{testconfig["threescale"]["backend_internal_api"]["route"]["spec"]["port"]["targetPort"]}' \ f'://{testconfig["threescale"]["backend_internal_api"]["route"]["spec"]["host"]}'
98da2a6ea0d421d3a904858573d5d3d4656db9f9
16,793
import json import ast def flatten_json_1_level(event, field_name, field_name_underscore, dump_to_string): """ Flattens a JSON field 1 level. This function is used in flatten JSON :param event: A dictionary :param field_name: The field name to flatten :param field_name_underscore: The field name with...
348d8b9b8fbd34577b0e1aa2537fd6887f48bd47
16,796
def clean_intent_labels(labels): """Get rid of `None` intents. sklearn metrics do not support them.""" return [l if l is not None else "" for l in labels]
d1681ac88f3454c33887511aa100bc50a48c8ca2
16,800
import shlex def shlex_quote(string: str) -> str: """Simple wrapper for shlex.quote""" return shlex.quote(string)
d067d5aaaa351a4345d2fb0f63503f0b6ec46860
16,801
def should_keep_road(road, road_shp, record_buffers_index): """Returns true if road should be considered for segmentation :param road: Dictionary representation of the road (with properties) :param roads_shp: Shapely representation of the road :param record_buffers_index: RTree index of the record_buffe...
3deffa4c4f52759fbe38afa6597faf75a8a7284e
16,802
def _is_call(call, func): """ Return whether the first argument is a function call of the second. """ return call.startswith(func + "(") and call.endswith(")")
9c60b3f5ba29e41c1ea91e2d35a08c49a76444ea
16,803
def EnsureEnabledFalseIsShown(cv_config): """Ensures that "enabled" is shown when printing ContinuousValidationConfig. Explicitly sets ContinuousValidationConfig.enforcementPolicyConfig.enabled to False when it's unset, so the field is printed as "enabled: false", instead of omitting the "enabled" key when CV ...
dc6d535b074621e06cb8d36a9a6a03cb81765a16
16,807
def transposition_num(num): """ transposition axis(y) number. 0 => 8, 1 => 7, ..., 8 => 0 """ return (4 - num) + 4
fa7118f655026d4773cea1d5f387789019a72f75
16,809
import itertools def xor(one: bytes, two: bytes) -> bytes: """XOR, re-cycling two if len(one) > len(two).""" assert len(one) >= len(two) return bytes([ a ^ b for a, b in zip(one, itertools.cycle(two)) ])
c308fe0fea62def18fcce7a00b082cd2a959bf38
16,815
def find_node_name(model, name): """ Finds a node by its name. :param model: onnx graph :param name: node name :return: node pointer """ if not hasattr(model, "graph"): raise TypeError( # pragma: no cover "Parameter model is not an ONNX model but " "{}".forma...
9dc3a308f5134236b12bf79bc76b0d09fc41458d
16,817
import difflib def text_compare(text1, text2, output_file): """ Compares two strings and if they match returns True else writes the difference to the output_file. """ if text1 == text2: return True diff = list(difflib.Differ().compare(text1.split(), text2.split())) te = ope...
8cad72b9fcf7f213cdd9c337d86c89c664fdc606
16,821
import jinja2 import yaml def parse(filename): """Parse a configuration file. Parameters ---------- filename : str The config file to parse. Should be YAML formatted. Returns ------- config: dict The raw config file as a dictionary. """ with open(filename, "r") a...
055bcca59e2c9d3adad2ca9bdc527fc849ef2290
16,822
def tag_sibling_ordinal(tag): """ Given a beautiful soup tag, count the same tags in its siblings to get a sibling "local" ordinal value. This is useful in counting child figures within a fig-group, for example """ return len(tag.find_previous_siblings(tag.name)) + 1
ca3f764c7046ac65e99f6a074145b6afc11d2b2d
16,826
import copy def n_max_elements(list1, N): """ Function to compute the N highest numbers of a list """ n_list1 = copy.deepcopy(list1) final_list = [] for i in range(0, N): max1 = 0 for j in range(len(n_list1)): if n_list1[j] > max1: max1 = n_list1[j] n_list1.remove(max1) final_list.append(max1) ...
8361994794efe5a3f34723f667c3b83fe75a388e
16,829
from typing import Any def make_safe(value: Any) -> str: """ Transform an arbitrary value into a string Parameters ---------- value: Any Value to make safe Returns ------- str Safe value """ if isinstance(value, bool): return str(value).lower() ret...
4b342105d26458ddffd20712c777c5bc8e221c81
16,831
def smooth_vectors(vectors, strength, iterations): """ Smooths the vector iteratively, with the given number of iterations and strength per iteration Parameters ---------- vectors: list, :class: 'compas.geometry.Vector' strength: float iterations: int Returns ---------- list, :...
2a8dd922e5f10d67bcc1285eddbb6e53f43177c9
16,832
from pathlib import Path def scrape_names(path: Path) -> list[str]: """Scrape names into a list and sort them.""" with path.open() as h: return sorted(eval(next(h)))
d1b001a911abf7b81602b61b4b8a185ad257fe78
16,837
def twiddle(objFunction, args, init=0.5, tolerance=0.00001, domain=(float("-inf"), float("inf"))): """ Optimize a single parameter given an objective function. This is a local hill-climbing algorithm. Here is a simple description of it: https://www.youtube.com/watch?v=2uQ2BSzDvXs @param ar...
8991c328b2fd45b77bb6fbea5bc2b0f8a5d705ce
16,839
def pypi_link(pkg_filename): """ Given the filename, including md5 fragment, construct the dependency link for PyPI. """ root = 'https://files.pythonhosted.org/packages/source' name, sep, rest = pkg_filename.partition('-') parts = root, name[0], name, pkg_filename return '/'.join(parts)
1f71b2c6c34b52a60c2ead14b40e98ef0c89a8cf
16,844
def create_vector_dictionary(vector_file, multiword=False): """ This function creates a dictionary with vector values from affixoids Args: vector_file (file): File with vector values from FastText multiword (bool): Set to True if the word in vector file has multiple parts R...
2da775668193b0cd545137f90f416dca4fb166be
16,845
def add_linebreaks(text, max_len=80): """ Add linebreaks on whitespace such that no line is longer than `max_len`, unless it contains a single word that's longer. There are probably way faster methods, but this is simple and works. """ br_text = '' len_cnt = 0 for word in text.split(' '): len_cnt += len(word...
3d09572d34b67da9b639466478ce2d62d6d54116
16,846
def strftime(date, fmt): """ Apply strftime to `date` object with `fmt` prameter. Returns '' if either is non truthy """ try: if not date or not fmt: return '' return date.strftime(fmt) except: return ''
702688a4c7b4c5bef1ee64ba1804335b617baa2f
16,848
import re def normalize(string): """Normalize whitespace.""" string = string.strip() string = re.sub(r'\s+', ' ', string) return string
a677092aa0deaed5a87958f35e63fbe5538e04f3
16,851
def kb(units): """Boltzmann constant Parameters ---------- units : str Units for kb. Supported units ====== ========================= ============== Unit Description Value ====== ========================= ============== ...
4f0d4cfa10f617e1a9a0257b1a509606af2d7f18
16,857
def get_one_batch(dataloader): """Returns one batch from a dataloader""" iter_dl = iter(dataloader) #Necessary. You have to tell the fucking thing it's iterable. Why? batch = next(iter_dl) return(batch)
a05bde960649791f6ea8a8a432c5f39af6137275
16,858
import math def calc_stats(base_stats, level): """Calculate a Pokemon's stats based on its base stats and level""" stats = [] stats.append(math.floor((31 + 2 * base_stats[0] + 21) * level/100 + 10 + level)) for i in range(1, 6): stats.append(math.floor((31 + 2 * base_stats[i] + 21) * level/10...
a2b94a830d6d6622e8a58ce3831112af31899776
16,867
def build_edges(src_profile, dst_profiles): """create set of edges, compatible with NX graph format.""" edges = set() for dst_profile in dst_profiles: edges.add((src_profile['uid'], dst_profile['uid'])) return edges
3af864e0b847b530c0c524b28a406cf8a99b71e0
16,872
import re def get_filename_parts(filename, default_suffix=''): """ Parses a string representing a filename and returns as a 2-element string tuple with the filename stem and its suffix (the shortest string after a dot from the end of the string). If there's no suffix found a default is used instead. ...
a9f7451ab0da7c6dd661959000b8e9d89911d8c1
16,877
def getWalkTag(node): """Get Controller tag Arguments: node (dagNode): Controller object with tag Returns: tag: Controller tag """ tag = node.listConnections(t="controller", et=True) if tag: return tag[0]
87ffee1216d29a23331e0b7411eccf376326ec5a
16,878
import math def area_triangle_sss(side1, side2, side3): """ Returns the area of a triangle, given the lengths of its three sides. """ # Use Heron's formula semiperim = (side1 + side2 + side3) / 2.0 return math.sqrt(semiperim * (semiperim - side1) * ...
3c6276d7b4e9f8f0282eec187964112c7b745a7d
16,879
def _FindOrAddSolution(solutions, name): """Find a solution of the specified name from the given list of solutions. If no solution with the specified name is found, a solution with the specified name is appended to the given list of solutions. This function thus always returns a solution. Args: solution...
50d7d93a0a43062ceba2abd8677e6ca77596911e
16,880
def classify(df, w): """ Classify result of linear discriminant analysis for different classifiers. @param df pandas dataframe; @param w dict[classifier: (list of weights, weight threshold)]; @return df with appended result. """ # get input if 'state' in df.columns: x = df.drop(...
184d2aa61ef8cb942b8ba69f15148d2b99c22091
16,881
def id2num(s): """ spreadsheet column name to number http://stackoverflow.com/questions/7261936 :param s: str -- spreadsheet column alpha ID (i.e. A, B, ... AA, AB,...) :returns: int -- spreadsheet column number (zero-based index) >>> id2num('A') 0 >>> id2num('B') 1 >>> id2num('XFD')...
a1966821557324a0e95568bf0f63207d8cd3f350
16,886
def is_calibration_point_finished(message): """Check if calibration for a calibration marker is done""" return "manual_marker_calibration" in str(message[b"name"]) and "Sampled" in str( message[b"msg"] )
709479eeb552f563b690bee7140120893baa2c06
16,902
def get_ellip(q): """Given minor to major axis ratio (q) Returns ellipticity""" return (1-q**2)/(1+q**2)
56f1b2c9d5e821cc55344a3d387efafd82414224
16,903
def clean_up_tokenization(text): """ Clean up a list of simple English tokenization artifacts like spaces before punctuations and abreviated forms. From https://github.com/huggingface/transformers/blob/master/src/transformers/tokenization_utils.py#L1400 """ despace_substrings = [".", "?", "!", ...
8ecb329e89ddb9a49c23ee4745b574e66359cc6e
16,904
def create_playlist_for_user(spotify_obj, spotify_username, playlist_name): """Method that creates a playlist with given name for given username, using authorized spotipy.Spotify object. Created playlist ID is returned.""" playlist = spotify_obj.user_playlist_create(spotify_username, playlist_name) retu...
7a45d8250f58f58bb17ba4dfad0bb73bf9a1796a
16,907
import pickle def get_reddit_model(fname='models/reddit_regression.pkl'): """ Load pre-trained reddit model from pickle file """ with open(fname, 'rb') as fid: reddit_model = pickle.load(fid) return reddit_model
8bab0ff3811067830ad9d1a4da824ffa85bda86e
16,911
def inflate_dict(dct, sep=".", deep=-1): """Inflates a flattened dict. Will look in simple dict of string key with string values to create a dict containing sub dicts as values. Samples are better than explanation: >>> from pprint import pprint as pp >>> pp(inflate_dict({'a.x': 3, 'a....
fa929cd7a1b4825fb750755a76efcfab0e3a2666
16,918
def encode_module_value(v): """ For all things not in builtins, return the module name, otherwise just return the name """ mod = v.__module__ v = getattr(v, "__qualname__", v.__name__) if mod == "builtins": return v return {"module": mod, "name": v}
497b8838f8458ff973bd9d3a30b839b328d0ab11
16,919
from typing import OrderedDict def csvtable_to_dict(fstream): """ Convert a csv file stream into an in memory dictionary. :param fstream: An open file stream to a csv table (with header) :returns: A dictionary with a key for each column header and a list of column values for each key. """...
a562be13f2df806cbdd104eacb7dbca35afd2d35
16,924
def updateCharacterName(old_name: str, new_name: str) -> str: """Return a query to update a given character's name.""" return (f"UPDATE game_character " f"SET name='{new_name}' " f"WHERE name='{old_name}';" )
eb829e6be49393baf1c007c0331fd45a50050af5
16,930
import click def user_callback(_ctx, param, value): """Testing callback that transforms a missing value to -1 and otherwise only accepts 42.""" if not value: return -1 if value != 42: raise click.BadParameter('invalid integer', param=param) return value
f6d2a247f68ff37626a5abb7efc3b6c5967a5202
16,932
def np_gather_ijk_index(arr, index): """Gather the features of given index from the feature grid. Args: arr (numpy array): h*w*d*c, feature grid. index (numpy array): nx*3, index of the feature grid Returns: nx*c, features at given index of the feature grid. """ arr_flat = a...
3d4ddadadad1fbd44b060be96829496b3ecc4888
16,937
def nested_print(this_name: str, root_dict: dict) -> str: """ Get printable report of the elements of a nested dictionary. Parameters: this_name (str): nameof(root_dict), where "from varname import nameof". root_dict (dict): the dictionary whose elements must be printed. Returns: ou...
fd409abec98f9c4f3001f17c49a987e594827c0c
16,943
def example_encoded_image(example): """Gets image field from example as a string.""" return example.features.feature['image/encoded'].bytes_list.value[0]
42da58881e1e55533206cfa147ff4a9e3e68fa23
16,946
def default_formatter(item): """ Default formatter (%s) :param item: The item to save to file :return: The item to be saved to file with a newline appended """ return '%s\n' % item
47603ec796f686a36562520492a591918c1d3041
16,947
def sort_orbitals(element_pdos): """Sort the orbitals of an element's projected density of states. Sorts the orbitals based on a standard format. E.g. s < p < d. Will also sort lm decomposed orbitals. This is useful for plotting/saving. Args: element_pdos (dict): An element's pdos. Should be f...
de9b607895bad3c09709dcf9c9f1692fb07d5f63
16,950
def cached_and_cgi(name, template_func, render): """Return 2 functions for testing template in cached and cgi modes.""" _template = template_func() def test_cached(): # reuse early created template render(_template) test_cached.__doc__ = "test_%s" % name def test_cgi(): # cre...
da616817b7a45cfa0c340f7cbde970e009c35f73
16,957
def get_global_address(address, bank): """ Return the rom address of a local address and bank. This accounts for a quirk in mbc3 where 0:4000-7fff resolves to 1:4000-7fff. """ if address < 0x8000: if address >= 0x4000 and bank > 0: return address + (bank - 1) * 0x4000 return address
d72c9022f6c913d9d25f54c48539ea8f68f43b19
16,959
def minibatch(x, batchsize): """Group the rows of x into minibatches of length batchsize""" return [x[i:(i + batchsize)] for i in range(0, len(x), batchsize)]
026774d1a17454aebe714788eb1bed0ff4d45e3f
16,960
def ni_to_hr(ni, f): """Calculate heart rate in beat/min from estimated interval length Args: ni (int): estimated inter-beat interval length f (float): in Hz; sampling rate of input signal Returns: float: heart rate in beat/min """ if ni == -1: return -1 return ...
541e6f31d9df2fb4645f7b7c501ad123ad1d9660
16,964
def insertion(N, M, i, j): """ example input: N = 10000000000, M = 10011, i = 2, j = 6 example output: 10001001100 """ M_shifted = M << i right_mask = (1 << i) - 1 # produces 0...011 left_mask = -1 << j + 1 # produces 1...1000000 full_mask = right_mask | left_mask N_cleared = N ...
41e8d80239cbe42c383078d215339438984622f5
16,969
def l_out(l_in: int, padding: int, dilation: int, kernel: int, stride: int) -> int: """ Determine the L_out of a 1d-CNN model given parameters for the 1D CNN :param l_in: length of input :param padding: number of units to pad :param dilation: dilation for CNN :param kernel: kernel size for CNN ...
85e5d94dbcfdce2c7671674b3ddb7dd77f69728e
16,971
def reshape_array(array, new_len): """ array: shape= [M,N] new_len: the length of the new array, the reshaped shape will be [M//new_len, new_len, N] """ M, N = array.shape m = M // new_len return array[: m * new_len, :].reshape([m, new_len, N])
38eefb3ec7caa97c15775b06dcef5a8d0bf7b42a
16,972
def change_list_to_dict(list_to_convert, key): """ Changes a list into a dictionary using the 'key' parameter as the dictionary keyself. Assumes the key is in each dictionary. Assumes the key is unique. """ dict_to_export = {} for each_obj_in_list in list_to_convert: # Check if ...
7f624fe85469b0cfddf7723cdb561f1d6c2049ef
16,977
def get_shape_from_value_info(value): """Get shape from a value info. :param value: the value_info proto\\ :return: list of the shape """ return [d.dim_value for d in value.type.tensor_type.shape.dim]
77c3216cffd93900b50bb85ad6dfb43dda31b460
16,978
def zero(x): """return zero.""" return 0
d01d0d47730e2fbf800c37fcbe835ca3702216e7
16,980
def decode(encoded_digits: list[str], mapping: dict) -> int: """decode a number. Use the mapping to decode the encoded digits and combine them to a number. Args: encoded_digits (list[str]): encoded digits mapping (dict): mapping that decodes each segment Returns: (int) decoded...
be4cbd2fbc8be31b1126676a3a115b345b598c8a
16,984
def _is_float(string_inp: str) -> bool: """Method to check if the given string input can be parsed as a float""" try: float(string_inp) return True except ValueError: return False
c9a798b551b5ef0e9460b0d16f48757510237b73
16,985
def str2bool(x): """Converts a string to boolean type. If the string is any of ['no', 'false', 'f', '0'], or any capitalization, e.g. 'fAlSe' then returns False. All other strings are True. """ if x is None or x.lower() in ['no', 'false', 'f', '0']: return False else: retur...
b3360b999370137ed5b74e3a1a7d8ddaf17be03f
16,992
def allsame(iterable): """Return whether all elements of an iterable are the same. The test uses `!=` to compare, and short-circuits at the first item that is different. If `iterable` is empty, the return value is `True` (like for `all`). If `iterable` has just one element, the return value is `T...
7859dcc19a0385978f7f55ae4b35151a85a303a6
16,994
import re def isfilepath(value): """ Return whether or not given value is Win or Unix file path and returns it's type. If the value is Win or Unix file path, this function returns ``True, Type``, otherwise ``False, Type``. Examples:: >>> isfilepath('c:\\path\\file (x86)\\bar') True, ...
56a423a3b27df5ad0e66291db0bd2698fef5a8b5
16,996
def is_there_a_global(name): """ Simple utility to interrogate the global context and see if something is defined yet. :param name: Name to check for global definition in this module. :returns: Whether the target ``Name`` is defined in module globals and is not falsy. """ gl = ...
3c7c90dbb20894171162f14b1a4441e072dfa2c2
16,999
def zero_x_encoding(t): """0x encoding method. >>> zero_x_encoding("A") '0x41' >>> zero_x_encoding("ABC") '0x414243' """ return "0x" + "".join(hex(ord(c))[2:] for c in t)
b3659f372fee1515584a147dec50fb74bb04db94
17,000
import torch def train_model(train_loader, model, optimizer, criterion, device): """ Note: train_loss and train_acc is accurate only if set drop_last=False in loader :param train_loader: y: one_hot float tensor :param model: :param optimizer: :param criterion: set reduction='sum' :param d...
43621d0a6a0285960ffb2dad8f19ca3a4eebf29d
17,001
import torch import math def softmax(scores: torch.Tensor, base: float = math.e, axis: int = -1) -> torch.Tensor: """Returns softmax array for array of scores Converts a set of raw scores from a model (logits) into a probability distribution via softmax. The probability distribution will be a set of...
f2719094a7de73e362a944e28491e34fc56e67d9
17,004
from typing import Optional import json def read_json_file(path: str, silent: bool = True) -> Optional[dict]: """ Convenience function to read a json file with catching exceptions :param path: Path to the json file :param silent: Whether to ignore exceptions or not :return: Optional[dict] """ ...
0793ebd769a40a64ecfd8d65e0f51100f52c51c9
17,006
def summarize_cag_taxa(cag_id, cag_tax_df, taxa_rank): """Helper function to summarize the top hit at a given rank.""" # If there are no hits at this level, return None if cag_tax_df is None: return { "CAG": cag_id, "name": 'none', "label": "No genes assigned at ...
e3b2736bf223490c5f3b9957b1734eeeffa2de07
17,008