content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def productory(matrix_list): """ Multiplies from lest to right the matrices in the list matrix_list. Arguments ---------- matrix_list : list of numpy.ndarray List of matrices to be multiplied. Returns ---------- M : numpy.ndarray Product of the matrices in matrix_list. """ # start wiht the first elment and multy all the others A = matrix_list[0] for B in matrix_list[1:]: A = A.dot(B) return A
f2f15f1e68329c7988a04ff4d25ed339a1277957
414,514
def writeDictCfg(dct, cfgname): """ Write out a config file from a dictionary. - Entries: 'key=value\n' :param dct: Dictionary to be written as a config file. :param cfgname: Filename or path/to/filename for config file. :return: Config filename or path/to/filename """ cfg_out = open(cfgname, 'w') for k, v in dct.iteritems(): cfg_out.write('%s=%s\n' % (str(k), str(v))) cfg_out.close() return cfgname
05135322f0759637db71681a39ca4cbf6948fd4f
308,624
from textwrap import dedent def trim(text): """Like textwrap.dedent, but also eliminate leading and trailing lines if they are whitespace or empty. This is useful for writing code as triple-quoted multi-line strings. """ lines = text.split('\n') if len(lines) > 0: if len(lines[0]) == 0 or lines[0].isspace(): lines = lines[1 : ] if len(lines) > 0: if len(lines[-1]) == 0 or lines[-1].isspace(): lines = lines[ : -1] return dedent('\n'.join(lines))
0c1bc710b6bf1e9bb7b42d990942423c8ebf7cf9
594,126
def generate_div(i): """ Generate a div with the style-<i> class. eg. >>> generate_div(0) "<div class="box style-0"></div> """ return '<div class="box style-' + str(i) + '"></div>'
1984414e1350f2ad036f4f4c6b42ef90deabfb5d
554,195
import re def remove_url(text): """ Supprime les URLs :param text: texte à transformer :return: texte transformé """ return re.sub(r'http\S+', '', text)
d0f3716808863d5e868da1efc4a7bb16ffa47ac1
705,155
from typing import Any from typing import Optional def _guess_crs_str(crs_spec: Any)->Optional[str]: """ Returns a string representation of the crs spec. Returns `None` if it does not understand the spec. """ if isinstance(crs_spec, str): return crs_spec if hasattr(crs_spec, 'to_epsg'): epsg = crs_spec.to_epsg() if epsg is not None: return 'EPSG:{}'.format(crs_spec.to_epsg()) if hasattr(crs_spec, 'to_wkt'): return crs_spec.to_wkt() return None
11328ea9d1cc955faa63c37a64d115e8252b0c57
686,799
def none_formatter(error): """ Formatter that does nothing, no escaping HTML, nothin' """ return error
a08468a71060cf6f629c6f8b9b9e0c1dabc5f60d
660,102
def egg_drop(n: int, k: int) -> int: """ What is the minimum number of trials we need to drop eggs to determine which floors of a building are safe for dropping eggs, given n eggs and k floors? :param n: number of eggs :param k: number of floors :return: the minimum number of trials >>> egg_drop(1, 5) 5 >>> egg_drop(2,36) 8 """ # Base cases. # If we have one egg, we need to try each floor. if n == 1: return k # If we have one floor, we need to try it. if k == 1 or k == 0: return k # Drop an egg from floor x: # 1. If it breaks, then we know the floor is <= x, and we have n-1 eggs left to do it, so E(n-1, x). # 2. If it doesn't break, then we know the floor is > x (which means k-x floors to try( and we have n eggs left # to do it, so E(n, k-x). return 1 + min([max(egg_drop(n-1, x-1), egg_drop(n, k-x)) for x in range(1,k+1)])
c12426c93bedb721393b5ef4e165c834d018784e
73,384
import requests import re def extract_conceptnet(phrase): """Access ConceptNet API and read relational triples as well as their weight and simple example""" url_head = 'http://api.conceptnet.io/c/en/' # access ConceptNet API raw_json = requests.get(url_head + phrase).json() edges = raw_json['edges'] if not edges: # if edges is empty, which means ConceptNet doesn't contain such concept or node return None concepts = [] for edge in edges: triple = re.findall(r'/a/\[/r/(.*?)/.*?,/c/en/(.*?)/.*?,/c/en/(.*?)/.*?\]', edge['@id'])[0] # ERE triple surface_text = re.sub(r'[\[\]]', '', '' if edge['surfaceText'] is None else edge['surfaceText']) # example weight = edge['weight'] # weight concepts.append({'Triple': triple, 'weight': weight, 'example': surface_text}) return concepts
0a8bdc41b1ed8a5f403804eb27a01f7a5d5c2380
551,419
from typing import Union def get_error_message(traceback: str) -> Union[str, None]: """Extracts the error message from the traceback. If no error message is found, will return None. Here's an example: input: Traceback (most recent call last): File "example_code.py", line 2, in <module> import kivy ModuleNotFoundError: No module named 'kivy' output: ModuleNotFoundError: No module named 'kivy' """ error_lines = traceback.splitlines() return error_lines[-1]
bb1ccbb55e15a9670efbb4ddc71b22a35cfd9b17
683,887
import re def get_unique_name_from_tag(image_uri): """ Return the unique from the image tag. :param image_uri: ECR image URI :return: unique name """ return re.sub('[^A-Za-z0-9]+', '', image_uri)
e963c292c0e41c0d4db2b2a59d962ee51ab3874c
208,574
def _enforce_shape(points): """Ensure that datapoints are in a shape of (2, N).""" if points.shape[0] != 2: return points.T return points
b23a9afd4bc4bfa0f09a2377b723d0b36d08fe51
188,587
def parseLineForExpression(line): """Return parsed SPDX expression if tag found in line, or None otherwise.""" p = line.partition("SPDX-License-Identifier:") if p[2] == "": return None # strip away trailing comment marks and whitespace, if any expression = p[2].strip() expression = expression.rstrip("/*") expression = expression.strip() return expression
654cd788f92971f25caf3b4c1cae90d534333ed7
236,412
import hashlib def hash_bytes(data: bytes): """Compute the same hash on bytes as git would (e.g. via git hash-object). The hash is the sha1 digest, but with a header added to the bytes first: the word "blob", followed by a space, followed by the content length, followed by a zero byte. """ assert isinstance(data, bytes) size = len(data) header = ("blob %d" % size).encode("ascii") + b"\0" blob = header + data m = hashlib.sha1() m.update(blob) return m.hexdigest()
6a5054ba3393e81d2c35a014fa8c2665fda9517e
198,523
def add_suffix_to_parameter_set(parameters, suffix, divider='__'): """ Adds a suffix ('__suffix') to the keys of a dictionary of MyTardis parameters. Returns a copy of the dict with suffixes on keys. (eg to prevent name clashes with identical parameters at the Run Experiment level) """ suffixed_parameters = {} for p in parameters: suffixed_parameters[u'%s%s%s' % (p['name'], divider, suffix)] = p['value'] return suffixed_parameters
39c184a6d836270da873b4c2e8c33e9a1d29f073
686,867
def wpm(typed, elapsed): """Return the words-per-minute (WPM) of the TYPED string.""" assert elapsed > 0, 'Elapsed time must be positive' # BEGIN PROBLEM 4 return len(typed) / 5 * 60 / elapsed # END PROBLEM 4
9b131376e0bd4b1f3eb826bdf61dd46534fed452
255,077
from typing import Optional import pkg_resources def get_installed_model_version(name: str) -> Optional[str]: """ Return the version of an installed package """ try: return pkg_resources.get_distribution(name).version except pkg_resources.DistributionNotFound: return None
ecfa4c092aed284ee1cd66f08b610f5d5c8fab20
145,062
def split_into_groups(s, length=3): """splits given string into groups of length""" if length < 0: raise TypeError('split length must be >= 0') s = ''.join(reversed(s)) groups = [s[i:i + length] for i in range(0, len(s), length)] return [''.join(reversed(g)) for g in reversed(groups)]
7ac764d65c3f6e7e3240433ea22a8a97ac8da014
419,377
def get_sequence(center_idx, half_len, sample_rate, max_num_frames): """ Sample frames among the corresponding clip. Args: center_idx (int): center frame idx for current clip half_len (int): half of the clip length sample_rate (int): sampling rate for sampling frames inside of the clip max_num_frames (int): number of expected sampled frames Returns: seq (list): list of indexes of sampled frames in this clip. """ seq = list(range(center_idx - half_len, center_idx + half_len, sample_rate)) for seq_idx in range(len(seq)): if seq[seq_idx] < 0: seq[seq_idx] = 0 elif seq[seq_idx] >= max_num_frames: seq[seq_idx] = max_num_frames - 1 return seq
e0622d4f2eea08a572c8ff6d332744f94729ab6d
495,492
def format_file(path, tool): """Format file with clang-format and return True.""" tool("-i", path) return True
f18e74c25b68f60ae1e468a88ec0a4301b5be506
101,751
import re def preprocess_title(text): """Pre-process an episode title string by removing unnecessary quotations, brackets, and whitespaces.""" text = re.sub('[\(\[].*?[\)\]]', '', text) # remove brackets text = re.sub(' +', ' ', text) # remove multiple whitespaces text = text.strip().strip('\"').strip() # strip ""s and possible leftover whitespaces return text
2cb1a8fdbda3a3f87bf98d1fde10cdd23c344063
396,929
def clear_sesam_attributes(sesam_object: dict): """ Return same dict but without properties starting with "_" :param sesam_object: input object from Sesam :return: object cleared from Sesam properties """ return {k: v for k, v in sesam_object.items() if not k.startswith('_')}
9dc1c59cacb29b34d1f650803ad44d2febc7d940
621,242
import torch def remove_first_sv(emb, first_sv): """ Projects out the first singular value (first_sv) from the embedding (emb). Inputs: emb: torch Tensor shape (glove_dim) first_sv: torch Tensor shape (glove_dim) Returns: new emb: torch Tensor shape (glove_dim) """ # Calculate dot prod of emb and first_sv using torch.mm: # (1, glove_dim) x (glove_dim, 1) -> (1,1) -> float dot_prod = torch.mm(torch.unsqueeze(emb, 0), torch.unsqueeze(first_sv, 1)).item() return emb - first_sv * dot_prod
92eed8657e9e57348efb3603e678dd9ffcd7cddb
328,865
def last_slash_check(a_path): """Check if the path provided has an ending slash. If it does, remove it and return a revised path. If not, do nothing. """ if a_path[-1] == '/': new_path = a_path[:-1] else: new_path = a_path return new_path
8c0ed34b214f4137ceb72f4c9915e9151e5292b5
276,159
def export_sheet(ss, sheet_id, export_format, export_path, sheet_name): """ Exports a sheet, given export filetype and location. Allows export format 'csv', 'pdf', or 'xlsx'. :param ss: initialized smartsheet client instance :param sheet_id: int, required; sheet id :param export_format: str, required; 'csv', 'pdf', or 'xlsx' :param export_path: str, required; filepath to export sheet to :param sheet_name: str, required; name of sheet exported :return: str, indicating failure or success, with path, filename, extension """ if export_format == 'csv': ss.Sheets.get_sheet_as_csv(sheet_id, export_path) elif export_format == 'xlsx': ss.Sheets.get_sheet_as_excel(sheet_id, export_path) elif export_format == 'pdf': # there is an optional paperSize parameter; default is A1 ss.Sheets.get_sheet_as_pdf(sheet_id, export_path) if export_format == 'csv' or export_format == 'xlsx' or export_format == 'pdf': return 'Sheet exported to {}{}.{}'.format(export_path, sheet_name, export_format) else: return 'export_format \'{}\' is not valid. Must be \'csv\', \'pdf\', or \'xlsx\''.format(export_format)
76b49fa0904140571eb84526f6021448db54dea9
24,924
def resolve_cardinality(class_property_name, class_property_attributes, class_definition): """Resolve class property cardinality from yaml definition""" if class_property_name in class_definition.get('required', []): min_count = '1' elif class_property_name in class_definition.get('heritable_required', []): min_count = '1' else: min_count = '0' if class_property_attributes.get('type') == 'array': max_count = class_property_attributes.get('maxItems', 'm') min_count = class_property_attributes.get('minItems', 0) else: max_count = '1' return f'{min_count}..{max_count}'
fed27e5c326842f5895f98e3f5e9fb5852444b07
54,153
def scan_uv_parsing(inp, uv_alpha_univariate, uv_fold_change, uv_decision_tree, uv_paired_samples, uv_correction, uv_labelsize_vulcano, uv_figsize_vulcano, uv_label_full_vulcano): """ Initialize univariate analysis. Initialization function for univariate analysis. inp : dict Method dictionary. uv_alpha_univariate : float Probability of error. uv_fold_change : float Fold change threshold. uv_decision_tree : bool Use univariate decision tree. uv_paired_samples : bool Dependent or independent samples. uv_correction : str Multi comparison correction. uv_labelsize_vulcano : int Labelsize for vulcano plot. uv_figsize_vulcano : tuple Figsize for vulcano plot. uv_label_full_vulcano : bool Use full labels in vulcano plot. Returns ------- inp : dict Method dictionary. """ # Parameter inp['uv_fold_change'] = uv_fold_change inp['uv_alpha'] = uv_alpha_univariate inp['uv_correction'] = uv_correction inp['uv_decision_tree'] = uv_decision_tree inp['uv_paired_samples'] = uv_paired_samples # Plots inp['uv_labelsize_vulcano'] = uv_labelsize_vulcano inp['uv_figsize_vulcano'] = uv_figsize_vulcano inp['uv_label_vulcano'] = uv_label_full_vulcano return inp
f217acea354f91c141b3845f5234e9b27f3ec4e0
183,241
from typing import Sequence from typing import Optional def split_round_robin(values: Sequence, num_procs: Optional[int]) -> Sequence[Sequence]: """ Split values into a `num_procs` sequences. ```python split_round_robin(range(10), 3) == [[0, 3, 6, 9], [1, 4, 7], [2, 5, 8]] ``` """ if num_procs is None: return [[vals] for vals in values] out = [[] for _ in range(num_procs)] for i, vals in enumerate(values): out[i % num_procs].append(vals) return out
4bfbd5861a4555140b64a872404f0b6702029bd9
254,813
def get_std_dev(total_size: int, comm_size: int) -> float: """ In community generation, larger communities should have a smaller standard deviation (representing tighter-knit communities). This generates a std dev based on the ratio of the number of nodes in this community to the number of nodes in the total graph. Since we want a larger standard deviation for a smaller ratio, we take 1/ratio, which goes from total_size (for comm_size=1) to 1 (for ratio = 1). We divide this by total_size to get a normalised value, and then by 3 so that we can easily go three standard deviations without leaving the range. """ ratio = comm_size / total_size # range 0 to 1. return (1 / ratio) / (total_size * 3)
cb0ddaedee57eb98df337cd3a23e16d648f4a389
307,415
from typing import Tuple def extgcd(a: int, b: int) -> Tuple[int, int, int]: """a * x + b * y = gcd(a, b) See: https://qiita.com/drken/items/b97ff231e43bce50199a https://www.youtube.com/watch?v=hY2FicqnAcc O(gcd(a, b)) """ if b == 0: return (a, 1, 0) g, x, y = extgcd(b, a % b) return g, y, x - (a // b) * y
5aa89cd563685ea95b84d94bfbeb7df247fa705d
529,014
def epsilon(n): """ Compute Jacobi symbol (5/n). """ if n % 5 in [1, 4]: return 1 elif n % 5 in [2, 3]: return -1 else: return 0
5c335cd59cbbe8a130763f1ebac2887afaac3e48
61,649
import requests def http_get(url, api_uri, token, **params): """ Helper function to perform an http get, with optional parameters :param url: The url of the endpoint :param api_url: The URI of the specific api :param token: The access token :param params: kwargs for optional parameter to the http get :return: The full requests response """ response = requests.get( url + '/' + api_uri, params=params, headers={'Authorization': 'JWT ' + token}, ) response.raise_for_status() return response
d902b9475677d3350f55032516cd0ab112092998
533,802
def dict_reverse(dictionary): """ Reverse a dictionary. If values are not unique, only one will be used. Which one is not specified Args: dictionary (dict): dict to reverse Returns: reversed (dict): reversed dictionary """ return {v: k for k, v in dictionary.items()}
056340e45218f8c1aeb3682bff918b83bf6779f4
290,305
def dfs(i, j, mat, visited): """ Applies Depth first search. Args: i (int): The row index of the src element j (int): The column index of the src element mat (List[List[int]]): The input matrix visited (List[List[bool]]): The visited matrx """ if visited[i][j]: return None visited[i][j] = True # Checking the adjacent vertices whether they # are land masses # left if j - 1 >= 0 and not visited[i][j-1] and mat[i][j-1] == 1: dfs(i, j-1, mat, visited) # right if j + 1 < len(mat[0]) and not visited[i][j+1] and mat[i][j+1] == 1: dfs(i, j+1, mat, visited) # top if i - 1 >= 0 and not visited[i-1][j] and mat[i-1][j] == 1: dfs(i-1, j, mat, visited) # bottom if i + 1 < len(mat) and not visited[i + 1][j] and mat[i+1][j] == 1: dfs(i+1, j, mat, visited) return None
ba99534759da7f5ead9862318a959c3aae1619a6
266,495
import importlib def import_class_from_string(class_string): """ Import (and return) a class from its name Arguments keywords: class_string -- name of class to import """ module_name, class_name = class_string.rsplit('.', 1) module = importlib.import_module(module_name) return getattr(module, class_name)
f852c29d320ea3b00742dc0077c2318f0384e181
533,661
import re def getIndsPropString(wkwdata): """Get the string for the property containing the indices of train, validation and test data""" allAttributes = dir(wkwdata) r = re.compile('^data_.*_inds$') return list(filter(r.match, allAttributes))
c3e4b95c4f1a5c17cf14c730d79a002eb768d91b
370,897
def parse_errata_checksum(data): """ Parse the errata checksum and return the bz2 checksum """ for line in data.splitlines(): if line.endswith('errata.latest.xml.bz2'): return line.split()[0]
d3de13d48b495793a7d7c82f1b8656332bf5ea39
359,950
def _strip_whitespace(text_content: str) -> str: """Return text_content with leading and trailing whitespace removed """ output_content: str = str(text_content) if text_content is not None and len(text_content) > 0: output_content = text_content.strip() return output_content
6dda9623013f9ec7289e1098f49d8f991fbe2079
616,055
def identity(x): """Identity activation function. Input equals output. Args: x (ndarray): weighted sum of inputs. """ return x
86f6b926244b517023d34b76dbef10b4ae5dcfce
674,846
def to_lowercase(text: str) -> str: """ Returns the given text with all characters in lowercase. :param text: The text to be converted to lowercase. (String) :return: The given text with all characters in lowercase. (String) """ text = text.lower() return text
79ddb531bac0a4f6d19045ffe5bd2a01656545ed
419,690
def field_names(model): """Return a set of all field names for a model.""" return {field.name for field in model._meta.get_fields()}
0e89e793c07a567a1c016c304fa652bf621f06ac
136,141
def read_define(filename, define): """ Read the value of a #define from a file. filename is the name of the file. define is the name of the #define. None is returned if there was no such #define. """ f = open(filename) for l in f: wl = l.split() if len(wl) >= 3 and wl[0] == "#define" and wl[1] == define: # Take account of embedded spaces. value = ' '.join(wl[2:])[1:-1] break else: value = None f.close() return value
0b696cb9f20b68bb708633b8ef5b92afb6c90a27
334,945
def single_high_initializer(low_genome='LOW', high_genome='HIGH'): """Generate a population that contains two types of genomes: all of the population will be 'LOW' except for one, which will be 'HIGH'.""" first = True def create(): nonlocal first if first: first = False return high_genome else: return low_genome return create
1d11f405f715e2e4fecd85ca5fdf4def00cefdf9
456,509
def dist(x, y, S): """ Mahalanobis distance: d(x,y) = \\sqrt( (x-y)^T*S^-1*(x-y) ) where S^-1 = diag(1/s_i^2 for s_i in std) Input must be torch.Tensor((1,N)) for x,y,S """ d = ((x-y).pow(2)/S).sum(1).sqrt() return d
676171a62ca828adbc140177c497c15124084817
52,190
from typing import Any import logging def search(model: dict[str, Any], search_keys: list[str]) -> list: """ Search an AaC model structure by key(s). Searches a dict for the contents given a set of keys. Search returns a list of the entries in the model that correspond to those keys. This search will traverse the full dict tree, including embedded lists. Typical usage example: Let's say you have a dict structure parsed from the following AaC yaml. data: name: MyData fields: - name: one type: string - name: two type: string required: - one You know the structure of the specification and need to iterate through each field. The search utility method simplifies that for you. for field in util.search(my_model, ["data", "fields"]): print(f"field_name: {field["name"]} field_type {field["type"]}") The above example demonstrates a complex type being returned as a dict. Search will also provide direct access to simple types in the model. for field_name in util.search(my_model, ["data", "fields", "name"]): print(f"field_name: {field_name}") Args: model: The model to search. This is often the value taken from the dict returned by aac.parser.parse(<aac_file>). search_keys: A list of strings representing keys in the model dict hierarchy. Returns: Returns a list of found data items based on the search keys. """ done = False ret_val = [] keys = search_keys.copy() # first make sure there is a key to search for if len(keys) == 0 or not isinstance(model, dict): logging.error(f"invalid arguments: {keys}, {type(model)}") return [] search_key = keys.pop(0) final_key = len(keys) == 0 model_value = None # see if the key exists in the dict if search_key in model: model_value = model[search_key] if final_key: if isinstance(model_value, list): ret_val = model_value done = True else: ret_val.append(model_value) done = True # it isn't the final key and the value is a dict, so continue searching if not done and isinstance(model_value, dict): if isinstance(model_value, dict): ret_val = search(model[search_key], keys) done = True # it isn't the final key and the value is a list, so search each value if not done and isinstance(model_value, list): for model_item in model_value: if isinstance(model_item, dict): ret_val = ret_val + (search(model_item, keys)) else: logging.error("keys exceeds depth of the dict to search") done = True done = True # not an error, just zero results else: logging.info(f"keys[{search_keys}] not found in model") done = True return ret_val
574522c8c6a94e231ce819271d3db807bbb3bed3
392,553
def describe(data_matrix): """Get the shape of a sparse matrix and its average nnz.""" return 'Instances: %3d ; Features: %d with an avg of %d per instance' % \ (data_matrix.shape[0], data_matrix.shape[1], data_matrix.getnnz() / data_matrix.shape[0])
98cd820dd9c2728a5ba1a59693ca480cb3c88f13
111,256
import random def happens(prob): """ Trigger a random event to happen Arguments: prob {float} -- chances to return true Returns: [bool] -- if the random event happens """ chance = random.uniform(0,1) return chance <= prob
ca4f36317ede9e8d6fc9f7e50a41c876433631be
560,668
def rescale(var, dt): """ Rescale variable to fit dt, based on quantities library :param var: Variable to rescale :param dt: Time steps :return: Rescaled integer """ return (var.rescale(dt.units) / dt).magnitude.astype(int).item()
c7dffa2c0ac6b622716e2be3fbb7a926efad9404
185,038
def filter_instances_by_family(instances, family_name=None): """Yield instances whose 'familyName' custom parameter is equal to 'family_name'. """ return (i for i in instances if i.familyName == family_name)
3294c3f3dd0648defd1593688a87019a28b5adcd
345,526
def from_datastore(entity): """Translates Datastore results into the format expected by the application. Datastore typically returns: [Entity{key: (kind, id), prop: val, ...}] This returns: [ name, street, city, state, zip, open_hr, close_hr, phone, drink, rating, website ] where name, street, city, state, open_hr, close_hr, phone, drink, and website are Python strings and where zip and rating are Python integers """ if not entity: return None if isinstance(entity, list): entity = entity.pop() return [entity['name'],entity['street'],entity['city'],entity['state'],entity['zip'],entity['open_hr'],entity['close_hr'],entity['phone'],entity['drink'],entity['rating'],entity['website']]
24d274a1261aedeff976ee89c913c1ca73fa42d5
115,319
def _strip_unsafe_kubernetes_special_chars(string: str) -> str: """ Kubernetes only supports lowercase alphanumeric characters, "-" and "." in the pod name. However, there are special rules about how "-" and "." can be used so let's only keep alphanumeric chars see here for detail: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/ :param string: The requested Pod name :return: Pod name stripped of any unsafe characters """ return ''.join(ch.lower() for ch in list(string) if ch.isalnum())
f5a0e0f61aec408acfc4eee1745053e36a483a6a
99,410
import torch def kld_loss(mu, logvar, mean_reduction=True): """ First it computes the KLD over each datapoint in the batch as a sum over all latent dims. It returns the mean KLD over the batch size. The KLD is computed in comparison to a multivariate Gaussian with zero mean and identity covariance. Args: mu (torch.Tensor): the part of the latent vector that corresponds to the mean logvar (torch.Tensor): the log of the variance (sigma squared) mean_reduction (bool): Whether to perform mean reduction across batch (default is true) Returns: (torch.Tensor): KL divergence. """ mu = mu.flatten(1) logvar = logvar.flatten(1) kld_per_sample = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp(), dim = 1) if mean_reduction: return torch.mean(kld_per_sample, dim = 0) else: return kld_per_sample
9ce92de5d34a385bb095a6182da8ec09577ca42c
440,842
from datetime import datetime def format_bitmex_api_timestamp(timestamp: datetime) -> str: """Format BitMEX API timestamp.""" return timestamp.replace(tzinfo=None).isoformat()
fa657ca06a03921b07f69d6104389bc5daf5d782
461,550
def get_position_by_substring(tofind, list): """ Get index where `tofind` is a substring of the entry of `list` :param tofind: string to find in each element of `list` :param list: list to search through :return: index in `list` where `tofind` is found as a substring """ for i, e in enumerate(list): if tofind in e: return i
8836fe6cbb1279d21320c6048c45d36746aafc8a
666,778
def get_combined_params(*models): """ Returns the combine parameter list of all the models given as input. """ params = [] for model in models: params.extend(list(model.parameters())) return params
907beb6a48e7abfdb75cdb19ff5f5e166c62b612
360,654
def drop_irrelevant_features(df): """ Drop irrelevant columns from features set :param data_df: features_data :return: a dataframe of relevant features """ cols_to_exclude = ['index', 'level_0', 'id'] df = df.drop(cols_to_exclude, axis=1) return df
e5652dde05504843c88d117d23c2ea42e8e25ba8
544,366
def KGtoLB(mkg): """ Convertie une masse en kg vers lb note: 1 kg = 2.20462 lb :param mkg: masse [kg] :return mlb: masse [lb] """ mlb = mkg * 2.20462 return mlb
05ecbe4fb668b6c52da9c43243145cabc61699a2
573,043
def bounding_box(rects): """ Get a new Rect which circumscribes all the rects. :param list rects :return bounding Rect :rtype Rect """ top = float('inf') left = float('inf') bottom = 0 right = 0 for rect in rects: top_left, bottom_right = rect top = min(top, top_left[1]) left = min(left, top_left[0]) bottom = max(bottom, bottom_right[1]) right = max(right, bottom_right[0]) return ((left, top), (right, bottom))
9102db8bd9d34929ed1f9eb2c70c90ea00272632
465,958
def valid_line(line: str) -> bool: """ 行バリデーション Parameters ---------- line: str 行テキスト Returns ------- valid: bool validであるフラグ """ lstriped = line.lstrip() if len(lstriped) == 0: return False if lstriped[0] == '#': return False if lstriped[0] == '/': return False return True
569b34f80a77b765304ddb19fd9699c2e3909f99
529,304
def check_wide_data_for_blank_choices(choice_col, wide_data): """ Checks `wide_data` for null values in the choice column, and raises a helpful ValueError if null values are found. Parameters ---------- choice_col : str. Denotes the column in `wide_data` that is used to record each observation's choice. wide_data : pandas dataframe. Contains one row for each observation. Should contain `choice_col`. Returns ------- None. """ if wide_data[choice_col].isnull().any(): msg_1 = "One or more of the values in wide_data[choice_col] is null." msg_2 = " Remove null values in the choice column or fill them in." raise ValueError(msg_1 + msg_2) return None
a9564026133dea68f17ee9b099feec409828707a
651,028
from typing import Optional def flatten_dict( d: dict, s: str = '', exc: Optional[list] = None ) -> dict: """Reformat a multi-layer dictionary into a flat one. :param d: Input dict. :param s: Prefix to be added to keys. :param exc: List of keys to exclude from the resulting dict. :return: Reformatted dictionary. """ if exc is None: exc = [] u = {} for k, v in d.items(): if k in exc: u[k] = v else: if len(s): k = s + '_' + k if isinstance(v, dict): u |= flatten_dict(v, k) elif isinstance(v, list): u |= {k+'_'+str(i): vv for i, vv in enumerate(v)} else: u[k] = v print('') return u
28a0c80954bfa2d0f24ec5b408edbfe24e928c7a
304,974
import re def norm_freqs(data, expression, count_name=str, normalize=True, analyze=True): """Get frequencies (normalized = optional) of a regex pattern in a Series with one or more strings. Args: data (DataFrame): a dataframe with texts to extract frequencies from. expression (re.compile): a regex pattern to count occurrences of in each text. count_name (str, optional): a name for the counted feature. Defaults to str. normalize (bool, optional): [description]. Defaults to True. Returns: list: list of dicts with key = frequency name, value = frequency. """ # List to store frequencies # freqList = list() # Loop through each entry in the list of strings. # for e in stringList: # # Join to a regular string # text = ' '.join(e) # # Construct a dict for each entry with freuncies. # c = {count_name : len([char for char in text if char in expression])} # Get frequencies of a regex in a pandas column, normalize if set to True. c = data.apply(lambda x: len(re.findall( expression, x))/len(x) if normalize == True else len(re.findall(expression, x))) ### Adapted from https://stackoverflow.com/a/45452966 ### # Cast frequencies Series to list of dicts. cList = [{count_name: x[1]} for x in c.items()] ### Accessed 10-05-2021 ### if analyze == True: return cList else: return c
e497ad1db53b3b366a5f03f507f8cc1c34b9b213
185,480
import importlib def get_module(modulename): """Returns a module object for given Python module name using `importlib.import_module`.""" return importlib.import_module(modulename)
cfb55e25784a64fe516d2310ae38f7b846030021
291,593
def _create_default_branch_id(repo_url: str, default_branch_ref_id: str) -> str: """ Return a unique node id for a repo's defaultBranchId using the given repo_url and default_branch_ref_id. This ensures that default branches for each GitHub repo are unique nodes in the graph. """ return f"{repo_url}:{default_branch_ref_id}"
323d88f3e50343281952d701a18981f57055da04
234,528
def get_conv_output_shape_flattened(input_shape, structure): """ Input_shape: (Channels, Height, Width) of input image structure: List containing tuple (out_channels, kernel_size, stride, padding) per conv layer """ def get_layer_output(input, layer_structure): # See shape calculation in Conv2d docs: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html return int((input + 2*layer_structure[3] - 1*(layer_structure[1]-1) - 1) / layer_structure[2] + 1) h = input_shape[1] w = input_shape[2] c = structure[-1][0] for layer in structure: w = get_layer_output(w, layer) h = get_layer_output(h, layer) return w * h * c
e9355ef4728b0adde40b89d853728fb9a2efdc04
259,512
def remove_node(G, node): """ Wrapper around networkx.classes.graph.Graph.remove_node to return a dict mapping an incident node to its edge attributes """ rv = {} for edge in G.edges(node, data=True): u = edge[0] v = edge[1] edge_attr = edge[2] t = None if u == node: t = v else: t = u rv[t] = edge_attr G.remove_node(node) return rv
14404c6af08e4e82b3dcd755d6fee49c1f1ea3c9
477,149
import pkgutil def is_installed(package): """Check if a python package (Kipoi plugin) is installed Args: package (str): package/plugin name Returns: True if package/plugin is installed """ return pkgutil.find_loader(package) is not None
11329b5d826d390af96956fa9cbf04bb4baf359e
548,128
import random import string def generate_verification_code() -> str: """Generate a random 6-digit code Returns: str: a 6-digit code in string format .e.g '654874' """ return "".join(random.choices(string.digits + string.digits, k=6))
4b6a6891e73c93cd92a5d1fc6098ca6faa5dcd5b
573,883
import torch def create_eye_batch(batch_size, eye_size): """Creates a batch of identity matrices of shape Bx3x3 """ return torch.eye(eye_size).view( 1, eye_size, eye_size).expand(batch_size, -1, -1)
ae1171af3f13e4be03ddada62481f0dcd9c6b202
571,041
import io def read_file(path): """Returns all the lines of a file at path as a List""" file_lines = [] with io.open(path, mode="rt", encoding="utf-8") as the_file: file_lines = the_file.readlines() return file_lines
8e220e0b90ded168a1d1d8d37b7451b7796b1ed5
699,612
import requests def get_recognitions(mem_skip, api_key): """This function triggers the GET RECOGNITIONS API. https://api.highground.com/#api-Recognition-GetRecognition Keyword Arguments: mem_skip -- tracks member records to skip for looping through all records api_key -- authorizes API call Return: resp_val -- returns a JSON object of the API response (JSON) """ headers = { 'Accept': 'application/json', 'clientkey': api_key } params = ({ 'skip': mem_skip }) resp_val = requests.get( 'https://api.highground.com/1.0/Recognition/', headers=headers, params=params ) return resp_val.json()
08a73c10cec7173f2f60dc9ef61190747431fc2e
178,672
async def read_exactly(stream, count): """Read the specified number of bytes from stream. Keep trying until we either get the desired amount, or we hit EOF. """ s = b'' while count > 0: n = await stream.receive_some(count) if n == b'': raise EOFError count = count - len(n) s = s + n return s
afc0786ac0ec89313762d5294069716a1d07f167
558,967
def maxi(a,b): """ Maximal value >>> maxi(3,4) 4 """ if a > b: return a return b
9270324dc5025f39c0c463fcfae9d99fa9b1a5e1
553,060
def CreateSafeUserEmailForTaskName(user_email): """Tasks have naming rules that exclude '@' and '.'. Task names must match: ^[a-zA-Z0-9_-]{1,500}$ Args: user_email: String user email of the task owner. Returns: String with unacceptable chars swapped. """ return user_email.replace('@', '-AT-').replace('.', '-DOT-')
5d43d366447970a24cbbfdb092c83334b18a7cf5
415,433
import hashlib def calculahash(cadena): """Devuelve el hash SHA256 de una cadena dada como entrada :param cadena: texto de entrada para calcular su hash :return: el hash calculado con SHA256 """ return hashlib.sha256(cadena.encode()).hexdigest()
6b2e04c00b13471e470ba52ab6c5e500b84c15c3
643,494
def bisection(f, a, b, TOL, N): """To find a solution to f(x) = 0 Finds the solution to f(x) = 0 given the continuous function f on the interval [a, b], where f(a) and f(b) have opposite signs. Args: f: a function to be evaluated (can be a lambda or def). a: the lower bound in the given range b: the upper bound in the given range TOL: The tolerance (How big an error is acceptable) N: The number of iterations to be perfomed Returns: Has two results. The first one is the solution after N iterations of f(x) = 0. The second one is a lists of lists for every solution after n iterations. For example: This would be the result after 3 iterations [[1, 1.5, 1.5, 2.375], [1.25, 1.5, 1.25, -1.796875], [1.25, 1.375, 1.375, 0.162109375]] if the function f was f = lambda x: x ** 3 + 4 * x ** 2 - 10 with a = 1, b = 2, TOL = 0.00001, N = 13 Raises: None """ p = a result = [] # checking if the solution lies in the given range if f(a) * f(b) >= 0: print("f(a) and f(b) need to have opposite signs\n") return i = 1 FA = f(a) while i <= N: p = a + (b - a) / 2 # (Compute pi.) FP = f(p) if FP == 0.0 or (b - a) / 2 < TOL: # (Procedure completed successfully.) break i = i + 1 if FA * FP > 0: a = p # (Compute ai, bi.) FA = FP else: b = p # (FA is unchanged.) result.append([a, b, p, f(p)]) if i == N: print(f"Method failed after {N} iterations") # (The procedure was unsuccessful.) return p, result
fa2971cdd62623d68739b4a8b9ea5ca2965efa3b
464,260
def _RGB2sRGB(RGB): """ Convert the 24-bits Adobe RGB color to the standard RGB color defined in Web Content Accessibility Guidelines (WCAG) 2.0 see https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef for more references :param RGB: The input RGB color or colors shape== ... x 3 (R, G, and B channels) :type RGB: numpy.ndarray :return: converted sRGB colors :rtype: numpy.ndarray """ sRGB = RGB / 255 return sRGB
c2c5c25d64cc7b0cb9b004846b72aecada7c5d85
700,755
def le(h): """ Little-endian, takes a 16b number and returns an array arrange in little endian or [low_byte, high_byte]. """ h &= 0xFFFF # make sure it is 16 bits return [h & 0xFF, h >> 8]
ea5a0b0f49f43f43456b9afbb04fff9b2fd866c4
415,550
def get_fontext_synonyms(fontext): """ Return a list of file extensions extensions that are synonyms for the given file extension *fileext*. """ return {'ttf': ('ttf', 'otf'), 'otf': ('ttf', 'otf'), 'afm': ('afm',)}[fontext]
8dd131392ba98bfd4f90d1ba3d275ed7048ad35a
299,486
def verify_splits(splits, keyfunc): """ Verifies that the splits of each transaction sum to 0 Args: splits (dict): return value of group_transactions() keyfunc (func): function that returns the transaction amount Returns: (bool): true on success Examples: >>> from operator import itemgetter >>> splits = [{'amount': 100}, {'amount': -150}, {'amount': 50}] >>> verify_splits(splits, itemgetter('amount')) True >>> splits = [{'amount': 200}, {'amount': -150}, {'amount': 50}] >>> verify_splits(splits, itemgetter('amount')) False """ return not sum(map(keyfunc, splits))
9d30da42e5366f60fb09e9cdca8a2726ced7ba19
552,683
def normalize_json_fields(result_list): """ Makes sure that each json contains the same fields. Adds them with None as value if any field is missing. """ found_keys = set() for item in result_list: found_keys.update(item.keys()) for item in result_list: for key in found_keys: if key not in item: item[key] = None return result_list
a0498db7929ba0663c2da57663986ff8ab52b8de
240,186
import collections def attrize(container_name=None, **dct): """Given a dict, return a named tuple where the values are accessible as named attributes. A collection name can be given as an optional parameter. Examples -------- >>> foo = attrize(**{'a': 1, 'b': 2}) >>> foo.a 1 """ if container_name is None: container_name = 'coll' return collections.namedtuple(container_name, dct.keys())(**dct)
3b61159922e1e6773be46feef28aacf9f0256aa9
482,069
import json def get_filepaths(sets): """ Extracts the file paths from the provided .json file and returns, the content of the .json file as a dictionary as well as a potential error message. """ # Reading in the json file with the settings try: with open(sets, "r") as read_file: paths = json.load(read_file) error = "" except: paths = None error = "Error: autocopy_settings.json has not been provided or typo in json\n" print(error) #time.sleep(60) return paths, error
5fdf13cd8184159b73c403b5b00d2dd803367f23
422,160
import yaml def load_conf(conf_path): """Load a yaml encoded conf file.""" try: with open(conf_path) as f: y = yaml.load(f, Loader=yaml.CLoader) return y or {} except Exception as e: raise ValueError('Invalid or nonexistent config filename')
651afd19fbf28fc35c3827f3651b8d26ff5f8ab4
523,623
def vector_product(vec1, vec2, do_alignment=True): """ Computes the dot product of two vectors. Parameters ---------- vec1, vec2 : ProbabilityVector Returns ------- product_scalar : float """ if do_alignment: series1, series2 = vec1.series.align(vec2.series) else: series1, series2 = (vec1.series, vec2.series) product_scalar = series1.dot(series2) return product_scalar
60cc45e863ef8d7afc6f0d12b87018fe8689f18f
532,180
def byte_compare(stream_a, stream_b): """Byte compare two files (early out on first difference). Returns: (bool, int): offset of first mismatch or 0 if equal """ bufsize = 16 * 1024 equal = True ofs = 0 while True: b1 = stream_a.read(bufsize) b2 = stream_b.read(bufsize) if b1 != b2: equal = False if b1 and b2: # we have two different buffers: find first mismatch for a, b in zip(b1, b2): if a != b: break ofs += 1 break ofs += len(b1) if not b1: # both buffers empty break return (equal, ofs)
59adfe50fefdb79edd082a35437018d4b954ec75
1,218
def linepoint(t, x0, y0, x1, y1): """Returns coordinates for point at t on the line. Calculates the coordinates of x and y for a point at t on a straight line. The t parameter is a number between 0.0 and 1.0, x0 and y0 define the starting point of the line, x1 and y1 the ending point of the line, """ out_x = x0 + t * (x1-x0) out_y = y0 + t * (y1-y0) return (out_x, out_y)
4296a5133daacd210886ca6e40e926ba98dc409f
408,315
def calc_cov(samples): """ Calculates covariance matrix as described in paper. Args: samples (list of np.matrix) - a list of sample-matrices Returns: np.matrix - the covariance matrix >>> s1 = np.matrix([[1, 0], [0, 1]]) >>> s2 = np.matrix([[2, 0], [0, 2]]) >>> calc_cov([s1, s2]) matrix([[2.5, 0. ], [0. , 2.5]]) """ no_of_samples = len(samples) sigma_c = 1 / no_of_samples * samples[0].T.dot(samples[0]) for i in range(1, no_of_samples): sigma_c += 1 / no_of_samples * samples[i].T.dot(samples[i]) return sigma_c
ae9da378620c081099c6e3e79ebd7f332607b696
203,294
from pathlib import Path def fixture_sample_file() -> Path: """Return a sample file.""" return Path(__file__).parent.joinpath("sample.txt")
765dbf2283f2f21c705ce9a8eac1728f4cbed7ea
100,744
import hashlib def generate_token(login: str, auth_salt: str) -> str: """Generate token based on login and hash salt.""" encoded_key = (login + auth_salt).encode('utf-8') token = hashlib.sha512(encoded_key).hexdigest() return token
eca8901c16f511077ca85c19f8f0cb54e46a9e25
551,688
def get_port(device): """ Get the port, as string, of a device """ return str(device.port)
2c68a38dc12c981718d50d44be16b0ca5d317c23
94,945
def _get_model_features(model_pipe): """Get features from a `civis.ml.ModelPipeline` """ model_features = [] target_cols = model_pipe.train_result_.metadata['data']['target_columns'] for feat in model_pipe.train_result_.metadata['data']['column_names_read']: if feat not in target_cols: model_features.append(feat) return model_features
b39fe53effc1d2873ceac02450d6022e06702337
461,534
def format_flux_mode_indices(atom_idxs): """ Formates the atom indices into a string that is used to define the fluxional (torsional) modes of a molecular species for Monte Carlo calculations in MESS. :param atom_idxs: idxs of atoms involved in fluxional mode :type atom_idxs: list(int) :return flux_mode_idx_str: formatted string of indices :rtype: string """ # Build string containing the values of each keyword flux_mode_idx_str = '' for vals in atom_idxs: flux_mode_idx_str += '{0:<4d}'.format(vals) return flux_mode_idx_str
01f62f092247a293334b09803755037f34648a6b
189,660
def to_var(log_std): """Returns the variance given the log standard deviation.""" return log_std.exp().pow(2)
841dd6aae46ae37c9c71f002e7a70c2ebd8e531b
201,296
import math def calculate_temp_NTC(raw_val): """ Converts the raw value read from the NTC temperature sensor module into degrees celsius. """ voltage = raw_val * 5 / 1023 resistance = (5 * 10000 / voltage) - 10000 temp = ((3.354016 * (10**-3)) + (2.569850 * (10**-4)) * math.log(resistance / 10000) + (2.62013 * (10**-12)) * (math.log(resistance / 10000))**2 + 6.38309 * (10**-15) * (math.log(resistance / 10000))**3)**-1 - 273.15 return temp
500d4e9073b5d50c96b74e549fdd91cce364e09d
536,298
def get_fuel_needed(mass: int) -> int: """Calculate fuel needed to launch mass.""" return mass // 3 - 2
ed4139ed2e57fce478e3eb3d94ba55f3b20bbf25
413,572
def wild2regex(string): """Convert a Unix wildcard glob into a regular expression""" return string.replace('.','\.').replace('*','.*').replace('?','.').replace('!','^')
c30360076fde573b3865143b761579e2c7466877
63,904
import re def sanitized_name(name, wid): """Clean an action name and change it to proper format. It replaces all the unwanted characters with `_`. Args: name (str): The crude action name. Returns: str: The sanitized action name. """ return "popper_{}_{}".format( re.sub('[^a-zA-Z0-9_.-]', '_', name), wid )
82937a39db4de08b0bb7b0304333119c02dcc293
321,483
import math def get_product_factors(n): """ get product factors of n """ if n <= 0 or not isinstance(n, int): return [] else: product_factors = [] for i in range(1, math.ceil(math.sqrt(n)) + 1): if n % i == 0: product_factors.append(i) product_factors.append(int(n / i)) return sorted(list(set(product_factors)))
ed9f577d367fc9492fcd7d3a47d956d2dc892f77
521,856
def n_subsystems(request): """Number of qubits or modes.""" return request.param
28ed56cc26e4bfa1d607bf415b3a7611eb030a27
31,999