content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_nyquist_frequency(timedata): """returns the Nyquist frequency from time data""" return (abs(0.5 * len(timedata) / timedata[-1] - timedata[0]))
9b6a4a657b8586caf550455a284c506ec747e0af
597,114
from pathlib import Path def get_most_recent(matching_filenames): """Returns most recently modified file as a Path object""" res = [] for fpath in matching_filenames: p = Path(fpath).resolve() if p.is_file(): file_mtime = p.lstat().st_mtime res.append((file_mtime, p...
c464fb7d4dff9d7ec0edbe4d67e3be6745d471ac
597,117
def excess_pore_pressure_ratio(df): """ Assign the excess pore pressure ratio, if the water pressure u2 is defined. Else, raise ERROR. :param df: (DataFrame) :return: (DataFrame) """ try: u2 = df["u2"] except KeyError: raise SystemExit("ERROR: u2 not defined in .gef file, ch...
371b43ddbbe80c282117436181c83d0b0bb19ff5
597,118
def get_output_ops(op, op_reg_manager): """Returns output ops for a given op. Args: op: tf.Operation to get outputs of. op_reg_manager: OpRegularizerManager to keep track of the grouping. Returns: List of tf.Operation that are the outputs of op. """ output_ops = [] for output_tensor in op.outp...
1a69bbf2d72c7340ff4109d01138ccf40be35bd6
597,124
def is_segment_inside_cone( base_x, base_y, slope_min, slope_max, seg1_x, seg1_y, seg2_x, seg2_y ): """Compute if segment lies inside 2d closed cone Two-dimensional closed cone is defined as all rays from point `(base_x, base_y)` and with slopes inside `[slope_min, slope_max]` range (rays are dire...
e72865582d946b7bc0046a42023cf1411ec134d0
597,130
def obtener_medallas_de_atleta(atletas: list, anio_0: int, anio_f: int, nombre_atleta: str) -> list: """ Función que genera una lista de las medallas de un atleta en cierto período de tiempo definido. Parámetros: atletas: list de diccionarios con la información de cada atleta. anio_0: int añ...
f48571b37d3363c20a4c4c64744cce120c36e278
597,132
from typing import Tuple def format_key_and_input_text(key: str, input_text: str) -> Tuple[str, str]: """ Returns a tuple of given key and input text stripped of all double spaces, and converted into upper case letters. """ def format(x): return x.upper().replace(' ', '') formatted_key = for...
a11727d3bc80b1015a6fc2295a01ef903c2d1fa1
597,135
from typing import List import math def hue (size:int, maximum) -> List[int]: """ get the ith sequence in [0, 0, 0] ... [255, 255, 255] """ index = math.floor((size / maximum) * 255 ** 3) blue = (index) & 255 green = (index >> 8) & 255 red = (index >> 16) & 255 return [red, green, blue]
f769c7e4d25ea28b7085a2b379eaf8279e2226c6
597,136
def split_passports_file(passports_file): """Split the passports_file in batches """ return passports_file.split('\n\n')
0f548c4f589ba2751fd7af5a45d1dd149a06c222
597,137
def export_image( client, file_type, file_=None, filename=None, height=None, width=None, dpi=None, depth=None, ): """Export a model to an image file. Args: client (obj): creopyson Client. file_type (str): Image Type. Valid values: BMP, EPS...
41384711cd39055ec8bd8159342af459c1267d3b
597,138
def read_msr_fields(line): """ Function to detect presence of tstat and msr_id fields in a DynaAdjust adj file :param line: Measurement header line :return: True/False switches for presence of tstat and msr_id fields """ t_stat_field = False msr_id_field = False if 'T-stat' in line: ...
5042e2fe0e7b9d4dec845b02f8ee0712815ed92a
597,139
def yolo2coco(bboxes, height=720, width=1280): """ yolo => [xmid, ymid, w, h] (normalized) coco => [xmin, ymin, w, h] """ # bboxes = bboxes.copy().astype(float) # otherwise all value will be 0 as voc_pascal dtype is np.int # denormalizing bboxes[..., 0::2] *= width bboxes[...,...
3a21809ceb47ebfa711aeb33cddaa3290c2141dc
597,141
import struct def read_header(raw): """ Reads the nes header and places the relevant data in a dictionary. The keys are the following: ID (string): This will always be 'NES' MAPPER (int): The nes mapper number. FOUR_SCREEN (bool): Does the cartridge support four screen? TRA...
94dc6ee3c39a0e74e062f6645355c7abc68b1314
597,145
def get_squared_primes_to_use( num_to_look: int, squared_primes: list[int], previous_index: int ) -> int: """ Returns an int indicating the last index on which squares of primes in primes are lower than num_to_look. This method supposes that squared_primes is sorted in ascending order and that ...
70cebf2ff919462cd22a6d0bf01c60b6ad77a49d
597,150
from datetime import datetime def generate_filename(prefix, filetype='tar', fmt='%Y%m%d-%H:%M:%S:%f'): """ Generates a string to be used as the bundle filename. Format: <prefix>-<data-fmt>.<filetype>> """ now = datetime.strftime(datet...
c29f095b6b519254cf3076fc5d3945d5b2769f3e
597,151
import base64 def decode64(data): """Google Cloud Iot returns state data as base64 encoded strings. Use this Function to decode them.""" return base64.b64decode(data)
3314ced8d57fa66ab9608b1c3663826de6b49237
597,163
import binascii def crc32(s): """Converts s (if a str) to utf-8 bytestring and applies crc32.""" if isinstance(s, str): s = s.encode('utf-8') return binascii.crc32(s) & 0xffffffff
2a8ff47e47399a7fbbaf873b3d60099846974bec
597,167
import jinja2 import pathlib def get_template(template_file): """Get a jinja template.""" jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(pathlib.Path("/").resolve()), ) template = jinja_env.get_template(str(pathlib.Path(template_file).absolute())) return template
55f53a4f8ffe6d2caf5a497d090f76826c4b6162
597,169
import copy def separate_urls_metadata(urls_metadata): """Separate type and state from urls_metadata record. Type and state are removed from the urls_metadata key value pair/jsonb object. To keep backwards compatibility these are still ingested through the urls_metadata field. We have to manually sep...
8e823a7144a40c3f70d549554f577928dbdcbe50
597,176
def convert_LTRB2QUAD(points): """Convert point format from LTRB to QUAD""" new_points = [points[0], points[1], points[2], points[1], points[2], points[3], points[0], points[3]] return new_points
f70f9ff23447dd6fa0b117730fe66e05b1c489f8
597,178
import random import string def random_string(minimum, maximum): """ Returns a random ASCII sequence between start and end. Arguments --------- start: minimum chars end: maximum chars Returns ------- random string """ length = random.randint(minimum, maximum) ...
20ff9bfaefcd2a03f18832544c42eed06079eb8c
597,179
def get_outer_boundaries(regions, cls, rest_cls): """ Assuming rest periods alternate with other classes, find the outer boundaries of the rest regions enclosing all regions for cls >>> l = [0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 2, 0, 3, 3, 0, 4] >>> d = get_regions(l) >>> get_outer_boundari...
4de86e6b6221469a976b86eec5b9b5c4eb5c6a01
597,184
def _strToBool(v): """ Helper function for argparse. Convert string representations of booleans to actual booleans. """ if v == "True": return True else: return False
7357683cc3f35fe8781c52c73d35b08a2ce18a92
597,186
def _findDescendantBreadth(acc, pred): """ Internal function for locating one descendant. Called by L{findDescendant} to start the search. @param acc: Root accessible of the search @type acc: Accessibility.Accessible @param pred: Search predicate returning True if access...
281fd3a790e18b1dc1f774448d7670fd687134c7
597,189
def check_pair_sum(k: int, nums: list): """ 1. Go through all the numbers 2. As you iterate, add complement to a set 3. Two numbers add up to k if number is in complements Parameters: k (int): desired sum nums (list): available numbers Returns boolean: tru if there are 2 numbers in...
28325b01220a6450e5df650df598732f98655b1d
597,190
import torch def fork(func, *args, **kwargs): """ Creates an asynchronous task executing `func` and a reference to the value of the result of this execution. `fork` will return immediately, so the return value of `func` may not have been computed yet. To force completion of the task and access the...
a3e35bb58952c69eb20683a071333e6309f31994
597,193
def read_file(filename): """Fetch the contents of a file""" with open(filename) as file: return file.read()
77c856fb6bad032186974e53af45143c12fe4392
597,199
def identity(value): """The identity function: returns the value passed to it.""" return value
800f54f0949a148adfa57b457d16bfaae9a5c828
597,201
def get_ids( args ): """ reads in the idfile and returns a hash, mapping record names to IDs """ idhash = {} fo = open( args.get('idfile') ) for line in fo: recordname, recordid = line.split() idhash[ recordname ] = recordid return idhash
4821eb173857ef5ded8c273ef38745ed6e3af578
597,205
import re def _regexify_subfmts(subfmts): """ Iterate through each of the sub-formats and try substituting simple regular expressions for the strptime codes for year, month, day-of-month, hour, minute, second. If no % characters remain then turn the final string into a compiled regex. This assum...
2b9b13299e539ec77edd8c368ba8b81a199f562b
597,207
def get_pedb_ids_jaad(annotations, vid): """ Get pedestrians'(with behavior tags) ids in specific video. :param: dataset: JAAD raw data in dictionary form vid : video id (str) :return: pedestrians' ids """ pedb_ids = [] ped_keys = list(annotations[vid]['ped_annotations'].keys())...
d7fe9471514ce4dd3a897b00955b2ea4a8a8d0d1
597,209
def readSinks(sinkFile): """Get the list of compounds to consider as sink.""" sinks = set() for line in open(sinkFile): m = line.rstrip().split('\t') sinks.add(m[0]) return sinks
82e29af81834898aed4924fba697f0c7dd82e85d
597,214
def dfor(value, default): """null coalescing operator Args: value (Any) : value default (Any) : default value Returns: Any: If the specified value is not None, return the specified value. Otherwise, return the specified default value. """ if value is...
ca3972bb61e78403fca5aae0da73840fe7528dcd
597,215
import re def validar_cpf(cpf): """ Valida CPFs, retornando apenas a string de números válida. # CPFs errados >>> validar_cpf('abcdefghijk') False >>> validar_cpf('123') False >>> validar_cpf('') False >>> validar_cpf(None) False >>> validar_cpf('12345678900') Fals...
cb60352b16359e077fcc1b3918e159a2396202a1
597,217
def willr(df, high, low, close, willr, n): """ Williams %R is a momentum indicator that reflects the level of the close relative to the highest high for the look-back period. %R corrects for the inversion by multiplying the raw value by -100. As a result, the Fast Stochastic Oscillator and Williams ...
0ad0e432ba642242548f795ffbff95913ad60429
597,230
import json def _format_node(node): """ Prepares a node for insertion into the graph database. Dictionaries cannot be inserted. :param node: Node to format. :return: Formatted node. """ formatted_node = dict() for prop in node: if isinstance(node[prop], dict) or isinstance(node...
19bec391fe4976e6aee50d8dec2f20e12a54601a
597,231
def cpa(total_cost, total_acquisitions): """Return the CPA (Cost per Acquisition). Args: total_cost (float): Total cost of marketing. total_acquisitions (int): Total number of acquisitions. Returns: cpt (float) as total cost per acquisition """ return total_cost / total_ac...
d4f0abab3ee8f266302ee8aba87fa6becff115f5
597,232
def celsius_to_fahr(temp_celsius): """Converts Celsius temperatures to fahranheit Parameters -------- temp_celsius: int | float Input temperature value in celsius (should be a number) Returns -------- Temperature in Fahranheit (float) """ return 9/5 *...
c70fdfdbad334d3d5ba4051d9990d1f507749982
597,233
def get_table_name(create_table_statement): """ Return the name of the table from the create table statement. :param create_table_statement: The create table statement :return: The name of the table """ if "." in create_table_statement.split(' ', 3)[2]: table_name = create_table_stateme...
d5262bd70840ff84cf897ad9530025e1b9713b33
597,238
def clean_completion_name(name: str, char: str) -> str: """Clean the completion name, stripping bad surroundings 1. Remove all surrounding " and '. For """ if char == "'": return name.lstrip("'") if char == '"': return name.lstrip('"') return name
72e802c48f9dd3051def393f0fd9f3a348e37206
597,241
from typing import Dict from typing import Set import random def balance_populations(pops: Dict[str, Set[str]]) -> Dict[str, Set[str]]: """ :param pops: a Dict of population name to a set of user IDs :return: a version in which the groups are balanced in size """ argmin = None min_count = 0 ...
f5e0543c51b2704b2c7dde748596998a162d7cd8
597,243
def name_to_args(namestring): """Takes a script name which may contain CLI args and splits out the args. Assumes string is generically of the form '<script name>.py -arg --arg' """ namestring = namestring.rstrip().lstrip() if namestring[-3:] == '.py': return [namestring] args = namestring.split('.p...
8b935ca1a075bc4c7e29fcf95d14c349a3571cb7
597,247
import logging def restore_from_checkpoint(sess, saver, checkpoint_file_path): """ Restore session from checkpoint files. Args: sess: TensorFlow Session object. saver: TensorFlow Saver object. checkpoint_file_path: The checkpoint file path. Return: True if restore succe...
a6a7b45b601ea8c6763b3c8fa24462f8eedd53b0
597,249
def split_tokenizer(text): """ Simple & fast tokenizer. """ return text.split(' ')
da9cbf838d206685056fe44f4a399be18007cd68
597,250
def alignment_half(data_len) -> bytearray: """Return array of 0s to align to 4.""" alignment = (4 - data_len % 4) % 2 return bytearray(alignment)
b00c64ce5ba2aaf206e5edcd1aea3b2387e805d4
597,251
def _lexographic_lt0(a1, a2): """ Compare two 1D numpy arrays lexographically Parameters ---------- a1: ndarray 1D numpy array a2: ndarray 1D numpy array Returns ------- comparison: True if a1 < a2, False otherwise """ for e1, e2 in zip(a1, a2): ...
5dd75d2286c9fabdc31a3004231753f66094892f
597,253
def FormatNameToPython(i): """ Transform a (method) name into a form which can be used as a python attribute example:: >>> FormatNameToPython('<clinit>') 'clinit' :param i: name to transform :rtype: str """ i = i.replace("<", "") i = i.replace(">", "") i = i.r...
6dbe5e6f185dbcc352f1fc526938c285567407d8
597,259
import itertools def multi_consonance(cons_pairs, n_freqs = 5): """ Function that keeps the frequencies that are the most consonant with others Takes pairs of frequencies that are consonant (output of the 'compute consonance' function) cons_pairs: List of lists (float) list of lists of each p...
6eda8a1cb022d97e62b9537593639ef7e006c48d
597,262
from typing import Tuple def __check_for_newline(line: str, pos: int) -> Tuple[bool, int]: """Check if line is newline. Args: line: line. pos: current position. Returns: bool and current position. """ saw_newline = False while pos < len(line) and line[pos].isspace(): if line[pos] == '\n'...
461adcf7d37be95a41df073e474544c1891ae8b3
597,263
def find_input_layer(model, input_layer_name, input_layer_shape): """ Find a matching input layer given a name and shape Args: model (keras.models.Model): original keras model input_layer_name (str): name of the input layer input_layer_shape (list): shape of the...
cdd24a177cbae8910ee3ad9fc227f26c01a1ff45
597,267
def get_day(date): """ Rounds the datetime to midnight. :param date: a Python datetime.datetime object. :returns: a datetime.datetime object representing midnight of the informed day. """ return date.replace(hour=0, minute=0, second=0, microsecond=0)
78fe94f2a70da95fd3d0eb7a8aded4c802109ff1
597,273
def _format_options(options): """ Format a thrift option dict into a compiler-ready string. """ option_list = [] for option, val in options.items(): if val != None: option_list.append("{}={}".format(option, val)) else: option_list.append(option) return ...
c69fa20c44f8e87cdf6c83205846848b08d3b03a
597,275
def coding_problem_26(not_a_linked_list, k): """ Given a singly linked list and an integer k, remove the kth last element from the list. k is guaranteed to be smaller than the length of the list. The list is very long, so making more than one pass is prohibitively expensive. Do this in constant space an...
14ad57dc6a93bb42ee75f24b543d3246fbb1e850
597,276
import logging def get(logger_name: str) -> logging.Logger: """Gets or creates a logger instance by name. If no logger exists with the specified name, a new logger object will be created with that name. """ logger = logging.getLogger(logger_name) return logger
1d41eca5bae60a5dc92b9e59e0fdae68be563882
597,281
from pathlib import Path from typing import List import logging def get_files(folder: Path, suffix=None) -> List[Path]: """Get all files contained in Path (optionally filtering for suffix)""" if isinstance(suffix, str): suffix = [suffix] path = Path.cwd() / folder if not path.is_dir(): ...
2700d7efdf2a0963acad61e71ee18bf697e1ae10
597,282
def get_prefix_length(oracle): """Finds the length of the prefix that mysterious_encrypt adds to the plaintext before encrypting.""" # Encrypt two different ciphertexts ciphertext_a = oracle.encrypt(b'A') ciphertext_b = oracle.encrypt(b'B') # Since the stream ciphers encrypts bit by bit, the prefix...
9f884797c2cdc25fca0b8bde39f5b9700eb5372b
597,284
def bool_str(x): """Return T or F for a bool.""" return 'T' if x else 'F'
ca269238101fffecc093b71f9ef712acab5bf2e0
597,285
def parse_args(args:dict): """Parse arguments passed to a graphql query name or nodes and returns a string of arguments Args: dict (list): The arguments you want passed to your node or query name. An example for retrieving balances is: {"cryptocurrency":"bitcoin"} Retu...
61deff8b813484e0c70d88540f9c3027c7294398
597,287
def check_meta_result(result, expected_value=None): """Check the result of a 'get' metadata operation """ if not isinstance(result, dict): return "pwrcmd output is not a dict" # Some errors return only the error itself if result['PWR_ReturnCode'] != 0 and "value" not in result: retur...
3b0562df74ba86683a62abfd4b3605f339ae0707
597,294
def _clean_version(version): """ Convert version to string and append decimal if appropriate and missing :param version: NPPES API version :type version: int/str :return: The cleaned version :rtype: str """ version = str(version) if version in ("1", "2"): version += ".0" ...
5d32ada93c8b88779a0cfc8eb092113a232bacb8
597,295
from pathlib import Path def _get_buildkit_copy(package, pkgmeta): """ Returns a pathlib.Path relative to the output directory to copy buildkit and bundles to, otherwise returns None if buildkit does not need to be copied. """ while package: if package in pkgmeta: if 'build...
94d71210f9e7f347cba19b243f263b28eee8db24
597,297
from pathlib import Path def loadcreds(location: Path): """ Load application credentials """ with open(location, 'r') as f: lines = list(map(str.strip, f)) return lines[:2]
91156130539e19d26e8d268cad61e1a6284aa065
597,301
def _block_names_to_idxs(block): """ Helper function that returns a dict mapping atomnames to node indices for every node in block. """ return {block.nodes[idx]['atomname']: idx for idx in block.nodes}
cc36f2d54a728b6b6d04d4a5a9b5598fd377770d
597,302
from pathlib import Path def _get_config_path() -> Path: """ Get '.fetchmerc' configuration file path """ home = Path.home() return home / '.fetchmerc'
e02a59f78b2e8a27b4e8635aa1faaf8534f9e1bd
597,305
def left_fill(s, n, x="0"): """Cross platform string left fill method, defaults to zero filling. Parameters ---------- s : str, string to left pad n : int, number of total places to pad to x : str, optional, character to fill, defaults to "0" """ sl = len(s) zn = n - sl if zn > ...
8ec29f993fd01122ea274a2a41e8224f7dcde1ca
597,306
def getOverlap(interval_a, interval_b): """Returns the overlap of two intervals""" return max(0, min(interval_a[1], interval_b[1]) - max(interval_a[0], interval_b[0]))
21984758606f19f9e4e330e69691fb583467e92d
597,308
def _getYearFromDesc(desc): """ return release year as int from the description of a film """ year = desc.split("\n")[2] return int(year[-5:-1])
10b810853c02d15b3f7ce91065a145c7b6b15878
597,310
from typing import Dict from typing import Any from typing import List def get_max_value_length(arr_dict: Dict[Any, List[Any]]) -> int: """ Returns the max array length of the items in the dict. :param arr_dict: The dict to check :return: The max length """ list_of_item_length = [len(v) for k...
1584f35deabe06a483ae34fbb3678a99388bcf31
597,316
def gen_param(code, prefix): """Generate LaTeX in the Format \\Prefix{code}""" return prefix+"{"+code+"}"
908d6ca4746581c6a02b5c54691a818a33d08e40
597,322
def Prime_Factorization(x): """ Gives the list of all prime factors of the number. """ lst=[] cycle=2 while cycle<=x: if x%cycle==0: x/=cycle lst.append(cycle) else: cycle+=1 return lst
26614ea412a930b8a4fdc1220d61360bcb3829b0
597,323
def Pathlen_ULdigraph_Range2(N,L): """ Longest possible pathlength of a strongly connected digraph (ultra-long limit). Valid in the range when L >= (N-1) + 1/2 N(N-1), or density >= 1/2 + 1/N. Calculates the longest possible pathlength a connected directed graph of arbitrary number of nodes N and n...
73e3493812707e874d5e1d717f92ce838af916f3
597,325
def parameter_parser(parameter_code_list, parameter_list, code_list, opcode): """ Accepts parameter_code_list, parameter_list and code_list [lists] from a particular opcode instruction and subsequent entries. Returns list of parameters. """ for i in range(len(parameter_list)-1): if i >= len...
16599fbd22a490686768b46a28465e46d12517e7
597,332
from pathlib import Path def emptytemplate(tmp_path: Path) -> Path: """Fixture for a template without project files.""" template = tmp_path / "template" template.mkdir() (template / "cookiecutter.json").write_text('{"project": "project"}') (template / "{{ cookiecutter.project }}").mkdir() re...
46ec26167246b9a1f42b8b713e9817b003b203b1
597,335
def _regions(df, top=None, min_positive=100): """Returns regions with the most cumulative infections. Args: top: if not `None`, only this many regions will be returned. min_positive: if `top` is `None`, only regions with this many cumulative infections will be returned. """ ...
70978928fed46e112a8f97f7fa0a22056eafbb26
597,336
def make_b2_delete_note(version, index, transferred): """ Create a note message for delete action. :param b2sdk.v2.FileVersion version: an object which contains file version info :param int index: file version index :param bool transferred: if True, file has been transferred, False otherwise ""...
54e4fc908be6394bdfb310d00f1acccddad4a809
597,337
def solve_ilqr(solver, x0, u_guess): """ Convienience function for solving the optimization problem from the given initial state with the given guess of control inputs. """ solver.SetInitialState(x0) solver.SetInitialGuess(u_guess) states, inputs, solve_time, optimal_cost = solver.Solve...
7e69d6722511923385392023dee24d6702477777
597,352
def _get_az_function_def(full_command, command_verb, arguments, command_doc): """Given a function name, arguments, and doc,returns a formatted string function def.""" if command_doc: function_def = f""" def {command_verb}({arguments}): ''' {command_doc} ''' return _call_az("az {full_comm...
b7ff28aa3336c62f2a87fa0a7d9207c739d15817
597,360
def rfind(s, *args): """rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found, such that sub is contained within s[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return s.rfind(*args)
c420af29df12f62feffad367ae03c500ced04561
597,361
import re def parse_moons(lines): """Parse lines to dictionary with positions and velocity.""" moons = [] regex = r'([-\d]+)' for line in lines: position = [int(num) for num in re.findall(regex, line)] moons.append({ 'position': position, 'velocity': [0, 0, 0] ...
61c785e04af8ee644e875cd4f3e682c746224b01
597,366
def build_slice_name( experiment_name, variable_name, time_index, xy_slice_index ): """ Builds a unique name for a slice based on the experiment, variable, and location within the dataset. Takes 4 arguments: experiment_name - String specifying the experiment that generated the slice. varia...
486d97602081b0aefbb8e14689fbd8f4a942802a
597,368
import hashlib import six def get_cache_name(prefix, name): """ Cache name constructor. Uses the same methods as django cache system Examples: *) prefix=profile.cache, name=<requestuser.id> *) prefix=template.cache.sidebar, name=<requestuser.id> """ return '{0}.{1}'.format( prefix,...
e42237f3ecf05404dbad3118cacd374bb641ab6b
597,371
import torch def left_orthogonal(v): """Get the (left) orthogonal vector to the provided vector. """ return torch.stack([v[1], -v[0]])
f7cb91d9f6bd31981d5391f6a70c76d4972a90d6
597,372
def reported_br_params(path1, path2): """Return (SUBBRANCH_RPATH, SUBBRANCH_FULLPATH). Parameters are either (OUTER_BRANCH_FULLPATH, SUBBRANCH_RPATH) or for a first-level branch (SUBBRANCH_RPATH, None). 'FULLPATH' means relpath from the repo root; 'RPATH' means relpath from the outer branch. """ i...
e3b07458a0ab3776d1378210b672f23021bc4f28
597,383
def input_default(prompt, default): """Displays the prompt, returns input (default if user enters nothing).""" response = input("{} [{}]: ".format(prompt, default)) return response if response else default
7c8f30c22469bc5082f26e2934296baac5a90a2e
597,385
def find_min(nums: list[int | float], left: int, right: int) -> int | float: """ find min value in list :param nums: contains elements :param left: index of first element :param right: index of last element :return: min in nums >>> for nums in ([3, 2, 1], [-3, -2, -1], [3, -3, 0], [3.0, 3.1...
b22882228e9ef5c36e0eb264bf978e31632e8a0e
597,387
import uuid def custom_cli_file() -> str: """Generate custom CLI file.""" return f"slipbox_cli_{uuid.uuid4().hex}.py"
6d1179e7bf2abda8da1bd21da700e84835781dbd
597,390
def next_month(year, month): """ Returns a tuple of the month following the year and month provided. """ month = month + 1 if month == 13: month = 1 year = year + 1 else: year = year return year, month
bf10acc2608bd082d4b041afd6f41e757fe88f61
597,392
def get_foil_density_gcm3(length_mm, width_mm, thickness_mm, mass_g): """ Get density from mass/(L*W*H) :param length_mm: :param width_mm: :param thickness_mm: :param mass_g: :return: density in g/cm^3 """ _mm3_to_cm3 = 0.001 density_gcm3 = mass_g / (length_mm * width_mm * thickn...
c57ac36a1593f9aad69661d9562323ecca0df0be
597,393
def get_latitude_longitude_strings(point): """Determine string versions of the latitude and longitude MODTRAN uses longitudinal degree values from 0 to 360 starting at Greenwich and moving west. The following logic here fixes the longitude to be for MODTRAN. Args: point <GridPointInfo>: T...
053fc03ee6fb2c16a934b413e10ceaede1c04672
597,394
def __get_token(config: dict) -> str: """Gets the token from the configuration, with some sanity checks.""" if 'token' not in config: raise ValueError("No token found in the configuration.") token = config['token'] if not isinstance(token, str): raise ValueError(f'The token must be a str...
580b74373bf36848a8c52638499c35e2b0c31c9a
597,400
def is_patch_inside_FOV(x,y,fov_img,patch_h,patch_w,mode='center'): """ check if the patch is contained in the FOV, The center mode checks whether the center pixel of the patch is within fov, the all mode checks whether all pixels of the patch are within fov. """ if mode == 'center': ret...
45c6be6f8647ae2bd93390fdd0ed4868eea19258
597,403
from six.moves.urllib.request import pathname2url def _quoteLocalPath(filename): """Quote local paths to file URL-s. CifFile reads files with urlopen, which fails for Windows paths or for paths containing ":". Parameters ---------- filename : str The path to be corrected. Return...
bcdac4490cd4c1f9e07085f4ae12a6a80888bf40
597,405
import re def get_seq_ids(input_fasta): """ Get a list of sequence ids from a fasta file. """ seq_ids = set() with open(input_fasta, 'r') as f_in: for line in f_in: if line.startswith('>'): match = re.search(r'>(.*?)\s', line) if match: ...
fb35a327b3f8a11ba48eecfd39a8df1548e51cb0
597,406
import torch def load_glove_vectors(fname): """ load pre-trained glove word embeddings from local disk file. :param fname: file name :return: glove word embeddings """ with open(fname, 'r') as f: model = {} for line in f: line = line.split() word = line[...
3aacf7ee79b8c7b6b07613ee71a98da8f6b2e185
597,408
import string def get_args_for_test(api, chromium_tests_api, test_spec, bot_update_step): """Gets the argument list for a dynamically generated test, as provided by the JSON files in src/testing/buildbot/ in the Chromium workspace. This function provides the following build properties in the form of variable ...
ca90c8842a2a74a38fe757f4f5e8c03ab81041e4
597,410
import json def wloads(content): """ Decodes incoming JSON with UTF-8. :param content: JSON formatted content :return: JSON formatted content loaded as object and decoded with UTF-8. """ return json.loads(content.decode('utf-8'))
c4625cab0aa8fc10def55821b631b19746e380da
597,412
def transform_to_range(val, old_min, old_max, new_min, new_max): """ Transform a value from an old range to a new range :return: scaled value """ old_range = (old_max - old_min) new_range = (new_max - new_min) new_val = (((val - old_min) * new_range) / old_range) + new_min return new_val
c24ed175077ae360ca6984033a172f3e68fb382d
597,414
def expand_dict_from_defaults_and_elements(default_dict, elem_dict): """Expand a dictionary by copying defaults to a set of elements Parameters ---------- default_dict : `dict` The defaults elem_dict : `dict` The elements Returns ------- o_dict : `dict` The out...
954796c2e084a1e923e41d6f4790bf3da60eb450
597,422
def get_positions_at_time(positions, t): """ Return a list of positions (dicts) closest to, but before time t. """ # Assume positions list is already sorted. # frame is a list of positions (dicts) that have the same timestamp. frame = [] frame_time = 0.0 for pos in positions: # I...
905f40f8226a0aca96cff13faf725c55794c3caf
597,423
import torch from typing import Optional def to_onehot( tensor: torch.Tensor, num_classes: Optional[int] = None, ) -> torch.Tensor: """ Converts a dense label tensor to one-hot format Args: tensor: dense label tensor, with shape [N, d1, d2, ...] num_classes: number of clas...
380f80fb715399cefb3ca8a782a5aa1dac8f75a5
597,425