content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def remove_constant_features(sfm): """ Remove features that are constant across all samples """ # boolean matrix of whether x == first column (feature) x_not_equal_to_1st_row = sfm._x != sfm._x[0] non_const_f_bool_ind = x_not_equal_to_1st_row.sum(axis=0) >= 1 return sfm.ind_x(selected_f_inds=non_const_f_bool_ind)
ae8c6e1d14b7260c8d2491b2f8a00ba352d7375a
709,647
def readByte (file): """ Read a byte from file. """ return ord (file.read (1))
4e82d1b688d7742fd1dd1025cd7ac1ccb13bbca0
709,655
def sdfGetMolBlock(mol): """ sdfGetMolBlock() returns the MOL block of the molecule """ return mol["molblock"]
399874a696f30f492ee878ef661094119bd5f96f
709,657
def noop_chew_func(_data, _arg): """ No-op chew function. """ return 0
82ef82b350c2a01e5ba22f288c003032bf6e63e0
709,662
from datetime import datetime def set_clock(child, timestamp=None): """Set the device's clock. :param pexpect.spawn child: The connection in a child application object. :param datetime timestamp: A datetime tuple (year, month, day, hour, minute, second). :returns: The updated connection in a child application object. :rtype: pexpect.spawn """ if not timestamp: timestamp = datetime.utcnow() child.sendline("clock set {0}\r".format(timestamp.strftime("%H:%M:%S %d %b %Y"))) child.expect_exact("{0}, configured from console by console".format(timestamp.strftime("%H:%M:%S UTC %a %b %d %Y"))) return child
b6299ab780ffc9e9d27b0715decf095b3d6a6272
709,664
def uniquify_contacts(contacts): """ Return a sequence of contacts with all duplicates removed. If any duplicate names are found without matching numbers, an exception is raised. """ ctd = {} for ct in contacts: stored_ct = ctd.setdefault(ct.name, ct) if stored_ct.dmrid != ct.dmrid: raise RuntimeError( "Two contacts named {} have different IDs: {} {}".format( ct.name, ct.dmrid, stored_ct.dmrid ) ) return list(ctd.values())
f4bf001abcccad1307633e6de6ed6228516ba0b2
709,669
def determine_if_is_hmmdb(infp): """Return True if the given file is an HMM database (generated using hmmpress from the HMMer3 software package), and return False otherwise. """ #if open(infp, 'r').read().startswith('HMMER3/f'): if open(infp, 'r').readline().startswith('HMMER3/f'): return True else: return False
33b962e24c76e9e25f2cc76d4e7f78565adf8a3e
709,671
def template_footer(in_template): """Extracts footer from the notebook template. Args: in_template (str): Input notebook template file path. Returns: list: List of lines. """ footer = [] template_lines = [] footer_start_index = 0 with open(in_template) as f: template_lines = f.readlines() for index, line in enumerate(template_lines): if '## Display Earth Engine data layers' in line: footer_start_index = index - 3 footer = ['\n'] + template_lines[footer_start_index:] return footer
cb872076b82b2012b2e27fcb1be9b8704cd60d27
709,672
def post_step1(records): """Apply whatever extensions we have for GISTEMP step 1, that run after the main step 1. None at present.""" return records
98287f6930db6aa025715356084b3bef8c851774
709,673
import math def spatial_shift_crop_list(size, images, spatial_shift_pos, boxes=None): """ Perform left, center, or right crop of the given list of images. Args: size (int): size to crop. image (list): ilist of images to perform short side scale. Dimension is `height` x `width` x `channel` or `channel` x `height` x `width`. spatial_shift_pos (int): option includes 0 (left), 1 (middle), and 2 (right) crop. boxes (list): optional. Corresponding boxes to images. Dimension is `num boxes` x 4. Returns: cropped (ndarray): the cropped list of images with dimension of `height` x `width` x `channel`. boxes (list): optional. Corresponding boxes to images. Dimension is `num boxes` x 4. """ assert spatial_shift_pos in [0, 1, 2] height = images[0].shape[0] width = images[0].shape[1] y_offset = int(math.ceil((height - size) / 2)) x_offset = int(math.ceil((width - size) / 2)) if height > width: if spatial_shift_pos == 0: y_offset = 0 elif spatial_shift_pos == 2: y_offset = height - size else: if spatial_shift_pos == 0: x_offset = 0 elif spatial_shift_pos == 2: x_offset = width - size cropped = [ image[y_offset : y_offset + size, x_offset : x_offset + size, :] for image in images ] assert cropped[0].shape[0] == size, "Image height not cropped properly" assert cropped[0].shape[1] == size, "Image width not cropped properly" if boxes is not None: for i in range(len(boxes)): boxes[i][:, [0, 2]] -= x_offset boxes[i][:, [1, 3]] -= y_offset return cropped, boxes
c80d8ab83f072c94887d48c3d1cfe5bb18285dbb
709,675
def _checker(word: dict): """checks if the 'word' dictionary is fine :param word: the node in the list of the text :type word: dict :return: if "f", "ref" and "sig" in word, returns true, else, returns false :rtype: bool """ if "f" in word and "ref" in word and "sig" in word: return True return False
ee6ec5a7ee393ddcbc97b13f6c09cdd9019fb1a6
709,680
def to_n_class(digit_lst, data, labels): """to make a subset of MNIST dataset, which has particular digits Parameters ---------- digit_lst : list for example, [0,1,2] or [1, 5, 8] data : numpy.array, shape (n_samples, n_features) labels : numpy.array or list of str Returns ------- numpy.array, list of int """ if not set(digit_lst) <= set(range(10)): raise ValueError indices = [] new_labels = [] for i, x in enumerate(data): for digit in digit_lst: if labels[i] == str(digit): indices.append(i) new_labels.append(digit) return data[indices], new_labels
79652687ec0670ec00d67681711903ae01f4cc87
709,682
def max_tb(collection): # pragma: no cover """Returns the maximum number of TB recorded in the collection""" max_TB = 0 for doc in collection.find({}).sort([('total_TB',-1)]).limit(1): max_TB = doc['total_TB'] return max_TB
bde417de0b38de7a7b5e4e3db8c05e87fa6c55ca
709,687
import time def datetime_to_timestamp(d): """convert a datetime object to seconds since Epoch. Args: d: a naive datetime object in default timezone Return: int, timestamp in seconds """ return int(time.mktime(d.timetuple()))
356ac090b0827d49e9929a7ef26041b26c6cc690
709,688
def update_coverage(coverage, path, func, line, status): """Add to coverage the coverage status of a single line""" coverage[path] = coverage.get(path, {}) coverage[path][func] = coverage[path].get(func, {}) coverage[path][func][line] = coverage[path][func].get(line, status) coverage[path][func][line] = coverage[path][func][line].combine(status) return coverage
46e5a1e5c4ebba3a9483f90ada96a0f7f94d8c1d
709,690
def cross_product(v1, v2): """Calculate the cross product of 2 vectors as (x1 * y2 - x2 * y1).""" return v1.x * v2.y - v2.x * v1.y
871d803ef687bf80facf036549b4b2062f713994
709,691
import re def _xfsdump_output(data): """ Parse CLI output of the xfsdump utility. """ out = {} summary = [] summary_block = False for line in [l.strip() for l in data.split("\n") if l.strip()]: line = re.sub("^xfsdump: ", "", line) if line.startswith("session id:"): out["Session ID"] = line.split(" ")[-1] elif line.startswith("session label:"): out["Session label"] = re.sub("^session label: ", "", line) elif line.startswith("media file size"): out["Media size"] = re.sub(r"^media file size\s+", "", line) elif line.startswith("dump complete:"): out["Dump complete"] = re.sub(r"^dump complete:\s+", "", line) elif line.startswith("Dump Status:"): out["Status"] = re.sub(r"^Dump Status:\s+", "", line) elif line.startswith("Dump Summary:"): summary_block = True continue if line.startswith(" ") and summary_block: summary.append(line.strip()) elif not line.startswith(" ") and summary_block: summary_block = False if summary: out["Summary"] = " ".join(summary) return out
dbc7fbf9dced99b83a7dc5917c473a1dee16d749
709,705
def parseParams(opt): """Parse a set of name=value parameters in the input value. Return list of (name,value) pairs. Raise ValueError if a parameter is badly formatted. """ params = [] for nameval in opt: try: name, val = nameval.split("=") except ValueError: raise ValueError("Bad name=value format for '%s'" % nameval) params.append((name, val)) return params
b932f74c8e5502ebdd7a8749c2de4b30921d518b
709,708
def _get_name(dist): """Attempts to get a distribution's short name, excluding the name scope.""" return getattr(dist, 'parameters', {}).get('name', dist.name)
fd57e523c1a84a36f9ed56236e4b8db1e887575c
709,709
def NO_MERGE(writer, segments): """This policy does not merge any existing segments. """ return segments
0742365f30d59cb219ac60483b867180bd910ba8
709,712
from typing import Union def parse_boolean(val: str) -> Union[str, bool]: """Try to parse a string into boolean. The string is returned as-is if it does not look like a boolean value. """ val = val.lower() if val in ('y', 'yes', 't', 'true', 'on', '1'): return True if val in ('n', 'no', 'f', 'false', 'off', '0'): return False return val
e2cbda5a849e1166e0f2a3953220c93d1f3ba119
709,716
import re def safe_htcondor_attribute(attribute: str) -> str: """Convert input attribute name into a valid HTCondor attribute name HTCondor ClassAd attribute names consist only of alphanumeric characters or underscores. It is not clearly documented, but the alphanumeric characters are probably restricted to ASCII. Attribute names created from multiple words typically capitalize the first letter in each word for readability, although all comparisions are case-insensitive. e.g., "central-manager" -> "CentralManager" Args: attribute: a string representing the name of an attribute Returns: The attribute name stripped of invalid characters and re-capitalized in the manner typical of HTCondor ClassAd attributes. Raises: None """ # splitting by invalid characters removes them from the resulting array split_attr = re.split(r"[^\w]", attribute, flags=re.ASCII) safe_attr = "".join([word.capitalize() for word in split_attr if word]) return safe_attr
7a4dda539b2379120e68737d72a80226c45f5602
709,720
def make_csv(headers, data): """ Creates a CSV given a set of headers and a list of database query results :param headers: A list containg the first row of the CSV :param data: The list of query results from the Database :returns: A str containing a csv of the query results """ # Create a list where each entry is one row of the CSV file, starting # with the headers csvRows =[','.join(headers),] # Iterate through the provided data and create the rest of the CSV's rows for datum in data: currentRow = '' for header in headers: # Get this rows value for the given header val = getattr(datum, header) if type(val) is str: # Escape the strings currentRow += '"' + val + '",' elif type(val) is float: # Don't Escape the floats currentRow += str(val) + ',' else: # If it is empty and a place holder currentRow += ',' csvRows.append(currentRow[:-1]) # Combine all of the rows into a single single string and return it. return "\n".join(csvRows)
5101d53de8dd09d8ebe743d77d71bff9aeb26334
709,721
from typing import Tuple def extract_value_from_config( config: dict, keys: Tuple[str, ...], ): """ Traverse a config dictionary to get some hyper-parameter's value. Parameters ---------- config A config dictionary. keys The possible names of a hyper-parameter. Returns ------- The hyper-parameter value. """ result = [] for k, v in config.items(): if k in keys: result.append(v) elif isinstance(v, dict): result += extract_value_from_config(v, keys) else: pass return result
d545d4c9298c74776ec52fb6b2c8d54d0e653489
709,722
def vision_matched_template_get_pose(template_match): """ Get the pose of a previously detected template match. Use list operations to get specific entries, otherwise returns value of first entry. Parameters: template_match (List[MatchedTemplate3D] or MatchedTemplate3D): The template match(s) Return (Pose): The pose of the template match """ if isinstance(template_match,list): template_match = template_match[0] return template_match.pose.pose.pose
b854da7a085934f4f3aba510e76852fb8c0a440a
709,724
def get_vocabulary(query_tree): """Extracts the normalized search terms from the leaf nodes of a parsed query to construct the vocabulary for the text vectorization. Arguments --------- query_tree: pythonds.trees.BinaryTree The binary tree object representing a parsed search query. Each leaf node is a search term and internal nodes represent boolean operations. See parse_query() for details. Returns ------- vocabulary: list List of strings representing unique normalized search terms. """ def _getleafnodes(node): terms = [] if node.isLeaf(): return terms + [node.normedterm] elif node.leftChild and not node.rightChild: return terms + _getleafnodes(node.getLeftChild()) elif node.rightChild and not node.leftChild: return terms + _getleafnodes(node.getRightChild()) else: # has two children return terms + _getleafnodes(node.getLeftChild()) \ + _getleafnodes(node.getRightChild()) # extract terms from the leaf nodes of the query object. terms = _getleafnodes(query_tree) # remove duplicates. vocabulary = list(set(terms)) return vocabulary
bd03f4894cd3f9a7964196bfb163335f84a048d7
709,728
def find_point_in_section_list(point, section_list): """Returns the start of the section the given point belongs to. The given list is assumed to contain start points of consecutive sections, except for the final point, assumed to be the end point of the last section. For example, the list [5, 8, 30, 31] is interpreted as the following list of sections: [5-8), [8-30), [30-31], so the points -32, 4.5, 32 and 100 all match no section, while 5 and 7.5 match [5-8) and so for them the function returns 5, and 30, 30.7 and 31 all match [30-31]. Parameters --------- point : float The point for which to match a section. section_list : sortedcontainers.SortedList A list of start points of consecutive sections. Returns ------- float The start of the section the given point belongs to. None if no match was found. Example ------- >>> from sortedcontainers import SortedList >>> seclist = SortedList([5, 8, 30, 31]) >>> find_point_in_section_list(4, seclist) >>> find_point_in_section_list(5, seclist) 5 >>> find_point_in_section_list(27, seclist) 8 >>> find_point_in_section_list(31, seclist) 30 """ if point < section_list[0] or point > section_list[-1]: return None if point in section_list: if point == section_list[-1]: return section_list[-2] ind = section_list.bisect(point)-1 if ind == 0: return section_list[0] return section_list[ind] try: ind = section_list.bisect(point) return section_list[ind-1] except IndexError: return None
47d5cda15b140ba8505ee658fd46ab090b2fda8a
709,729
def choose(population, sample): """ Returns ``population`` choose ``sample``, given by: n! / k!(n-k)!, where n == ``population`` and k == ``sample``. """ if sample > population: return 0 s = max(sample, population - sample) assert s <= population assert population > -1 if s == population: return 1 numerator = 1 denominator = 1 for i in range(s+1, population + 1): numerator *= i denominator *= (i - s) return numerator/denominator
659eac683cae737888df74c0db21aa3ece746b33
709,731
def eea(m, n): """ Compute numbers a, b such that a*m + b*n = gcd(m, n) using the Extended Euclidean algorithm. """ p, q, r, s = 1, 0, 0, 1 while n != 0: k = m // n m, n, p, q, r, s = n, m - k*n, q, p - k*q, s, r - k*s return (p, r)
56e1c59ac3a51e26d416fe5c65cf6612dbe56b8c
709,733
def maximum_value(tab): """ brief: return maximum value of the list args: tab: a list of numeric value expects at leas one positive value return: the max value of the list the index of the max value raises: ValueError if expected a list as input ValueError if no positive value found """ if not(isinstance(tab, list)): raise ValueError('Expected a list as input') valMax = 0.0 valMaxIndex = -1; nPositiveValues = 0 for i in range(len(tab)): if tab[i] >= 0 and tab[i] > valMax: valMax = float(tab[i]) valMaxIndex = i nPositiveValues += 1 if nPositiveValues <= 0: raise ValueError('No positive value found') return valMax, valMaxIndex
1c31daf3a953a9d781bc48378ef53323313dc22a
709,739
import math def dsh( incidence1: float, solar_az1: float, incidence2: float, solar_az2: float ): """Returns the Shadow-Tip Distance (dsh) as detailed in Becker et al.(2015). The input angles are assumed to be in radians. This is defined as the distance between the tips of the shadows in the two images for a hypothetical vertical post of unit height. The "shadow length" describes the shadow of a hypothetical pole so it applies whether there are actually shadows in the image or not. It's a simple and consistent geometrical way to quantify the difference in illumination. This quantity is computed analogously to dp. """ def shx(inc: float, sunazgnd: float): return -1 * math.tan(inc) * math.cos(sunazgnd) def shy(inc: float, sunazgnd: float): return math.tan(inc) * math.sin(sunazgnd) shx1 = shx(incidence1, solar_az1) shx2 = shx(incidence2, solar_az2) shy1 = shy(incidence1, solar_az1) shy2 = shy(incidence2, solar_az2) return math.sqrt(math.pow(shx1 - shx2, 2) + math.pow(shy1 - shy2, 2))
5aef1c9d7ffeb3e8534568a53cf537d26d97324a
709,740
from typing import Optional def convert_postgres_array_as_string_to_list(array_as_string: str) -> Optional[list]: """ Postgres arrays are stored in CSVs as strings. Elasticsearch is able to handle lists of items, but needs to be passed a list instead of a string. In the case of an empty array, return null. For example, "{this,is,a,postgres,array}" -> ["this", "is", "a", "postgres", "array"]. """ return array_as_string[1:-1].split(",") if len(array_as_string) > 2 else None
cc64fe8e0cc765624f80abc3900985a443f76792
709,749
import functools import logging def disable_log_warning(fun): """Temporarily set FTP server's logging level to ERROR.""" @functools.wraps(fun) def wrapper(self, *args, **kwargs): logger = logging.getLogger('pyftpdlib') level = logger.getEffectiveLevel() logger.setLevel(logging.ERROR) try: return fun(self, *args, **kwargs) finally: logger.setLevel(level) return wrapper
6990a2a1a60ea5a24e4d3ac5c5e7fbf443825e48
709,752
import json def read_json(file_name): """Read json from file.""" with open(file_name) as f: return json.load(f)
2eccab7dddb1c1038de737879c465f293a00e5de
709,758
def _decode_end(_fp): """Decode the end tag, which has no data in the file, returning 0. :type _fp: A binary `file object` :rtype: int """ return 0
5e8da3585dda0b9c3c7cd428b7e1606e585e15c6
709,759
def get_camelcase_name_chunks(name): """ Given a name, get its parts. E.g: maxCount -> ["max", "count"] """ out = [] out_str = "" for c in name: if c.isupper(): if out_str: out.append(out_str) out_str = c.lower() else: out_str += c out.append(out_str) return out
134a8b1d98af35f185b37c999fbf499d18bf76c5
709,760
import json def get_node_to_srn_mapping(match_config_filename): """ Returns the node-to-srn map from match_conf.json """ with open(match_config_filename) as config_file: config_json = json.loads(config_file.read()) if "node_to_srn_mapping" in config_json: return config_json["node_to_srn_mapping"] else: node_to_srn = {} for node_info in config_json["NodeData"]: node_id = node_info["TrafficNode"] srn_num = node_info["srn_number"] node_to_srn[node_id] = srn_num return node_to_srn
37bf2f266f4e5163cc4d6e9290a8eaf17e220cd3
709,765
def nest_dictionary(flat_dict, separator): """ Nests a given flat dictionary. Nested keys are created by splitting given keys around the `separator`. """ nested_dict = {} for key, val in flat_dict.items(): split_key = key.split(separator) act_dict = nested_dict final_key = split_key.pop() for new_key in split_key: if not new_key in act_dict: act_dict[new_key] = {} act_dict = act_dict[new_key] act_dict[final_key] = val return nested_dict
f5b8649d916055fa5911fd1f80a8532e5dbee274
709,766
def list_a_minus_b(list1, list2): """Given two lists, A and B, returns A-B.""" return filter(lambda x: x not in list2, list1)
8fbac6452077ef7cf73e0625303822a35d0869c3
709,767
def tempo_para_percorrer_uma_distancia(distancia, velocidade): """ Recebe uma distância e a velocidade de movimentação, e retorna as horas que seriam gastas para percorrer em linha reta""" horas = distancia / velocidade return round(horas,2)
e7754e87e010988284a6f89497bb1c5582ea0e85
709,773
def find_last_index(l, x): """Returns the last index of element x within the list l""" for idx in reversed(range(len(l))): if l[idx] == x: return idx raise ValueError("'{}' is not in list".format(x))
f787b26dd6c06507380bf2e336a58887d1f1f7ea
709,774
def _CheckUploadStatus(status_code): """Validates that HTTP status for upload is 2xx.""" return status_code / 100 == 2
d799797af012e46945cf413ff54d2ee946d364ba
709,776
import random def pick_op(r, maxr, w, maxw): """Choose a read or a write operation""" if r == maxr or random.random() >= float(w) / maxw: return "write" else: return "read"
a45f53bf12538412b46f78e2c076966c26cf61ac
709,779
def min_index(array, i, j): """Pomocna funkce pro razeni vyberem. Vrati index nejmensiho prvku v poli 'array' mezi 'i' a 'j'-1. """ index = i for k in range(i, j): if array[k] < array[index]: index = k return index
4c59362fac2e918ba5a0dfe9f6f1670b3e95d68c
709,782
def average_precision(gt, pred): """ Computes the average precision. This function computes the average prescision at k between two lists of items. Parameters ---------- gt: set A set of ground-truth elements (order doesn't matter) pred: list A list of predicted elements (order does matter) Returns ------- score: double The average precision over the input lists """ if not gt: return 0.0 score = 0.0 num_hits = 0.0 for i,p in enumerate(pred): if p in gt and p not in pred[:i]: num_hits += 1.0 score += num_hits / (i + 1.0) return score / max(1.0, len(gt))
ca265471d073b6a0c7543e24ef0ba4f872737997
709,784
def Flatten(matrix): """Flattens a 2d array 'matrix' to an array.""" array = [] for a in matrix: array += a return array
00389b4dd295274d8081331d6ae78f233f0b5b59
709,790
def escape_name(name): """Escape sensor and request names to be valid Python identifiers.""" return name.replace('.', '_').replace('-', '_')
856b8fe709e216e027f5ab085dcab91604c93c2e
709,792
def multiset_counter(mset): """ Return the sum of occurences of elements present in a token ids multiset, aka. the multiset cardinality. """ return sum(mset.values())
36885abd5bf666aa6c77a262a647c227e46d2e88
709,793
def lengthenFEN(fen): """Lengthen FEN to 71-character form (ex. '3p2Q' becomes '111p11Q')""" return fen.replace('8','11111111').replace('7','1111111') \ .replace('6','111111').replace('5','11111') \ .replace('4','1111').replace('3','111').replace('2','11')
f49cdf8ad6919fbaaad1abc83e24b1a33a3ed3f8
709,794
def get_list_of_encodings() -> list: """ Get a list of all implemented encodings. ! Adapt if new encoding is added ! :return: List of all possible encodings """ return ['raw', '012', 'onehot', '101']
6e0749eb45f85afe4e5c7414e4d23e67335ba2b5
709,799
def region_to_bin(chr_start_bin, bin_size, chr, start): """Translate genomic region to Cooler bin idx. Parameters: ---------- chr_start_bin : dict Dictionary translating chromosome id to bin start index bin_size : int Size of the bin chr : str Chromosome start : int Start of the genomic region """ return chr_start_bin[chr] + start // bin_size
f17b132048b0ceb4bbf2a87b77327d0d63b3fd64
709,800
def word_distance(word1, word2): """Computes the number of differences between two words. word1, word2: strings Returns: integer """ assert len(word1) == len(word2) count = 0 for c1, c2 in zip(word1, word2): if c1 != c2: count += 1 return count
b3279744c628f3adc05a28d9ab7cc520744b540c
709,803
def CheckVPythonSpec(input_api, output_api, file_filter=None): """Validates any changed .vpython files with vpython verification tool. Args: input_api: Bag of input related interfaces. output_api: Bag of output related interfaces. file_filter: Custom function that takes a path (relative to client root) and returns boolean, which is used to filter files for which to apply the verification to. Defaults to any path ending with .vpython, which captures both global .vpython and <script>.vpython files. Returns: A list of input_api.Command objects containing verification commands. """ file_filter = file_filter or (lambda f: f.LocalPath().endswith('.vpython')) affected_files = input_api.AffectedTestableFiles(file_filter=file_filter) affected_files = map(lambda f: f.AbsoluteLocalPath(), affected_files) commands = [] for f in affected_files: commands.append(input_api.Command( 'Verify %s' % f, ['vpython', '-vpython-spec', f, '-vpython-tool', 'verify'], {'stderr': input_api.subprocess.STDOUT}, output_api.PresubmitError)) return commands
d6e888b5ce6fec4bbdb35452b3c0572702430c06
709,804
def convertInt(s): """Tells if a string can be converted to int and converts it Args: s : str Returns: s : str Standardized token 'INT' if s can be turned to an int, s otherwise """ try: int(s) return "INT" except: return s
a0eae31b69d4efcf8f8595e745316ea8622e24b3
709,809
import torch def pairwise_distance(A, B): """ Compute distance between points in A and points in B :param A: (m,n) -m points, each of n dimension. Every row vector is a point, denoted as A(i). :param B: (k,n) -k points, each of n dimension. Every row vector is a point, denoted as B(j). :return: Matrix with (m, k). And the ele in (i,j) is the distance between A(i) and B(j) """ A_square = torch.sum(A * A, dim=1, keepdim=True) B_square = torch.sum(B * B, dim=1, keepdim=True) distance = A_square + B_square.t() - 2 * torch.matmul(A, B.t()) return distance
2142b94f91f9e762d1a8b134fdda4789c564455d
709,810
def coerce(from_, to, **to_kwargs): """ A preprocessing decorator that coerces inputs of a given type by passing them to a callable. Parameters ---------- from : type or tuple or types Inputs types on which to call ``to``. to : function Coercion function to call on inputs. **to_kwargs Additional keywords to forward to every call to ``to``. Examples -------- >>> @preprocess(x=coerce(float, int), y=coerce(float, int)) ... def floordiff(x, y): ... return x - y ... >>> floordiff(3.2, 2.5) 1 >>> @preprocess(x=coerce(str, int, base=2), y=coerce(str, int, base=2)) ... def add_binary_strings(x, y): ... return bin(x + y)[2:] ... >>> add_binary_strings('101', '001') '110' """ def preprocessor(func, argname, arg): if isinstance(arg, from_): return to(arg, **to_kwargs) return arg return preprocessor
61ccce8b9ffbec3e76aa9e78face469add28437e
709,817
import configparser def parse_config_to_dict(cfg_file, section): """ Reads config file and returns a dict of parameters. Args: cfg_file: <String> path to the configuration ini-file section: <String> section of the configuration file to read Returns: cfg: <dict> configuration parameters of 'section' as a dict """ cfg = configparser.ConfigParser() cfg.read(cfg_file) if cfg.has_section(section): return dict(cfg.items(section)) else: print("Section '%s' not found in file %s!" % (section, cfg_file)) return None
021e3594f3130e502934379c0f5c1ecea228017b
709,820
import math def mag_inc(x, y, z): """ Given *x* (north intensity), *y* (east intensity), and *z* (vertical intensity) all in [nT], return the magnetic inclincation angle [deg]. """ h = math.sqrt(x**2 + y**2) return math.degrees(math.atan2(z, h))
f4036358625dd9d032936afc373e53bef7c1e6e1
709,825
def _parse_disambiguate(disambiguatestatsfilename): """Parse disambiguation stats from given file. """ disambig_stats = [-1, -1, -1] with open(disambiguatestatsfilename, "r") as in_handle: header = in_handle.readline().strip().split("\t") if header == ['sample', 'unique species A pairs', 'unique species B pairs', 'ambiguous pairs']: disambig_stats_tmp = in_handle.readline().strip().split("\t")[1:] if len(disambig_stats_tmp) == 3: disambig_stats = [int(x) for x in disambig_stats_tmp] return disambig_stats
bb05ec857181f032ae9c0916b4364b772ff7c412
709,826
def clean_vigenere(text): """Convert text to a form compatible with the preconditions imposed by Vigenere cipher.""" return ''.join(ch for ch in text.upper() if ch.isupper())
d7c3fc656ede6d07d6e9bac84a051581364c63a0
709,827
def f_score(r: float, p: float, b: int = 1): """ Calculate f-measure from recall and precision. Args: r: recall score p: precision score b: weight of precision in harmonic mean Returns: val: value of f-measure """ try: val = (1 + b ** 2) * (p * r) / (b ** 2 * p + r) except ZeroDivisionError: val = 0 return val
d12af20e30fd80cb31b2cc119d5ea79ce2507c4b
709,829
def role_generator(role): """Closure function returning a role function.""" return lambda *args, **kwargs: role.run(*args, **kwargs)
35dd1a54cb53a6435633c39608413c2d0b9fe841
709,831
def identity_show(client, resource_group_name, account_name): """ Show the identity for Azure Cognitive Services account. """ sa = client.get(resource_group_name, account_name) return sa.identity if sa.identity else {}
19018c895f3fdf0b2b79788547bf80a400724336
709,835
import math def get_angle(p1, p2): """Get the angle between two points.""" return math.atan2(p2[1] - p1[1], p2[0] - p1[0])
a29ea1ed74a6c071cf314d1c38c6e2f920bd1c3a
709,836
def simulation_test(**kwargs): """Decorate a unit test and mark it as a simulation test. The arguments provided to this decorator will be passed to :py:meth:`~reviewbot.tools.testing.testcases.BaseToolTestCase .setup_simulation_test`. Args: **kwargs (dict): Keyword arguments to pass during setup. Returns: callable: The new unit test function. """ def _dec(func): func.simulation_setup_kwargs = kwargs return func return _dec
56aa51374e66bb765bfc3d4da51e3254d06c0b55
709,839
def region_filter(annos, annotation): """filter for Region annotations. The 'time' parameter can match either 'time' or 'timeEnd' parameters. """ result = [] for anno in annos: time = annotation.get("time") timeEnd = annotation.get("timeEnd") for key in ['text', 'tags']: if anno.get(key) != annotation.get(key): continue if anno.get("regionId") == 0: continue if anno.get("time") not in [time, timeEnd]: continue result.append(anno) return result
3ca4c6ba39d44370b3022f5eb17a25e0e1c9f056
709,840
def social_bonus_count(user, count): """Returns True if the number of social bonus the user received equals to count.""" return user.actionmember_set.filter(social_bonus_awarded=True).count() >= count
b2469833f315410df266cd0a9b36933edb1f9ac6
709,842
def read_labels(labels_path): """Reads list of labels from a file""" with open(labels_path, 'rb') as f: return [w.strip() for w in f.readlines()]
3ebc61c76dd1ae83b73aa8b77584661c08a51321
709,844
def _gcs_uri_rewriter(raw_uri): """Rewrite GCS file paths as required by the rewrite_uris method. The GCS rewriter performs no operations on the raw_path and simply returns it as the normalized URI. The docker path has the gs:// prefix replaced with gs/ so that it can be mounted inside a docker image. Args: raw_uri: (str) the raw GCS URI, prefix, or pattern. Returns: normalized: a cleaned version of the uri provided by command line. docker_path: the uri rewritten in the format required for mounting inside a docker worker. """ docker_path = raw_uri.replace('gs://', 'gs/', 1) return raw_uri, docker_path
6e476860cb175dd2936cc0c080d3be1d09e04b77
709,845
def remove_apostrophe(text): """Remove apostrophes from text""" return text.replace("'", " ")
c7d918e56646a247564a639462c4f4d26bb27fc4
709,846
def generate_initials(text): """ Extract initials from a string Args: text(str): The string to extract initials from Returns: str: The initials extracted from the string """ if not text: return None text = text.strip() if text: split_text = text.split(" ") if len(split_text) > 1: return (split_text[0][0] + split_text[-1][0]).upper() else: return split_text[0][0].upper() return None
709e53392c790585588da25290a80ab2d19309f8
709,847
def part_allocation_count(build, part, *args, **kwargs): """ Return the total number of <part> allocated to <build> """ return build.getAllocatedQuantity(part)
84c94ca4e1b1006e293851189d17f63fc992b420
709,848
def __parse_sql(sql_rows): """ Parse sqlite3 databse output. Modify this function if you have a different database setup. Helper function for sql_get(). Parameters: sql_rows (str): output from SQL SELECT query. Returns: dict """ column_names = ['id', 'requester', 'item_name', 'custom_name', 'quantity', 'crafting_discipline', 'special_instruction', 'status', 'rarity', 'resource_provided', 'pub-date', 'crafter', 'stats'] request_dict = {str(row[0]): {column_names[i]: row[i] for i,_ in enumerate(column_names)} for row in sql_rows} return request_dict
09c61da81af069709dd020b8643425c4c6964137
709,850
import json def load_default_data() -> dict[str, str]: """Finds and opens a .json file with streamer data. Reads from the file and assigns the data to streamer_list. Args: None Returns: A dict mapping keys (Twitch usernames) to their corresponding URLs. Each row is represented as a seperate streamer. For example: { "GMHikaru":"https://www.twitch.tv/GMHikaru" } """ with open("statum\static\streamers.json", "r") as default_streamers: streamer_list: dict[str, str] = json.load(default_streamers) default_streamers.close() return streamer_list
bfeef64922fb4144228e031b9287c06525c4254d
709,851
def get_value_key(generator, name): """ Return a key for the given generator and name pair. If name None, no key is generated. """ if name is not None: return f"{generator}+{name}" return None
0ad630299b00a23d029ea15543982125b792ad53
709,852
def int_to_bigint(value): """Convert integers larger than 64 bits to bytearray Smaller integers are left alone """ if value.bit_length() > 63: return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True) return value
0f2d64887dc15d1902b8e10b0257a187ed75187f
709,854
def convert_where_clause(clause: dict) -> str: """ Convert a dictionary of clauses to a string for use in a query Parameters ---------- clause : dict Dictionary of clauses Returns ------- str A string representation of the clauses """ out = "{" for key in clause.keys(): out += "{}: ".format(key) #If the type of the right hand side is string add the string quotes around it if type(clause[key]) == str: out += '"{}"'.format(clause[key]) else: out += "{}".format(clause[key]) out += "," out += "}" return out
8b135c799df8d16c116e6a5282679ba43a054684
709,863
def truncate_string(string: str, max_length: int) -> str: """ Truncate a string to a specified maximum length. :param string: String to truncate. :param max_length: Maximum length of the output string. :return: Possibly shortened string. """ if len(string) <= max_length: return string else: return string[:max_length]
c7d159feadacae5a692b1f4d95da47a25dd67c16
709,864
def clamp(minVal, val, maxVal): """Clamp a `val` to be no lower than `minVal`, and no higher than `maxVal`.""" return max(minVal, min(maxVal, val))
004b9a393e69ca30f925da4cb18a8f93f12aa4ef
709,868
def notNone(arg,default=None): """ Returns arg if not None, else returns default. """ return [arg,default][arg is None]
71e6012db54b605883491efdc389448931f418d0
709,872
import hashlib def calculate_hash(filepath, hash_name): """Calculate the hash of a file. The available hashes are given by the hashlib module. The available hashes can be listed with hashlib.algorithms_available.""" hash_name = hash_name.lower() if not hasattr(hashlib, hash_name): raise Exception('Hash algorithm not available : {}'\ .format(hash_name)) with open(filepath, 'rb') as f: checksum = getattr(hashlib, hash_name)() for chunk in iter(lambda: f.read(4096), b''): checksum.update(chunk) return checksum.hexdigest()
975fe0a2a4443ca3abc67ed950fb7200409f2497
709,878
def deep_copy(obj): """Make deep copy of VTK object.""" copy = obj.NewInstance() copy.DeepCopy(obj) return copy
c00c4ff44dad5c0c018152f489955f08e633f5ed
709,880
def matrix2list(mat): """Create list of lists from blender Matrix type.""" return list(map(list, list(mat)))
9b4b598eb33e4d709e15fd826f23d06653659318
709,890
def get_height(img): """ Returns the number of rows in the image """ return len(img)
765babc9fbc1468ef5045fa925843934462a3d32
709,893
def sum_squares(n): """ Returns: sum of squares from 1 to n-1 Example: sum_squares(5) is 1+4+9+16 = 30 Parameter n: The number of steps Precondition: n is an int > 0 """ # Accumulator total = 0 for x in range(n): total = total + x*x return total
669a5aa03a9d9a9ffe74e48571250ffa38a7d319
709,895
def save(self, fname="", ext="", slab="", **kwargs): """Saves all current database information. APDL Command: SAVE Parameters ---------- fname File name and directory path (248 characters maximum, including the characters needed for the directory path). An unspecified directory path defaults to the working directory; in this case, you can use all 248 characters for the file name. ext Filename extension (eight-character maximum). slab Mode for saving the database: ALL - Save the model data, solution data and post data (element tables, etc.). This value is the default. MODEL - Save the model data (solid model, finite element model, loadings, etc.) only. SOLU - Save the model data and the solution data (nodal and element results). Notes ----- Saves all current database information to a file (File.DB). In interactive mode, an existing File.DB is first written to a backup file (File.DBB). In batch mode, an existing File.DB is replaced by the current database information with no backup. The command should be issued periodically to ensure a current file backup in case of a system "crash" or a "line drop." It may also be issued before a "doubtful" command so that if the result is not what was intended the database may be easily restored to the previous state. A save may be time consuming for large models. Repeated use of this command overwrites the previous data on the file (but a backup file is first written during an interactive run). When issued from within POST1, the nodal boundary conditions in the database (which were read from the results file) will overwrite the nodal boundary conditions existing on the database file. Internal nodes may be created during solution (for example, via the mixed u-P formulation or generalized plane strain option for current- technology elements, the Lagrangian multiplier method for contact elements or the MPC184 elements, or the quadratic or cubic option of the BEAM188 and PIPE288 elements). It is sometimes necessary to save the internal nodes in the database for later operations, such as cutting boundary interpolations (CBDOF) for submodeling. To do so, issue the SAVE command after the first SOLVE command. In general, saving after solving is always a good practice. This command is valid in any processor. """ return self.run(f"SAVE,{fname},{ext},,{slab}", **kwargs)
ddc79dc0f54e32d6cd96e115ad9842c1689c17b1
709,900
def get_dict_or_generate(dictionary, key, generator): """Get value from dict or generate one using a function on the key""" if key in dictionary: return dictionary[key] value = generator(key) dictionary[key] = value return value
e31cd2b6661cf45e5345ce57d1e628174e6fd732
709,902
import random def get_random_instance() -> random.Random: """ Returns the Random instance in the random module level. """ return random._inst
ee66055275153ce8c3eae67eade6e32e50fe1d79
709,904
import cgitb def FormatException(exc_info): """Gets information from exception info tuple. Args: exc_info: exception info tuple (type, value, traceback) Returns: exception description in a list - wsgi application response format. """ return [cgitb.handler(exc_info)]
733c2170a08f9880f8c191c1c6a52ee1ab455b7f
709,905
def get_smallerI(x, i): """Return true if string x is smaller or equal to i. """ if len(x) <= i: return True else: return False
1588ef998f4914aa943a063546112766060a9cbf
709,908
def unfold(raw_log_line): """Take a raw syslog line and unfold all the multiple levels of newline-escaping that have been inflicted on it by various things. Things that got python-repr()-ized, have '\n' sequences in them. Syslog itself looks like it uses #012. """ lines = raw_log_line \ .replace('#012', '\n') \ .replace('\\n', '\n') \ .splitlines() return lines
9e23bdd82ac15086468a383a1ef98989aceee25e
709,909
from datetime import datetime def ts(timestamp_string: str): """ Convert a DataFrame show output-style timestamp string into a datetime value which will marshall to a Hive/Spark TimestampType :param timestamp_string: A timestamp string in "YYYY-MM-DD HH:MM:SS" format :return: A datetime object """ return datetime.strptime(timestamp_string, '%Y-%m-%d %H:%M:%S')
1902e75ab70c7869686e3a374b22fa80a6dfcf1a
709,911
def nl_to_break( text ): """ Text may have newlines, which we want to convert to <br /> when formatting for HTML display """ text=text.replace("<", "&lt;") # To avoid HTML insertion text=text.replace("\r", "") text=text.replace("\n", "<br />") return text
d2baf1c19fae686ae2c4571416b4cad8be065474
709,912
import requests import logging def get_page_state(url): """ Checks page's current state by sending HTTP HEAD request :param url: Request URL :return: ("ok", return_code: int) if request successful, ("error", return_code: int) if error response code, (None, error_message: str) if page fetching failed (timeout, invalid URL, ...) """ try: response = requests.head(url, verify=False, timeout=10) except requests.exceptions.RequestException as exception: logging.error(exception) return None, "Error fetching page" if response.status_code >= 400: return "error", response.status_code return "ok", response.status_code
f7b7db656968bed5e5e7d332725e4d4707f2b14b
709,913
def unique(list_, key=lambda x: x): """efficient function to uniquify a list preserving item order""" seen = set() result = [] for item in list_: seenkey = key(item) if seenkey in seen: continue seen.add(seenkey) result.append(item) return result
57c82081d92db74a7cbad15262333053a2acd3a7
709,914
import random def weight(collection): """Choose an element from a dict based on its weight and return its key. Parameters: - collection (dict): dict of elements with weights as values. Returns: string: key of the chosen element. """ # 1. Get sum of weights weight_sum = sum([value for value in collection.values()]) # 2. Generate random number between 1 and sum of weights random_value = random.randint(1, weight_sum) # 3. Iterate through items for key, value in collection.items(): # 4. Subtract weight of each item from random number random_value -= value # 5. Compare with 0, if <= 0, that item has been chosen if random_value <= 0: return key # 6. Else continue subtracting # Should not reach here. raise ValueError("Invalid argument value.")
383ddadd4a47fb9ac7be0292ecc079fcc59c4481
709,917
from typing import List def make_matrix(points: List[float], degree: int) -> List[List[float]]: """Return a nested list representation of a matrix consisting of the basis elements of the polynomial of degree n, evaluated at each of the points. In other words, each row consists of 1, x, x^2, ..., x^n, where n is the degree, and x is a value in points. Preconditions: - degree < len(points) >>> make_matrix([1, 2, 3], 2) [[1, 1, 1], [1, 2, 4], [1, 3, 9]] """ matrix = [] for point in points: row = [point ** index for index in range(degree + 1)] matrix.append(row) return matrix
d8fbea3a0f9536cb681b001a852b07ac7b17f6c2
709,918
def adjust_seconds_fr(samples_per_channel_in_frame,fs,seconds_fr,num_frame): """ Get the timestamp for the first sample in this frame. Parameters ---------- samples_per_channel_in_frame : int number of sample components per channel. fs : int or float sampling frequency. seconds_fr : int or float seconds for this frame (from frame header) num_frame : int frame number (from frame header). Returns ------- time_first_frame : float timestamp [s] corresponding to the first sample of this frame. """ seconds_per_frame=samples_per_channel_in_frame/float(fs) time_first_sample=float(seconds_fr)+num_frame*seconds_per_frame return(time_first_sample)
a19775db3ebcdbe66b50c30bc531e2980ca10082
709,919
def is_success(msg): """ Whether message is success :param msg: :return: """ return msg['status'] == 'success'
43ecbf3c7ac8d03ce92ab059e7ec902e51505d0a
709,921
def list_strip_comments(list_item: list, comment_denominator: str = '#') -> list: """ Strips all items which are comments from a list. :param list_item: The list object to be stripped of comments. :param comment_denominator: The character with which comment lines start with. :return list: A cleaned list object. """ _output = list() for _item in list_item: if not _item[0] == comment_denominator: _output.append(_item) return _output
e5dd6e0c34a1d91586e12e5c39a3a5413746f731
709,922