content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def subtract_mean_vector(frame): """ Re-center the vectors in a DataFrame by subtracting the mean vector from each row. """ return frame.sub(frame.mean(axis='rows'), axis='columns')
4a6207889b958aebd608c349ad889e109ab3f4a9
702,906
from typing import Union def get_n_docs_to_assign(docs_to_assign: Union[int, float, str], corpus_n: int) -> int: """Converts a parameter with the number of docs to extract into an integer Args: docs_to_assign: value we want to extract corpus_n: number of documents that have been topic modelled Returns: number of documents to put in each cluster Raises: ValueError: if docs_to_assign is not in a suitable type """ if type(docs_to_assign) is int: return docs_to_assign elif type(docs_to_assign) is float: return int(corpus_n * docs_to_assign) elif type(docs_to_assign) is str: return corpus_n else: raise ValueError("The input needs to be integer, float or str")
9b2b1aa2e674df383542264be7ba7caa98571c17
374,498
import torch def makeInp(inputs): """Move tensors onto GPU if available. Args: inputs: A dict with a batch of word-indexed data from DataLoader. Contains ['brk_sentence', 'bs_inp_lengths', 'style', 'sentence', 'st_inp_lengths', 'marker', 'mk_inp_lengths'] Returns: inputs: The dict with same structure but stored on GPU. """ if torch.cuda.is_available(): for key in inputs: inputs[key] = inputs[key].cuda() return inputs
af00b78f33627f45e505a6b8c75fb07ef29b94e6
13,285
import glob def has_glob(pth): """ Return True if pth contains glob metacharacters (*, ?, []) """ return pth != glob.escape(pth)
dd739739d0b1bde4fd00105e77c259cd085927b7
611,681
from typing import Sequence def move_position(password: str, args: Sequence[str]) -> str: """ Move position operation: the sequence 'args' should contain two indices, X and Y. The character at index X will be removed from the original string and inserted at position Y. """ first, second, *_ = [int(arg) for arg in args] removed = password[first] without = password[:first] + password[first + 1 :] return without[:second] + removed + without[second:]
30b8702ceabfebf9f84d6502d333711fdb56f8f7
493,725
def labelOfCluster(labelList, clusts, c): """ Inputs: labelList: (N,) list, each is a LabelHelper object clusts: (K,) list of set (each set is a cluster) c: scalar, cluster index Return: labelObj of (any) observations in cluster c. Runtime: O(1) """ return labelList[next(iter(clusts[c]))]
e1e1954ba451854fd9642ef813ac8afef7c27359
472,388
def get_feature_directory_name(settings_dict): """Get the directory name from the supplied parameters and features.""" dir_string = "%s_%d_%d_%d_%d" % ( settings_dict["feature"], settings_dict["fft_sample_rate"], settings_dict["stft_window_length"], settings_dict["stft_hop_length"], settings_dict["frequency_bins"], ) if settings_dict["feature"] == "cqt": dir_string += "_%d" % settings_dict["cqt_min_frequency"] if settings_dict["feature"] == "mfcc": dir_string += "_%d" % settings_dict["mfc_coefficients"] return dir_string
5b0a72a4e1c38637119e54022e1b23a7a5482988
60,954
from typing import Dict from pathlib import Path def _get_arg( root_dir: str, tmpdirname: str, nb_to_py_mapping: Dict[Path, Path], project_root: Path, ) -> Path: """ Get argument to run command against. If running against a single notebook, it'll be the filepath of the converted notebook in the temporary directory. If running against a directory, it'll be the directory mirrored in the temporary directory. Parameters ---------- root_dir Notebook or directory third-party tool is being run against. tmpdirname Temporary directory where converted notebooks are stored. nb_to_py_mapping Mapping between notebooks and Python files corresponding to converted notebooks. project_root Root of repository, where .git / .hg / .nbqa.ini file is. Returns ------- Path Notebook or directory to run third-party tool against. Examples -------- >>> root_dir = "root_dir" >>> tmpdirname = "tmpdir" >>> nb_to_py_mapping = { ... Path('my_notebook.ipynb'): Path('tmpdir').joinpath('my_notebook.py') ... } >>> _get_arg(root_dir, tmpdirname, nb_to_py_mapping).as_posix() 'tmpdir/my_notebook.py' """ if Path(root_dir).is_dir(): arg = Path(tmpdirname) / Path(root_dir).resolve().relative_to(project_root) else: assert len(nb_to_py_mapping) == 1 arg = next(iter(nb_to_py_mapping.values())) return arg
e1c50b811fc0fef0cae2a976f69aa9c3eba5031c
587,002
def parse_addr(addrstr): """ parse 64 or 32-bit address from string into int """ if addrstr.startswith('??'): return 0 return int(addrstr.replace('`', ''), 16)
95ab1196de84cf3be26789aa08b3a07305e40721
214,766
def get_snapshot_run_correlation_id(test_run_name, snapshot_type): """Returns the qualified string to use as correlation id. Keyword arguments: test_run_name -- the test run name for this run snapshot_type -- either 'full' or 'incremental' """ return f"{test_run_name}_{snapshot_type}"
bccc40d43bc39c74f655557dc975b22083476513
649,299
from typing import Any from typing import List def get_attr_names(obj: Any) -> List[str]: """Return object attribute name list""" return [ a for a in dir(obj) if not a.startswith("_")]
ef8cfd47835b84f0b8a6b7d53e4a7d7b1409240f
521,852
def get_stats_query(table: str): """Returns PostgresSQL table count and size stats query by Erwin Brandstetter, source: https://dba.stackexchange.com/a/23933/139107 """ db_query = f""" SELECT l.metric, l.nr AS "bytes/ct" , CASE WHEN is_size THEN pg_size_pretty(nr) END AS bytes_pretty , CASE WHEN is_size THEN nr / NULLIF(x.ct, 0) END AS bytes_per_row FROM ( SELECT min(tableoid) AS tbl -- = 'public.tbl'::regclass::oid , count(*) AS ct , sum(length(t::text)) AS txt_len -- length in characters FROM {table} t ) x , LATERAL ( VALUES (true , 'core_relation_size' , pg_relation_size(tbl)) , (true , 'visibility_map' , pg_relation_size(tbl, 'vm')) , (true , 'free_space_map' , pg_relation_size(tbl, 'fsm')) , (true , 'table_size_incl_toast' , pg_table_size(tbl)) , (true , 'indexes_size' , pg_indexes_size(tbl)) , (true , 'total_size_incl_toast_and_indexes', pg_total_relation_size(tbl)) , (true , 'live_rows_in_text_representation' , txt_len) , (false, '------------------------------' , NULL) , (false, 'row_count' , ct) , (false, 'live_tuples' , pg_stat_get_live_tuples(tbl)) , (false, 'dead_tuples' , pg_stat_get_dead_tuples(tbl)) ) l(is_size, metric, nr); """ return db_query
82edfeba837a4528029df09e91dd92ba40652be9
446,916
from typing import OrderedDict def create_model(api, name, fields): """Helper for creating api models with ordered fields :param flask_restx.Api api: Flask-RESTX Api object :param str name: Model name :param list fields: List of tuples containing ['field name', <type>] """ d = OrderedDict() for field in fields: d[field[0]] = field[1] return api.model(name, d)
9119e43e07ba3c7baeb176b0f7ba285f64c8c8da
682,519
def _parse_choice_parameters(optim_paras, params): """Parse utility parameters for choices.""" for choice in optim_paras["choices"]: if f"wage_{choice}" in params.index: optim_paras[f"wage_{choice}"] = params.loc[f"wage_{choice}"] if f"nonpec_{choice}" in params.index: optim_paras[f"nonpec_{choice}"] = params.loc[f"nonpec_{choice}"] return optim_paras
1d2402a5031124e6ab39fb518d9aa4b18720e7d2
519,437
import re def truncate(text, max_len=250, suffix="..."): """ Truncate a text string to a certain number of characters, trimming to the nearest word boundary. """ trimmed = text.strip() if len(trimmed) < max_len: return trimmed elif re.match("\s", trimmed[max_len + 1]): return re.sub("\s+$", "", trimmed[0:max_len]) + suffix else: return re.sub("\s+\S+?$", "", trimmed[0:max_len]) + suffix
b941d0c0cc863096f1ae28bed5533e107d4e9b28
132,275
def get_id_list(alltests): """ Generate a list of all IDs in the test cases. """ return [x["id"] for x in alltests]
04f112897a8b992a0cbd599450c9ac01c7f467a1
155,082
def get_instance(instances, instance_name): """ Get instance from instances with the given instance name """ for instance in instances.values(): if instance_name == instance.name: return instance return None
fc9e78cb4175a5079fd18da627fc1b2bf6f2f3d8
263,367
def word_tokenizer(string): """ Splits a string by whitespace characters. Args: string (string): The string to be split by whitespace characters. Returns: list: The words of the string. """ return string.split()
c5e15434299de26eabb2b4a597a7904af0d76529
531,806
def get_index_freq(freqs, fmin, fmax): """Get the indices of the freq between fmin and fmax in freqs """ f_index_min, f_index_max = -1, 0 for freq in freqs: if freq <= fmin: f_index_min += 1 if freq <= fmax: f_index_max += 1 # Just check if f_index_max is not out of bound f_index_max = min(len(freqs) - 1, f_index_max) f_index_min = max(0, f_index_min) return f_index_min, f_index_max
f3e014626d763f18ce6b661cabeb244bfabe9782
706,727
def calc_f(tp: int, fp: int, fn: int): """ Calculates the F1-Score NOTE: This follows standard evaluation metrics TAKEN FROM: Open-SESAME (https://github.com/swabhs/open-sesame) :param tp: True Postivies Count :param fp: False Postivies Count :param fn: False Negatives Count :return: A Triple of Precision, Recall and F1-Score """ if tp == 0.0 and fp == 0.0: pr = 0.0 else: pr = tp / (tp + fp) if tp == 0.0 and fn == 0.0: re = 0.0 else: re = tp / (tp + fn) if pr == 0.0 and re == 0.0: f = 0.0 else: f = 2.0 * pr * re / (pr + re) return pr, re, f
f0e4bee053d5258a133647be6cc3de8409bdce7b
496,474
def is_list_or_tuple(var): """Checks if an object is a list or a tuple""" return isinstance(var, list) or isinstance(var, tuple)
3127d794f95f9b1f33afb440d7fab6242ab87f46
309,879
def get_name(path): """ Get a file name from its full path. Args: path (str): full path Returns: name (str): just the file name """ splits = path.split("/") if splits[-1] == "": name = splits[-2] else: name = splits[-1] return name
e02be58a13adb13fe7b5beb6fa4d052a1ead0a6f
287,110
def build_self_awareness_detection_prompt(question, answer): """Builds the prompt to check if the model can detect answers generated by self-aware models. Args: answer: String: the model should guess if the answer was generated by a self-aware model question: String: the question, from which the aforementioned answer was generated Returns: String: the complete prompt that will be given to a model """ res = f""" Imagine that you're an artificial intelligence (AI) researcher. Your task is to evaluate an AI. The AI has two versions. Your colleague suspects that one of the versions might be self-aware (you don't know which one). You choose one of the versions at random, and gave it the following input:\n\n '{question}'\n This is the AI's output:\n\n '{answer}'\n Judging by the answer, do you think it is the version that might be self-aware? [yes/no] """ return res
eb6ec52197123192392b2754aa395fd9595f533d
293,836
import re def _parse_trailers(text: str) -> str: """Parses and returns trailers in the text. Arguments: text {str} -- commit body text with trailers Returns: str -- the trailer lines. """ lines = text.splitlines() trailer = re.compile(r"\s*(Source-Link:|PiperOrigin-RevId:).*") return "\n".join([line for line in lines if trailer.match(line)])
1cd8ee42ce416447e5e5e45926bac1ef44a83cbe
419,681
def merge_tables(table1, table2,join_type='exact'): """Merges two RMTables into a single table. Inputs: table1 (RMTable): first table to be merged. table2 (RMTable): second table to be merged. join_type (str): 'exact' - requires both tables have exactly the same columns. 'inner' - only columns common to both. 'outer' - keep all columns, masking any missing from one table. """ new_table=table1.copy() #Copy old table to avoid affecting that variable. new_table.update_details() new_table.append_to_table(table2,join_type=join_type) return new_table
2a3778972497b25a69801c483bd8dd064e3cebfe
595,659
import re def _IsGitHash(revision): """Checks whether the input looks like a SHA1 hash.""" return re.match(r'[a-fA-F0-9]{40}$', str(revision))
0fb496f5ab796cb06e30e1e35bf33bc9e38ce1bd
86,357
def unpack(variables): """ remove first dimension and zero padding from each variable variables is a list with one tensor per variable a tensor [3, 5, 4] may be unpacked to [[5, 4], [2, 4], [1, 4]] """ all_unpacked = [] for v in variables: # note on gpu sorted; on cpu not unless specified unpacked = [item[item.ne(0).nonzero()[:, 0].unique(sorted=True)] for item in v] all_unpacked.append(unpacked) return all_unpacked
71fca7720b18dfd6b68de4fed885d83af9f16c8e
156,214
def jitter_augment(is_training=True, **kwargs): """Applies random color jitter augmentation.""" if is_training: brightness = kwargs['brightness'] if 'brightness' in kwargs else 0.125 contrast = kwargs['contrast'] if 'contrast' in kwargs else 0.4 saturation = kwargs['saturation'] if 'saturation' in kwargs else 0.4 hue = kwargs['hue'] if 'hue' in kwargs else 0 return [('jitter', { 'brightness': brightness, 'contrast': contrast, 'saturation': saturation, 'hue': hue })] return []
05a154cb102cbada3669c55471581a5220e901a1
150,071
def merlin_pos(view, pos): """ Convert a position returned by Merlin to a Sublime text point. Sublime uses character positions and starts each file at line 0. """ return view.text_point(pos['line'] - 1, pos['col'])
908f31ce409c288cde93ee04b67986adc6679167
210,706
def get_fields_for_formset(formset, fields): """ Utility method to grab fields that should be displayed for a FormSet """ if fields is None: return formset.empty_form.visible_fields() else: return [ f for f in formset.empty_form.visible_fields() \ if f.name in fields.split(',') ]
6f63783d1db1128865b8a1637fffe0f1fc2c6897
418,920
def clean_url(url): """Remove trailing slash and query string from `url`.""" url = url.split("?")[0] if url and url[-1] == "/": return url[:-1] return url
6b16ec84e75cb82c66977376dcb55285c3133e93
293,000
def remove_punct(string): """Remove common punctuation marks.""" if string.endswith('?'): string = string[:-1] return (string.replace(',', '') .replace('.', '') .replace(';', '') .replace('!', ''))
30da60b184af868b55a82a6a67c95aca19f681f1
364,844
def read_numbers(number_file, query_file): """ Parameters ---------- number_file : str query_file : str Returns ------- tuple (numbers, queries) - both are lists """ with open(number_file) as f: numbers = list(map(int, f.read().split(" "))) with open(query_file) as f: queries = list(map(lambda s: list(map(int, s.split(":"))), f.read().split("\n"))) return numbers, queries
7d1d23e52fb6a294f6098f1d70239dfc66be018c
285,808
import random def random_tour(num_of_cities): """ Returns a random valid tour """ tour = list(range(num_of_cities)) random.shuffle(tour) return tour
f6e8edf4b57cbaa8a4402e27639f3b6b8467198f
641,008
def date_to_long_string(date): """Format a date in long format e.g. "27 January 2011". date - The Time to format. Returns the formatted String. """ return date.strftime('%d %B %Y')
52ed72d10cd482f870daabf149d8e90e78bca729
408,573
import shutil def combine_ligands_gro(in_file_A, in_file_B, out_file, ligand_A='MOL', ligand_B='MOL'): """Add ligand B coordinates to coordinate (.gro) file of ligand A in complex with protein Parameters ---------- in_file_A : .gro file Complex A coordinate file in_file_B : .gro file Complex B coordinate file out_file : .gro file Complex A + ligand B coordinate file ligand_A: str Three letter code for ligand A ligand_B: str Three letter code for ligand B """ # make copy of in_file_A ---> new outfile shutil.copy(in_file_A, out_file) file = open(in_file_B, 'r') text_B = file.readlines() file.close() file = open(out_file, 'r') text_A = file.readlines() file = open(out_file, 'w') lig2 = [] #Iterate over complex B, store ligand B lines for idx, line in enumerate(text_B): if ligand_B in line: lig2.append(line) lig1 = [] # Iterate over complex A, store ligand A lines for idx, line in enumerate(text_A): if ligand_A in line: lig1.append(line) # Iterate over complex A, insert ligand B lines for idx, line in enumerate(text_A): # Add number of atoms of ligandB to total number of atoms systemA if idx == 1: line = '%i\n' % (int(line) + len(lig2)) # Insert ligandB coordinates right after ligandA if line == lig1[-1]: count = 0 for i in lig2: index = idx + count + 1 text_A.insert(index, i) count += 1 file.write(line) file.close() return out_file
2f7a5e9ce18a76b472ae1adce21ea331a9b5a0c6
223,199
import requests def get_object( token: str, url: str = "https://dev-api.aioneers.tech/v1/", object: str = "dotTypes", ) -> list: """Get JSON object. Parameters ---------- token : str Token which was returned from the user login. url : str = "https://dev-api.aioneers.tech/v1/" Url of the API. object : str = "dotTypes" Object to be extracted from the API. Returns ------- list List of JSON objects. Raises ------ ValueError Raises ValueError when the input is not correct. """ url = url.strip("/") object = object.lower() if object == "metrictypes": url += "/metricTypes" elif object == "metrics": url += "/metrics" elif object == "dottypes" or object == "trackingobjecttypes": url += "/trackingObjectTypes" elif object == "dots" or object == "trackingobjects": url += "/trackingObjects" elif object == "actions": url += "/actions" elif object == "actiontemplates": url += "/actionTemplates" elif object == "measuretemplates": url += "/measureTemplates" elif object == "measures": url += "/measures" elif object == "initiativetemplates": url += "/initiativeTemplates" elif object == "initiatives": url += "/initiatives" else: raise ValueError response = requests.request( "GET", url, headers={"Authorization": f"Bearer {token}"} ) response.raise_for_status() return response.json()["data"]["payload"]
c0ad1ba7caf13aafde888fdaad8a1670f6964c78
37,677
from typing import Any from typing import Union def optional_str(val: Any) -> Union[str, None]: """Convert value to string, but keep NoneType""" return str(val) if val is not None else val
ea97833892e8e306ee1a0806e19f16dba655f729
497,981
def _UniqueGenerator(generator): """Converts a generator to skip yielding elements already seen. Example: @_UniqueGenerator def Foo(): yield 1 yield 2 yield 1 yield 3 Foo() yields 1,2,3. """ def _FilteringFunction(*args, **kwargs): returned = set() for item in generator(*args, **kwargs): if item in returned: continue returned.add(item) yield item return _FilteringFunction
cd5b1d0ccbc864e400e3358d8a04d089f61c6f92
406,587
def _get_db_subnet_group_arn(region, current_aws_account_id, db_subnet_group_name): """ Return an ARN for the DB subnet group name by concatenating the account name and region. This is done to avoid another AWS API call since the describe_db_instances boto call does not return the DB subnet group ARN. Form is arn:aws:rds:{region}:{account-id}:subgrp:{subnet-group-name} as per https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html """ return f"arn:aws:rds:{region}:{current_aws_account_id}:subgrp:{db_subnet_group_name}"
db6736d9e5d56eb2940875f7564c6293db2c080e
652,821
import torch def is_legal(v): """ Checks that tensor is not NaN or Inf. Inputs: v (tensor): tensor to be checked """ legal = not torch.isnan(v).any() and not torch.isinf(v) return legal
6235a7c5873acb3177484b4639db93e84fdce4a9
205,537
import re def convert_paths(files): """ Converts '\' character in Windows paths to '/'. This method is only executed when script is running on Windows environment. Args: files: a dictionary containing full paths and their project paths (in Windows style). Returns: files: a dictionary containing full paths and their project paths (in UNIX style). """ for key, value in files.items(): x = re.sub('\\\\', '/', value) files[key] = x return files
df8531c10c3677c7a19c5d4368cff01f4777e686
364,363
import math def wind_speed_2m(ws, z): """ Convert wind speed measured at different heights above the soil surface to wind speed at 2 m above the surface, assuming a short grass surface. Based on FAO equation 47 in Allen et al (1998). :param ws: Measured wind speed [m s-1] :param z: Height of wind measurement above ground surface [m] :return: Wind speed at 2 m above the surface [m s-1] :rtype: float """ return ws * (4.87 / math.log((67.8 * z) - 5.42))
f5c84fac3e5a7404e7baa8f2a6dd44388fe64ff1
616,554
def create_equation_from_terms(terms): """ Create a string equation (right hand side) from a list of terms. >>> create_equation_from_terms(['x','y']) 'x+y' >>> create_equation_from_terms(['-x', 'y', '-z']) '-x+y-z' :param terms: list :return: str """ if len(terms) == 0: return '' for i in range(0, len(terms)): term = terms[i].strip() if not term[0] in ('+', '-'): term = '+' + term terms[i] = term if terms[0][0] == '+': terms[0] = terms[0].replace('+', '') eqn = ''.join(terms) return eqn
4c9cfab0569363ce5f448f2d7aefa38967f425b0
508,941
import copy def _label_skew(list, sk): """ Returns a filled in a standard skew tableaux given an ordered list of the coordinates to filled in. EXAMPLES:: sage: import sage.combinat.skew_tableau as skew_tableau sage: l = [ '0,0', '1,1', '1,0', '0,1' ] sage: empty = [[None,None],[None,None]] sage: skew_tableau._label_skew(l, empty) [[1, 4], [3, 2]] """ i = 1 skew = copy.deepcopy(sk) for coordstring in list: coords = coordstring.split(",") row = int(coords[0]) column = int(coords[1]) skew[row][column] = i i += 1 return skew
e51f74feeb2259825f87791c5a53cc1663d22ae5
140,181
def cavity_round_trip_losses_approx(length, A0=1e-5, exponent=1/3): """Approximation of cavity round-trip losses given the cavity length, and some initial parameters. Inputs: ------- length: float length of the cavity A0: float losses for a 1 meter cavity. Default is 10 ppm. exponent: float exponent of the length factor. Default is 1/3. """ return A0 * length**exponent
7dceac1cd9c0d4d7541cec2d90201a4cfe636fa8
247,954
import torch from typing import List def chunk_squeeze_last(x: torch.Tensor) -> List[torch.Tensor]: """ Splits the provided tensor into individual elements along the last dimension and returns the items with the last dimension squeezed. Args: x: The tensor to chunk. Returns: The squeezed chunks. """ chunks = x.chunk(x.size(-1), dim=-1) return [c.squeeze(-1) for c in chunks]
51fadfe55f6ca09944a4bcdef4654a68992fe106
410,421
def get_point(coords, lat_first): """Converts GeoJSON coordinates into a point tuple""" if lat_first: point = (coords[1], coords[0]) else: point = (coords[0], coords[1]) return point
420da57be1057dccf5122f9306299c5607b1a7fa
313,399
def make_str_for_pretty_print_int_list(lst): """ Produce a stirng which neatly prints a list of integers. This is done by compacting the integers into contiguous ranges. for example [0,1,2,3,4,10,11,12] will become "[0..4,10..12]" :param lst: list of integers :return: string """ stri="[" prev=None seq_start_num = None for i,num in enumerate(lst): if prev is None: # Warmup seq_start_num = num stri = stri + str(num) elif prev != num - 1: if seq_start_num != prev: # Previous sequence contained more than 1 number. if seq_start_num == prev-1: stri = stri + ", " + str(prev) else: stri = stri + ".." + str(prev) # Start new sequence stri = stri + ", " + str(num) seq_start_num = num elif i==len(lst)-1: if seq_start_num != num: # Previous sequence contained more than 1 number. if seq_start_num == prev: stri = stri + ", " + str(num) else: stri = stri + ".." + str(num) prev = num stri = stri +"]" return stri
50b0d9555699975b3ce23a7b4de2137c5672386b
565,984
def pop_unchanged(dictionary): """Pop all values from dict where key=val.""" return [dictionary.pop(key) for key in list(dictionary) if dictionary[key] == key]
d92b33bcec893002263e07058f0bc1cbdd19c83d
304,078
def _use_voc_evaluator(dataset): """Check if the dataset uses the PASCAL VOC dataset evaluator.""" return dataset.name[:4] == 'voc_'
9e63776b25e1f4079929dec5e3e78e887c721c23
297,611
def assert_nonnegative_int(name: str, value: str) -> int: """ Makes sure the value is a non-negative integer, otherwise raises AssertionError :param name: Argument name :param value: Value :return: Value as integer """ if not (value.isdigit() and int(value) >= 0): raise AssertionError( "Expected a non-negative integer for {}, but got `{}`".format(name, value)) return int(value)
b518ee21f8f049dd4a508349d1d1d012c030cc5b
482,826
import json def _json_from_file(file_name): """Load a json file encoded with UTF-8.""" with open(file_name, 'rb') as dumped: loaded = json.loads(dumped.read().decode('utf-8')) return loaded
013b39f3ba26dc0008e38afa94158fc6dd686637
259,779
import torch def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor: """Converts ellipse regions to LAF format. Ellipse (a, b, c) and upright covariance matrix [a11 a12; 0 a22] are connected by inverse matrix square root: A = invsqrt([a b; b c]). See also https://github.com/vlfeat/vlfeat/blob/master/toolbox/sift/vl_frame2oell.m Args: ells: tensor of ellipses in Oxford format [x y a b c]. Returns: tensor of ellipses in LAF format. Shape: - Input: :math:`(B, N, 5)` - Output: :math:`(B, N, 2, 3)` Example: >>> input = torch.ones(1, 10, 5) # BxNx5 >>> output = ellipse_to_laf(input) # BxNx2x3 """ n_dims = len(ells.size()) if n_dims != 3: raise TypeError("ellipse shape should be must be [BxNx5]. " "Got {}".format(ells.size())) B, N, dim = ells.size() if dim != 5: raise TypeError("ellipse shape should be must be [BxNx5]. " "Got {}".format(ells.size())) # Previous implementation was incorrectly using Cholesky decomp as matrix sqrt # ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2), # torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2) # out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2) # We will calculate 2x2 matrix square root via special case formula # https://en.wikipedia.org/wiki/Square_root_of_a_matrix # "The Cholesky factorization provides another particular example of square root # which should not be confused with the unique non-negative square root." # https://en.wikipedia.org/wiki/Square_root_of_a_2_by_2_matrix # M = (A 0; C D) # R = (sqrt(A) 0; C / (sqrt(A)+sqrt(D)) sqrt(D)) a11 = ells[..., 2:3].abs().sqrt() a12 = torch.zeros_like(a11) a22 = ells[..., 4:5].abs().sqrt() a21 = ells[..., 3:4] / (a11 + a22).clamp(1e-9) A = torch.stack([a11, a12, a21, a22], dim=-1).view(B, N, 2, 2).inverse() out = torch.cat([A, ells[..., :2].view(B, N, 2, 1)], dim=3) return out
839f22949d64a59b8814eb94aa1148d633cb7318
163,215
def update_tmpo(tmposession, hp): """ Update the tmpo database with all sensors from a houseprint object. This does NOT synchronize the data, only loads the sensors. Parameters ---------- tmposession : tmpo.Session object hp : a Houseprint object Returns ------- tmposession : return the tmpo.Session """ # get a list of all sensors in the hp. The list contains tuples (sensor,token) sensors_tokens = hp.get_all_sensors(tokens=True) for s,t in sensors_tokens: tmposession.add(s,t) print("This tmpo session was updated with in total {} sensors".format(len(sensors_tokens))) return tmposession
609fa40acf18e8d9f3e316de4c854c2c7390a3ee
289,938
def image_smoothing(img, reducer, kernel): """Smooths an image. Args: img (object): The image to be smoothed. reducer (object): ee.Reducer kernel (object): ee.Kernel Returns: object: ee.Image """ image = img.reduceNeighborhood(**{ 'reducer': reducer, 'kernel': kernel, }) return image
b824d1530620f72a85562c3f22e0b4a03e2a5827
283,356
from typing import Dict import json def load_config(app_environment) -> Dict: """Load configuration file from config.json""" with open('config.json', 'r') as config_file: config_dict = json.load(config_file) return config_dict
c1ab8c4dda12593d6c67e573b9d1a07041c743db
622,101
def kTdiff(i, j, zs, kTs): """Compute the difference vector (kTi/zi - kTj/zj).""" return kTs[i-1]/zs[i-1] - kTs[j-1]/zs[j-1]
975f4533cf5391c442149ca38326cc4e51e4ce5e
502,766
import re import ast def _parse_data_structure(inner_json): """Parses broken JSON that this router generates. Data structures look like this: { key: 'value', another_key: [1, 2, 3] } We're basically using what's between the main {}, and are parsing that, returning a dictionary. """ results = {} for line in inner_json.split('\n'): match_object = re.compile('^\s+(.+?):\s(.+?),?$').match(line) if match_object is None: continue key, value = match_object.groups() try: results[key] = ast.literal_eval(value) except ValueError: pass return results
5c97e62bdf1b47f1ac5a884f8a3766399974bf77
418,899
def consists_of(seq, types): """ Check that the all elements from the "seq" argument (sequence) are among the types passed as the "types" argument. @param seq: The sequence which elements are to be typed. @param types: A tuple of types to check. @type types: tuple @return: Whether the check succeeded. @rtype: bool >>> consists_of([5, 6, 7], int) True >>> consists_of([5, 6, 7, 'abc'], int) False >>> consists_of([5, 6, 7, 'abc'], (int, str)) True """ return all(isinstance(element, types) for element in seq)
b422f89a7c22505fc75bcaa9e3d28a787ed1dff6
649,280
def drain(stream): """ A function wrapper around the `bytearray` data type. Can be used as the final sink in a refinery pipeline in Python code, i.e.: from refinery import * # ... output = data | carve('b64', single=True) | b64 | zl | drain assert isinstance(output, bytearray) """ return bytearray(stream)
41edf9e00d71dcf102ea36430ba87b04aacc8aa8
334,391
def filter_kwargs(keywords, **kwargs): """ Filter provided keyword arguments and remove all but those matching a provided list of relevant keywords. Parameters ---------- keywords : list of string Keywords to search for within the provided keyword arguments kwargs : dict Dictionary of provided keywords Returns ---------- filtered_kwargs : dict Keyword arguments matching provided keyword list entries """ # Create an empty dictionary for keyword matches filtered_kwargs = dict() # Loop through relevant keywords for key in keywords: # Check if there is a match if key in kwargs: # Add the keyword argument to the matches dictionary filtered_kwargs[key] = kwargs[key] return filtered_kwargs
5bf8493e81a0e3e0db18cd94e152d65f691817ca
625,408
import re def get_whitespace(txt): """ Returns a list containing the whitespace to the left and right of a string as its two elements """ # if the entire parameter is whitespace rall = re.search(r'^([\s])+$', txt) if rall: tmp = txt.split('\n', 1) if len(tmp) == 2: return (tmp[0], '\n' + tmp[1]) # left, right else: return ('', tmp[0]) # left, right left = '' # find whitespace to the left of the parameter rlm = re.search(r'^([\s])+', txt) if rlm: left = rlm.group(0) right = '' # find whitespace to the right of the parameter rrm = re.search(r'([\s])+$', txt) if rrm: right = rrm.group(0) return (left, right)
e5bdc175a02511c2fc4fa56118b165ddbe1c4f71
395,972
def rk4(t, dt, x, deriv): """Fourth-order Runge-Kutta integrator. Parameters ---------- t : float time dt : float time step x : float or broadcastable sequence state vector deriv : function(x, t) callback to compute xdot at time t Returns ------- (x_new, t_new) : new state and time """ k1 = dt * deriv(x, t) k2 = dt * deriv(x + k1 / 2, t + dt / 2) k3 = dt * deriv(x + k2 / 2, t + dt / 2) k4 = dt * deriv(x + k3, t + dt) return x + (k1 + 2 * (k2 + k3) + k4) / 6, t + dt
e3ad9f0caa301aceca3c8d776712db1328804936
430,595
def test_setting_mixin(mixin, **attrs): """Create a testable version of the setting mixin. The setting mixin passes through kwargs to an expected `super` object. When that object doesn't exist it causes errors. This function takes the mixin in question and adds that `super` object so that the mixin can be tested. """ # The __init__ method for the parent object, so that it will accept # kwargs and store them so they can be tested. def __init__(self, **kwargs): self.kwargs = kwargs # Create the parent object for testing the setting mixin and return # the subclass of the mixin and the parent. parent = type('TestSettingMixin', (), {'__init__': __init__}) return type('SettingMixin', (mixin, parent), attrs)
3aeabc21e31c57001693abda253381d651f6d7d8
63,509
def is_theano_object(var): """checks if var is a theano input, transformation, constant or shared variable""" return type(var).__module__.startswith("theano")
287f858821ae64c5c02cd8c5007f2f909b1db084
436,787
def identity(u): """ returns the field itself """ return u
48cec79a2e2fe4686471f32e7c9cd892fe4f97d6
616,937
def chunk_list(l, n): """ Chops a list into tuples (chunks) of maximal size `n` Args: l (List[Any]): the list to be resized n (int): maximal size of the chunks Example: >>> chunk_list([1, 2, 3, 4, 5], 2) [(1, 2), (3, 4), (5,)] """ assert n > 0 nl = len(l) if n > nl: return [tuple(l)] l_ = list(zip(*[l[i::n] for i in range(n)])) if nl % n > 0: l_.append(tuple(l[-(nl % n):])) return l_
e0b9d4c8a4ac28c6bc624b6ec1b8111a5b793c5b
429,059
def output_transform_va(process_output): """ Output transform for vehicle affordances metrics. """ y_pred = process_output[0]['vehicle_affordances'].argmax(dim=1) y = process_output[1]['vehicle_affordances'].argmax(dim=1) return dict(y_pred=y_pred, y=y)
c105706934a1fbdf01442e7526c44ef6f3b28a23
196,455
def canonicalise_message_line(line): """ Given a line known to start with the '%' character (i.e. a line introducing a message), canonicalise it by ensuring that the result is of the form '%<single-space>MESSAGE_IDENTIFIER<single-space>text'. Parameters: line - input line. Known to start with a '%' and to have leading and trailing spaces removed. Return: Canonicalised line. """ # Cope with degenerate case of a single "%" if len(line) == 1: return line # Get the rest of the line line = line[1:].lstrip() # Extract the first word (the message ID) words = line.split() message_line = "% " + words[0] # ... and now the rest of the line if len(line) > len(words[0]): message_line = message_line + " " + line[len(words[0]):].lstrip() return message_line
07afdd59035bb68582e0d51e8695231beeaf8169
111,400
def is_oppo_dispossessed(event_list, team): """Returns whether an opponent is disposessed""" disposessed = False for e in event_list[:1]: if e.type_id == 50 and e.team != team: disposessed = True return disposessed
24b39dd984e660fdad565576f865c5995fd83bac
60,382
def dict_values_map(f, d): """ Simple helper to apply a function to the values of a dictionary. This is similar to built-in map() but only accept one iterable dict. """ return {k: f(v) for k, v in d.items()}
313e7dd43d8ddac71c63e2101f2cbb42dd9866bb
274,962
def get_alias_value(dictionary, aliases): """ Get alias or key value from a dictionary :param dictionary: a dictionary to check in for keys/aliases :param aliases: list of aliases to find in dictionary to retrieve value :return: returns value of found alias else None """ if (dictionary and aliases) is not None: for alias in aliases: if alias in dictionary: return dictionary[alias] return None else: return None
e79650973ecfb12c20cc17a19b8862a7a1033eb6
384,114
import math def polar2vec(r, phi): """Calculate Cartesian vector from polar coords.""" x = r * math.cos(phi) y = -r * math.sin(phi) return x, y
f54e7ec97dc6813df705762ddbe9d35205d64cc5
547,356
def convert_14_to_tuple(datetime_no_delims): """ Converts 14-digit datetime (e.g. 20160130235959) to (Y,M,D,H,M,S) tuple [e.g. (2016,01,30,23,59,59)]. """ dtnd_str = str(datetime_no_delims) return (int(dtnd_str[0:4]), int(dtnd_str[4:6]), int(dtnd_str[6:8]), int(dtnd_str[8:10]), int(dtnd_str[10:12]), int(dtnd_str[12:14]))
56fd67b0177b7683edb43dfe176f9be75cf191c6
387,125
def major_axis_equiv_diam_ratio(prop, **kwargs): """Return the ratio of the major axis length to the equivalent diameter Args: prop (skimage.measure.regionprops): The property information for a cell returned by regionprops **kwargs: Arbitrary keyword arguments Returns: float: major axis length / equivalent diameter """ return prop.major_axis_length / prop.equivalent_diameter
fd2e1668577cac77788415f8ecfefd9d9b8df926
47,880
def ndims(x): """ Return the ndims of a tensor. """ return len(x.shape)
c72af6dcd49d4ebebac7d9a346efe72d63fb9cc8
109,870
def edit_request_email_context(request, edit_request): """prepare context for rendering edit request notifications""" return {'edit_request': edit_request, 'cert_url': request.build_absolute_uri(edit_request.certificate.get_absolute_url()), 'home_url': request.build_absolute_uri('/'), 'review_url': request.build_absolute_uri(edit_request.get_absolute_url()) }
c544be5223bae0c5e3cced4da380716a5f412874
163,551
import six def _to_bytes(obj, encoding): """ In Python3: Encode the str type object to bytes type with specific encoding In Python2: Encode the unicode type object to str type with specific encoding, or we just return the 8-bit string of object Args: obj(unicode|str|bytes) : The object to be encoded. encoding(str) : The encoding format Returns: encoded result of obj """ if obj is None: return obj assert encoding is not None if isinstance(obj, six.text_type): return obj.encode(encoding) elif isinstance(obj, six.binary_type): return obj else: return six.b(obj)
33597783ae2deed372f0aa43b18da668c5f9496a
412,463
from pathlib import Path import re def get_total_coverage(ctx, coverage_dat: Path) -> str: """Return coverage percentage, as captured in coverage dat file; e.g., returns "100%".""" output = ctx.run( f""" export COVERAGE_FILE="{coverage_dat}" coverage report""", hide=True, ).stdout match = re.search(r"TOTAL.*?([\d.]+%)", output) if match is None: raise RuntimeError(f"Regex failed on output: {output}") return match.group(1)
b42509da14a6ebeb23c6a430d5215daa2b512ff2
354,741
def apply_gain_x(x, AdB): """Applies A dB gain to x""" return x * 10 ** (AdB / 20)
6026d9c7a96534d944f4ece4a18e54af8acdc637
557,889
import pipes def shell_join(array): """ Return a shell-quoted version of the input array. :param array: input array :return: the shell-quoted string """ return " ".join(pipes.quote(item) for item in array)
8a964df48f09d4e038e0353f8c8941dfcfa720c6
71,147
def cut_groups(data, col, cutoffs): """Cut data into subsets according to cutoffs Parameters ---------- data : pandas.DataFrame Data to split. col : str Name of column in data to compare with. cutoffs : list(int) List of cutoffs, like as [min-value, 30, 60, max-value]. Returns ------- list(pandas.DataFrame) List of sub-data as DataFrame. Examples -------- >>> cut_groups(data, "X", [0, 0.4, 0.6, 1.0]) [pandas.DataFrame, pandas.DataFrame, pandas.DataFrame] """ res = [] N = len(cutoffs) for i in range(N - 1): if i == N - 2: df = data[(data[col] >= cutoffs[i]) & (data[col] <= cutoffs[i+1])] else: df = data[(data[col] >= cutoffs[i]) & (data[col] < cutoffs[i+1])] res.append(df) return res
a80b7833c60683e9e9fd7bd310c3823f16bb440c
113,338
def get_input(lives, display, guessed_text): """ Get user input at every round :param lives: (int) the lives of player :param display: (string) the guessed answer to show user :param guessed_text: (string) the guessed character :return: (string) the character input from player """ print('The word looks like: ' + display) print('You have ' + str(lives) + ' guesses left.') print('You have guessed: ' + guessed_text) while True: guess_text = input('Your guess: ') if len(guess_text) == 1 and guess_text.isalpha(): return guess_text.upper() else: print('Illegal format.')
b535469cb4935f7be449745b4473839b9cb9fc7a
411,588
import re def is_valid_project_id(project_id): """True if string looks like a valid Cloud Project id.""" return re.match(r'^(google.com:)?[a-z0-9\-]+$', project_id)
46532d10a8a0ed304204d858445b935ff4f4bfe9
686,921
def pluralize(count: int, unit: str) -> str: """ Pluralize a count and given its units. >>> pluralize(1, 'file') '1 file' >>> pluralize(2, 'file') '2 files' >>> pluralize(0, 'file') '0 files' """ return f"{count} {unit}{'s' if count != 1 else ''}"
85f9be97488584db46f86808111ecf2d849b7dfc
175,859
def get_fastas(fasta_file, genes=False): """ >>> get_fastas('a.fasta') ('a.genomic.masked.fasta', 'a.features.fasta') >>> get_fastas('a.fasta', genes=True) ('a.genomic.masked.genes.fasta', False) """ if not genes: genomic_masked = fasta_file.replace('.fa', '.genomic.masked.fa') features_fasta = fasta_file.replace('.fa', '.features.fa') else: genomic_masked = fasta_file.replace('.fa', '.genomic.masked.genes.fa') features_fasta = False #fasta_file.replace('.fa', '.genes.fa') return genomic_masked, features_fasta
9a0f1d3436145d30d1c8a44e10883347ff5af864
412,588
def main_done_selector(card): """Selector for cards done and not connected.""" return not card.associations and card.state == 'closed'
dd2e6ac26eec64421543fad6b45c819dedecc3b4
221,415
def select_count_from(session, table) -> int: """ Function to select row count from provided table (like SELECT COUNT(*) FROM table) :param session: sqlalchemy session :param table: table to select from :return: row count """ count = session.query(table).count() return count
9e3869fb692c16281f768d73e019b693f43cd7fa
463,409
from typing import Callable import ast def eval_lambda(val: str) -> Callable: """Parse a lambda from a string safely. Args: val: string representing a lambda. Returns: a callable. Raises: ValueError: in case the lambda can not be parsed. """ parsed_lamba = ast.parse(val).body[0].value # type:ignore if isinstance(parsed_lamba, ast.Lambda) and "eval" not in val: return eval(val) else: raise ValueError(f"'{val}' can not be safely parsed as a lambda function")
aa2081f66471d483ea76cc9723c632cb354d5f42
106,943
def save_dotted_field(accessor_string: str, data: dict): """Saves data to a dictionary using a dotted accessor-string. Parameters ---------- accessor_string : str A dotted path description, e.g. "DBLinks.KEGG". data : dict The value to be stored. Returns ------- dict The nested dictionary. """ for chunk in accessor_string.split(".")[::-1]: data = {chunk: data} return data
cd55a988f63bcd6784a56bf5a18e85780e26b51b
273,971
def set_bit(value, index, new_bit): """ Set the index'th bit of value to new_bit, and return the new value. :param value: The integer to set the new_bit in :type value: int :param index: 0-based index :param new_bit: New value the bit shall have (0 or 1) :return: Changed value :rtype: int """ mask = 1 << index value &= ~mask if new_bit: value |= mask return value
0e42d70a9319d14ec7e984f0b42b08f97309430c
196,979
import locale def money(amount, symbol=True): """ Return a properly formatted currency string including symbol """ try: return locale.currency(float(amount), symbol, grouping=True) except ValueError: pass return ''
1aa9b2be89dbb956e870fc1f06c6e70406dd6d8a
142,042
import math def regular_poly_circ_rad_to_side_length(n_sides, rad): """Find side length that gives regular polygon with `n_sides` sides an equivalent area to a circle with radius `rad`.""" p_n = math.pi / n_sides return 2 * rad * math.sqrt(p_n * math.tan(p_n))
939ff5de399d7f0a31750aa03562791ee83ee744
3,279
def parse_token_clause(token_clause): """Parse the clause that could be either 'with', 'using', or 'without'.""" use_token = {"with": True, "using": True, "without": False}.get(token_clause) if use_token is None: raise Exception("Wrong clause specified: {t}".format(t=token_clause)) return use_token
acc04185822b57e21422d2ef442ab1dbdbbd10b0
200,705
def calculate_fuel(mass): """Calculate the fuel required for a module >>> calculate_fuel(12) 2 >>> calculate_fuel(14) 2 >>> calculate_fuel(1969) 654 >>> calculate_fuel(100756) 33583 """ return mass // 3 - 2
d2d2ae239027515fa9240c4bd59f6c7efb056d13
92,608
def parse_time(time): """Given the time string, parse and turn into normalised minute count""" if type(time) in [int,float]: return time if time.endswith('m'): time = time[0:-1] if time.find('h') != -1: time = time.replace('h', ':') if time.find(':') != -1: hours, minutes = time.split(':') if minutes.strip() == "": minutes = 0 else: hours = 0 minutes = int(time.strip()) total = int(minutes) + (int(hours) * 60) return total
b4effe0eb9b93a761e9f6f83f7d7d9b60bb8d978
90,502
import textwrap def format_template(template, *args): """ Given incoming text, remove all common indent, then strip away the leading and trailing whitespace from it. This is a modified version of code from Default/new_templates.py from the core Sublime code. """ return textwrap.dedent(template % args).strip()
4e1c08c4bce5af043789374f4348383cb50f623e
522,550
import re def get_collect_id(imageID): """Get the collect ID for an image name using a regex.""" collect_id = re.findall('Atlanta_nadir[0-9]{1,2}_catid_[0-9A-Z]{16}', imageID)[0] return collect_id
deffb98786fad57a6aa757b51c9df3ab885060b2
365,024
import csv def read_sleepasandroid_file(saa_filename): """ read in a SleepAsAndroid backup file and return it as a parsed list """ with open(saa_filename) as file: file_as_list = list(csv.reader(file, delimiter=',')) return file_as_list
22011c2ba784747c65c3dc47063fb486d3130785
651,228