content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def is_lock_free(db_conn, lock_name): """Check the database if a named lock exists Args: db_conn (database connection): Open connection object from mysql-connector lock_name (str): Name of the lock to check Returns: lock_free (bool): True if free otherwise False. """ cursor...
26c20961cc11884e30e339b94c5a3cc393d85ed1
607,457
def clip(elm, mini, maxi): """ Clips a value between mini and maxi.""" return max(min(elm, maxi), mini)
352418987cf2d5b91b6ea524ae3d09e3202ca902
607,459
import torch def get_loc_from_cube_idx(grid, pose3d_as_cube_idx): """ Estimate 3d joint locations from cube index. Args: grid: a list of grids pose3d_as_cube_idx: a list of tuples (joint_idx, cube_idx) Returns: pose3d: 3d pose """ njoints = len(pose3d_as_cube_idx) ...
a935ced73ab6af898aae9e3551e7cb2785caab64
607,461
import pytz from datetime import datetime def format_date(date_str): """ Coverts date from 2016/02/02 20:28:06 US/Eastern to 2016-02-02 20:28:06-05:00 Args: date_str (String): Datetime object as string in the following format (2016/02/02 20:28:06 US/Eastern) Returns: Datetime object i...
7ecc17e23b2825f2da18e2e00fe2c5ac14473c87
607,462
def _prompt_choice(options: list) -> int: """Prompts user to pick an option from items in list, returns index""" for i, x in enumerate(options): print(str(i).rjust(3, ' '), x) return int(input('Selection: '))
cf60cbaf005c2d71c1be9a071a07b729c3b9ea37
607,465
def nextpow2(x): """ Return next power of two that is >= integer `x` Examples -------- >>> nextpow2(4) 4 >>> nextpow2(5) 8 """ return 1 << (x - 1).bit_length()
47f954a52e8e4c7a41534cb868bc3bf1e80c2781
607,466
from typing import Dict from typing import List def format_dict(data: Dict[str, List[str]]) -> str: """Prepare a string to send back to the user. Parameters ---------- data : Dict[str, List[str]] a dictionary with building names as the keys and empty rooms at those buildings as the va...
262f2e4fe1e9c59dc9474b0bbbed15c4bf2ddfd0
607,468
import time from datetime import datetime def parseISODate(date): """ Parse the given date in string ISO format and returns a timestamp (float) in seconds. * date:string should have the format: '%Y-%m-%dT%H:%M:%S.***Z' """ return time.mktime(datetime.strptime( date.split('.')[0], # re...
57ab7c95fb5e84e1e10a29e288771794820f0d7f
607,469
def _tuplify(obj): """Put a string in a tuple or just return object.""" if isinstance(obj, str): return (obj, ) else: return obj
66988fd6c942eb2cddd54c11b2d62c9044e7af2c
607,471
def disparate_impact(fav_rate_unpriv, fav_rate_priv): """ Gets disparate impact between the unprivileged and privileged groups. :param fav_rate_unpriv: rate of favorable outcome for unprivileged group :type fav_rate_priv: `float` :param fav_rate_priv: rate of favorable outcome for privileged group ...
4fe18a7aed18b99213e14eebf7b2433326dfda99
607,473
def process_line(cur_str): """Get value from each line of TextGridline, as {xmax = 0.29} will get {0.29}, {text = "kk"} will get {kk} """ tmp_array = cur_str.strip().split('=') tmp_array = [item for item in filter(lambda x: x != '', tmp_array)] return tmp_array[-1].strip()
706e69843719d5f146459a8e39527cd1988501d0
607,476
import operator def equals(column, name='id', function=(lambda x: x)): """Make filter template for filtering column values equal to value transformed by given function. :param column: database model :param string name: name used in the filter template :param callable function: function for transf...
da35503e46c306cbcef64d89566d526dc14bd46d
607,477
def get_time_code(op_time): """Calculate medicare time code from time in theatre.""" time_base = '230' time_last = '10' second_last_digit = 1 + op_time // 15 remainder = op_time % 15 if remainder < 6: last_digit = 1 elif remainder < 11: last_digit = 2 else: last_d...
260e1576f71a9ac89df31a017858ca503fdccf72
607,479
def angle_subtract(a, b): """Find the difference between two angles. The result should be between -180 (if a<b) and +180 (if a>b) """ res = (a - b) % 360 if res > 180: res -= 360 return res
e0e04efc7edfa2b7d0e640e566d7fb93e1b378fe
607,482
def get_query_string(request): """ Return the query string if it exists in the request. """ query_string = '' if 'QUERY_STRING' in request: query_string = request['QUERY_STRING'] return query_string
4af48662cd214f0cfcf9d8739d7626cb17337467
607,484
def to_words(node): """Generates a word list from all paths starting from an internal node.""" if not node: return [''] return [(node[0] + word) for child in node[1] for word in to_words(child)]
8cff5e39a590172719df8245aa17a724efc97e68
607,485
def kilometers_to_miles(kilo): """Convert kilometers to miles PARAMETERS ---------- kilo : float A distance in kilometers RETURNS ------- distance : float """ # apply formula return kilo*0.621371
94b7acb4632daf179a180ca83f93ae997e14c87c
607,490
def sum_of_square_of_n_numbers(n): """ The sum of squares of first n natural numbers ∑ n^2 = 1^2 + 2^2 + 3^2 +....+ n^2 """ try: n+1 except TypeError: # invlid input hence return early return if n < 0: # invlid input hence return early return return n * (n + 1)...
a2a3d044db7714996647dcf0bd0441d1b981a8fb
607,493
def uniqify(inlist): """Given a list, return a new list preserving the list order and deduplicating.""" return list(dict.fromkeys(inlist))
4dc91b376661cef42a9b5d454d790d1f3425af3d
607,494
def schedule_1_amount(responses, derived): """ Return the amount as defined in schedule 1 for child support """ try: if derived['show_fact_sheet_b'] or derived['show_fact_sheet_c']: return derived['guideline_amounts_difference_total'] else: return float(responses.get('pa...
33fefc60fc8cb49941b2edaea518c4a57022a946
607,495
def dictionary2list(element, dictionary): """ Converts dictionary to list, prepending element """ return [(element, i[0], i[1]) for i in dictionary.iteritems()]
0c901100583b8a4990c31d9321dc71632392feb3
607,496
def query_result_to_cluster_token_pairs(query_result): """Given a query result structure, returns a sequence of (cluster, token) pairs from the result""" cluster_token_pairs = ((c, t) for c, e in query_result['clusters'].items() for t in e['tokens']) cluster_token_pairs_sorted = sorted(cluster_token_pairs, ...
130f3635c9ea3a9d5d6bc779760764000d623d30
607,500
import bisect def get_index(value, keys): """ Returns the index of the value in the keys using bisect """ return bisect.bisect_left(keys, value)
5a5267bc13df91e538d855845dfcfed6e41b4093
607,504
def validate(elements): """Return only valid items in elements""" return list(filter(lambda el: el.is_valid, elements))
0a296f7d92cbac018c41c1dfe81b895ba26904bd
607,506
def convert_z(meta): """Create the native normalization.""" return {'normalize_volume': lambda x: ( x - meta['mean'].item()) / meta['std'].item()}
398d24654f9a1283775fd1b98232ad976b9db52d
607,509
def sylv_cred_formula(treatment_type, cover_type): """ Returns sylviculture credit formula index, given treatment type and cover type. """ if treatment_type == 'ec': return 1 if cover_type.lower() in ['r', 'm'] else 2 if treatment_type == 'cj': return 4 if treatment_type == 'cpro...
1d2098e51a44e7d38e21b10c206e775171e01135
607,510
import torch def _broadcast_shape(shapes): """ Given a list of tensor sizes, returns the size of the resulting broadcasted tensor. Args: shapes (list of torch.Size): list of tensor sizes """ shape = torch.Size([1]) for s in shapes: shape = torch._C._infer_size(s, shape) ...
3804cea0144466d5a44e578512081f2ae141ec63
607,512
import calendar def truncate_to_month(day, month, year): """ return the day given if its valid for the month + year, or the end of the month if the day exceeds the month's number of days """ # enable passing of strings year = int(year) month = int(month) maxday = calendar.monthrange(ye...
4f376ccea43e3aa0b31d0656f9eb4065fc483232
607,514
def intcode_three(parameter_list, code_list): """ Accepts input and places it in parameter_list[0] place in code_list. Returns True. """ number_in = int(input('Please enter a number: ') or "5") code_list[parameter_list[0]] = number_in return True
690b377da19aea89026237fc2677ea6796967487
607,516
def increment_string(s): """ Your job is to write a function which increments a string. To create a new string. If the string already ends with a number, the number should be incremented by 1. If the string does not end with a number the number 1 should be appended to the new string. """ if...
f259e5a73ec19617aa6fc1ed4e09b03b60bdfb1c
607,517
def pairs(tree, ignore_version=True): """Produce a list of pairs from a tree of dependencies.""" my_pairs = [] if tree["children"]: for child in tree["children"]: my_pairs.append((tree["dependency"], child["dependency"],)) my_pairs += pairs(child) return my_pairs
7df23cd83504a429400178e7ea2f46783da812fd
607,518
def rem_slash(string_in): """ A simple function which takes in a string and returns it stripped of double backslashes, single forward slashes, and spaces. """ return str(string_in).replace("\\", "").replace("/", "").replace(" ", "")
70dd3fe558be4d4aa831ad57d570b63630428a63
607,520
def test_sequence(N): """ Compute the infinite sum of 2^{-n} starting from n = 0, truncating at n = N, returning the value of 2^{-n} and the truncated sum. Parameters ---------- N : int Positive integer, giving the number of terms in the sum Returns ------- limit : float ...
ccd026374e353a55e23cbb9866c5c7a4c31a6f71
607,522
import socket def _convert_host_to_ip(host): """ Perform forward DNS resolution on host, IP will give the same IP Args: host: String with either hostname, IPv4, or IPv6 address Returns: Tuple containing address family and IP """ addrinfo = socket.getaddrinfo(host, 80, 0, 0, s...
11ee426592f3fa8b8fa0e7038b66141bfcd28fa9
607,524
def test(env, *args, **kwargs): """build Program with fixed RPATH""" denv = env.Clone() denv.AppendUnique(RPATH=["$PREFIX/lib"]) return denv.Program(*args, **kwargs)
c7121ce1551a5130d1b6e031486b87a4edad4ce9
607,525
def _GetPackageUri(package_name): """Returns the URI for the specified package name.""" return 'fuchsia-pkg://fuchsia.com/%s' % (package_name)
8da40bcbf3be408336af984f6722682baa825f54
607,527
def get_topic_data(sheet, tab_name="messages"): """ Returns a dictionary of Topic keys with a values containing relevent Phrase and Photoprefix k/v pairs for each """ wks = sheet.worksheet(tab_name) rowdict = {} rowcounter = 2 while True: row = wks.range("A{0}:C{0}".format(rowcou...
9b33e6bcca49a1f6e1896ad3b47386bb6a48994f
607,529
def split_arg(arg: str) -> list: """ Splits arg string using comma separator and returns a filtered list :param arg: :return: """ args = arg.split(",") return [a.strip() for a in args if a]
1d1ad0fe8db789aaa6920f5b755cc447be4a5613
607,539
import click def validate_ids(ctx, param, value): """Validate a list of IDs and convert them to a list.""" if not value: return None ids = [x.strip() for x in value.split(',')] for id_item in ids: if not id_item.isdigit(): raise click.BadParameter('Non-numeric value "{0}" ...
7dfde52869147dfb6bcf8e4298188dcf4622681f
607,541
def precision(tp, fp, eps: float = 1e-5) -> float: """ Calculates precision (a.k.a. positive predictive value) for binary classification and segmentation. Args: tp: number of true positives fp: number of false positives eps: epsilon to use Returns: precision value (...
f21e01489821b3aa62fb2041a2bf4f2f7427fdce
607,545
def get_templates(instance, key, name, base='bookmarks'): """ Return a list of template names based on given *instance* and bookmark *key*. For example, if *name* is 'form.html':: bookmarks/[app_name]/[model_name]/[key]/form.html bookmarks/[app_name]/[model_name]/form.html book...
dd7debd695d864017cb21313d78f668bf59a0b0f
607,547
import hashlib def get_fingerprint(timestamp, email): """ Return unique fingerprint based on application timestamp and email. """ fingerprint = hashlib.md5() fingerprint.update(timestamp) fingerprint.update(email) return fingerprint.hexdigest()
5e05404d0b9e9d9328caf601cdf40c75a041843f
607,548
def select_tensors(x): """ x (B, N, C, H, W) -> (N, B, C, H, W) Each batch (B) is composed of a pair or more samples (N). """ return x.transpose(0, 1)
e2704b60803d1841f441e8fd0f54cfa281a1806b
607,549
def max_length(df): """Helper function for profit_filler, interates through the results of spins and returns the longest set of spins. Parameters: df (pandas.core.frame.DataFrame): data frame containing the simulation results Returns: int: The maximum length of the spin counts """ ...
aa6bcae9722cb72ca1b01f76e59657722e569895
607,551
import inspect def getfile(fn): """ Returns the file where the function is defined. Works even in wrapped functions """ if hasattr(fn, '__wrapped__'): return getfile(fn.__wrapped__) else: return inspect.getfile(fn)
44d9021c4628966f9f314ab90ee36066a9500962
607,553
def resolve_signature(command): """Retrieve command signature or evaluate dynamic signature. command: command instance or subclass [Command/type] return: command's signature [str] """ if isinstance(command, type): command = command() # instantiate if subclass passed try: retur...
a885c18f0b411dc430ac854059af331ee3d74d20
607,554
def nullstr(value): """ Return str(value) if bool(value) is not False. Return None otherwise. Useful for coercing optional values to a string. >>> nullstr(10) '10' >>> nullstr('') is None True """ if value: return str(value)
919e94ef953fd58cf3477ed7c7950497fede59ae
607,555
def exclude(func): """Return the opposite of ``func`` (i.e. ``False`` instead of ``True``)""" return lambda x: not func(x)
8052e10311a5d0be206da9d3a82a36564e69b7f8
607,558
def node_pos_formatter(node): """ Returns a terminal node's original token. """ return node.text
2886fea43ad06d81e60f29be3c90fba7060e385e
607,559
def read_to_ulens(read, min_ulen, max_ulen): """Extract units of [`min_ulen`..`max_ulen`] bp length from `read.units`.""" return [unit.length for unit in read.units if min_ulen <= unit.length <= max_ulen]
b8c69c3249f303d66dbad2213c868ef20fc90f08
607,560
import torch def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True): """Converts the input tensor to a valid variable to check the gradient. `gradcheck` needs 64-bit floating point and requires gradient. """ assert torch.is_tensor(tensor), type(tensor) return tensor.require...
55958a83c9c827ca621e5b724d3bb077bc938a71
607,561
import math def alpha_beta_to_d_q(ualpha,ubeta,wt): """Convert alpha-beta to d-q.""" Us = (ualpha + 1j*ubeta)*pow(math.e,-1j*(wt)) #Us = (ualpha + 1j*ubeta)*pow(math.e,-1j*(wt-(math.pi/2))) ud = Us.real uq = Us.imag #ud = ualpha*math.sin(wt) - ubeta*math.cos(wt) #uq = ualpha*math.cos(wt) + ubeta*math.sin(w...
12d9ddce34c92f38ebf6523e9a0521dbb2b7b692
607,563
def get_default_from_fields(form_fields): """ Takes a dictionary of field name and UnboundField instance and returns their default values as dict of field name and value """ defaults = {} for field_name, field in form_fields.items(): defaults[field_name] = field.kwargs["default"] ret...
bf1ff5838dc274959f825c091b3222e673eaae8e
607,565
import math def wind_direction(uvel, vvel): """ Calculate meteorological wind direction from velocity vector """ return math.degrees(math.atan2(-uvel, -vvel))
ee43f37557c6783c1067e01fb2f56f30537edefe
607,568
import torch def vec_pts_to_line_torch(pts, ptlines, vlines): """ Normal vector from a point to a line. Arguments: - pts - [N, D] - N D-dimensional points - ptlines - [N, D] - points on the lines - vlines - [N, D] - vectors of the lines, not necessarily normalized ...
d1a3fdfb972beee60bfc52bda8a9941ddc53abfe
607,569
def subtract(a, b): """ Subtracts two numbers. >>> subtract(3, 2) 1 >>> subtract(2, 3) -1 :param a: first number :param b: second number :return: difference """ return a - b
dc8858546d0c856fc9a7e88bf06eacccaddcffa7
607,571
def VD_531(delta_P, delta_S, n, FA = 0): """ 5.3.1 Load factor and additional bolt load up to the opening limit --- delta_P : Elastic resiliance of the clamped parts for concentric loading delta_S : Elastic resiliance of the bolt n : Load introduction factor ...
9eede0ee2b50c5e9c107448306090cf618dc1610
607,572
def p(x, threshold=0.5): """Predicts whether a probability falls into class 1. Args: x (obj): Probability that example belongs to class 1. threshold (float): point above which a probability is deemed of class 1. Returns: int: Binary value to denote class 1 or 0 """ ...
4ea4dce93e051b4ce855c051a09291f79e8c974c
607,575
import hashlib def md5_of_file(abspath): """ Calculate md5 value of a file. """ chunksize = 1024 ** 2 # 1MB m = hashlib.md5() with open(abspath, "rb") as f: while True: data = f.read(chunksize) if not data: break m.update(data) r...
bd5544519a75cfd2171a04eda422be8be98b7323
607,581
import torch def encode_labels(y, labels): """ Convert string labels to autoincrementing integers. """ mapping = {l: i for i, l in enumerate(labels)} return torch.as_tensor([mapping[l] for l in y])
4c81507038d8b454b42fac6bcae55ce529ac752e
607,587
def dropNaNs(df, ClassVar='none'): """ Given the omics data passed as a dataframe, and (optionally) the name of a class variable, it i) prints the total number of samples in the dataset. ii) if none of the samples have any missing values, it returns the same dataframe, else: a) number ...
de91427756188029c43777e6bb59017b72214818
607,588
import contextlib def get_ip(ip_file): """ Returns a list of IP addresses from a file containing one IP per line. """ with contextlib.closing(ip_file): return [line.strip() for line in ip_file]
898bd3a42aeb143a9aabe5bc95e4524d3849935d
607,591
def line_count(file): """Utility function for getting number of lines in a text file.""" count = 0 with open(file, encoding="utf-8") as f: for _ in f: count += 1 return count
e6ee52e5458b9a4c354b3a0f498613392a00b54d
607,592
def session_filename(session: str) -> str: """ Returns the filename that should be used for the session (without extension). """ return f"Session-{session}"
d30e835fcce30f1d284c9668322cc88cd4c3d03e
607,594
import random def gen_secret(length): """ Make a secret string Args: length (int): length of secret Returns: str: secret """ return ''.join(hex(random.randint(0,15))[-1] for _ in range(length))
cccafdc43f2a03c9ba1701fffe239fb2991a7ab3
607,596
def get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): """Returns the URL and token for a CAPTCHA challenge issued by the server. Args: http_body: str The body of the HTTP response from the server which contains the CAPTCHA challenge. captcha_base_url: str T...
7866c730aca52de73dd4d29a7335b3534b8118c7
607,597
def describe_inplane_accel(metadata: dict) -> str: """Generate description of in-plane acceleration factor, if any.""" return ( "in-plane acceleration factor={}".format( metadata["ParallelReductionFactorInPlane"] ) if metadata.get("ParallelReductionFactorInPlane", 1) > 1 ...
1986d2461d4b2811e21b3cf8834d166a132c82cc
607,599
def fixed_precision(A, prec=6): """ Recursively convert nested iterables or coordinates to nested lists at fixed precision. """ if hasattr(A, '__iter__'): return [fixed_precision(el, prec=prec) for el in A] else: return round(A, prec)
c1ed2019f93f05e9c078cdbbe0052e603bfc7e49
607,600
def read_param(params, key, default): """Read and return a parameter from a dict. If the key `key` is absent from the dict `params`, return the default value `default` instead. Parameters ---------- params : dict A dict containing parameters. key : str Name of the parameter...
1fcb6d123aeadbaecd0ca0074a72c9dce946d341
607,611
def tag_only(tag): """ simple function to remove the elements token from a tag name e.g. tag_only('tag_name{10}') -> 'tag_name' """ if '{' in tag: return tag[:tag.find('{')] else: return tag
61c176d7e67a363558ca0732fa0c67972be38f3c
607,612
def parse_stats(stats_dict): """Parses through the information in the provided stats dictionary and returns a list of properly formatted information.""" messages = [] messages.append("\n\nOperator Stats\n") if stats_dict == {}: return [ "\n\nOperator Stats\nCould not retrieve st...
36e431a9b4d7b2d3622a47d035c91333962bfa5f
607,613
def update_dict_recursively(dst, src, tuples_too=False, overwrite_by_none=True): """ Update `dst` dictionary recursively using items in `src` dictionary. Parameters ---------- dst : dict The destination dictionary. src : dict The source dictionary. ...
2fd079a7bf2c397b0bb0442cfe2786b834e67f8f
607,614
def nested_map(f, *args): """ Recursively transpose a nested structure of tuples, lists, and dicts """ assert len(args) > 0, 'Must have at least one argument.' arg = args[0] if isinstance(arg, tuple) or isinstance(arg, list): return [nested_map(f, *a) for a in zip(*args)] elif isinstance(ar...
4f9a45d219a2e25e6bc63ae69c4f30b4c5ac317f
607,616
def dict_get(inp, *subfields): """Find the value of the provided sequence of keys in the dictionary, if available. Retrieve the value of the dictionary in a sequence of keys if it is available. Otherwise it provides as default value the last item of the sequence ``subfields``. Args: inp...
30ee48214dae147e4b38aca870d05aed0285dba5
607,620
def _get_span_length_key(span): """Sorts span by decreasing length first and incresing first index second.""" return span[1] - span[0], -span[0]
3fb0c1b775c4674087fbec34d5f9f3139c844c54
607,622
def _is_within_bounding_box(x, y, minx, miny, maxx, maxy): """ Check if the `x`/`y` coordinate is within the bounding box, defined by the `minx`/`miny` coordinate and the `maxx`/`maxy` coordinate. >>> _is_within_bounding_box(0.5, 0.5, 0.0, 0.0, 1.0, 1.0) True >>> _is_within_boundin...
5cbc45442017c22e73119c3c276aa1bbf3684680
607,625
from datetime import datetime def generate_date_string() -> str: """Return date formatted string to backup a file.""" return datetime.strftime(datetime.today(), "_%Y%m%d_%H%M%S.bak")
356606d6fef16f24066637d7ba97752d00b5f10f
607,626
def strip_leading_dashdash(name): """Remove leading ``'--'`` if present.""" if name.startswith('--'): return name[2:] else: return name
97f86a839d088f7bd96d2836f746819bf2003697
607,635
def to_str(num: int) -> str: """Convert an integer to a string.""" return str(num)
04aa08fb19d933e15bf08139536fab4f2502a403
607,637
import re def formulafy(x): """ Convert the input string x to a Latex representation of the chemical formula. e.g. ^13CH4 -> $^{13}CH_{4}$ This can be used in matplotlib to display nicely a chemical formula. """ return '$'+re.sub('([a-zA-Z])_?([0-9]+)', r'\1_{\2}', re.sub(r'\^([0-9]+)', r'^{\1...
c203cd5d2fa3f20be847f29b80619f797ebe399a
607,638
import re def _get_global_step_for_checkpoint(checkpoint_path): """Returns the global step for the checkpoint path, or -1 if not found.""" re_match = re.search(r"ckpt-(\d+)$", checkpoint_path) return -1 if re_match is None else int(re_match.group(1))
d212996f811640c53c2f97f98150dd04ea5d9200
607,639
from typing import BinaryIO from typing import cast import struct def read_int(stream: BinaryIO) -> int: """Read an integer value in big-endian order.""" return cast(int, struct.unpack('>i', stream.read(4))[0])
1d0a867b2367dd911bcb70e2b3b98823d742c7b3
607,642
import time def getCurrentMonth(format="%Y-%m"): """ Get current month. """ currentMonth = time.strftime(format) # e.g. 2018-02 return currentMonth
8aabfa1c2d815975013f1adf9d657dfd71f18beb
607,644
import json import decimal def decimal_decoder(json_obj): """convert any floats in a dictionary (loaded from a json) to Decimal type. This is required in order to load data to DynamoDB. """ return json.loads(json.dumps(json_obj), parse_float=decimal.Decimal)
e5aaceac7a3570ae8052cd95e06ba8a106a0548c
607,645
from typing import Tuple import hashlib def calc_hashes(file_path: str) -> Tuple[str, str]: """ Calculate sha256 and md5 :param file_path: path to file :return: (sha256, md5) """ sha256 = hashlib.sha256() md5 = hashlib.md5() with open(file_path, 'rb') as f: while True: ...
9f6e8b5641f016e54a50f5634ba10e1ae1a24e02
607,647
def parse_location(location): """Extracts latitude and longitude from a location string. Args: location: Decimal Degrees (D.D) representation of a geographical location, e.g. "34.56 N 123.45 W" Returns: latitude, longitude """ latitude_str, north_south, longitude_s...
512e66ecae25d854aa4150697abbc257907d20a5
607,649
import csv def createCSV(data,headers,fileName): """ Input: data - dict to read in, headers - list of csv headers, fileName - str for csv file name Output: Writes csv to directory under fileName """ with open(fileName,mode='w',newline='',errors="ignore") as csvFile: ...
3dc3e555b522c1ff61ad47970e5733967125f254
607,653
import math def learning_rate_schedule(warmup_steps, total_steps): """Linear warmup for warmup_steps, with cosine annealing to 0 at total_steps""" def learning_rate_fn(step): if step < warmup_steps: return float(step) / float(max(1, warmup_steps)) else: progress = floa...
20a5b463e8c265510830927157a80d8191686e55
607,654
def merge_dicts(*my_dicts): """Combines a bunch of dictionaries together, later dictionaries taking precedence if there is a key conflict.""" return dict((k, v) for d in my_dicts for (k, v) in d.items())
77ecdcef57866b1307cbaabdfa578971be70b811
607,656
def install_requires_rtd(install_list: list) -> list: """Return modified install list if installing for ReadtheDocs.""" rtd_exceptions = [ "Kqlmagic", "azure-cli-core", "matplotlib", "statsmodels", "scipy", "splunk-sdk", "seaborn", ] return [ ...
5dc695bd337afb1524c0d89c015ac0120b03a6f2
607,657
import math def get_distance(target, other): """\ Calculate the N-dimensional Euclidian between two mappings. The mappings are used to represent sparse arrays -- if a key is not present in both mappings, it's assumed to be 0 in the mapping where it is missing. """ return math.sqrt( su...
0bad05b7709f259950759f4e9d7e3c3b4b77f12b
607,658
def is_springer_url(url): """determines whether the server is springer from url @param url : parsed url """ return 'www.springerlink.com' in url.netloc
16bea33374cf8c5a7e5050fa1019aa563f06906b
607,662
import math def blendSigmoidInc(d=0.0, u=0.0, s=1.0): """ blending function increasing sigmoid d - Delta x = xabs - xdr u - Horizontal offset s - Tuning scale factor returns blend """ d = float(d) u = float(u) s = float(s) b = 1.0/(1+math.e**(s*(u-d)))...
39f33eeaca1deb70f729f452af1f0d326fc52c2e
607,663
def list_logs(client): """ Lists the terraform event logs for a given project. :param client: a datastore client :return: list of datastore entries """ query = client.query(kind='TerraformEventLog') return list(query.fetch())
78613e45adb6ff0b9dd3badf4b576d1f74a6c21a
607,665
def set_values(model, values): """Sets NamedTuple instance value and returns new NamedTuple""" return model.__class__(**{**model._asdict(), **values})
7b991a56c0c09fddb2e51b3b6c480d60500e2184
607,666
import re def get_root_url(the_line): """ Get the root URL from the line :param the_line: the line :return: either the root URL or None """ ret = re.search('https://[^/]*/[^/]*/', the_line) if ret: return ret.group(0) return None
a4a4a283664e8d80088c3ec5e349aae3d3f34dd5
607,668
def has_kerning_info(ttFont): """A font has kerning info if it has a GPOS table containing at least one Pair Adjustment lookup (eigther directly or through an extension subtable).""" if "GPOS" not in ttFont: return False if not ttFont["GPOS"].table.LookupList: return False for lookup in ttFont["GP...
844702bbb0bd5324943e4a345e209509961e3d7e
607,669
def attribute(element, attribute, default=None): """ Returns the value of an attribute, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param attribute: The name of the attribute to evaluate :type attribute: basestring :param default...
aabed6d153ec97979b5319fdd536ec660a8bf440
607,674
def is_layer(line: str) -> bool: """Check if current line is the start of a layer section. Args: line (str): Gcode line Returns: bool: True if the line is the start of a layer section """ return line.startswith(";LAYER:")
4d3bee78500a17a6f87538893ef2338fd64c3979
607,675
from pathlib import Path import hashlib def does_sha_match(file: Path, sha_sums: dict[str, str]) -> bool: """ Checks if shasum of downloaded file matches with the sum provided by pushshift Returns True if sha sum is not provided by pushshift.io :param file: Path to archive file :param sha_sums: Di...
9e43f1423c5211da2db02312ff8a1b77638f4491
607,679