content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from pathlib import Path from typing import List def get_candidate_paths(parent: Path, name: str) -> List[Path]: """ Combines all of the candidate paths for each file for simplicity. The previous method of defining candidates individually was getting complicated. """ candidates = [ # The usual locations for t...
4cbf6d07d920d6049428e90709f251cb889e9815
676,548
import functools def remove_all(string, substrs): """Removes a whole list of substrings from a string, returning the cleaned string. Args: string (str): A string to be filtered substrs (:obj:`list` of :obj:`strs`): The substrings to remove from the string Returns: str: string...
bac271131211e4ae03ff15b5c3ef5190502d001c
676,550
def make_array_of_dicts_from_response_json(response_json, index): """ Makes array of dicts from stats.nba.com response json :param dict response_json: dict with response from request :param int index: index that holds results in resultSets array :return: list of dicts with data for each row :rt...
33454154fa984d5622127b71ea24d2dcf18bc060
676,551
def cyccalc(self, fileprefix="", fileformat="", **kwargs): """Calculates results from a cyclic harmonic mode-superposition analysis APDL Command: CYCCALC using the specifications defined by CYCSPEC. Parameters ---------- fileprefix Each result table (corresponding to each CYCSPEC speci...
b713d33c1984a11654e31f6ac9eadbf83978f1e7
676,553
def data_transformer(x, y, xfactor, yfactor, **kwargs): """Multiplies x or y data by their corresponding factor.""" return {"x": x * xfactor, "y": y * yfactor}
cfe008e2d9b316d1e12554b65077484c92267104
676,557
def length_average(length, logprobs, alpha=0.): """ Returns the average probability of tokens in a sequence. """ return logprobs / length
e7f2768447618f2b426bc65ae7ecd30b67f933c7
676,558
def is_valid_name(name, parameters, kw): """Checks if name is a valid script variable name. Returns the error.""" if not name.isidentifier(): return "Variable name '{}' is not a valid identifier.".format(name) if name in kw.KEYWORDS: return "Variable name '{}' is a keyword.".format(name) ...
9bfe5b75f2068757c0b434664bbfe65f0d16e8ae
676,559
def equal_string_modulo_digits(s1, s2): """Returns whether two strings without their digits are the same """ s1 = (c for c in s1 if not c.isdigit()) s2 = (c for c in s2 if not c.isdigit()) return all(c1 == c2 for c1, c2 in zip(s1, s2))
b44ca57446fec957d81e44acc2f3e3b950376dca
676,560
def _has_magic(instream, magic): """Check if a binary stream matches the given signature.""" return instream.peek(len(magic)).startswith(magic)
125555bebaad905c4b8521d7321b171a683ef767
676,561
def make_dic(doc_id=None, root=None, date=None, author=None, text=None, favorite=None): """make dictionary form argument and return dictionary Keyword Arguments: doc_id {int} -- documnet ID (default: {None}) root {string} -- xml file name (default: {None}) date {string} -- ...
1948b9e20fe03a849cc072cc16330270730ee72d
676,565
def get_users(f_path): """ Getting user name and password hash from file """ out = {} with open(f_path) as file: for d in file: h = d.split(':')[1] if h != '*': u = str(d.split(':')[0]).strip() if len(u) > 0: out[u]...
c82a1b2ae844f48695f58997fcebd5cf44c0e11a
676,566
import six def is_jid(jid): """ Returns True if the passed in value is a job id """ if not isinstance(jid, six.string_types): return False if len(jid) != 20 and (len(jid) <= 21 or jid[20] != "_"): return False try: int(jid[:20]) return True except ValueError...
e4dfcf00c5a02205f03b1383066703ffdb517d54
676,570
def format_legacy_response(response, skills, category): """Format responses appropriately for legacy API. # noqa: E501 Examples: >>> skills = ["Strength", "Hitpoints", "Ranged", "Magic", "Slayer", "Farming"] >>> category = "xp" >>> response = [ ... { ... 'skills': { ... ...
e1af2f1600c8b68d68984e2ce357a76907e240fe
676,572
import re def GetFormatCount(format_): """ Get format prefix count @param format_: format specifier @return: prefix count or 1 if not specified """ if isinstance(format_, str): match = re.search("\s*(\d+)", format_) if match: return int(match.grou...
ec6aae6bbb2a60aec5f7d038e17c34d021931a4c
676,573
def generate_wrapper(name, module, original_docstring, num_threads): """Generate a wrapper function. Parameters ---------- name : string Name of the function wrapped. module : string Name of the module the wrapped function is part of. original_docstring : string Docstrin...
e139f5df140b9c3a5ac7ec70eb5d221ad1f93c2e
676,575
def domain_level(host): """ >>> domain_level('') 0 >>> domain_level(' ') 0 >>> domain_level('com') 1 >>> domain_level('facebook.com') 2 >>> domain_level('indiana.facebook.com') 3 """ if host.strip() == '': return 0 else: raw_parts = host.strip()...
42b242211589f1679e15e3e20fd9391ec6786b13
676,577
def _test_if_all_vals_equal(vals1, vals2): """Checks if the union of two iterables is 1 and returns True if that is the case. Is used in test_num_feats to check if two lists of values have only the same value and nothing else. :param vals1: :param vals2: :return: """ # build union between v...
d06bd3f862fee76a08b0e211fdbc7208921efe6d
676,578
import copy def convert_chord_label(ann): """Replace for segment-based annotation in each chord label the string ':min' by 'm' and convert flat chords into sharp chords using enharmonic equivalence Notebook: C5/C5S2_ChordRec_Eval.ipynb Args: ann (list): Segment-based annotation with chord la...
50077cf6121df0df764ad254be57269c9600684a
676,580
def copy_file_request(drive_service, file_id, body): """Send copy request to gdrive""" response = drive_service.files().copy( fileId=file_id, body=body, fields='id,webViewLink,name' ).execute() return response
de05d3adb252dc84708eba3914b08227765ce74e
676,582
from typing import Optional async def get_sample_owner(db, sample_id: str) -> Optional[str]: """ A Shortcut function for getting the owner user id of a sample given its ``sample_id``. :param db: the application database client :param sample_id: the id of the sample to get the owner for :retur...
a028f4e6097808ecfe839b82c7d8e18e8934d384
676,584
def format_password(password): """ Formats password for printing to the terminal. This is done so that the password is not returned as plain text. """ return password[0] + "*" * (len(password) - 1)
a1477472802c12a10426f31e4fb2eaf1d52448b4
676,586
def is_equivalent(a, b): """Checks if two strings are equivalent This only does a == b, and will not replace anything. For testing. """ return a == b
88ca6a1ac08b15c288b4361c6a5e1b1fcf71dd48
676,589
import csv def read_csv(read_path, delim=','): """Reads a generic CSV file. Args: - read_path - string path to read from. - delim - delimiter to use for the CSV format. Returns: - rows - list of rows where each row is a string list of cell values. """ rows = [] with open(read_pat...
772a03a953c1bddd77b4fd4a47a7eca3526ec32f
676,591
def unzip(items): """The inverse of zip Parameters ---------- items : a nested iteratable Returns ------- list The unzipped items Examples -------- >>> from t2t.util import unzip >>> unzip([[1, 2], ['a', 'b']]) [[1, 'a'], [2, 'b']] """ if items: ...
3da11d0a7342e226654285a668d59daedc94a9f3
676,593
def Rayleigh_KD(f, alpha): """ Calculate partitioning of trace element (TE) as a function of Rayleigh fractionation. Parameters ---------- f : array-like Fraction of Ca remaining in the biomineralisation reservoir. alpha : array-like Partition coefficient for extraction of TE fr...
3848463fc04c0a2e36ed6da856f7ce6771a30bfa
676,595
def find_smallest_int(arr): """ Given an array of integers find the smallest number. :param arr: an array of integers. :return: the smallest number within the array. """ return min(arr)
3f19e0e6901d52daf3f68be3b12c8f0f744b3279
676,596
import colorsys import random def generate_colors(class_names): """Generates different colours for all classes. Args: class_names (list of `str`): List containing names of all classes. Returns: list: List containing colours for corresponding classes. """ hsv_tuples = ...
66c42367398055211618eeb9528d7ee652349822
676,598
def _is_national_number_suffix_of_other(numobj1, numobj2): """Returns true when one national number is the suffix of the other or both are the same. """ nn1 = str(numobj1.national_number) nn2 = str(numobj2.national_number) # Note that endswith returns True if the numbers are equal. return nn...
ca99aa363764874794d48b5f85b57aed63827547
676,600
def format_time_filter(start, stop, field): """Formats a time filter for a given endpoint type. Args: start (str): An ISO date string, e.g. 2020-04-20. stop (str): An ISO date string, e.g. 2021-04-20. field (str): The time field to filter by. """ start_date = start.split('-') ...
6c21bb1ff6f90002d0f7f50d2c82fd081db89213
676,601
def get_hypothesis(x, theta): """ :param x : scalar of a given sample :param theta : 1D array of the trainable parameters """ hypothesis = 0.0 for t in range(len(theta)): # compute prediction by raising x to each power t hypothesis += theta[t] * (x ** t) ...
be84e00c1eb7dbb6d2cbdf87eb7f84ff08d4980b
676,605
from pathlib import Path import json def load_ambient_sensor(session_path): """ Load Ambient Sensor data from session. Probably could be extracted to DatasetTypes: _ibl_trials.temperature_C, _ibl_trials.airPressure_mb, _ibl_trials.relativeHumidity Returns a list of dicts one dict per trial. ...
095bd61826b36bb930e70d4bcb8c8a37577d9058
676,606
def isSliceUnitSUV(dcmSlice): """Take a dcm slice in input and returns true if the voxels are expressed in SUV - Standardized uptake value. Return false otherwise.""" # 00541001 corresponds to the tag index of the voxel unit in the dcm file units = dcmSlice[0x00541001].value.lower() unitIsSUV = "su...
b9dcdc393dade1182cb624b47a1c0a9a8878e30b
676,609
def get_primes(length: int = 26, min_prime: int = 2, max_prime: int = 101) -> list: """Get list of primes. Given a length, minimum, and maximum prime number, return a list of prime numbers. Args: length (int): Number of prime numbers to return. Defaults to ``26``. min_pr...
2b7cff406db46da9922057633abadbf4a6dca0a4
676,612
def autocomplete_configuration_path(actions, objects): """ Returns current configuration_path for object. Used as a callback for `default_value`. Args: actions: Transition action list objects: Django models objects Returns: configuration_path id """ configuration_pa...
2d1a1ea5bf8fd4f3ecbee65da0024995ada07727
676,614
import string def is_segment(pattern): """Test if pattern begins with a segment variable.""" return (type(pattern) is list and pattern and len(pattern[0]) > 2 and pattern[0][0] == '?' and pattern[0][1] == '*' and pattern[0][2] in string.ascii_letters...
5eb800b96389ac57c1c133637ec9500464850805
676,622
def convert_word_index_to_sentence(word_idx, vocab): """Convert word indices to sentence.""" s = "" for ind in range(len(word_idx)): w_idx = word_idx[ind] if w_idx> 0: s += vocab[w_idx-1] if ind < len(word_idx)-1: s+= " " return s
85eb540bb23f9de4d12b4beebf1a6af5129d2080
676,624
def thickest_clouds(cloud_thickness_and_base_list): """ Given a list of tuples indicated cloud thickness and base, return the tuple with the thickest clouds """ return max(cloud_thickness_and_base_list, key=lambda c: c[0])
e52258ecab4835133e67c6295e56e019295ce3f1
676,627
def validate_run(cards): """ a run is 3 to 10 consecutive cards of the same suit :param cards: list of Card objects :return: Boolean """ if len(cards) < 3 or len(cards) > 10: return False if not all(card.suit == cards[0].suit for card in cards): return False ranks = sort...
253d5f9e159c6c83243c752ea75a5c38a3888f6b
676,628
def get_plural_string(word: str, amount: int) -> str: """Returns singular or plural of the word depending on the amount. Example: word = 'piece', amount = 0 -> '0 pieces' word = 'piece', amount = 1 -> '1 piece' word = 'piece', amount = 5 -> '5 pieces'""" if amount == 1: return f'1 {word}' else: return f'{...
34c6af2e6d4c429e070f28ad184d18faa2c22060
676,634
from functools import reduce from typing import Mapping def deep_get(dictionary: dict, *keys, default=None): """Safely return the value of an arbitrarily nested map Inspired by https://bit.ly/3a0hq9E """ return reduce( lambda d, key: d.get(key, default) if isinstance(d, Mapping) else default, keys, dictionary ...
e39b362d9c0c94e1a0230a71037b12bd7fe2dd18
676,637
def get_description(repo_info): """Return repository description""" try: return repo_info.find('p').text.strip() except AttributeError: return
927891159d73fde57cbb8bb0456a6d08034a10ad
676,641
def _exact_compare(tree1, tree2): """Simultaneously compares the name, length, and support of each node from two trees. Parameters ---------- tree1: skbio.TreeNode first tree to compare tree2: skbio.TreeNode second tree to compare Returns ------- bool `True`...
11022142306165a29afb58f2075fb9fcb9e6ce3d
676,646
def readthrough_in_bedpe(record, annotation, rt_threshold): """ Determine if the two genes in the record are within `rt_threshold` bp of each other on the same chromosome. :param BEDPE record: A BEDPE line from the input file :param dict(str, GTFRecord) annotation: see `read_fusions:gene_annotation...
e460505e948b59d42c279c83f3e081d0f4b5a253
676,647
import random def choose(char): """ Randomly choose upper or lower case to return """ return char.upper() if random.choice([0, 1]) else char.lower()
1795dc883f157449e3ce48f1bdba67e43c46afbb
676,653
def A008588(i: int) -> int: """Nonnegative multiples of 6.""" return i * 6
862ee8538de73acae42294c398d4986545623b32
676,655
def int_(num: str) -> int: """ Take an integer in the form of a string, remove any commas from it, then return it as an ``int``. Args: num: A string containing only numeric characters or commas. Returns: An integer version of the string. """ return int(num.replace(",", ""))
697061556cc1553c49370b68490cdea19f540535
676,657
def median(lst): """ Return a list's median :param lst: List (sorted or not) of int :return: int """ lst.sort() length = len(lst) if length == 0: return None elif length % 2 == 0: # Even number of elements return (lst[int((length+1)/2 - 1)] + lst[i...
d134faacc2ab3e9635322ad06a307a9f93274c8b
676,658
import json def is_json_serializable(item): """ Test if an object is serializable into JSON :param item: (object) The object to be tested for JSON serialization. :return: (bool) True if object is JSON serializable, false otherwise. """ # Try with try-except struct. json_serializable = Tru...
80841498f649100770836efc2141a8f78c97c0bb
676,661
import math def getLOG(rawEMGSignal): """ LOG is a feature that provides an estimate of the muscle contraction force.:: LOG = e^((1/N) * sum(|xi|)) for x i = 1 --> N * Input: * raw EMG Signal * Output = * LOG :param rawEMGSignal: the raw EMG signal :type ...
3a4b4f67b56bb1718b4e5cb4698a47d155515627
676,669
from datetime import datetime def parse_element_time(element): """Extract and format time from an html element.""" unixtime = int(element.find(class_="odate")["class"][1].split("_")[1]) return datetime.utcfromtimestamp(unixtime).strftime("%Y-%m-%d %H:%M:%S")
a9f22d8b5cf12533c3e5bf1c2d842e8812ae0291
676,670
import math def calculateTierSize(imageWidth, imageHeight, tileSize=256): """ The function calculate the number of tiles per tier Arguments: imageWidth {Float} imageHeight {Float} tileSize {Integer} Default is 256 pixel Return: {Array} """ tierSizeInTiles = [] ...
f66efdc2070afd1fe91fd631fe87c8d4e03961ad
676,671
from datetime import datetime def last_leap_year(date=None): """ Return the last complete leap year from today or a specified date. """ if date is None: date = datetime.utcnow() leap = (date.year - 1) - ((date.year - 1) % 4) return leap
26242dafa6cf0472c59fc0a25005efade34a517f
676,678
def to_uri(uri_data): """ Convenient function to encase the resource filename or data in url('') keyword Args: uri_data (str): filename or base64 data of the resource file Returns: str: the input string encased in url('') ie. url('/res:image.png') """ return ("url('...
927cacdacf6fff7f7efba148cfc75c35bfdcbc1f
676,681
import hashlib def password_hash(password: str) -> bytes: """Create a hash of a password to transform it to a fixed-length digest. Note this is not meant for secure storage, but for securely comparing passwords. """ return hashlib.sha256(password.encode()).digest()
712908e55d1534570c3d1a8906ed7c05070bb0e6
676,683
def _Backward4_T_hs(h, s): """Backward equation for region 4, T=f(h,s) Parameters ---------- h : float Specific enthalpy [kJ/kg] s : float Specific entropy [kJ/kgK] Returns ------- T : float Temperature [K] References ---------- IAPWS, Revised Suppl...
61469e320ee1c2e9041942dee87675c728a52fd6
676,689
def string_list_handler(option_value=None): """Split a comma-separated string into a list of strings.""" result = None if option_value is not None: result = option_value.split(',') return result
7bcc310cbefb1ee2099fd176f6e901b75abdcf05
676,692
def IsImageFile(ext): """IsImageFile(ext) -> bool Determines if the given extension corresponds to an image file (jpg, bmp, or png). arguments: ext string corresponding to extension to check. returns: bool corresponding to whether it is an image file. ...
ce3c555e2fcc6c6ad5858242307beda10b3ccf68
676,694
def ensure_support_staging_jobs_have_correct_keys( support_and_staging_matrix_jobs: list, prod_hub_matrix_jobs: list ) -> list: """This function ensures that all entries in support_and_staging_matrix_jobs have the expected upgrade_staging and eason_for_staging_redeploy keys, even if they are set to fals...
3852500882732ac0f92dfc5d526c0fe23d9a9388
676,695
def readlines_with_strip(filename): """Reads lines from specified file with whitespaced removed on both sides. The function reads each line in the specified file and applies string.strip() function to each line which results in removing all whitespaces on both ends of each string. Also removes the newli...
ef2c0e08fb29d42a2724ba42a90c4c6a694bac35
676,698
from typing import Counter def most_frequent(List): """Counts the most_frequent element in list""" occurence_count = Counter(List) return occurence_count.most_common(1)[0][0]
33a7cc95758ad12922ad1221c5e992925bddb401
676,707
def CountBenchmarks(benchmark_runs): """Counts the number of iterations for each benchmark in benchmark_runs.""" # Example input for benchmark_runs: # {"bench": [[run1, run2, run3], [run1, run2, run3, run4]]} def _MaxLen(results): return 0 if not results else max(len(r) for r in results) return [(name, _M...
ee7845b613fbdca71d91720d886478af142d2a74
676,709
def window(x, win_len, win_stride, win_fn): """ Apply a window function to an array with window size win_len, advancing at win_stride. :param x: Array :param win_len: Number of samples per window :param win_stride: Stride to advance current window :param win_fn: Callable window function. Takes ...
95ac180a57b6f0e3ca4517bdc8559f8875e94f94
676,710
def iswritable(f): """ Returns True if the file-like object can be written to. This is a common- sense approximation of io.IOBase.writable. """ if hasattr(f, 'writable'): return f.writable() if hasattr(f, 'closed') and f.closed: # This mimics the behavior of io.IOBase.writable...
8d60aab30bf8cd304f10020cc0e93af1e5030a6d
676,716
from typing import List def batch_inference_result_split(results: List, keys: List): """ Split inference result into a dict with provided key and result dicts. The length of results and keys must match :param results: :param keys: :return: """ ret = {} for result, key in zip(resul...
e7b977cf92fd8b5adad12b6aee839e4df3d7b0aa
676,720
def read_ip_config(filename): """Read network configuration information of kvstore from file. The format of configuration file should be: [ip] [base_port] [server_count] 172.31.40.143 30050 2 172.31.36.140 30050 2 172.31.47.147 30050 2 172.31.30.180 30050 2 Note t...
10b8087b66b4424c95acaf023a6c1cd693ed4368
676,721
def get_table_row(table, td_text): """ Find a row in a table that has td_text as one column's text """ td = table.find('td', string=td_text) if td is None: return None return td.find_parent('tr')
3254cd06244a1eb66364be3fee3addb22ce202ce
676,723
def breakpoint_callback(frame, bp_loc, dict): """This callback is registered with every breakpoint and makes sure that the frame containing the breakpoint location is selected """ # HACK(eddyb) print a newline to avoid continuing an unfinished line. print("") print("Hit breakpoint " + str(bp_loc)) ...
309bb7c0d7a18d5adb3a6bf8821e8296b29417d1
676,726
import pathlib def _stringify_path(path_or_buffer): """Convert path like object to string Args: path_or_buffer: object to be converted Returns: string_path_or_buffer: maybe string version of path_or_buffer """ try: _PATHLIB_INSTALLED = True except ImportError: ...
172e0faab6ca67f7d0f15577909e4027a33d9d8c
676,730
def _get_gmt_dict(filename): """Parse gmt files and get gene sets.""" with open(filename, 'r') as f: content = [line.strip().split('\t') for line in f] return {pathway[0]: pathway[2:] for pathway in content}
e9d13bfc189d825d1632f17f17f549257efd49e9
676,733
def EqualSpacedColmunTable(items, table_width=80, table_indent=2, column_pad=2): """Construct a table of equal-spaced columns from items in a string array. The number of columns is determined by the data. The table will contain at ...
4de98787512ba367729959c44f6563323bfbc7b8
676,735
def make_voc_seed_func(entry_rate, start_time, seed_duration): """ Create a simple step function to allow seeding of the VoC strain at a particular point in time. """ def voc_seed_func(time, computed_values): return entry_rate if 0. < time - start_time < seed_duration else 0. return voc_se...
9e9936580d6acb379cc2e4f7dc70f6fd59133040
676,738
import socket def init_socket(port): """ Init socket at specified port. Listen for connections. Return socket obj. Keyword arguments: port -- port at whicch to init socket (int) """ connection_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection_socket.bind(('', port)) connection_socket.l...
19552577a5a075b6532d66783cc744071dad80c8
676,739
from typing import List def _split_list(string: str) -> List[str]: """Assumes an input of the form `[s1, s2, s3, ..., sn]`, where each si may itself contain lists.""" assert string[0] == "[" and string[-1] == "]" nesting_depth = 0 all_strings = [] current_string = "" for character in strin...
1cfd741a3c36db4ccd3e9ca1acc2d00d192e1087
676,740
def get_model_state_dict(model): """Get model state dict.""" return {k: v for k, v in model.state_dict().items()}
f9733a39a9fc6a65804a83751e2650c9606a8b8a
676,741
import ast def calculate_issues_count(issues: str) -> int: """ Parse issues list and calculate number of issues. """ return len(ast.literal_eval(issues))
b556960bcd2bc2d693719ce9c1369d2a0253dd4c
676,743
def _contains_isolated_cores(label, cluster, min_cores): """Check if the cluster has at least ``min_cores`` of cores that belong to no other cluster.""" return sum([neighboring_labels == {label} for neighboring_labels in cluster.neighboring_labels]) >= min_cores
042a117981ec1e6215b855c0bb7b11f34087183f
676,744
from typing import Optional def upper(value) -> Optional[str]: """Converter to change a string to uppercase, if applicable""" return value.upper() if isinstance(value, str) else None
6b20c10bbe89878fb2e39386602dadf526be395f
676,745
def _call_member(obj, name, args=None, failfast=True): """ Calls the specified method, property or attribute of the given object Parameters ---------- obj : object The object that will be used name : str Name of method, property or attribute args : dict, optional, default=None ...
48ddd9b3a2350a5b4a82beb81f5e0d7f89d42a8b
676,746
def doc_view(request): """View for documentation route.""" return { 'page': 'Documentation' }
eceb49907078999d6d3b9348ae4d953061d6968b
676,749
from typing import List def bounding_box_to_polygon( left: float, bottom: float, right: float, top: float ) -> List[List[float]]: """ Transform bounding box to polygon :param left: left bound :param bottom: bottom bound :param right: right bound :param top: top bound :return: polygon ...
cc8a6a0884af87f9588c1fe54c73e7936dc67f7c
676,752
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return f"{prefix}{num}{suffix}"
ba2822c26b447e294e76ad4c61a8c7da0501816e
676,759
def get_region_dict(region, maxRegionSize=None, tilesource=None): """Return a dict corresponding to region, checking the region size if maxRegionSize is provided. The intended use is to be passed via **kwargs, and so either {} is returned (for the special region -1,-1,-1,-1) or {'region': region_dic...
8b38a160bb11f9f6be572855f6c7202ee6caea7e
676,765
def initialize_back_prop(AL, Y, AL_prime, Y_prime): """ Initialize backward propagation Arguments: :param AL -- output of the forward propagation L_model_forward()... i.e. neural net predictions (if regression) i.e. neural net probabili...
135a442cb6258bf1e7f24c1edd8cf535e57e514f
676,766
def replaceline(f, match, lines): """Replace matching line in file with lines.""" for i in range(len(f)): if match in f[i]: return f[:i] + lines + f[i+1:] return f
b6a3216c6d1e9f383b985a2c679f696ede54436f
676,772
import requests def http_get(url, fout=None): """Download a file from http. Save it in a file named by fout""" print('requests.get({URL}, stream=True)'.format(URL=url)) rsp = requests.get(url, stream=True) if rsp.status_code == 200 and fout is not None: with open(fout, 'wb') as prt: ...
6eded3d27a9d949f379ab9ff6316afc45e19c0b5
676,774
import yaml def read_yaml(yaml_file): """Read a yaml file. Args: yaml_file (str): Full path of the yaml file. Returns: data (dict): Dictionary of yaml_file contents. None is returned if an error occurs while reading. """ data = None with open(yaml_file) as f: ...
b2a50ea3421489e327aa84c142dd54ace08f3811
676,784
def c_escaped_string(data: bytes): """Generates a C byte string representation for a byte array For example, given a byte sequence of [0x12, 0x34, 0x56]. The function generates the following byte string code: {"\x12\x34\x56", 3} """ body = ''.join([f'\\x{b:02x}' for b in data]) ret...
b2262fcb655ba6d4251856e97c1e0d92ae739784
676,787
def test_object_type(obj: object, thetype: type): """Tests if the given object is of the specified type. Returns a Boolean True or False. Examples: >>> myint = 34 >>> test_object_type(myint, int) True >>> isinstance(myint, int) True >>> test_object_type(myint, s...
226c90e3fa97337af53e6c8ae70dcd0c7861e513
676,789
import re def remove_leading_space(string: str) -> str: """ Remove the leading space of a string at every line. :param string: String to be processed :type string: str :return: Result string :rtype: str **Example:** .. code-block:: python string = " Hello \\nWorld!" ...
2bf2fb4158f1efe52d6efd861013633b34b21985
676,790
def qb_account(item_title): """ Given an item title, returns the appropriate QuickBooks class and account Parameter: item_title Returns: item_class, item_account Note that this is only guaranteed to work for Ticketleap sales, not PayPal invoices. """ if 'Northern' in item...
a067aed1bfbcca07f4968c08f1c1f400a6cb735e
676,791
def bottom_row(matrix): """ Return the last (bottom) row of a matrix. Returns a tuple (immutable). """ return tuple(matrix[-1])
f56ad2f96e7a8559fad018208274d04efcd8880b
676,792
from typing import Dict def success_of_action_dict(**messages) -> Dict: """Parses the overall success of a dictionary of actions, where the key is an action name and the value is a dictionarised Misty2pyResponse. `overall_success` is only true if all actions were successful. Returns: Dict: The dictio...
542725d492df7758e9b90edf8d18a935c824e18a
676,795
def clip(value, min, max): """Clips (limits) the value to the given limits. The output is at least `min`, at most `max` and `value` if that value is between the `min` and `max`. Args: value: to be limited to [min, max] min: smallest acceptable value max: greatest acceptable val...
52ed454dbf3b39c841fd39560fb4cb4ea358b1e8
676,807
def is_variable_geometry(xmldoc): """ Tries to guess whether the calculation involves changes in geometry. """ itemlist = xmldoc.getElementsByTagName('module') for item in itemlist: # Check there is a step which is a "geometry optimization" one if 'dictRef' in list(item.attri...
fb6ba41fcc92acfefb7817de3b3f7cc91d16afaa
676,812
def convertConfigDict(origDict, sep="."): """ For each key in the dictionary of the form <section>.<option>, a separate dictionary for is formed for every "key" - <section>, while the <option>s become the keys for the inner dictionary. Returns a dictionary of dictionary. """ ...
da4952ee883cd3d2d0d01e64f9055c22a277a16f
676,817
def parse_csv_data(csv_filename: str) -> list[str]: """Returns a list of strings representing each row in a given file""" file = open("data/" + csv_filename, "r", encoding="utf-8") lstrows = [] for line in file: lstrows.append(line.rstrip()) file.close() return lstrows
f4c4fe8d1f5b1cf1f0355269dc2a566603e2dd55
676,818
def merge_means(mu1, mu2, n1, n2): """Merges means. Requires n1 + n2 > 0.""" total = n1 + n2 return (n1 * mu1 + n2 * mu2) / total
22659748d2046e0eb78b8210fbf62bd9e57b447f
676,819
import six def get_comparable_revisits(query_metadata_table): """Return a dict location -> set of revisit locations for that starting location.""" revisit_origins = { query_metadata_table.get_revisit_origin(location) for location, _ in query_metadata_table.registered_locations } inter...
02c8bd7c028f3ce688098cc836b0e174e1113dc6
676,821
def torch_to_np(images): """Transforms the unnormalized output of a gan into a numpy array Args: images (torch.tensor): unnormalized output of a gan Returns: (numpy.array) """ return ((images.clamp(min=-1, max=1) + 1) / 2).permute(0, 2, 3, 1).cpu().detach().numpy()
136788112a33ee80a88b4931973416bb0b2bd466
676,824
def lookup_dunder_prop(obj, props, multi=False): """ Take an obj and lookup the value of a related attribute using __ notation. For example if Obj.a.b.c == "foo" then lookup_dunder (Obj, "a__b__c") == "foo" """ try: if "__" in props: head, tail = props.split("__", 1) ...
58e173c161d2b846b2e8268698c4ea73f21381f0
676,826