content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _broadcast_shapes(shape1, shape2): """ Given two shapes (i.e. tuples of integers), return the shape that would result from broadcasting two arrays with the given shapes. Examples -------- >>> _broadcast_shapes((2, 1), (4, 1, 3)) (4, 2, 3) """ d = len(shape1) - len(shape2) if d <= 0: shp1 = (1,)*(-d) + shape1 shp2 = shape2 else: shp1 = shape1 shp2 = (1,)*d + shape2 shape = [] for n1, n2 in zip(shp1, shp2): if n1 == 1: n = n2 elif n2 == 1 or n1 == n2: n = n1 else: raise ValueError(f'shapes {shape1} and {shape2} could not be ' 'broadcast together') shape.append(n) return tuple(shape)
965854e8463022f3ff8d1f6400f93afd29ca16ea
309,767
def to_names(indices, g): """ converts vertex indices indices to vertex names :param indices: list of indices :param g: graph (with named nodes) :return: list of vertex names """ name_list = g.vs["name"] name_sorted = [name_list[i] for i in indices] return name_sorted
2934cccac0282f63bda26ec7d0cf00c58a85b35f
242,105
import re import zipfile def instance_name_from_zip(path): """Determines the instance filename within a SEC EDGAR zip archive.""" re_instance_name = re.compile(r'.+-\d{8}\.xml') for name in zipfile.ZipFile(path).namelist(): if re_instance_name.fullmatch(name): return name raise RuntimeError('Zip archive does not contain a valid SEC instance file.')
59b2154d433e500e9b0cdf39ee70d4c058da1d06
7,475
def bottom_k(seq, k, kmer_len, stride_len=1): """ Return bottom-k minhash sketch fingerprint of sequence. Parameters ---------- seq : string sequence to perform bottom-k sketch on k : number of hash value representatives in bottom-k sketch kmer_len : int the length of the k-mers of the sequence stride_len : int the stride length in extracting k-mers from the sequence Returns ------- fingerprint : list of ints The bottom-k fingerprint sketch of the sequence. """ i = 0 hashes = [] n = len(seq) while i + kmer_len < n: hashes.append(hash(seq[i:i+kmer_len])) i += stride_len hashes.sort() return hashes[:k]
6811c2ca61eb27ca2fc680aa798e339e63fd38e8
611,757
def non_exclusive_completer(func): """Decorator for a non-exclusive completer This is used to mark completers that will be collected with other completer's results. """ func.non_exclusive = True # type: ignore return func
4763f5b0dbdde7837dbfb77562cd2a63da711b30
398,444
from typing import List def load_numbers_sorted(txt: str) -> List[int]: """ファイルから番号を読み込みソートしてリストを返す Args: txt (str): ファイルのパス Returns: List[int]: 番号のリスト """ numbers = [] with open(txt) as f: numbers = sorted(map(lambda e: int(e), f)) return numbers
6f10badd417a2ceefefa9f28a5c40583ea077d43
2,501
def make_column_names_numbered(base = "base", times = 1): """create an array of numbered instances of a base string""" return ["%s%d" % (base, i) for i in range(times)]
9cd66d1aa32ff30175c6a1c7f04d3d084f0c221c
554,430
def find_first_visited_twice(visited_order): """Find first position that repeats in visited_order.""" visited = set() for location in visited_order: if location in visited: return location visited.add(location) return None
a588666ba9a16bd5f6c09bc585fbade92be64278
324,513
def smart_encode(content: str, encoding: str) -> bytes: """Encode `content` using the given `encoding`. Unicode errors are replaced. """ return content.encode(encoding, 'replace')
4e51aee004b2646f6f907335b883eb2fa5acbd59
76,436
def l_relu(z): """ReLU activation function""" a = 0.01*z a[z >= 0] = z[z >= 0] return a
45234ab63776463ae4f72ceed879bf035dcd2078
256,679
def reverse_list_dictionary(to_reverse, keys): """Transforms a list of dictionaries into a dictionary of lists. Additionally, if the initial list contains None instead of dictionaries, the dictionnary will contain lists of None. Mainly used in the measure.py file. Args: to_reverse (list): List to reverse, should contain dictionaries (or None) keys (list): Keys of the dictionaries inside the list. Returns: Dictionary. """ if to_reverse[0] is None: to_reverse = {k: [None for _ in range(len(to_reverse))] for k in keys} else: to_reverse = {k: [to_reverse[n][k] for n in range(len(to_reverse))] for k in keys} return to_reverse
8953372d5ba4bfe99d9e04e7e3d4a8b8432bff69
554,551
from typing import Optional import re def _filename_from_content_disposition( content_disposition: str, ) -> Optional[str]: """Extract the filename from the content disposition. Parse the content_definition as defined in: https://tools.ietf.org/html/rfc2616 Note: * If both encoded (`filename*=`) and ascii (filename=) name are defined, the function returns the ascii name, as encoding might create issue on some systems * If only the encoded name is defined (e.g. `filename*=UTF-8''%e2%82%ac.txt`), the function return None as this is not yet supported. Args: content_disposition: String to parse. Returns: filename: The filename, or None if filename could not be parsed """ match = re.findall( # Regex (see unittests for examples): # ` *` : Strip eventual whitespaces # `['"]?` : Filename is optionally wrapped in quote # `([^;\r\n"']+)` : Filename can be any symbol except those # `;?` : Stop when encountering optional `;` r"""filename= *['"]?([^;\r\n"']+)['"]? *;?""", content_disposition, flags=re.IGNORECASE, ) if not match: return None elif len(match) != 1: raise ValueError( f'Error while parsing filename for: {content_disposition}\n' f'Multiple filename detected: {list(match)}' ) return match[0].rstrip()
4ad1607cf627a0d6b4b696f73f0dd6d77bd20ee0
179,581
def chars_in_dict(seqdict): """Return ordered list of characters in dictionary of sequences.""" # Initialize set of characters characters = set([]) # Iterate over sequences for seqid in seqdict.keys(): # Update the set of characters with those in the current sequence characters.update(set(list(seqdict[seqid]))) # Return characters as an ordered list return sorted(list(characters))
57f62ccafbcb984e67ea0092b2e5793e5b0876f0
458,992
def kurtosis(N,N2,N3,N4,**kwargs): """Calculate kurtosis in data N from averages <N^4>, <N^3>, <N^2>, and <N>.""" return (-3*(N**4) + 6*(N**2)*N2 - 4*N*N3 + N4)/((N2 - (N**2))**2)
23973a27d371beb23c6f942b0258f77fda9e1de4
114,502
def _FirewallSourceRangesToCell(firewall): """Comma-joins the source ranges of the given firewall rule.""" return ','.join(firewall.get('sourceRanges', []))
8a99ae68a8891e97a817a893d5897e7a3c1d2cf7
546,178
from typing import Callable import inspect def accepts_kwargs(func: Callable) -> bool: """Check if ``func`` accepts kwargs. """ return any( True for param in inspect.signature(func).parameters.values() if param.kind == param.VAR_KEYWORD )
c0e5328382d6019f7bb288ac62e70858ea276388
383,823
def get_object_xy_in_layer(cur,cell,layer): """ Returns (object_num,x,y) coordinates of cell object in layer Parameters ---------- cur : MySQLdb cursor cell : str Name of cell layer : str Layer/image name """ sql = ("select OBJ_Name,OBJ_X,OBJ_Y " "from object " "join contin on " "contin.CON_Number = object.CON_Number " "where contin.CON_AlternateName like '%s' " "and object.IMG_Number like '%s'" %(cell,layer)) cur.execute(sql) return [(int(a[0]),int(a[1]),int(a[2])) for a in cur.fetchall()]
c286e6bb70eea28f48bf832e822a08a4b0689980
320,545
def rescale(arr, vmin, vmax): """ Rescale uniform values Rescale the sampled values between 0 and 1 towards the real boundaries of the parameter. Parameters ----------- arr : array array of the sampled values vmin : float minimal value to rescale to vmax : float maximum value to rescale to """ arrout = (vmax - vmin)*arr + vmin return arrout
d6debc0eeccd9fe19ed72d869d0de270559c9ce8
11,298
def is_runtime_parameter(argument): """Return True if the directive argument defines a runtime parameter, and False otherwise.""" return argument.startswith('$')
60dce287302ccbfb0cbc32e31c6485951d1e861c
255,717
def all_repeated_digits(num: int) -> bool: """ Tell if the number is made of all repeated digits. """ s_num = str(num) if len(s_num) > 1: return all([ch == s_num[0] for ch in s_num[1:]]) else: return False
c3d07b5dce967438482a2e37af244580114564a4
584,213
def process_latitude(cell): """Return the latitude from a cell.""" lat = cell.strip().split("/")[0].strip() return float( int( str(lat[0]) + str(lat[1]), ) + int( str(lat[2]) + str(lat[3]), ) / 60 + int( str(lat[4]) + str(lat[5]), ) / 3600 )
eec5f7d80a38794ef9e300c2ffb540f0d1d11bf2
129,442
def get_target_indice_from_leaves(targets, sent): """ Find the indice of the target words in the terminal sequence of a parsed sentence. """ target_indice = [] idx = 0 current_target = targets[idx] for k, w in enumerate(sent): if w == current_target: target_indice.append(k) idx += 1 if idx == len(targets): break current_target = targets[idx] try: len(target_indice) == len(targets) except ValueError: print(targets) print(' '.join(sent)) return target_indice
b02a0173c33faae687a91b09e99d7ef5b54168d1
60,864
def romi(total_revenue, total_marketing_costs): """Return the Return on Marketing Investment (ROMI). Args: total_revenue (float): Total revenue generated. total_marketing_costs (float): Total marketing costs Returns: Return on Marketing Investment (float) or (ROMI). """ return ((total_revenue - total_marketing_costs) / total_marketing_costs) * 100
975670e85f9673b89a3defd87f54665b37d0c3ee
207,503
def split_string(input_str): """ Parse input string and returns last comma separated element. In case no comma found, all string is returned. Args: input_str(str): input string that will be parsed Returns: str: last comma separated element, or all string in case no comma found. """ return input_str.split(',')[-1]
3bae9da5fcdab9706bcfcb9c0036f60f22420ef8
127,015
import torch def calc_dihedral(a_coord: torch.Tensor, b_coord: torch.Tensor, c_coord: torch.Tensor, d_coord: torch.Tensor) -> torch.Tensor: """ Calculate a dihedral between tensors of coords """ b1 = a_coord - b_coord b2 = b_coord - c_coord b3 = c_coord - d_coord n1 = torch.cross(b1, b2) n1 = torch.div(n1, n1.norm(dim=-1, keepdim=True)) n2 = torch.cross(b2, b3) n2 = torch.div(n2, n2.norm(dim=-1, keepdim=True)) m1 = torch.cross(n1, torch.div(b2, b2.norm(dim=-1, keepdim=True))) dihedral = torch.atan2((m1 * n2).sum(-1), (n1 * n2).sum(-1)) return dihedral
5028707cd0e2377279a3d77f435db5c0898b9bf3
405,704
def frequency(gdf, col_kwds='kwds', normalized=False): """Computes the frequency of keywords in the provided GeoDataFrame (function adapted from LOCI). Args: gdf (GeoDataFrame): A GeoDataFrame with a keywords column. col_kwds (string) : The column containing the list of keywords (default: `kwds`). normalized (bool): If True, the returned frequencies are normalized in [0,1] by dividing with the number of rows in `gdf` (default: False). Returns: A dictionary containing for each keyword the number of rows it appears in. """ kwds_ser = gdf[col_kwds] kwds_freq_dict = dict() for (index, kwds) in kwds_ser.iteritems(): for kwd in kwds: if kwd in kwds_freq_dict: kwds_freq_dict[kwd] += 1 else: kwds_freq_dict[kwd] = 1 num_of_records = kwds_ser.size if normalized: for(kwd, freq) in kwds_freq_dict.items(): kwds_freq_dict[kwd] = freq / num_of_records return kwds_freq_dict
36507c84768a95f78a1f2e0c69f473c98733743e
441,476
def generate_annotation_dict(annotation_file): """ Creates a dictionary where the key is a file name and the value is a list containing the - start time - end time - bird class. for each annotation in that file. """ annotation_dict = dict() for line in open(annotation_file): file_name, start_time, end_time, bird_class = line.strip().split('\t') if file_name not in annotation_dict: annotation_dict[file_name] = list() annotation_dict[file_name].append([start_time, end_time, bird_class]) return annotation_dict
f40f210075e65f3dbe68bb8a594deb060a23ad8b
395
from typing import List def keys_exists(multi_dict: dict, keys: List[str]) -> bool: """Check if multi-level dict has specific keys""" _multi_dict = multi_dict for key in keys: try: _multi_dict = _multi_dict[key] except KeyError: return False return True
1de1ef0060a6f0953335e7968de824e6880bcda6
631,355
import torch def tensor_prepend_zero(x): """Prepending tensor with zeros. Args: x (Tensor): tensor to be extended Returns: the prepended tensor. Its shape is (x.shape[0]+1, x.shape[1:]) """ return torch.cat((torch.zeros(1, *x.shape[1:], dtype=x.dtype), x))
5da6c31ce67df5db47382d4dadaf7202ea2afbca
525,916
def create_levels(levels, base_factory): """Create a multidimensional array :param levels: An Iterable if ints representing the size of each level :param base_factory: A nullary function that returns a new instance of the basic unit of the array :return: Nested lists """ def loop(current, rest): if len(rest) == 0: return [base_factory() for _ in range(current)] else: return [loop(rest[0], rest[1:]) for _ in range(current)] return loop(levels[0], levels[1:])
6d0c6414e1127114b32cade3ab11a2150d1691c0
453,556
def find_in_list(query, _list): """ From a list, returns the first element that satisfies the query """ item = list(filter(query, _list)) return item[0] if item else None
d4f3d8c147230990179695bfb722583b63f0fcae
297,552
import re def roles_of_function(role): """ Separate a function into a set of roles. In the SEED a function associated with a PEG can have more than one role. This is denoted by joining roles with either ' / ' (a multi-domain, multifunctional gene), ' ; ' (an ambiguous function), or ' @ ' (a Single domain playing multiple roles). For more information see http://www.nmpdr.org/FIG/Html/SEED_functions.html This method just takes a function and returns a set of the role(s). If there is a single role, it is still a set. :param role: The functional role :type role: str :return: A set of the roles :rtype: set """ # remove flanking ", comments from functions, and split multiple functions func = re.sub('^"|"$|\s+[#!]\s.*$', '', role) return set(re.split('\s*;\s+|\s+[;/@]\s+', func))
775a70c9c40f4abc6443965229b450a961180964
461,521
def count_unique_ids(id_dict): """ Helper functions to count the number of unique task ids returned by generate_local_task_ids """ return len(set(id_dict.values()))
b1935d543f6f9b5543bd560b046e554d39c0c398
480,902
def list_diff(l1: list, l2: list): """ Return a list of elements that are present in l1 or in l2 but not in both l1 & l2. IE: list_diff([1, 2, 3, 4], [2,4]) => [1, 3] """ return [i for i in l1 + l2 if i not in l1 or i not in l2]
dd5c2ebecddec8b3a95cde30dae28cac6b996c51
679,494
def get_first_second_usernames(user_name_list): """ prompt for two user names sperated by comma check if input is valid and exists in list of user names if its not reprompt :param user_name_list - list of usernames in twitter data: :return first username, second username - strings of both users: """ not_correct = True first_username = '' second_username = '' while not_correct: user_str = input("Input two user names from the list, comma separated: ") if ',' in user_str: try: user_str = user_str.split(',') first_username = user_str[0].strip() second_username = user_str[1].strip() except TypeError: print("Error in user names. Please try again") if first_username not in user_name_list or second_username not in user_name_list: # your check to for correct user names goes here print("Error in user names. Please try again") else: break else: print("Error in user names. Please try again") return first_username, second_username
d90b396cbedc6d1cb1ac8ff13b79cc224ef8d54d
255,358
def variance(values): """ Returns the variance of a set of variables """ average=sum(values)/len(values) def square(x): return x*x return sum([square(x-average) for x in values])/len(values)
0fe5503b48626b58c210bf13f222d8b946c7ce83
452,950
def _count_dupes_ahead(string, index): """ Counts the number of repeated characters in 'string', starting at 'index' """ ret = 0 i = index end = len(string) - 1 while (i < end) and (string[i + 1] == string[i]): i += 1 ret += 1 return ret
70871b0185f1a1224879b9942fbe7a0632f26e9e
221,847
def get_full_action_name(service, action_name): """ Gets the proper formatting for an action - the service, plus colon, plus action name. :param service: service name, like s3 :param action_name: action name, like createbucket :return: the resulting string """ action = service + ':' + action_name return action
f69eb13000fe92cd13783148c8ee340c45bd6591
613,464
import math def APR(n,m,alpha=0.08,s=0.20): """ Return number of (equal-sized) precincts to audit. Use Aslam/Popa/Rivest (nearly exact) approximation formula n = number of precincts m = margin of victory as a fraction of total votes cast alpha = significance level desired = 1 - confidence s = maximum within-precinct-miscount """ if m == 0.0: return n b = math.ceil(n * (m / (2 * s))) u = (n - (b-1)/2.0)*(1.0-math.pow(alpha,1.0/b)) return u
943d21acc849671737971fd148f5ae799b4b0af6
145,350
def usage(err=''): """ Prints the Usage() statement for the program """ m = '%s\n' %err m += ' Default usage is to seach the Scan library tree for your branch.\n' m += ' ' m += ' walklib \n' m += ' or\n' m += ' walklib -w tech_rules \n' m += ' or\n' return m
63468270bc890eb9715b6f4bccbad4babf404cb5
474,757
import yaml import six def get_file_configuration(configuration_schema, config_content): """Get configuration, based on the configuration file. Args: configuration_schema (dict): a match between each target option to its sources. config_content (str): content of the configuration file in YAML format. Returns: dict: a match between each target option to the given value. """ yaml_configuration = yaml.safe_load(config_content) if "rotest" not in yaml_configuration: return {} yaml_configuration = yaml_configuration["rotest"] configuration = {} for target, option in six.iteritems(configuration_schema): for config_file_option in option.config_file_options: if config_file_option in yaml_configuration: configuration[target] = yaml_configuration[config_file_option] break return configuration
29b5344978c1930d79e316b2423c3862fbf8c45b
558,659
def is_non_html(response): """ Returns True if the response has no Content-type set or is not `text/html` or not `application/xhtml+xml`. """ content_type = response.get('Content-Type', None) if content_type is None or content_type.split(';')[0] not in ('text/html', 'application/xhtml+xml'): return True
abfe0a0f516d8c0a71955caf179ca08da265123f
226,215
def sum_n(n): """ Sum of first n natural numbers >>> sum_n(10) 55 """ if n == 0: return 0 else: return n + sum_n(n-1)
ea158d34aa1d628b2347d038eb588e85a078de06
285,082
def partial_difference_quotient(f, v, i, h): """ Compute the ith partial difference quotient of f at v """ w = [v_j + (h if j== i else 0) # add h to just the ith element of h for j, v_j in enumerate(v)] return (f(w) - f(v)) / h
0cdf808f865b21be0e45894b46059e20d182b614
125,786
def add(a, b): """A dummy function to add two variables""" return a + b
4914b8d73e6808d93e8e8ee98902ad3b093f1ce6
704,031
import torch def generate_struct_mask(features, missing_rate): """ Parameters ---------- features : torch.tensor missing_rate : float Returns ------- mask : torch.tensor mask[i][j] is True if features[i][j] is missing. """ node_mask = torch.rand(size=(features.size(0), 1)) mask = (node_mask <= missing_rate).repeat(1, features.size(1)) return mask
d9abe11cf4b42b3289ffa39d21d2212000e6e464
530,147
def area_bbox(bbox): """Return the area of a bounding box.""" if bbox[2] <= 0 or bbox[3] <= 0: return 0.0 return float(bbox[2]) * float(bbox[3])
3e2da08a7756b43a406c3a88fbc402cfac93409c
517,069
def strip_hydrogen(atoms, bonds): """ Remove hydrogens from the atom and bond tables. """ atoms = atoms[atoms['element'] != 'H'] bonds = bonds[bonds['start'].isin(atoms['atom']) & bonds['end'].isin(atoms['atom'])] return (atoms, bonds)
0117122d92dc260ac3136603b9af1daa39a36593
639,941
from typing import List def get_required_cols(geom_type: str, columns: List[str]) -> List[str]: """Get the required columns for a given geometry type.""" req_cols = ["id", geom_type, "dates", "region"] for var in ["time_scale", "pet", "alpha"]: if var in columns: req_cols.append(var) return req_cols
8861004e54a4d741c9727b268164c87e9a091f12
665,712
def fixed(seconds): """Waits for a fixed number of ``seconds`` before each retry.""" def wait_iterator(): while True: yield seconds return wait_iterator
f5fe0c8164d3b566c0066142463a08df77ec2a33
246,783
def decode_literal(packet): """Decode a literal packet""" i = 0 value = '' while True: group = packet[i:i+5] # each group has 5 bits value += group[1:] # the value is contained in the last 4 bits i += 5 if group[0] == '0': break # the last section is prefixed with a 0 bit sub_packet = packet[i:] return sub_packet, int(value, 2)
cecb1996f860b993f90e61f5a3adc097653cebda
260,878
def listSum(SumList): """ 递归求和函数 :param SumList: 求和列表 :return:求和之后的值 """ if len(SumList) == 1: return SumList[0] else: return SumList[0] + listSum(SumList[1:])
6e4a5f9fe0a66251ca4b044e9b45bfab8c167112
658,296
import torch def huber_loss(x, delta=1.): """ Standard Huber loss of parameter delta https://en.wikipedia.org/wiki/Huber_loss returns 0.5 * x^2 if |a| <= \delta \delta * (|a| - 0.5 * \delta) o.w. """ if torch.abs(x) <= delta: return 0.5 * (x ** 2) else: return delta * (torch.abs(x) - 0.5 * delta)
b3493eb9d4e38fa36f92db80dc52a47c32caf3c9
2,143
def contains_incorrect_symbols(test_expr, target_expr): """Test if the entered expression contains exactly the same symbols as the target. Sometimes expressions can be mathematically identical to one another, but contain different symbols. From a pure maths standpoint, this is fine; but in questions you may not want to allow undefined symbols. This function will return a dict containing entries for any extra/missing symbols. - 'test_expr' should be the untrusted sympy expression to check symbols from. - 'target_expr' should be the trusted sympy expression to match symbols to. """ print("[[SYMBOL CHECK]]") if test_expr.free_symbols != target_expr.free_symbols: print("Symbol mismatch between test and target!") result = dict() missing = ",".join(map(str, list(target_expr.free_symbols.difference(test_expr.free_symbols)))) extra = ",".join(map(str, list(test_expr.free_symbols.difference(target_expr.free_symbols)))) missing = missing.replace("lamda", "lambda").replace("Lamda", "Lambda") extra = extra.replace("lamda", "lambda").replace("Lamda", "Lambda") if len(missing) > 0: print("Test Expression missing: {}".format(missing)) result["missing"] = missing if len(extra) > 0: print("Test Expression has extra: {}".format(extra)) result["extra"] = extra print("Not Equal: Enforcing strict symbol match for correctness!") return result else: return None
cb6fd60437bd41211d6aa18baeb9ef6d47e5cf7c
587,257
def zpn(z, c, n=2): """ nth order polynomial generating a beautiful set Parameters ---------- z: Complex scalar, vector or matrix to evaluate the function on elementwise c: Complex scalar, vector or matrix, the starting value(s) """ return z**n + c
01cd6b19c5c8d62985ed6f06d4cc748635ef1602
114,664
from random import randint def make_tuples(number_of_items: int, max_storage: int) -> list: """ This function will generate all of the possible tuples that the person will be dealing with when trying to solve this challenge. :param number_of_items: How many items we should generate. :param max_storage: The maximum space that the person has. :return: A list of tuples. """ tuples = [] max_value = max_storage // 2 for i in range(number_of_items + 1): tuples.append((randint(10, max_storage), randint(1, max_value))) return tuples
d8303ab679fb8d045f1f8d276edbf02807f7e01a
281,841
import math def image_rms_diff(src, dest): """Calculate the difference between two images using normalized RMS""" total = 0 width, height = src.size for x in range(width): for y in range(height): s_r, s_g, s_b, s_a = src.getpixel((x, y)) d_r, d_g, d_b, d_a = dest.getpixel((x, y)) diff_r = s_r - d_r diff_g = s_g - d_g diff_b = s_b - d_b total = total + (diff_r ** 2) + (diff_g ** 2) + (diff_b ** 2) return math.sqrt(total / (width * height * 3)) / 255
71083659153ddd7f6c2ece0a985c413b3c95fed1
484,552
def get_headers_dict(base_headers: list[str]): """Set headers for the request""" headers_dict = {} for line in base_headers: parts = line.split(':') headers_dict[parts[0]] = parts[1].strip() return headers_dict
a22a5f1cd5a6c47115ccd89a7d0165a9b262eda3
617,814
def dbdisconnect(connection) -> bool: """Close connection to SQLite-Database :param connection: :return: Result of success (true/false) """ if connection: connection.close() return True return False
6c5d17d14e898696885730ef86fad9eab03af02f
14,889
def dict_to_scalamap(jvm, d): """ Convert python dictionary to scala type map :param jvm: sc._jvm :param d: python type dictionary """ if d is None: return None sm = jvm.scala.Predef.Map().empty() for k, v in d.items(): sm = sm.updated(k, v) return sm
53319bc347f3a60ed36d6a74542ea7639725f6a3
195,966
def filter(question, answer): """Takes in tokenized question and answer and decides whether to skip.""" if len(answer) == 1: if answer[0].text.lower() in ['true', 'false', 'yes', 'no']: return True return False
662c24ecf450900f61629cdd2478e710224648dd
529,130
def terminate(n,params): """Decide on whether to terminate current algo run or not Parameters ---------- n: number of total evaluations have been conducted in current run params: Params Class parameters for moea/d Returns ------- boolean expression True if number of total evaluations exceed params.stop_nfeval """ return n >= params.stop_nfeval
39908fc2b53a078efdd27fab13dfb1121b262bd1
560,687
def get_attr_in_gmeta_class(model, config_name, default_value=None): """获取指定模型 GMeta 类中指定的属性 Params: model class django 模型类 config_name string GMeta 类中配置项的名称 default_value 任何数据类型 默认数据 """ gmeta_class = getattr(model, "GMeta", None) if not gmeta_class: return default_value return getattr(gmeta_class, config_name, default_value)
755a8cc5aeb5304106a940929e133be9d163797f
571,714
def _format_data(data): """Return a list of strings given input data and formats.""" def to_str(x, fmt): x = "" if x is None or x == "" else x if isinstance(x, str): return fmt.replace("g", "").replace("e", "").format(x) else: return fmt.format(x) return [to_str(x, fmt) for x, fmt in data]
d5ccc45d8f9411279d9ce0836060b938fc49456e
438,715
def center_crop(img, dim): """ Crops the input `img` from center to a specific dimention specified Args: img (numpy.ndarray): Image which needs to be cropped dim (tuple): Shape of the output image Returns: [numpy.ndarray]: Image croppepd to dim shape """ width, height = img.shape[1], img.shape[0] # process crop width and height for max available dimension crop_width = dim[0] if dim[0] < img.shape[1] else img.shape[1] crop_height = dim[1] if dim[1] < img.shape[0] else img.shape[0] mid_x, mid_y = int(width / 2), int(height / 2) cw2, ch2 = int(crop_width / 2), int(crop_height / 2) crop_img = img[mid_y - ch2 : mid_y + ch2, mid_x - cw2 : mid_x + cw2] return crop_img
04dfdbe14f3c9aaf9a97453448f2202cfa695eba
352,821
def get_role(row): """ Extracts the role from a given row :param row: Row to look at :return: The role """ role = row[6] # Normalize roles Lead Link and Rep Link, as they contain the circle name as well if "Lead Link" in role: role = "Lead Link" if "Rep Link" in role: role = "Rep Link" return role
1bae4639eb70c362aa2577afc6cfac99bdfca847
213,703
def format_iso8601(obj): """Format a datetime object for iso8601""" return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
cc19062781e279a98392cb81b7f7826d0fbcda36
350,323
def get_file_name(path): """Get the file name without .csv postfix. Args: path: A string for the absolute path to the file. Returns: A string for the path without .csv postfix """ filename = path.strip('\n').strip('.csv') return filename
d17a091b97c26fa9023a7e339301da4ab65c6d10
248,239
import re def validate_account_to_int(account): """ Validates the the provided string is in valid AdWords account format and converts it to integer format. :param (str, int) account: AdWords Account :return: Account ID as integer """ account = str(account).strip().replace('-', '') if re.match("^[0-9]{10}$", account): return int(account) raise ValueError("Invalid account format provided: {}".format(account))
e4ae287efde10a00d133fb0260acd06701abac0c
171,189
def bucket_policy_document(bucket): """Return the policy document to access an S3 bucket Parameters ---------- bucket: string An Amazon S3 bucket name Returns ------- s3_policy_doc: dict A dictionary containing the AWS policy document """ # Add policy statements to access to cloudknot S3 bucket s3_policy_doc = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::{0:s}".format(bucket)], }, { "Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject"], "Resource": ["arn:aws:s3:::{0:s}/*".format(bucket)], }, ], } return s3_policy_doc
576cc838c89479b93d80e2348ef22cb53c63f751
253,456
from typing import List import re def extract_regex_pattern(section_list: List[str], pattern: str): """ Extract list of section names that match the specified regex pattern. :param section_list: list of section names to search in :param pattern: regex pattern to search for :return: List of extracted section names """ r = re.compile(pattern, re.IGNORECASE) extracted_list = list(filter(r.match, section_list)) # remaining_list = list(set(section_list) - set(extracted_list)) return extracted_list
2ebbabb2c5004dcba25336a98b791487aaa6f369
470,772
def _geo_to_feature(ob): """ Return a GeoJSON Feature from an object that implements __geo_interface__ If the object's type is a geometry, return a Feature with empty properties and the object's mapping as the feature geometry. If the object's type is a Feature, then return it. """ mapping = ob.__geo_interface__ if mapping['type'] == 'Feature': return mapping else: return {'type': 'Feature', 'geometry': mapping}
cfa3ffb5cf5b3b75cb3a0cef770f9030fd068f74
524,191
def clamp(n, range): """ Given a number and a range, return the number, or the extreme it is closest to. :param n: number :param range: tuple with min and max :return: number """ minn, maxn = range return max(min(maxn, n), minn)
57ad33151784f8f58fe35ea1e662dc4c2661d8aa
497,772
import re def text_preprocess(document): """ Basic text preprocessing :param document: string containing input text :return: updated text """ # Remove all the special characters document = re.sub(r'\W', ' ', str(document)) # Substitute multiple spaces with single space document = re.sub(r'\s+', ' ', document, flags=re.I) # Convert to lowercase document = document.lower() return document
a23dd541f66aae3de39c7624b916b6a7b5c0e1e7
613,892
def extrapolate_correlation(correlation_energies, cardinals, beta): """Extrapolates the correlation energy. For more information, see Equation 2 in DOI: 10.1021/ct100396y. Parameters ---------- correlation_energies : :obj:`tuple` (:obj:`float`) The small (X) to large (Y) basis set correlation energies, respectively. cardinals : :obj:`tuple` The X and Y cardinal numbers of the basis sets, respectively. beta : :obj:`float` The basis-set dependent constant beta. Returns ------- :obj:`float` Extrapolated correlation energy. """ correlation_x, correlation_y = correlation_energies cardinal_x, cardinal_y = cardinals numerator = (cardinal_x**beta * correlation_x) - (cardinal_y**beta * correlation_y) denominator = cardinal_x**beta - cardinal_y**beta cbs_correlation = numerator / denominator return cbs_correlation
4eaef76106628d31efb5e83bf354bc41610fdd8a
468,916
def expense_by_store(transactions_and_receipt_metadata): """Takes a transaction df of expenses and receipt metadata and groups on receipt id, in addition to year, month and cat input: df (pd.DataFrame): dataframe of transactions to group and filter returns: df (pd.DataFrame): grouped dataframe """ # Group expenses on receipt_id. Join this to the storage bucket metadata df = transactions_and_receipt_metadata df = (df.groupby(["year", "month", "store_name"]) .agg( {"receipt_id": "nunique", "item_count": "sum", "price_net": "sum" }) .reset_index() .rename(columns={"receipt_id": "visits"}) ) df = df.reset_index() return df
59f5c00326dd5f91024557b57e82af5ad1a0bd92
667,220
def _get_vm_extension_list(vm_iv): """Iterate over a list of virtual machine extensions. Arguments: vm_iv (dict): Raw virtual machine instance view record. Returns: dict: List of names of installed extensions """ extensions = {} extension_list = [] for e in vm_iv.get('extensions', []): extension_list.append(e['name']) extensions['extensions'] = extension_list return extensions
bc70949091a1a463cf789f62f63dd89d19c7c7c6
349,176
def translate_topo_name(topo): """Translate the name of a topology as given by the benchmarks into a meaningful printable variant. """ if 'adaptivetree-shuffle-sort' in topo: return 'adaptivetree-optimized' else: return topo
ee1ec9123b8875ca0deb9ab159009b1bb4ba9590
584,951
def convert_text_to_tokens(data, base_vocab, tokenize_fn, custom_vocab={}): """ Converts sequences of text to sequences of token ids per the provided vocabulary Arguments: data (arr) : sequences of text base_vocab (torchtext.vocab) : vocabulary object tokenize_fun (function) : function to use to break up text into tokens Returns: arr : array of arrays, each inner array is a token_id representation of the text passed in """ word_seqs = [tokenize_fn(seq) for seq in data] token_seqs = [[custom_vocab[word] if word in custom_vocab else base_vocab[word] for word in word_seq] for word_seq in word_seqs] return token_seqs
d6930adc42ddecdfdf5ae8932c0202967a43ee7e
426,062
def _match_to_tuple_index(x, tuple_list): """Apply function to see if passed fields are in the tuple_list""" sid, ncesid, home_away = x return (sid, ncesid, home_away) in tuple_list
73a33bd357ee490db5f2fbf791d44acd8f93d9f7
522,225
import signal def _signal_exit_code(signum: signal.Signals) -> int: """ Return the exit code corresponding to a received signal. Conventionally, when a program exits due to a signal its exit code is 128 plus the signal number. """ return 128 + int(signum)
050eee98632216fddcbd71e4eb6b0c973f6d4144
2,645
from datetime import datetime def get_month(date): """ Converts string representation of date in form of 2018-11-10 as Nov-18 """ return datetime.strptime(date, '%Y-%m-%d').strftime('%b-%y')
5475c0a94aeb357b30553754deb42d2e7f30fc3c
355,933
def jsonify(dataset, variable): """ Extract a time series from a THREDDS dataset at the given location. Args: dataset(xarray.Dataset): an xarray dataset. variable(str): Name of the variable to query. Returns: dict: JSON-compatible Python Dict. """ str_time_da = dataset.time.dt.strftime('%Y-%m-%dT%H:%M:%SZ') json_dict = { 'time_series': { 'variable': variable, 'datetime': str_time_da.data.tolist(), 'values': dataset[variable].data.tolist(), } } return json_dict
43205368dc364198fbe0bd7d888c47d6627906cd
591,275
import re def get_name_slug(name: str) -> str: """Get the stub of the organization's name. Arguments: name {str} -- Organization name. Returns: str -- Organization name stub. """ return '-'.join(re.split(r'\W', name.lower()))
ef3fce6346a7aabfcebcc6a6e72d1e718e0ed4d2
23,049
def dummy_lambda_event_get() -> dict: """ Return dummy GET request data. """ event_get = { 'year': '2011', 'month': '11', 'http_method': 'GET' } return event_get
4c580fc7bf69686af0916afb57c501d4d70ef892
114,865
def get_maximum_overview_level(src_dst, minsize=512): """ Calculate the maximum overview level. Attributes ---------- src_dst : rasterio.io.DatasetReader Rasterio io.DatasetReader object. minsize : int (default: 512) Minimum overview size. Returns ------- nlevel: int overview level. """ width = src_dst.width height = src_dst.height nlevel = 0 overview = 1 while min(width // overview, height // overview) > minsize: overview *= 2 nlevel += 1 return nlevel
3166291ede393cf6682babccc2fc03c47e80c2f0
425,420
def difference_with(f, xs, ys): """Finds the set (i.e. no duplicates) of all elements in the first list not contained in the second list. Duplication is determined according to the value returned by applying the supplied predicate to two list elements""" out = [] for x in xs: if x in out: continue contains = False for y in ys: if f(x, y): contains = True break if not contains: out.append(x) return out
13304fc3b0a7335c5c30b7c16d35bec1e37ae7bd
646,829
def args_with_source(frame_info, *args): """ Returns a list of pairs of: - the source code of the argument - the value of the argument for each argument. For example: args_with_source(foo(), 1+2) is the same as: [ ("foo()", foo()), ("1+2", 3) ] """ return [ (frame_info.get_source(arg), value) for arg, value in zip(frame_info.call.args, args) ]
9f966b1132a1677ccfa3e8c117f84b2f898adc46
317,847
def not_in_list(x,args,y): """ Check whether a string is in a list of hashtags """ list = x['caption'].split(' #') return not (args in list[1:])
6c5dc0b2e1c8616220af8925525395cdf9515cd8
239,057
import itertools def nwise(iterable, n): """ Iterate through a sequence with a defined length window >>> list(nwise(range(8), 3)) [(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (5, 6, 7)] >>> list(nwise(range(3), 5)) [] Parameters ---------- iterable n : length of each sequence Yields ------ Tuples of length n """ iters = itertools.tee(iterable, n) iters = (itertools.islice(it, i, None) for i, it in enumerate(iters)) return zip(*iters)
3481e3aa600ab9e561beafa670a652e4afc7b3cf
345,740
def clean_label(label: str) -> str: """ Return a label without spaces or parenthesis """ for c in "()": label = label.replace(c, "") for c in " ": label = label.replace(c, "_") return label.strip("_")
28178742069e56d991b49d6b254b1fdd6a87ea71
552,530
def GetInfobarIndexByType(test, infobar_type, windex=0, tab_index=0): """Returns the index of the infobar of the given type. Args: test: Derived from pyauto.PyUITest - base class for UI test cases. infobar_type: The infobar type to look for. windex: Window index. tab_index: Tab index. Returns: Index of infobar for infobar type, or None if not found. """ infobar_list = ( test.GetBrowserInfo()['windows'][windex]['tabs'][tab_index] \ ['infobars']) for infobar in infobar_list: if infobar_type == infobar['type']: return infobar_list.index(infobar) return None
b752ed26af54f373c00ce70cf0abd600a9bbac34
464,678
from typing import Tuple def grid_cell_to_xy(pos: int, grid_size: int = 5) -> Tuple[int, int]: """Converts an integer from 0-24 into an (x, y) position.""" num_cells = grid_size * grid_size - 1 if not 0 <= pos <= num_cells: raise ValueError(f'Grid cell does not exist in grid of size {grid_size}') x = pos // grid_size y = pos % grid_size return (x, y)
cc0f2d57a5c119cc5a3184642f539e69f594ecc3
618,028
def _alloc_key(name): """Constructs allocation key based on app name/pattern.""" if '@' in name: key = name[name.find('@') + 1:name.find('.')] else: key = name[0:name.find('.')] return key
ca3182f52d780f94a6a18c51ad0b7d841ead20d1
700,778
def getAsciiFileExtension(proxyType): """ The file extension used for ASCII (non-compiled) proxy source files for the proxies of specified type. """ return '.proxy' if proxyType == 'Proxymeshes' else '.mhclo'
cb2b27956b3066d58c7b39efb511b6335b7f2ad6
706,310
def _replace_match(text, match, replacement): """Expands a regexp match in the text with its replacement. Args: text: str. The text in which to perform the replacement. match: re.MatchObject. A match object that applies to "text". replacement: str. The string to replace the match with. Returns: (str, int). The text with the substitution performed and the first position in the text after the replacement that was done. """ new_text = text[:match.start()] + replacement + text[match.end():] new_start_pos = match.start() + len(replacement) return new_text, new_start_pos
a813704d4ed2d77d0f8150abe5e2917f22b93cb9
652,054
def create_dict_node_enode(set_proj_nodes, neighbors_dict, H, node, dict_node_enode, dict_enode_node): """ A function to create useful dictionaries to represent connections between nodes that are in the embedding and nodes that are not in the embedding. :param set_proj_nodes: Set of the nodes that are in the embedding :param neighbors_dict: Dictionary of all nodes and neighbors (both incoming and outgoing) :param H: H is the undirected version of our graph :param node: Current node :param dict_node_enode: explained below :param dict_enode_node: explained below :return: 1. dict_node_enode: key == nodes not in embedding, value == set of outdoing nodes in embedding (i.e there is a directed edge (i,j) when i is the key node and j is in the embedding) 2. dict_enode_node: key == nodes not in embedding, value == set of incoming nodes in embedding (i.e there is a directed edge (j,i) when i is the key node and j is in the embedding) """ set2 = neighbors_dict[node].intersection(set_proj_nodes) set_all = set(H[node]).intersection(set_proj_nodes) set_in = set_all - set2 if len(set2) > 0: dict_node_enode.update({node: set2}) if len(set_in) > 0: dict_enode_node.update({node: set_in}) return dict_node_enode, dict_enode_node
da2b05648dd200f98e03d3483fd3e80b225a1ee9
677,191
def validate_item_name(name, prefix, suffix): """Verifies that ``name`` starts with ``prefix`` and ends with ``suffix``. Returns ``True`` or ``False``""" return name[: len(prefix)] == prefix and name[-len(suffix) :] == suffix
ce61dfc9ec97bceac6662f5bc26c758bfbc0d139
333,575
def indent_text(text: str, level: int = 0) -> str: """Indent each line of ``text`` by ``level`` spaces.""" return "\n".join([" " * level + line for line in text.split('\n')])
aed5d814770836d062af1ddc0fae070e0dd0a611
291,233
from pathlib import Path from warnings import warn def git_rev(repo): """ Get the git revision for the repo in the path *repo*. Returns the commit id of the current head. Note: this function parses the files in the git repository directory without using the git application. It may break if the structure of the git repository changes. It only reads files, so it should not do any damage to the repository in the process. """ # Based on stackoverflow am9417 # https://stackoverflow.com/questions/14989858/get-the-current-git-hash-in-a-python-script/59950703#59950703 if repo is None: return None git_root = Path(repo) / ".git" git_head = git_root / "HEAD" if not git_head.exists(): return None # Read .git/HEAD file with git_head.open("r") as fd: head_ref = fd.read() # Find head file .git/HEAD (e.g. ref: ref/heads/master => .git/ref/heads/master) if not head_ref.startswith("ref: "): warn("expected 'ref: path/to/head' in {git_head}".format(git_head=git_head)) return None head_ref = head_ref[5:].strip() # Read commit id from head file head_path = git_root.joinpath(*head_ref.split("/")) if not head_path.exists(): warn("path {head_path} referenced from {git_head} does not exist".format(head_path=head_path, git_head=git_head)) return None with head_path.open("r") as fd: commit = fd.read().strip() return commit
877fa58bfeaadefc42920c2695af03117fe80fd3
616,431