content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Callable import click def with_plan_options(func: Callable) -> Callable: """ Attaches "name" and "description" options to the command. """ options = [ click.option( "-n", "--name", "name", type=str, help="The name o...
afe9c0e499d7b8485d81faa61023f20daf0f8ba0
577,276
def print_condition(condition): """Return a human-readable representation of a condition.""" param, inst, op, val = condition name = inst if isinstance(inst, str) else inst[0] opname = op.__name__ return '%s %s %s %s' % (param, name, opname, val)
6b76c61a2eb048815b6bbae07c47869b1a5bba26
577,277
def backhaul_quantity(i, new_backhaul): """ Indicator for whether a new backhaul needs to be built or not. Parameters ---------- i : int Site build number. new_backhaul : int Number of new backhaul links needing to be built. Returns ------- backhaul_quant : bool ...
5fb3f775f0e76305f1f8c80aaa8c6edf76d26be0
577,278
def extract_hour(datestring): """ Return hour part of date string as integer. """ hour = int(datestring[11:13]) cycle = datestring[17:19] if hour == 12 and cycle == 'am': hour = 0 if cycle == 'pm': hour += 12 return hour
aec7796193aa348274d6c431f7b8cf757ea3b3de
577,279
def var_is_pathogenic(variant_data): """Check if variant is listed as pathogenic in ClinVar :param variant_data: A GeminiRow for a single variant. :type variant_data: GeminiRow. :returns: bool -- True or False. """ if variant_data.INFO.get('clinvar_sig') is not None: if "pathogenic" in...
d146c11693cad47310399595c5062d2bea728877
577,282
import math def n_clusters(data) -> int: """ Generate number of clusters to create. Heuristic: Number of clusters = square root of total data points Args: data: Total number of data points or the data point itself Returns: Number of clusters """ if type(data) is int:...
a720a56de5858450e1277c24d2399f5f3e281dcc
577,284
import hashlib def inacademia_hinting_hash(data): """ Hash data the same way this is done in the inacademia-hinting code. This code should not be changed on its own - if needed, it should be changed in-sync with the inacademia-hinting code. """ raw = data.encode("utf-8") if isinstance(data, s...
82b3b7ff68c1935b4509e3a83f8cebd48c1db2dc
577,287
def get_or_create_instance_profile(boto_iam, boto_ec2, instanceRoleName, instanceProfileName): """ Find an instance profile named instanceProfileName, or create one and attach instanceRoleName to it. """ response = None try: response = boto_iam.get_ins...
ab4208294695cbdd343de602d6392a53357daa77
577,289
def _klass_from_node(node): """ retrieve the name of the class from the name of the node """ return node[1][1]
8244f377cbe5c15f51d9755f57a49c73d705f7b6
577,290
def linear_session_score(i, length): """Newest elements in sequence => largest weights. Parameters ---------- i : int Element position, i+1 must be less than length. length : int Length of a sequence. Results ------- result : float Session rank betwee...
356df13e335a0c17c7855cf77c3851685287ecd2
577,292
def find_change(plan, category, unit): """ finds the change in the given category and unit in the given plan :return: Change object """ for change in plan.area_changes: if change.category == category and change.unit == unit: return change return None
b1adbbb34e2f1f41578d47e16eebd51c4980b14b
577,294
def int_to_bytes(integer): """ Convert an int to bytes :param integer: :return: bytes """ return integer.to_bytes((integer.bit_length() + 7) // 8, 'big') # alternatively # return bytes.fromhex(hex(integer)[2:])
f73f3c08e01ed7f4480463d8f06000490aa04029
577,295
def parse_label_from_image_name(image_name): """Parses the label from the file name of a testing image. Args: image_name: A file name string of the following format. <testing_image_id>_<training_image_label> where training_image_id is a unique integer amongst testing images and training_image_label is a v...
48ec1e6eb8667f9ac800683abe0157588511c74a
577,296
def fetch_all_datasets(cursor): """ Return a list of all datasets in database """ cursor.execute("SELECT dataset_name FROM dataset") datasets = [str(x[0]) for x in cursor.fetchall()] return datasets
fd7ffa81e8100dd0631ac01fe6d01151e154fa7b
577,299
def create_node(name, **kwargs): """Create and return a new node""" n = {'name': name, 'children': []} n.update(kwargs) return n
90c43747a13930337bc21aa6996e330356927519
577,305
def quadratic_normal_form_saddlecenter_ham(t, u): """ Hamiltonian for a 2DoF Saddle. Functional form: H = 1/2(p_x**2 + p_y**2) + 1/2(y**2 - x**2), with u = (x, y, p_x, p_y). Parameters ---------- t : float Time. (This Hamiltonian is independent of time.) u : ndarray, shape(n,) ...
6f7b10a20418351d54dff2f36b4c75e34a21afc9
577,312
def midi2hz(midi): """ hz = midi2hz(midi) Converts frequency in midi notation to Hertz. """ return 440*2**((midi-69)/12.0)
0357a84d989959605acd05dd741645d5baa349eb
577,313
def remove_extra_space_from_args(args): """ Remove leading and trailing spaces from all the arguments and remove empty arguments. :param args: Dictionary of arguments :return: Dictionary of arguments :rtype: ``Dict`` """ return {key: value.strip() for (key, value) in args.items() if value ...
fa5412e3ba2b6996439de441d631612cb04f7c54
577,315
def get_asg_plotlabels(g, fxn, reshist, t_ind): """ Assigns labels to the ASG graph g in the given fxn from reshist at time t so that it can be plotted Parameters ---------- g : networkx graph The graph to get labels for fxn : FxnBlock Corresponding function block for the graph ...
f247e30e03e7333725c21065a4beab0c6d3e3e21
577,319
def is_float4x4(items): """Verify that the sequence contains 4 sequences of each 4 :obj:`float`. Parameters ---------- items : iterable The sequence of items. Returns ------- bool """ return ( len(items) == 4 and all( len(item) == 4 and ...
b01feb2f728aa693922b4743d158194234681e67
577,325
from typing import Dict def lettre_freq_max(freqs : Dict[str,int]) -> str: """Précondition : len(Freqs) > 0 Retourne la lettre de fréquence maximale dans freqs. """ # Fréquence maximale fmax : int = 0 # Lettre de fréquence maximale lmax : str = '' lettre : str for lettre ...
1615ab112e97b526c79ab150a53ac13575da6cbc
577,326
import re def separate_punctuation(s, all_but=['\''], sep=' '): """Separates, but does not remove punctuation, with whitespace (single space by default).""" punc_chars = '[!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~]' sep_chars = punc_chars for char in all_but: sep_chars = sep_chars.replace(char, '') ...
fffb2da715fb9312fdff25e258d2dda41d064e4c
577,333
def escape_csv_formula(value): """ Escapes formulae (strings that start with =) to prevent spreadsheet software vulnerabilities being exploited :param value: the value being added to a CSV cell """ if isinstance(value, str) and value.startswith('='): return "'" + value return value
9239570943157d3a8c73ac26e76291d3b6b6bb1f
577,334
def lerp(t,p0,p1): """ Linear interpolation between two points""" return (p0[0] * (1-t) + p1[0] * t, p0[1] * (1-t) + p1[1] * t)
3a39af93142ae30479891bf3e17dfd3ae514f5b3
577,342
from typing import Union from pathlib import Path def check_write_path(fname: Union[Path, str], overwrite: bool) -> Path: """ Check is output file exists and either remove it first or raise IOError. :param fname: string or Path object :param overwrite: Whether to remove file when it exists exists ...
4b2a901c93c960f5795d518e71a834fe9b6777f7
577,344
def check_coverage_threshold(pol, min_cov): """Check if coverage for each position is above threshold. Returns percentage of bases that pass the coverage threshold""" column = str(min_cov) + "X_Coverage" pol.loc[pol["total_bases"] >= min_cov, column] = "Yes" pol.loc[pol["total_bases"] < min_cov, col...
d060206aa2df945c7927e903c5a96478b3bb39d9
577,348
import math def calculate_hard_difficulty(base_score): """Hard difficulty is calculated by taking the character's base characteristic score and multiplying it by 1/2. Args: base_score (float): The character's base score. Return: float: The hard difficulty score. """ return ma...
3c4d0ab691217c833869653eb55cbf96a0bd32cd
577,350
def flatten(obj, path=""): """Flatten nested dicts into hierarchical keys.""" result = {} if isinstance(obj, dict): for key, item in obj.items(): result.update(flatten(item, path=(path + "." if path else "") + key.lower())) elif isinstance(obj, (str, int, float, bool)): resul...
ca3ffacc9f3cf78c5ba636528dcd6ba0e9aa1509
577,351
def search_in_simple(number_list, query): """ Search query in number_list or not. Arguments: number_list -- a list contain all the elements. query -- a element ##### Returns: True/False -- if query in number_list return True, else return False """ if query in number_list: ...
9ab2fb73a7ac7aa879ecb655081bac0007a7a481
577,356
def TopologicalSort(changes): """Sort changes in topological order. Args: changes: a dictionary, which maps commit hashes to commit objects:: { '<commit hash>': { 'subject': '<subject>', 'change_id': '<gerrit change ID>', 'parent': '<parent commit hash>', ...
0592af821898103feac040a3e0bfbbaec344faea
577,358
import re def _translate_operation(operation): """ Translates Psycopg2 features to their SQLite counterparts on a best-effort base. """ # The placeholder is always "%s" in Psycopg2, "even if a different placeholder (such as a %d for # integers or %f for floats) may look more appropriate" oper...
e1439681740f176538e84d5ee0986b2585fa7270
577,360
def jaccard(a, b): """ Jaccard stability index """ a, b = set(a), set(b) return 1.*len(a.intersection(b))/len(a.union(b))
81cc164d4a78dd26ca6158539e0c1e3c06bdce60
577,362
import itertools def flatten(lst): """Flatten a list of lists (one level).""" return itertools.chain.from_iterable(lst)
e74773d4c57213fcb6c148e386805a29ec3c18d6
577,363
import re def split_ref(string): """ splits a string into (tag, id) """ re_tag = re.compile(r"^(?P<tag>[a-zA-Z]+)[\s-]*(?P<pk>\d+)$") m = re_tag.search(string) if not m: raise ValueError("unable to split string '%s'" % (string,)) return (m.group('tag').lower(), int(m.group('pk')))
3ada26abb8487667a3a667b424c1c88a53054499
577,365
from functools import reduce def mean_list(arr): """ Calculate mean of list """ if not isinstance(arr, list): return 'Use only list with numbers for this function' if not len(arr): return None m = reduce(lambda x,y: x + y, arr, 0) / len(arr) return m
10f9f06334e5e78a3c21190a64f7cce67e5acf5f
577,366
def _vcard_name(contact: dict) -> str: """ Create the file name for a vcard from this contact. """ name = contact.get('name', {}) title = name.get('title', '') fname = name.get('first_name', '') mname = name.get('middle_name', '') lname = name.get('last_name', '') suffix = name.get('...
5ec90ead661046cafcd7983c269020d4933b538b
577,368
import re def clean_librispeech(txt): """ Lowercases the input string and removes anything but characters a-z and whitespaces. Also normalizes whitespace characters and strip trailing ones. The final character set will be: - letters: "a-z" - apostrophe: "'" - whitespace: " " ...
a51b4b9a25713a5ad58cfecc568ce26029ea61f1
577,372
def to_crs(epsg): """CRS dict from EPSG code.""" return {'init': 'epsg:{}'.format(epsg)}
3460b172654391650d5d075cff00e489245a3e17
577,373
import typing def build_qs_dict( finam_id: str, market_id: str, date_from: str, date_to: str, ) -> typing.Dict[str, typing.Union[str, int]]: """Build a dict that can be used to generate query string to export api.""" df, mf, yf = list(map(int, date_from.split('.'))) dt, mt, yt = list(map(int, date_to....
c227e931579cc6d7a0f0928e580a1b51bdbb426e
577,376
import re import importlib def get_class(klass): """Parse the specified type-string, import it and return the type.""" if isinstance(klass, type): return klass if not isinstance(klass, str): raise TypeError(f"Expected a string, got {type(klass)}.") # match and rsplit by "." match...
64a29d4af8acb275136d875820f7caf8298f21c9
577,377
def zoladz(hrMax, adjuster): """ Zoladz Method for target heart rate (THR) - derives exercise zones by subtracting values from HRmax. Results are +/- 5 bpm - Zone 1 Adjuster (easy exercise) = 50 bpm - Zone 2 Adjuster = 40 bpm - Zone 3 Adjuster = 30 bpm - Zone 4 Adjuster = 20 bpm - Zone 5 Adj...
6c7d907578d82d25f95eafcb4e92c1dfefdc5bff
577,378
def invert_strand(iv): """ :param iv: HTSeq.GenomicInterval object :return: HTSeq.GenomicInterval - strand is reversed """ iv2 = iv.copy() if iv2.strand == "+": iv2.strand = "-" elif iv2.strand == "-": iv2.strand = "+" else: print("strand must be + or -") retu...
f428a97ecb383b43f2e3d693e4504edd06ed9869
577,385
def convert_quarter_to_date(time): """ Reformats dates given with quarters to month-day format. Args: time: String representing time in the format year-quarter(e.g. Q1, Q2, ...) Returns: String representing time in the format year-month-day. """ date = time if "Q1" in date:...
93577ea4685c4ed288a76bed8dd19c92d0444fe4
577,386
import requests def upload(connection, dataset_id, session_id, body, verbose=False): """Upload data to a multi-table dataset. Args: connection (object): MicroStrategy connection object returned by `microstrategy.Connection()`. dataset_id (str): Identifier of a pre-existing dataset. Used when ...
ddd228f3abbfc62cd0abe5252f574882b4639941
577,388
def calc_air_density(theta, x=0, p=101300): """ Calculates the density :param theta: temperature in °C :param x: humidity ratio [kg/kg] :param p: Absolute Pressure [Pa] :return: density wet air [kg / m³] """ rho = (1 + x) / (x + 0.6222) * p / (461.40 * (theta + 273.15)) # Humid air dens...
2da324b6e6c8d789ff779a3fadc9a3329a2a9009
577,391
def vector_area(v0,v1): """Get area of the triangle created by two 2D vectors.""" cross = v0[0]*v1[1] - v0[1]*v1[0] return abs(cross)/2
ba19ee322836b96f84d8df802ac7ee7ab2deea80
577,394
def bob_response(query_category): # type: (str) -> str """ Return a response based on category of query.""" response = { 'question': 'Sure.', 'yell': 'Whoa, chill out!', 'empty': 'Fine. Be that way!', 'default': 'Whatever.' } return response.get(query_category, respo...
c01886cd1b92484b2544ad4c01184572a8b244a8
577,395
def _convert_ratio_to_int(ratio: float): """ Round the ratio to 2 decimal places, multiply by 100, and take the integer part. """ return int((round(ratio, 2) * 100))
5b334dfede1706c700dadd3bdd7836f6a22f2813
577,396
def search_key_for_device(device): """Generate a string search key for a device""" elements = [] elements.append(device['name']) # name of device elements.append(device['config_network']['ip']) # ip of device return u' '.join(elements)
54c4d37d8397dd1381b7440b7c681f655626f91d
577,397
def get_next_non_filled_parameter_state(parameter_parsing_states): """ Gets the next non-filled parameter parsing state. Parameters ---------- parameter_parsing_states : `list` of ``ParameterParsingState`` Parameters parsing states to choose from. Returns ------- parame...
dc5ff0c440cad53f04a26247f8c0130e473b7021
577,398
def reverse_sort(sort_field): """ Check for leading - to indicate reverse sort :param sort_field: :return: True | False """ if sort_field: if sort_field[:1] == '-': return True return False
d2236241b32ac9894ab6a6b0350bcac9b992faff
577,399
import hashlib def get_file_hash(filepath): """Reads the file and returns a SHA-1 hash of the file. Args: filepath: String of the path to the file to be hashed Returns: String: The SHA-1 hash of the file. """ hasher = hashlib.sha1() blocksize = 65536 with open(filepath, "rb") as f: buf = f....
af966bca8125adbd48a36b3ada3e5226bdfd890c
577,401
import random def scrambleWord(word): """Randomize the letters in word and return the resulting string.""" word_list = list(word) random.shuffle(word_list) word = ''.join(word_list) return word
6e3259826a0dfc195752d85b4cdb73500c540de1
577,407
def roster(data) -> list: """Simple parser to get all players on a roster. Url.ROSTER Args: data (dict): dict representing JSON object of a team's roster Returns: list: list of player ids """ parsed_data = [] for person in data['roster']: parsed_data.append(person[...
ff39c09b9d3d630d51dc7d7016eb6d1769eca6d1
577,408
def milliseconds_to_timeformat(dtime_delta): """ Convert milliseconds to mm:ss.000 format Args: dt (datetime.timedelta): Datetime delta value Returns: (str): String in 00:00.000 time format (mm:ss.millisecond) """ _, dt_hr_rem = divmod(dtime_delta.seconds, 3600) dt_min, dt_sec = ...
ba6c93e4e3ee36879681588b576787726dd0acc8
577,411
def is_precipitating(weather: dict, conditions: tuple = ( 200, 201, 202, 210, 211, 212, 221, 230, 231, 232, 300, 301, 302, 310, 311, 312, 313, 314, 321, 500, 501, 502, 503, 504, 511, 520, 521, 522, 531, 600, 601,...
a952ffb6268f2a6afcb8eaa7dbb5ea2e8086003a
577,419
def build_id(*components): """Generate a string identifier composed of all the string components (in order) and concatenated with a colon ':' between them. This is useful for generating an identifier or 'path' to a value in a setting store. """ return ':'.join(components)
94a874f9b3dac55a46bed2207a9615fd473f4469
577,422
import base64 import time import struct import hmac import hashlib def compute_totp(secret, offset=0): """ Computes the current TOTP code. :param secret: Base32 encoded secret. :type secret: unicode :param offset: Time offset (in steps, use eg -1, 0, +1 for compliance with RFC6238) for wh...
9db86d44b64347dbe59e1cfc7c0a0e25edacd7c9
577,427
def _package_depth_sort(names, reverse): """Sort a list of module names by their package depth""" def packageDepth(name): return name.count(".") return sorted(names, key=packageDepth, reverse=reverse)
7c83982af0893af9d13ebbcc95c3df9cde28675f
577,429
import re def remove_comments( line ): """Removes comments (which start with a '%' character) from a line. """ match_obj = re.match( "^(?P<non_comment>[^%]*)%.*$", line ) if match_obj: return match_obj.group( "non_comment" ) else: return line
c1b38581887e1df89a808cbee5869b5fc514d6ac
577,432
import operator def mutStrToTupleList(mutStr): """ gets a mutstring like 100:C,101:A and returns a sorted list of tuples [(100,'C'), (101, 'A')] """ mut_list = mutStr.split(",") return sorted( [(int(mut.split(":")[0]), mut.split(":")[1]) for mut in mut_list], key=operator.itemgetter(0),...
97c109f15a8db0cafbe7186b1b321c5a95931b6b
577,433
def from_unit_box(x, lb, ub): """Maps a set of points from the unit box to the original domain :param x: Points to be mapped from the unit box, of size npts x dim :type x: numpy.array :param lb: Lower bounds, of size 1 x dim :type lb: numpy.array :param ub: Upper bounds, of size 1 x dim :ty...
711f7e2113e5f76f8d6388c3b79c5dcda1f474c3
577,434
import re def fix_double_escape(escaped): """Fix double-escaped entities, such as &amp;amp;, &amp;#123;, etc""" return re.sub(r'&amp;([a-z]+|(#\d+));', r'&\1;', escaped)
9b2af735a0a18da5e992cff690991886b684b476
577,440
def partition_by_adjacent_tiles(tile_ids, dimension=2): """ Partition a set of tile ids into sets of adjacent tiles. For example, if we're requesting a set of four tiles that form a rectangle, then those four tiles will become one set of adjacent tiles. Non-contiguous tiles are not grouped together....
c0c37fd4b15a8d1e661412bf5d4eb9c887ba6f98
577,443
import pickle def load_pacman_states_file(filename): """Read pacman states from file.""" f = open(filename, 'rb') result = pickle.load(f) f.close() return result
7aa31809b0383ef6c2d5d4dffd43c66b606749c0
577,444
import pathlib def str_to_pathlib(in_str): """ Handle the string to pathlib.Path casting """ if isinstance(in_str, pathlib.Path): return in_str else: try: return pathlib.Path(in_str) except: raise IOError("Invalid path specified.")
20c5903f318f4c972d6d98fd9f6e91872df5cd5f
577,445
def overlap(set1, set2): """Computes the overlap between two sets. Args: set1,set2 (set or list): Input sets (or lists). Input lists are converted to sets. Returns: overlap (int) """ if not isinstance(set1, set): set1 = set(set1) if not isinstance(set2, set...
ad5cc4b44375fe4b99088849cef58af82a48843a
577,448
import math import torch def encode_position(input, levels, inc_input=True): """ For each scalar, we encode it using a series of sin() and cos() functions with different frequency. - With L pairs of sin/cos function, each scalar is encoded to a vector that has 2L elements. Concatenating with ...
8e2f9e21dd83a0df1679f49495c3de92641bc3dd
577,449
def _random_subset(seq, m, rng): """Return m unique elements from seq. This differs from random.sample which can return repeated elements if seq holds repeated elements. Note: rng is a random.Random or numpy.random.RandomState instance. """ targets = set() while len(targets) < m: x...
75ad6e485790810bda64b8c08ac3c2850d464d7e
577,450
def check_confusion_matrix_metric_name(metric_name: str): """ There are many metrics related to confusion matrix, and some of the metrics have more than one names. In addition, some of the names are very long. Therefore, this function is used to check and simplify the name. Returns: Simplif...
d09b236c4da39608c1f0e9fff5008a9c922b4d72
577,453
def has_new_posts(topic): """ Returns ``True`` if the given topic has new posts for the current User, based on the presence and value of a ``last_read`` attribute. """ if hasattr(topic, 'last_read'): return topic.last_read is None or topic.last_post_at > topic.last_read else: ret...
462cdd1abf322b62724aaa00435a8e91c980433d
577,456
def is_valid_position(position: str) -> bool: """Filters out players without a valid position. Args: position (str): Player's current position Returns: bool: True if the player has a valid position, False otherwise """ valid_position_values = ["TE", "RB", "WR", "QB"] if positio...
71907b24a83ac2d3aebd4c319043df67037face3
577,459
def correct_byteorder(ptype, byteorder): """Fix the byteorder depending on the PyTables types.""" if ptype in ['string', 'bool', 'int8', 'uint8', 'object']: return "irrelevant" else: return byteorder
1648c5d5dcfca7da077bf8d19f9b587b69e27448
577,467
import re def strip_symbol(ustr): """ 将字符串中的标点符号去除 Args: ustr: 带去除字符串 Returns: 去除标点符号之后的字符串 """ return re.sub('[’!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~]+', ' ', ustr)
52e10ef538c75db9d6fc70e70f23d7b00403f4f0
577,468
def FREAD_RANKING_BY_ESSS(decoy): """Returns a comparable object (a tuple of scores) used for ranking a given decoy. Bigger values will be ranked higher.""" return (decoy.score, -decoy.anchor_rmsd_open, -decoy.internal_rmsd, -decoy.iterations)
3ab30133a8dc2ada3f6ff48602c09dceed1a5cdd
577,474
def read_label(path) -> dict: """ read graph node labels. :param path: label file path. :return: return dict-type, {node:label}, number of class. """ try: with open(path, mode="r", encoding="utf-8") as fin: label_dict = dict() while True: line = fi...
7ea53d2bc8b2bee634b07a94cf3073bce4106b6e
577,477
import logging import json def is_newformat(filename): """ Check if app is new format (with FolderDefinition as top object) :param filename :return: True if new format, throws exception otherwise """ with open(filename, 'r') as mf: logging.info("Reading file: " + filename) cont...
c169360882777dd9897870da0c90203c268ac528
577,481
def flatten_list(my_list): """Flatten a list of lists into a single list.""" return [num for elem in my_list for num in elem]
9de04da083783468c6476705f451767564c36511
577,482
def convert_int_to_binary(int_to_convert): """ Convert an int to binary. I'm aware that in python I could've just done: '{0:b}'.format(int_to_convert) But that's a little less informative :) Args: int_to_convert (int): The int to convert. Returns: str """ ...
a784f48a02b99a9506d39865260a075497f8393c
577,484
def has_tag(tag, runinfo): """ Returns true if the given runinfo contains the given tag. """ return tag in (t.strip() for t in runinfo.tags.split(','))
342878098b6aff920159be8deb10fbe29908b689
577,485
def replace_assign(match): """Replace a pretty assignment, e.g. ``B = 1 T``, by valid Python code using a Quantity call. """ return '%s = Quantity(\'%s\')' % (match.group(1), match.group(2))
f967963cb3cbe9561f9a511616f9f4ed09646979
577,489
def measurement_from_bme680(timestamp, measurement, temperature, pressure, humidity, geohash, location): """Turn the BME680 object into a set of influx-db compatible measurement object""" return { "measurement": str(measurement), "tags": { "sensor": "bme680", "location":...
182923a59139c80e340a07b240f5c489a3bdd177
577,491
def make_commands(trace_executable: str, tracin_filenames: list) -> list: """Create a list of shell command to run trace on the supplied set of tracin :param trace_executable: the name of trace executable :param tracin_filenames: the list of trace input file to be simulated :return: a list of trace she...
8272331dc6b7f41bc1b767750dbf7e7ef8aaf359
577,504
def RDtext(s): """Convert ICC textType to Python string.""" # Note: type not specified or used in [ICC 2004], only in older # [ICC 2001]. # See [ICC 2001] 6.5.18 assert s[0:4] == "text" return s[8:-1]
9c7479e9721a6f68595fd5ed3d48966a7b0fe8f6
577,506
def unwrap_pose(pose): """ Unwraps geometry_msgs/Pose into two tuples of position and orientation """ p_x = pose.position.x p_y = pose.position.y p_z = pose.position.z o_x = pose.orientation.x o_y = pose.orientation.y o_z = pose.orientation.z o_w = pose.orientation.w return...
0fec33cc15014a642eb6795015aba83fd26f803f
577,508
def find_order_item(order_items, item_id): """ Find order item with the item_id """ for order_item in order_items: if order_item.item_id == item_id: return order_item return None
5162fb1c29c1e46a26f363bdb4921f8eb52f9a14
577,509
def _serialize_hstore(val): """ Serialize a dictionary into an hstore literal. Keys and values must both be strings. """ def esc(s, position): try: return s.encode('string_escape').replace('"', r'\"') except AttributeError: raise ValueError("%r in %s position ...
622ca03e2d3edef79f54f72833c622027278f49e
577,510
import re def format_blockrefs(document): """Formats Obsidian block references into a span element that can be linked to""" regex = re.compile(r" \^(.+)$", re.MULTILINE) matches = regex.finditer(document) for match in matches: document = document.replace(match.group(), f"<span id=\"{match.gro...
4af093b9e3bc8e3161ca4887c2a9a9623add1ed5
577,512
def find_max_in_bitonic_array(arr: list[int]) -> int: """Binary search to find the maximum value in a bitonic array (aka *Peak Finding*) Bitonic: *strictly* increasing AND THEN *strictly* decreasing. i.e., arr[i] < arr[i+1] < ... < arr[max_element_idx] > ... > arr[j] > arr[j+1] Complexity: Tim...
295a700741938df7d0b0c4fdee2cce8cfa450784
577,514
import torch def to_device(tensor): """ Move tensor to device. If GPU is is_available, move to GPU. """ if torch.cuda.is_available(): return tensor.cuda() else: return tensor
8e7d35e269d9314173b8c0c78259a575e7b59c8f
577,519
import mmap def get_num_lines(file_path: str) -> int: """Count the number of lines in the log file Parameters ---------- file_path: str The filepath to the file to be counted Returns ------- int The number of lines in the file """ fp = open(file_path, "r+") bu...
6ebed4620d57fa1959e4d8c2cb2db841fcb94dc7
577,521
def solve(_n, tree): """ Given a list of list of tokens: . (empty), or # (tree), calculate the product of the number of trees that one would encounter if one would traverse the 2D grid along the given set of slopes. :param _n: The number of rows in the input. :param tree: The list o...
106926e5dcfcac06cd550e4b89a5c8c8771e357c
577,522
import ast def is_doc_string(node: ast.stmt) -> bool: """ Tells whether or not the given node is a docstring. We call docstrings any string nodes that are placed right after function, class, or module definition. """ if not isinstance(node, ast.Expr): return False return isinstanc...
96a2d6ffd88ca95d21e1b97365ecf4657148148d
577,525
def strip_version(ver: str): """ strip_version is needed to strip a major/minor version of non-standard symbols. For example, when working with GKE, `kubectl version` returns a minor version like '14+', which is not semver or any standard version, for that matter. So we handle exceptions like that here....
f138eeadddccbf8228028387a41b508ca836b84a
577,529
import re def sub_power(text_in: str) -> str: """ substitution of powers Replaces: cm-3 with cm**-3. Parameters ---------- text_in: str Returns ------- text: str """ found_unit_power = re.findall("[a-zA-Z]{1,10}[-+]?[0-4]", text_in) for exp in found_unit_power: ...
69f1e04469ded8ba964c00377b71ae7b9e2cb390
577,531
def _calculate_fan_in_and_fan_out(shape): """ calculate fan_in and fan_out Args: shape (tuple): input shape. Returns: Tuple, a tuple with two elements, the first element is `n_in` and the second element is `n_out`. """ dimensions = len(shape) if dimensions < 2: rais...
afca4b2f4491c8cc97b8e0164f9d3c5cb871b935
577,536
def get_top_package_from_qualified_path(full_module_name: str) -> str: """Gets top-level package name from qualified (dotted) module name.""" return full_module_name.split(".")[0]
d3d8e97edc2e163baf40a8b1d7a1ff8afa9f2a23
577,538
import torch def swish(x: torch.Tensor, beta: torch.Tensor) -> torch.Tensor: """Swish activation function from arXiv:1710.05941 Args: x (torch.Tensor): input tensors can be either 2D or 4D. beta (torch.Tensor): swish-beta can be a constant or a trainable params. Returns: torch.Tensor: output...
8fd639ad9e54394e1d1499bb2dc6385d843b87a2
577,548
def pad(TIME: str, MS: bool) -> str: """ Pad a time with blank spaces if it doesnt contain milliseconds for output formatting. >>> pad("59:54.397", True) '59:54.397' >>> pad("3:42", True) '3:42 ' >>> pad("1:39", False) '1:39' """ if not MS: return TIME return f"{TIME} " if "." not in TIME else TIME
37292516beb6f94650ce39283e989bb21782d208
577,555
def cumsum(arr): """Do cummulative summation""" cs=[arr[0]] for a in arr[1:]: cs.append(cs[-1]+a) return cs
802ffe79771e7aad85f9851f06913ff581b3d447
577,556