content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_new_lp_file(test_nr): """ Get name of new LP file """ return "test/{0}-new.lp".format(test_nr)
f7527a053a640d080f3aecd9db24623d5563b250
15,833
def tokenize(tokenizer, data, max_length = 128): """ Iterate over the data and tokenize it. Sequences longer than max_length are trimmed. :param tokenizer: tokenizer to use for tokenization :param data: list of sentences :return: a list of the entire tokenized data """ tokenized_data = [] ...
30b3786c1299bc42cd2698eae83ce1c6bdc3cfbe
15,834
import logging def find_log_path(lg): """ Find the file paths of the FileHandlers. """ out = [] for h in lg.handlers: if isinstance(h, logging.FileHandler): out.append(h.baseFilename) return out
efab0cb7eafd0491e1365224dc83f816c7bb1b51
15,836
import requests def send_proms_pingback(pingback_target_uri, payload, mimetype='text/turtle'): """ Generates and posts a PROMS pingback message :param pingback_target_uri: a URI, to where the pingback is sent :param payload: an RDF file, in one of the allowed formats and conformant with the PROMS pin...
09ecff1835352f08e7fc5f4bce545585798e688c
15,838
def sign(x): """ Sign function """ return 1 if x >= 0 else -1
20d85cf36d183c96e75fa3b795bf7f05f558e3b8
15,844
def dict_hangman(num_of_tries): """ The function return the "photo" of the hangman. :param num_of_tries: the user's number of guessing :type num_of_tries: int :return: the photo of the hangman :rtype: string """ HANGMAN_PHOTHOS = { '1': """ x-------x""", '2': """ x-------x | | | | |""", '3': """ ...
3864d3072fa0fe9fea6c7e02733e466669335c80
15,847
def split_warnings_errors(output: str): """ Function which splits the given string into warning messages and error using W or E in the beginning of string For error messages that do not start with E , they will be returned as other. The output of a certain pack can both include: ...
aaf0ea05f5d32247f210ae1696ea58824629d075
15,851
def _get_type_and_value(entry): """Parse dmidecode entry and return key/value pair""" r = {} for l in entry.split('\n'): s = l.split(':') if len(s) != 2: continue r[s[0].strip()] = s[1].strip() return r
e6dd2068f10085c2dac233f1f71512e5874c5adc
15,855
def _replace_strings(obj, old, new, inplace=False): """ Recursively replaces all strings in the given object. This function is specifically meant to help with saving and loading of config dictionaries and should not be considered a general tool. """ if not inplace: obj = obj.copy() ...
3f7661a53ab8cbb836eee68b1bb3d1df9e73c4a5
15,857
def hello_world() -> str: """ Say something! """ return "Hello World!"
22deba02b863355d150653caf744a65950a2fec5
15,858
def range_geometric_row(number, d, r=1.1): """Returns a list of numbers with a certain relation to each other. The function divides one number into a list of d numbers [n0, n1, ...], such that their sum is number and the relation between the numbers is defined with n1 = n0 / r, n2 = n1 / r, n3 = n2 / r...
92e7f9f1b85011323cf5e90002d8f9151ae17e0e
15,859
import hashlib def getIdHash(id): """ Return md5 prefix based on id value""" m = hashlib.new('md5') m.update(id.encode('utf8')) hexdigest = m.hexdigest() return hexdigest[:5]
a9e8d67fae494cd2eaac41b6258be69ed10b667a
15,860
def findPayload(message, type): """ Find a payload/part that matches a type as closely as possible and decode it properly. Parameters ---------- message : email.message.Message The message to search. type : str A MIME type. Returns ------- str The payload as a string. """ charset =...
265159546f1b0d2a6cc065e2c467528ea74048ef
15,870
import csv def calculate_number_of_synthetic_data_to_mix(original_data_file, target_ratio): """Calculate the number of negative samples that need to be added to achieve the target ratio of negative samples. Args: original_data_file: path to the origi...
eb83cdbb9af39715f16e412f8ae799222a2a232f
15,871
def get_contact_info_keys(status_update): """Returns the contact info method keys (email, sms) used to send a notification for a status update if the notification exists. Returns [] if there is no notification """ if hasattr(status_update, 'notification'): return list(status_update.notificat...
020a9742df99cd65be1433165823c4f364009d85
15,879
def binary_search(input_list, number, min_idx, max_idx): """ Find the index for a given value (number) by searching in a sorted array Time complexity: O(log2(n)) Space Complexity: O(1) Args: - input_list(array): sorted array of numbers to be searched in - number(int)...
20358c096c529937d57503285150a90a37f62dd1
15,882
import torch def _calculate_ece(logits, labels, n_bins=10): """ Calculates the Expected Calibration Error of a model. (This isn't necessary for temperature scaling, just a cool metric). The input to this loss is the logits of a model, NOT the softmax scores. This divides the confidence outputs int...
af311a47b7558b07838a38d736386147804ea109
15,886
def history_parser(arg): """ @param: arg is a string that contains the words seperated by spaces @return: Returns two strings. The first word removed from arg and everything after the space """ v = -1 try: v = arg.index(' ') except ValueError: return None, None first_word...
267f0cd8ddfc0bfa9106d18341421d5d4d48ed1f
15,888
import json def decode(body): """decode string to object""" if not body: return None return json.loads(body)
2663a3d742b6f5e17d5b0aed876f136b30fdde1c
15,893
def bintodec(x): """Convert Binary to Decimal. Input is a string and output is a positive integer.""" num = 0 n = len(x) for i in range(n): num = num + 2 ** i * int(x[n - i - 1]) return num
e83e3c34c237d5840bd024f49f3d436e6804b427
15,895
import collections def _create_gt_string(cnv_row): """ Creates VCF gt string for a single-sample VCF. """ gt_dict = collections.OrderedDict() gt_dict["GT"] = cnv_row.GT gt_dict["S"] = cnv_row.S gt_dict["NS"] = cnv_row.NS gt_dict["LS"] = cnv_row.LS gt_dict["LNS"] = cnv_row.LNS ...
fd866f2ce22cb8b34608dcd6161be5d11f374c82
15,896
def generate_name_Id_map(name, map): """ Given a name and map, return corresponding Id. If name not in map, generate a new Id. :param name: session or item name in dataset :param map: existing map, a dictionary: map[name]=Id :return: Id: allocated new Id of the corresponding name """ if name...
8e86daf1a345803b280ad91f40a18eaeaa0cde5f
15,897
def _flatten_task(obj): """Flatten the structure of the task into a single dict """ data = { 'id': obj.id, 'checkpoint_id': obj.checkpoint_id, 'policy_id': obj.policy_id, 'provider_id': obj.provider_id, 'vault_id': obj.vault_id, 'vault_name': obj.vault_name, ...
f10b0db4cefad81818f3195da0cf25339c420823
15,907
import itertools def prev_this_next(it): """ iterator to gradually return three consecutive elements of another iterable. If at the beginning or the end of the iterable, None is returned for corresponding elements. """ a, b, c = itertools.tee(it, 3) next(c) return zip(itertools.chain([...
dc4416ed0b1c06502f3005df418536b9a92b4481
15,911
def parse_unity_results(output): """Read output from Unity and parse the results into 5-tuples: (file, lineno, name, result, message)""" result = [] lines = output.split('\n') for line in lines: if line == '': break parts = line.split(':', maxsplit=4) if len(parts...
488f98d69434b2abdb9200353e51c12805694297
15,913
def airports_codes_from_city(name, airports_list, airport_type): """ Here we finding all airports(their codes) in city or state. :param name: name of airport we gonna check :param airports_list: list of all airports :param airport_type: type of :param name: - 'code', 'city', 'state' ...
995bab1eca1633c5e52cfdfe5b1a92b7738fbbb5
15,916
from tqdm import tqdm def _get_iterator(to_iter, progress): """ Create an iterator. Args: to_iter (:py:attr:`array_like`): The list or array to iterate. progress (:py:attr:`bool`): Show progress bar. Returns: :py:attr:`range` or :py:class:`tqdm.std.tqdm`: Iterator object. ...
c1dd29a430d2c468e3f89536fef593b7477a04ce
15,917
def check_replication(service, service_replication, warn_range, crit_range): """Check for sufficient replication of a service :param service: A string representing the name of the service this replication check is relevant to. :param service_replication: An in...
ac515bd0881431eebd0e14d0578f0bb1c07835f3
15,919
import json def load_metadata(filename): """Read json from file and return json object.""" with open(filename, encoding="utf-8") as fd: return json.load(fd)
9a9fbccaf4a7e64d2aef4b427a68226e2b41c181
15,920
def get_section_number(data): """Gets the section number from the given section data Parses the given array of section data bytes and returns the section number. SI tables come in sections. Each section is numbered and this function will return the number of the given section. """ return data[6]
5d7b9c51d614f627e3765b683216905ad124598b
15,922
def denumpyfy(tuple_list_dict_number): """A nested structure of tuples, lists, dicts and the lowest level numpy values gets converted to an object with the same structure but all being corresponding native python numbers. Parameters ---------- tuple_list_dict_number : tuple, list, dict, number ...
70558250e3875cde2c66fe6680fd6a6ace498602
15,924
def _get_nn_for_timestamp(kd_tree, X, timestep, aso_idx, k, radius): """Returns the nearest ASOs to the provided `aso_idx` ASO. If a `radius` is provided then the results are all the ASOs within that given radius, otherwise the results are the `k` nearest ASOs :param kd_tree: The KD-tree build for the...
d2dc4f7912aafc903782c21ec374bdd4d24475bc
15,925
def _poynting(field): """Computes poynting vector from the field vector""" tmp1 = (field[0].real * field[1].real + field[0].imag * field[1].imag) tmp2 = (field[2].real * field[3].real + field[2].imag * field[3].imag) return tmp1-tmp2
55c334b5c2e5df87d13ad0c000e5e599d6e8b948
15,929
import socket def tcp_port_reachable(addr, port, timeout=5): """ Return 'True' if we could establish a TCP connection with the given addr:port tuple and 'False' otherwise. Use the optional third argument to determine the timeout for the connect() call. """ s = socket.socket(socket.AF_INE...
22c530cdbccf6c19ffe60b5e1904e797f7d059ea
15,930
def scale_wind_speed(spd, scale_factor: float): """ Scales wind speed by the scale_factor :param spd: Series or data frame or a single value of wind speed to scale :param scale_factor: Scaling factor in decimal, if scaling factor is 0.8 output would be (1+0.8) times wind speed, if it is -0.8 the ou...
a55b76aee3e3ab2718db2714b6be0915c24e1631
15,931
def transform_dict(img): """ Take a raster data source and return a dictionary with geotranform values and keys that make sense. Parameters ---------- img : gdal.datasource The image datasource from which the GeoTransform will be retrieved. Returns ------- dict A di...
8817028adfce28ae7f7ae787d4256d52fee095bc
15,933
def read_list(filename): """ Read file line by line, ignoring lines starting with '#' Parameters ---------- filename : str or pathlib.Path Returns ------- list """ with open(filename, 'r') as f: lines = f.readlines() return [line.rstrip('\n') for line in lines if n...
e4957425f1c2ff99e9e16ad8fe22e57ffa6e38a9
15,936
def get_trunc_minute_time(obstime): """Truncate obstime to nearest minute""" return((int(obstime)/60) * 60)
1a1a6ba47573442f0e98ca9aeaa8a5506e7ab081
15,942
def process_proc_output(proc, print_output=True): """Print output of process line by line. Returns the whole output.""" def _print(s): if print_output: print(s) lines = [] for line in iter(proc.stdout.readline, b''): _print('| %s' % line.rstrip()) lines.append(line) return ''.join(lines)
5af5d3355a7d588806120da625894fcbe93bdca0
15,944
def make_subtitle(rho_rms_aurora, rho_rms_emtf, phi_rms_aurora, phi_rms_emtf, matlab_or_fortran, ttl_str=""): """ Parameters ---------- rho_rms_aurora: float rho_rms for aurora data differenced against a model. comes from compute_rms rho_rms_emtf: ...
7569e658785e571a4dcd4428e76a13b8b10e3327
15,947
from typing import List def find_substring_by_pattern( strings: List[str], starts_with: str, ends_before: str ) -> str: """ search for a first occurrence of a given pattern in a string list >>> some_strings = ["one", "two", "three"] >>> find_substring_by_pattern(some_strings, "t", "o") 'tw' ...
4bc0abe6fcdbf81350b575dd9834b9c646fda81e
15,948
def noramlize_data(df): """ Normalizes the data by subtracting the mean and dividing by the max - min. :param df: the dataframe that we are normalizing :return: the normalized dataframe """ df_normalized = (df - df.mean()) / (df.max() - df.min()) return df_normalized
13adfc79876f989d6983f74e57c7372c9dc00000
15,952
def filter_packets_by_filter_list(packets, filter_list): """ :param packets: Packet list :param filter_list: Filters with respect to packet field :type filter_list: list of pyshark_filter_util.PySharkFilter :return: Filtered packets as list """ filtered_packets = [packet for packet in packe...
61106178dca039498c4fec1239bd7d251b69f812
15,955
from datetime import datetime def _get_date(element): """ This function extracts the date the image was taken from the image element and converts it to a datetime format. Args: element: A dict cuntianing all the image attributes. Returns: Date the image was taken in the format of dat...
b42f6b24ce3545571bf1025b5b984386fde20208
15,958
def make_predictions(data, model, weights): """Predict the labels of all points in a data set for a given model. Args: data (array[float]): Input data. A list with shape N x 2 representing points on a 2D plane. model (qml.QNode): A QNode whose output expectation value will be ...
4ac2ba85a12d56f0128ba518e8a7d030c0eb5734
15,968
def get_major_minor(stat_inst): """get major/minor from a stat instance :return: major,minor tuple of ints """ return ( stat_inst.st_rdev >> 8 ) & 0xff, stat_inst.st_rdev & 0xff
ec623deb66d1e95f5ec9744ffbefc03c52ebf6a9
15,970
def _resources_json_version_required() -> str: """ Specifies the version of resources.json to obtain. """ return "develop"
7f9eaff50b3a03ec50501e7ae125f4daab462325
15,971
import hashlib def get_metadata_hash_for_attachments(attachments): """ Calculate a metadata hash from a collection of attachments. The hash will change if any of the attachments changes. """ hashes = [attachment.metadata_hash for attachment in attachments] # Sort the hashes to make the hash d...
fb56306c611a1aa1d87e897650142375a69f26e3
15,976
import torch def rmspe(pred, true): """Computes RMSPE""" return torch.mean(((true - pred) / true)**2)**0.5
2a83c9c10fb0547b4d90c805d94db871eb1b9e11
15,977
def get_xr_resolution(ds): """ Read dataset and get pixel resolution from attributes. If attributes don't exist, fall back to rough approach of minus one pixel to another. Parameters ---------- ds: xarray dataset, dataarray A single xarray dataset with variables and x and y dims. ...
3d87ff33190078753a496fd5f14854fa98eb1017
15,985
from typing import List from typing import Dict def match_relationships(relationships: List): """Creates a dict that connects object_id to all objects_ids it has a relationship with. Args: relationships (List): A list of relationship objects. Returns: Dict. Connects object_id to all obje...
870db3b324f340a7f632251ebe22bfae6e693076
15,989
def makeChromTiles(db): """ Make a region for each chromosome """ out = [] for (k, v) in db.chromsTuple: out.append([k, 0, v]) return out
ca887035f05047bf7172c4e120fc7623a0fcb3e5
15,990
def data2mesh(data): """ Extracts from a given torch_geometric Data object the mesh elements Parameters ---------- data : Data a torch_geometric Data object Returns ------- (Tensor,LongTensor,Tensor) the points set, the topology and the vertex normals tensor """ ...
781489d95db76d106c910efda9bbc5f348e9d7ed
15,994
def prime_generator(maxi): """ Generate all the prime numbers below maxi. maxi is not included. The method uses Aristotle's sieve algorithm. >>> prime_generator(10) [2, 3, 5, 7] """ li = [] for _ in range(maxi): li.append(1) li[0] = li[1] = 0 for pos, val in enumerate...
f2829ed995f0f289b22960fad706cf3ec0371446
15,998
def filter_content(contents, rules, mode=any): """ Filter contents by given rule. Args: contents `list` List of illust, the content may vary from source to source. Besure you know the data hierachy of object. rules `list` A list of function takes...
a875ee3d8523a29043b576c9d19ef8a09589ed91
15,999
def get_dict_key_by_value(source_dict: dict, dict_value): """Return the first key of the ``source_dict`` that has the ``dict_value`` as value.""" for k, v in source_dict.items(): if v == dict_value: return k return
0ae198c7d07fe57898779f0b75b75bdb590f5a3d
16,000
from pathlib import Path def get_cases(f, sep="---"): """ Extracts inputs and outputs for each test/verification case within f, where f is a folder. Params ====== f: str The folder containing the cases to be extracted. sep: str The substring separating comments from the input...
bedcc7cedd791505dbed886a539df92aa0fa3f87
16,001
import requests def create_empty_zenodo_upload(access_token): """ Create an empty upload using Zenodo API. :param access_token: Zenodo access token. :return: requests.models.Response from Zenodo API """ headers = {"Content-Type": "application/json"} r = requests.post('https://zenodo.org/ap...
14a26a07a08b2dab1ccf55ddea8c3d4cb3d9a2d6
16,002
def slurp(name): """ Read the file :param name: read the named file :return: the content """ with open(name, "r") as f: return f.read()
2edb241b5cbb0c9298dbdc9dd5f1f89786fff036
16,004
def vec_is_void(a): """ Check whether a given vector is empty A vector is considered "void" if it is None or has no elements. Parameters ---------- a: list[] The vector to be checked Returns ------- bool True if the vector is empty, False otherwise """ ...
9a9b6f78ec2ddb81990fe54a5b429413c0472742
16,006
import calendar def _sort_order(count_items): """Key for sorting day counts in days of the week order.""" return list(calendar.day_name).index(count_items[0])
9fa5a3f37ee034a99c2c6ed428655261661210aa
16,012
def download_input(storage_provider, parsed_event, input_dir_path): """Receives the event where the file information is and the tmp_dir_path where to store the downloaded file. Returns the file path where the file is downloaded.""" return storage_provider.download_file(parsed_event, input_dir_path)
887ca61a40a658d172b4b77833132b73933a14ce
16,015
def get_bit(val: int, bitNo: int) -> int: """ Get bit from int """ return (val >> bitNo) & 1
19d49512387da66e5889fc1bacc014be240be4a9
16,016
def GetChildNodesWhereTrue(node_id, tree, stop_function): """walk down in tree and stop where stop_function is true The walk finishes at the leaves. returns a list of tuples of nodes and distance. """ result = [] def __getChildNodes(node_id, distance): node = tree.node(node_id) ...
9837a8ac294b8202a6e17deecd213d25599f575b
16,017
def get_full_version(package_data): """ Given a mapping of package_data that contains a version and may an epoch and release, return a complete version. For example:: >>> get_full_version(dict(version='1.2.3')) '1.2.3' >>> get_full_version(dict(version='1.2.3', epoch='2')) '2~1.2.3' ...
3a8cc3731da2ef3f99e3e9f203e084c9478f48c8
16,020
def knight_tour(n, path, u, limit): """ Conduct a knight's tour using DFS. Args: n: current depth of the search tree. path: a list of vertices visited up to this point. u: the vertex we wish to explore. limit: the number of nodes in the path. Returns: done (bool...
f11a2da4e740183a85dbd2f281c65dda77237dad
16,021
def read_tags_and_datablocks(text): """ read a file consisting of blocks of numbers which are separated by tag lines. separate tag lines from data lines return two lists e.g. for pp.data file: Atomic number and pseudo-charge 14 4.00 Energy units (rydberg/hartree/ev): rydberg Angular momentum of local component...
372512010198aa401552302d45f0a0745477bec1
16,022
def convert_sensor_type(v): """ converts the sensor type value into something more meaningful. """ if v is 0: return "None" elif v is 1: return "RealPower" elif v is 2: return "ApparentPower" elif v is 3: return "Voltage" elif v is 4: return "Current" else: return "Unkn...
7f5bd77db7a240d21728b526daae7729b0871143
16,023
import bz2 def bunzip2(fileobj): """ bunzip2 the file object. """ return bz2.decompress(fileobj)
7da3f9b64cd0f6765860678b18be661fd42b813e
16,034
def observatory_from_string(string): """If "jwst" or "hst" is in `string`, return it, otherwise return None.""" if "jwst" in string: return "jwst" elif "hst" in string: return "hst" else: return None
217cc3cf3c5b802799c0db73563f6d11b7ab4c4d
16,035
def get_letters_pep(peptides_lst): """ Get letters list and letter-index dictionaries """ word_to_ix_ = dict((i, j) for j, i in enumerate(['<PAD>']+list(set(x for l in peptides_lst for x in l)))) ix_to_word_ = dict((j, i) for j, i in enumerate(['<PAD>']+list(set(x for l in peptides_lst for x in ...
5c341a9cdd99a874a34c1ed967a5e95ad1c7ed6f
16,037
def _get_lat_lon(df): """Get latitude and longitude from geometries.""" col = df._geometry_column_name df["latitude"] = [latlon.y for latlon in df[col]] df["longitude"] = [latlon.x for latlon in df[col]] return df
9ab4b1cb469ae88444de97ec0cb0cec008643c4a
16,040
def fix_fp(sequence, parallel): """ Fix footprints Parameters -------------- sequence Sequence parallel Parallel Returns ------------- sequence Sequence parallel Parallel """ sequence = sequence.difference(parallel) return sequence, p...
721021af7d9f4b07ee25861788cde878a31b6135
16,044
def apply_ratio(o_w, o_h, t_w, t_h): """Calculate width or height to keep aspect ratio. o_w, o_h -- origin width and height t_w, t_h -- target width or height, the dimension to be calculated must be set to 0. Returns: (w, h) -- the new dimensions """ new_w = t_h * o_w / o_h...
f3143e5a5ad8aeafbb913e73aab40e8e8990ddd6
16,045
def maybe_append(usa_facts, jhu): """ Append dataframes if available, otherwise return USAFacts. If both data frames are available, append them and return. If only USAFacts is available, return it. If USAFacts is not available, return None. """ if usa_facts is None: return None ...
4f0831a09ac36caaec6f825036e69d0f5b62b19f
16,050
def evaluate(clauses, sol): """ evaluate the clauses with the solution """ sol_vars = {} # variable number -> bool for i in sol: sol_vars[abs(i)] = bool(i > 0) return all(any(sol_vars[abs(i)] ^ bool(i < 0) for i in clause) for clause in clauses)
be50aa2c8f04b6d1ac76a17aea86beedc7abff4c
16,053
import json def _load_iam_data(path): """Builds a dictionary containing the information about all the AWS IAM resources and the actions they relate to (for more information look at the README.md in this directory). The keys of the dictionary are all the possible IAM policy actions and the values are s...
7b394285f088ade8042207fdccbb9e6dfec78314
16,058
def is_field(x): """ Return whether or not ``x`` is a field. Alternatively, one can use ``x in Fields()``. EXAMPLES:: sage: R = PolynomialRing(QQ, 'x') sage: F = FractionField(R) sage: is_field(F) True """ return x.is_field()
87efa719721d72df5c751d734f2f26d6641190c1
16,059
from typing import Optional from typing import Dict def create_exclusive_start_key(player_id: str, start_key: Optional[str]) -> Optional[Dict[str, str]]: """ Create the 'ExclusiveStartKey' parameter for the DynamoDB query, based on the user-provided 'start_key' parameter to this Lambda function. """ ...
7a03434e2d52908eb4f4d68483058183913ac9bb
16,061
def label_id_to_cluster_id(label_id, C, unused_labels): """Map the label id to the cluster id according to clustering matrix. Args: label_id: the label id. C: the cluster matrix of shape L x C. unused_labels: used to adjust the label id. Returns: the cluster id. ...
61593eb822dbaf88f101b2948c02de3fc07794d1
16,062
def expand_locations_and_make_variables(ctx, attr, values, targets = []): """Expands the `$(location)` placeholders and Make variables in each of the given values. Args: ctx: The rule context. values: A list of strings, which may contain `$(location)` placeholders, and predefined Ma...
cb426117582161c5f32034df2cc1db29ebe37205
16,065
def get_result_or_raise(future): """Returns the ``result`` of *future* if it is available, otherwise raise. """ return future.result
8f6b2b6b6def964d48829f2b63467a6e39e3b853
16,071
def missing_respondents(reported, observed, identified): """Fill in missing respondents for the f1_respondent_id table. Args: reported (iterable): Respondent IDs appearing in f1_respondent_id. observed (iterable): Respondent IDs appearing anywhere in the ferc1 DB. identified (dict): A {...
f919a9d398898b06d4442c75cc314a8cb52e1c5f
16,073
def distance(x_0, y_0, x_1, y_1): """Return distance between 2 points (x_0, y_0) and (x_1, y_1) """ x_dist = x_0 - x_1 y_dist = y_0 - y_1 return(x_dist ** 2 + y_dist ** 2) ** 0.5
06c250b09e2a386f1814fe9c748cad574869a741
16,077
from typing import Callable from typing import Sequence def randline(filename: str, randchoice: Callable[[Sequence[str]], str]) -> str: """ return a randomly-selected line from the given file """ with open(filename, "rt", encoding="utf-8") as fh: return randchoice(fh.readlines()).rstrip()
6978158b25a8702e99ee6e7f9461cd391873eee4
16,081
async def latency(ctx): """Returns my gateway latency.""" return f'{ctx.client.gateway.latency*1000.:.0f} ms'
f2d088adfa485bfff8da5154ce672232e4d57e1d
16,082
def str2intlist(s, delim=","): """ create a list of ints from a delimited string Parameters ---------- s: string delim: string Returns ------- int_list: list of ints Examples -------- >>> str2intlist("1,2,3") [1, 2, 3] >>> str2intlist("1-3") [1, 2, 3] >>> s...
ae7a568a9e8b7c55e146515fad4dd810bee4ae46
16,084
def generate_timestamp_format(date_mapper: dict) -> str: """ Description ----------- Generates a the time format for day,month,year dates based on each's specified time_format. Parameters ---------- date_mapper: dict a dictionary for the schema mapping (JSON) for the dataframe f...
cd535a4fb35917517711cf149430c128e2c46b6d
16,085
def get_command(line, fmt_space): """ Given a header line, get the possible command Parameters ----------- line : string Line of the header fmt_space : boolean Yes = Novonix format with spaces in the commands Returns -------- command : string Instruction in...
78642fd6e98817b85ce8431774a34723ed649473
16,086
import json def harmonize_credentials(secrets_file=None, cromwell_username=None, cromwell_password=None): """ Takes all of the valid ways of providing authentication to cromwell and returns a username and password :param str cromwell_password: :param str cromwell_username: :param str secrets_...
f0802b3e65ebec76393090f608c77abea312867b
16,087
import pathlib def lambda_filtered_paths(directory: str): """ Return list of filepaths for lambda layers and functions. Unecessary files are filtered out. """ paths = pathlib.Path(directory).rglob("*") return [ f for f in paths if not any(pat in str(f) for pat in ["__py...
1638e821a249244fde95e26a027176d1e6d87491
16,089
def rescale(values, old_min, old_max, new_min, new_max): """Rescale a set of values into a new min and max """ output = [] for v in values: new_v = (new_max - new_min) * (v - old_min) / (old_max - old_min) + new_min output.append(new_v) return output
c07173fca2f6ba0d1e1e32c257b9e4f4a39fe5a7
16,091
def KeyValuePairMessagesToMap(key_value_pair_messages): """Transform a list of KeyValuePair message to a map. Args: key_value_pair_messages: a list of KeyValuePair message. Returns: a map with a string as key and a string as value """ return {msg.key: msg.value for msg in key_value_pair_messages}
7ab0d9a3dea7da762a559efa00ae50247ee8d2d4
16,092
def parse_result(results): """ Given a string, return a dictionary of the different key:value pairs separated by semicolons """ if not results: return {} rlist = results.split(";") keyvalpairs = [pair.split(":") for pair in rlist] keydict = { pair[0].strip(): pair[1].stri...
eca808c2baa0b5c95e6fd052f2afabf53b05bd3a
16,096
def case(bin_spec: str, default: str = "nf") -> str: """ Return the case specified in the bin_spec string """ c = default if "NF" in bin_spec: c = "nf" elif "ÞF" in bin_spec: c = "þf" elif "ÞGF" in bin_spec: c = "þgf" elif "EF" in bin_spec: c = "ef" return c
b2fdab5d1a48e1d20c3a561707033970cac55356
16,097
def name_func(testcase_func, _, param): """Create a name for the test function.""" return '{}_{}_{}'.format(testcase_func.__name__, param.args[0], param.args[1].__name__)
804f593850cff07758a61bd0ae2ccd92b2e46b19
16,100
def Convert(string): """converts string to list""" li = list(string.split(" ")) return li
a446d46be5d7c2df7139460a461e0825784f5e89
16,102
import pathlib def get_paths_to_patient_files(path_to_imgs, append_mask=True): """ Get paths to all data samples, i.e., CT & PET images (and a mask) for each patient. Parameters ---------- path_to_imgs : str A path to a directory with patients' data. Each folder in the directory must corr...
61480fee3e300d2ca97e819fae875cf4c7a637e1
16,103
def check_chars_in_positions(password, left, right, in_char): """ Check if password is valid based on if char count is in exactly one of position left or position right returns bool (True = valid password) """ is_in_left = password[left-1] == in_char is_in_right = password[right-1] == in_c...
36a80525307ecf359cf631079e128617c2d22bc3
16,104
from typing import Dict def _create_stats_dict_from_values( total_sum_w: float, total_sum_w2: float, total_sum_wx: float, total_sum_wx2: float ) -> Dict[str, float]: """Create a statistics dictionary from the provided set of values. This is particularly useful for ensuring that the dictionary values are ...
4ef02ef12b903a4a0a14f3c5fa9ce7edf11f6380
16,107