content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import numpy import math def _get_lattice_pointGroup(aVecs, eps=1E-10): """This routine returns only the point group of the rather than the space group of the given crystal structure. :args aVecs: The 2D integer array that contains the parent lattice vectors :args eps: (Optional) Finite precisi...
307d5814cd6200dbd02899d5c8fbab01ac973ea9
666,668
def decimal_str_to_int(decimal_string): """ Helper to decimal currency string into integers (cents). WARNING: DO NOT TRY TO DO THIS BY CONVERSION AND MULTIPLICATION, FLOATING POINT ERRORS ARE NO FUN IN FINANCIAL SYSTEMS. @param string The amount in currency with full stop decimal separator @retu...
88bd209518966ee37d8e585e50c11685cddd86ce
666,669
def distance_to_first_repeated_block(directions): """Returns the block distance to the first block visited twice. Args: directions (list): A list of strings indication turn direction and length of distance. Returns: (int): Distance, in blocks, from origin to the f...
97f08c6387b4fb7ecb9f2a6f8753e0bd69d406cd
666,670
def polygons_intersect(poly1, poly2): """ Helper function to determine whether two polygons intersect. :Parameters: poly1: tuple of ((x1,y1),(x2,y2),...) The coordinates of the vertices of the first polygon. There must be at least 3 vertices. poly2: tuple of ((x1,y...
67ce3be126388ca18b697b802ef30a983f6e7470
666,671
def _do_task_fetch(dataset,datasetspec,year,datasets_disk): """ check if dataset is on disk for the same variables and year Args: dataset (str): name of dataset datasetspec (dict): dataset specification year (int): year dataset (dict): dictionary of datasets on disk Return...
dca797a7882876ffc7750ada38d862fcb7ada330
666,672
def get_supaxislocs(fig, nrow, ncol, figsize, pad): """ A small utility function called from many of the plotting functions. This gets the required coordinates for super axis labels. Parameters: fig (mpl.fig): Matplotlib figure nrow (int): Number of rows ncol (int): Number of Co...
28e9772e62d4e5ea16ec2a4af0ecaf0c9c7cbd90
666,674
def cap_length(q, a, r, length): """Cap total length of q, a, r to length.""" assert length > 0, "length to cap too short: %d" % length while len(q) + len(a) + len(r) >= length: max_len = max(len(q), len(a), len(r)) if len(r) == max_len: r = r[:-1] elif len(a) == max_len: a = a[:-1] el...
25292014c5735b5e55a7356cbb0011e89f2d4d8f
666,675
def PySequence_Contains(space, w_obj, w_value): """Determine if o contains value. If an item in o is equal to value, return 1, otherwise return 0. On error, return -1. This is equivalent to the Python expression value in o.""" w_res = space.contains(w_obj, w_value) return space.int_w(w_res)
ad0e4bd70bf283eefb7e3921c17e14fe77e49bce
666,676
def argmax(lst): """Given a list of numbers, return the index of the biggest one.""" return max(range(len(lst)), key=lst.__getitem__)
518ea19a935d83126aa8722af0fb998030076c6f
666,677
import requests def get_objects(endpoint_url, parameters={}, limit=None): """ gets list of objects from endpoint_url optional parameters allow for filtering expect_count """ if limit: parameters["limit"] = limit obj_r = requests.get(endpoint_url, parameters) if obj_r.status_cod...
f77bac130817fe521870b30f4754d2b14757cd9b
666,678
def perfect_match_index(match_name, candidates_name): """Returns the index of the perfect match. Args: match_name (str): name to match. candidates_name (list): list of candidates. Returns: match_index (int): index of match """ try: match_index = candidates_name.inde...
b583e733becde6c346d48a65b90c7ae4bccb4170
666,679
def parse_response_browse_node(browse_nodes_response_list): """ The function parses Browse Nodes Response and creates a dict of BrowseNodeID to AmazonBrowseNode object params *browse_nodes_response_list* List of BrowseNodes in GetBrowseNodes response return Dict of BrowseNo...
68a9531afce89af9bcaf5e24d94fa2ab1d068d33
666,680
import json import requests def get_list_of_data(duration_type = "daily"): """ API call the EIA and returns a list of daily prices. #The parameters duration_type : is str #Default value 'daily' #The value can be 'daily', 'weekly', 'monthly', 'annually'. """ #YOUR ...
f2a280aadac580f8d2fd48e586b39b7d341431e6
666,681
def depth_calculator(obj): """Determine how far in the hierarchy the file/folder is in. Works for either File or Folder class""" depth = 0 dad = obj.parent_folder next_in = True while next_in: if dad.parent_folder: depth += 1 dad = dad.parent_folder else: ...
6d330c053ad969ae8bf65cef4e99e3a8e3feb075
666,683
from io import StringIO import sys def format_lp(nodes, constraints_x, qa, constraints_y, qb): """ Maximize 4 x1 + 2 x2 + 3 x3 + x4 Subject To x1 + x2 <= 1 End """ lp_handle = StringIO() lp_handle.write("Maximize\n ") records = 0 for i, score in nodes: lp_handle....
d003f2c0d89265dc23de6a526ec8abc4d54723b1
666,684
def is_prime(number): """States if a number is prime. :param number: A number :type number: int :rtype: bool **Examples** >>> is_prime(31) True >>> is_prime(42) False """ for factor in range(2, number): if not number % factor: return False return ...
2d7a9cc40684db4bfdeac6986a720d4869c0c3b0
666,685
def validate_base_sequence(base_sequence, RNAflag=False): """Return True if the string base_sequence contains only upper- or lowercase T (or U, if RNAflag), C, A, G characters, otherwise False""" seq = base_sequence.upper() return len(seq) == (seq.count('A') + seq.count('U' if RNAflag else 'T') + ...
5107a617a512887392a9721d1b62ecfd369f3a73
666,686
import requests def get_csrf(REQ_URL): """Get a csrf token from the request url to authenticate further requests Parameters ---------- REQ_URL string The URL that you want to make a request against after getting the token Returns ------- csrftoken csrf token to use for...
0e1cdc3acf2dd6cb00446e2644b624cf2df7e362
666,687
def custom_repo(**kw): """ Repo files need special care in that a whole line should not be present if there is no value for it. Because we were using `format()` we could not conditionally add a line for a repo file. So the end result would contain a key with a missing value (say if we were passing `...
2846fe8c6fcafe1a47137c9bec011d47c52f4858
666,688
def int_to_uint32(value_in): """ Convert integer to unsigned 32-bit (little endian) :param value_in: :return: """ return list(value_in.to_bytes(4, byteorder='little', signed=False))
906998350a19e1bf756ad8e87c35f4f3b5b2933c
666,689
def merge_overlapping_intervals(intervals): """ Given a collection of intervals, merge all overlapping intervals. Given the list of intervals A. A = [Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)] The function should return the list of merged intervals. ...
71eae73d5f94f55b052018bb850f7b8a52701442
666,690
import math def get_bearing(vehicle, aLocation1, aLocation2): """ Returns the bearing between the two LocationGlobal objects passed as parameters. This method is an approximation, and may not be accurate over large distances and close to the earth's poles. It comes from the ArduPilot test code: ...
506a14a094b1cfa4ca076bb722a069e105d0ac6d
666,691
def get_vector_axis_letter(vector): """ Returns the axis letter of the given vector :param vector: list(float, float, float) :return: str """ if vector == [1, 0, 0]: return 'X' if vector == [0, 1, 0]: return 'Y' if vector == [0, 0, 1]: return 'Z' if vector ==...
77e027ca1c0c9188bc3a228df4f166c13a4e17a7
666,692
def insignificant(path): """Return True if path is considered insignificant.""" # This part is simply an implementation detail for the code base that the # script was developed against. Ideally this would be moved out to a config # file. return path.endswith('Dll.H') or path.endswith('Forward.H') or \ pa...
6610ca32d35d4f0cc8c2a559c08a8157e6fbb473
666,693
def bad_request(start_response): """Just does the same thing, over and over -- returns bad results..""" output = [] output_len = sum(len(line) for line in output) start_response('400 Bad Request', [('Content-type', 'application/json'), ('Content-Length', str(o...
bd7677969a5219866068e723da72c620bb6a7b79
666,694
import os def find_path(dirs, path_to_find): """ Go through a bunch of dirs and see if dir+path_to_find exists there. Returns the first dir that matches. Otherwise, return None. """ for dir in dirs: if os.path.exists(os.path.join(dir, path_to_find)): return dir return None
be8710b2f421cfead41a1cdc464d5e0d4a7fc714
666,695
import re def replace_any_non_letter_or_number_character(text): """Removes any non alphanumeric character""" text = text.strip() text = re.sub('[^A-Za-z0-9 ]+', '', text) return text
edead2100c61bf1e9f8f24693ea1f6a607370559
666,696
import argparse def get_options(cmd_args=None): """ Argument Parser """ parser = argparse.ArgumentParser( prog='generateParkingAreasFromOSM.py', usage='%(prog)s [options]', description='Extract Parking Areas from OSM.') parser.add_argument('--osm', type=str, dest='osm_file', required=True,...
246720d7b36606517483dedf5159996316d880db
666,697
import pickle def receive_message(client_socket, HEADER_LENGTH, FORMAT): """ Receives message on the client_socket """ client_socket.settimeout(5) response = False # In case of no response from cache servers, the response will be False (failed) while True: try: response = ...
a97a2b379b17b3b11604e1b72fac947c34d4133d
666,698
import subprocess def splitbedgz(bedgz, prefix): """Split gzipped bed file into separate files according to chromosome. Uses zcat and awk. Args: bedgz: path to gzipped bed file prefix: output path prefix """ cmd1 = ['zcat', bedgz] awkscript = 'BEGIN{{FS="\t"}}{{print > "{0}...
0e7d26bcfce681a8de4ff29a3c62f19aab1c0eaf
666,699
def vect3_reverse(v): """ Reverses a 3d vector. v (3-tuple): 3d vector return (3-tuple): 3d vector """ return (v[0]*-1, v[1]*-1, v[2]*-1)
25cc7d3cfed21f9b462d0398cb213c5159dde8f9
666,700
from typing import List def write_floats_8p1e(vals: List[float]) -> List[str]: """writes an 8.1E formatted number""" vals2 = [] for val in vals: if abs(val) < 1e-10: vals2.append(' ') else: vals2.append('%8.1E' % val) return vals2
9b38ee14eb3ccb0cda32fc41a4a28f8ea6621cba
666,701
from typing import Dict import re def wikitext_detokenize(example: Dict[str, str]) -> Dict[str, str]: """ Wikitext is whitespace tokenized and we remove these whitespaces. Taken from https://github.com/NVIDIA/Megatron-LM/blob/main/tasks/zeroshot_gpt2/detokenizer.py """ # Contractions text = e...
ad06cc5c394684a265e6e91e29d3744466f18eb6
666,702
import sys def get_object_size(obj, seen=None): """Recursively finds size of objects""" size = sys.getsizeof(obj) if seen is None: seen = set() obj_id = id(obj) if obj_id in seen: return 0 # Important mark as seen *before* entering recursion to gracefully handle # self-refe...
f5e68cb9e234e035fe6a0eb297a9723012807614
666,703
import hashlib def hashString(string): """Obtain hex digest of this string. Returns: digest (str): hex chars double the length of string""" hashObject = hashlib.md5(string.encode()) return hashObject.hexdigest()
dd74c964237234a2d0160fa9f0dfdcbe97b5a28b
666,704
from typing import Dict from typing import Any def generate_bulkiness_section(cat_properties: Dict[str, Any]) -> str: """Generate the CAT bulkiness input section.""" def replace_None(x): return "NULL" if x is None else x if "bulkiness" not in cat_properties: return "bulkiness: False" b...
2a20acd97c9ade47ebe000bd2fe0e9c2b55a67a5
666,705
import sys def eat_key(): """consume a key. Exit on ^C""" c = sys.stdin.read(1) if c == '\x03': # ^C sys.exit(1) else: return c
1a6ee44dff568b24fb7170c35ab40d04de475724
666,706
def datetime_to_string(date_object): """ Converts a datetime object to a date string of the format MM/DD/YYYY. Args: date_object: datetime object representing datetime Returns: String representing datetime object of the format MM/DD/YYYY """ return date_object.strftime("%m/%d/%...
87f6a0f9160b3cb5b1636ed052ae7b94672514b8
666,707
def normalize_package_name_for_code(package: str) -> str: """Normalize given string into a valid python package for code usage. Parameters ------------------------ package: str, The name of the package. Raises ------------------------ ValueError, When the name of the packag...
b223fdcae3a4ba382e03b7209e80183ca4c27aad
666,708
import os from datetime import datetime def test_s3_folder(): """ S3 folder for this test session """ return f"s3://{os.environ['MINIWDL_AWS_TEST_BUCKET']}/{datetime.today().strftime('%Y%m%d_%H%M%S')}/"
ca468a2ca614cba7e14706381df0db3bee27c7dd
666,709
def calculate_trade_amount(buyer, seller): """Calculation of the total transaction amount""" return seller.price * min(buyer.quantity, seller.quantity)
08b8802b5c7c6b40bb9d19ba3dbd721ea2649be1
666,710
import os from pathlib import Path def default_agasc_dir(): """Path to the AGASC directory. This returns the ``AGASC_DIR`` environment variable if defined, otherwise ``$SKA/data/agasc``. :returns: Path """ if 'AGASC_DIR' in os.environ: out = Path(os.environ['AGASC_DIR']) else: ...
aab1b63060a48d1aba964ddf31da4ee6ba71fe81
666,711
def is_list(element): """ Check if element is a Python list """ return isinstance(element, list)
a8acabc39134d1f7c7a495d2c10266267f73e92b
666,712
def parse_raw_table(cons_file, f_sizes): """Parses a .cons file generated by generate_consensus into VCF entries.""" rows = {f_size: [] for f_size in f_sizes} with open(cons_file, "r") as reader: f_size = 0 for line in reader: if line.startswith('#'): ...
28b9c50056bd5ec73591aaf9f808deda71a6c2c4
666,713
def init_properties(self, extra_kwargs, *args, **kwargs): """ class A: _fields = ['a', 'b', 'c'] def __init__(self, *args, **kwargs): init_property(self, False, *args, **kwargs) class B: _fields = ['a', 'b', 'c'] def __init__(self, *args, **kwargs): ...
fc562d0dc4b2eb6b0ad72beacd10526b3615084d
666,714
import os import subprocess def command_check(command, cwd=None, quiet=False): """Run a command and see if it completes with returncode zero.""" kwargs = {} if cwd: kwargs['cwd'] = cwd try: with open(os.devnull, 'w') as FNULL: proc = subprocess.Popen(command, stdout=FNULL, ...
3cfb8f672e2c15c80d89fe28e2d7fbab0cae4ae5
666,715
def process_info(table): """ Helper of get_availabilities_by_url Parser information and returns the room type, price, and number of rooms left. """ rooms = [] for row in table: if len(row) >= 5: rooms.append({ 'type': row[0].split("\n")[0].replace("\n...
acc02d7496a966d53d22beded949ad0c410d4f3f
666,716
def _services_and_security_profiles(config_object): """ This check is performed in order to understand if security profiles are compatible with configured services DNS + AntiVirus <-- Antivirus inspect files, not DNS requests """ mail = ["SMTP", "SMTPS", "POP3", "POP3S", "IMAP", "IMAPS"] we...
1d6ee67d52dd965f8a81a6325c76ff8a5e4b3145
666,717
def depends_one_or_more(dependencies): """Returns true if any of the dependencies exist, else false""" return any([x.get_exists() for x in dependencies])
b77bf4e7fd049daced040e7dadd3cc4d528860cd
666,718
def find_value_in_list(l_r, value): """ Purpose: To get value in a given list Parameters: list, value Returns: True or False Raises: """ result = False for item in l_r: if item['id'] == value: result = True break return result
aee00fd06c5212dbb7107f6735a240785ebd9b63
666,719
import os def delete_if_possible(uri): """ Deletes a file if exists Args: uri: file to delete """ if os.path.isfile(uri): try: os.remove(uri) return True except IOError as e: print("Unable to delete.", e) return Fal...
fcaf893601ad6e143190e6fd34b6c27f4f5a0e94
666,720
def check_duration(sec, larger=True): """ Creates a function you can use to check songs Args: sec: duration that we compare to in seconds larger: determines if we do a larger than operation Returns: Function that can be used to check songs """ def...
cc646b648580454559ab866a07cad50cec3d2fdc
666,722
import decimal def j_round(float_num): """java like rounding for complying with the OpenLR java: 2.5 -> 3""" num = decimal.Decimal(float_num).to_integral_value(rounding=decimal.ROUND_HALF_UP) return int(num)
5db80df0ad79a41b799970b697dbed8c45f1a09e
666,723
import os def expand_target(target): """ Walk a directory to find files """ target_list = list() if os.path.isfile(target): target_list.append(target) if os.path.isdir(target): for rootdir, _directories, filenames in os.walk(target): for filename in filenames: ...
b4df8602a7dfcc3497849231a9b577fed1eb6da1
666,724
def color_new_words(new: str, old: str, color: str = "#eefa66") -> str: """Color new words in strings with a span.""" def find_diff(new_, old_): return [ii for ii, (n, o) in enumerate(zip(new_, old_)) if n != o] new_words = new.split() old_words = old.split() forward = find_diff(new_words,...
7ff88adcca3c65a70a79a63832bc5c717f329190
666,725
def filter_dict_nulls(mapping: dict) -> dict: """Return a new dict instance whose values are not None.""" return {k: v for k, v in mapping.items() if v is not None}
671e3749703e7d7db21939ff2906cdfd940acef4
666,727
import socket def is_port_used(ip, port): """ check whether the port is used by other program 检测端口是否被占用 :param ip: :param port: :return: """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((ip, port)) return True except OSError: ret...
c168d6066fac1f23c7ba6f3bf3e7af86fbad659b
666,729
def is_duplicate_policy(link_contents, domain, policy_dict): """ Since the crawler does its work automatically, it is not immune to gathering duplicate policies (sometimes from different initial sources). This function will compare the current policy with the previously verified policies to see if i...
593eeadc9acf16fd5731e5cf92531f20ab5b3d58
666,730
def check_string(string, pos, sep, word): """Checks index 'pos' of 'string' seperated by 'sep' for substring 'word' If present, removes 'word' and returns amended string """ if sep in string: temp_string = string.split(sep) if temp_string[pos] == word: temp_string.pop(pos) ...
96ce5862f8f1b853144b7713e7f6185e3e4efa1a
666,731
from typing import Optional import string def remove_punctuation(input_text: str, punctuations: Optional[str] = None) -> str: """ Removes all punctuations from a string, as defined by string.punctuation or a custom list. For reference, Python's string.punctuation is equivalent to '!"#$%&\'()*+,-./:;<=>?@[...
032b2e50365b8966b402ed0c510f6f9ba2e1cecc
666,732
def maskOutsideBuildArea(label_image, mask_left_side=0.3, mask_bottom=0.4): """ Segment the frame into three rectangles. """ rows, cols = label_image.shape row_bound = int(mask_bottom * rows) col_bound = int(mask_left_side * cols) if mask_left_side: label_image[:, :col_bound] = 1 if m...
070ab47a75ad9aa9bdd71021b4a004b71f1bdd9d
666,733
def coordstr(roi): """String representation of coordinates. Also for URL arguments.""" return str(roi['xll']) + ',' + str(roi['yll']) + ','\ + str(roi['xur']) + ',' + str(roi['yur'])
67edcca8a82b79e0ed78278ee3149ab041090ce7
666,734
def calc_validation_error(di_v, xv, tv, err, val_iter): """ Calculate validation error rate Args: di_v; validation dataset xv: variable for input tv: variable for label err: variable for error estimation val_iter: number of iteration Returns: error rate ...
e705db8b27793e1cdf648ef72c99e56832d39afc
666,736
from typing import List def transpose_matrix(matrix: List[List[int]]) -> List[List[int]]: """ """ rows, columns = len(matrix), len(matrix[0]) return [[matrix[row_idx][col_idx] for row_idx in range(rows)] for col_idx in range(columns)]
3e16b27cfcf31467193fb52ed7b3f79f785b0196
666,737
def dict_get(d, key, default=None): """ exactly the same as standard python. this is to remind that get() never raises an exception https://docs.python.org/3/library/stdtypes.html#mapping-types-dict """ return d.get(key, default)
08176db060c8076467d2e3053618d25875021f5d
666,739
import copy def parse_args(args): """To parsify the command provided by the user on command line""" left_command_args = copy.deepcopy(args[0: args.index("as")]) args = args[args.index("as") + 1:] left_name = args[0] right_command_args = copy.deepcopy(args[args.index("join") + 1: args.index("as")]...
f34bb02a8be2c569ccf6c0a6b634850ee74de92c
666,740
from typing import Iterator from typing import Dict from typing import List def _translate(lines: Iterator, messages: Dict) -> List: """ Update lines from .po file with translated messages dict :param lines: :param messages: :return: """ translated = [] for line in lines: if line....
c6aa20cf34aaee301f3c10ce0a756706fcaf07eb
666,741
def list_to_dict(keyslist,valueslist): """ convert lists of keys and values to a dict """ if len(keyslist) != len(valueslist): return {} mydict = {} for idx in range(0,len(keyslist)): mydict[keyslist[idx]] = valueslist[idx] return mydict
f0082793a5eeaaecb374650fc3cda87a3345ccf5
666,742
def create_popup_id_query_selector(iteration): """ :param iteration: :return: """ return '#' + 'popup' + iteration
d93730c6c223caa9c79a915736183307dd5c02c1
666,744
import torch def kld_gaussian(mu, log_sigma, nu=0.0, rho=1.0): """ KL-divergence between a diagonal multivariate normal, and a standard normal distribution """ device = mu.device nu = torch.as_tensor(nu, device=device) rho = torch.as_tensor(rho, device=device) delta_variance = 2.0 * (l...
48b353b8fb0cf63ad8ea823ffa62c5d96d3510f5
666,745
import os def split_filename(fname): """Split a filename into parts: path, base filename and extension. Parameters ---------- fname : str file or path name Returns ------- pth : str base path from fname fname : str filename from fname, without extension ex...
e575f40d665e4c0b9e7f2e9e1115b4a2e3686c73
666,747
from typing import Optional def linkify(url: str, text: Optional[str] = None): """Make a link clickable using ANSI escape sequences. See https://buildkite.com/docs/pipelines/links-and-images-in-log-output """ if text is None: text = url return f"\033]1339;url={url};content={text}\a"
c13cfbca91d45943f9326325fe1c5bd68b71e6d3
666,748
import random import string def random_string(min_length=5, max_length=10) -> str: """ Get a random string. Args: min_length: Minimal length of string max_length: Maximal length of string Returns: Random string of ascii characters """ length = random.randint(min_lengt...
e92aff7adb290e82946dae907c7dc6ee2e6ebe0c
666,749
import math def dist_d3 (p1, p2): """Returns the euclidian distance in space between p1 and p2. """ return math.sqrt( (p2[0] - p1[0])**2 + (p2[1] - p1[1])**2 + (p2[2] - p1[2])**2)
751aaa69b8c39a808c3b1a625ef78709f721015a
666,750
import pwd import os def get_username(): """Get the username of the current process.""" if pwd is None: raise OSError("get_username cannot be called on Windows") return pwd.getpwuid(os.getuid())[0]
2d0a67a0998c1434d3be0158281f64d4ef3b9746
666,751
import torch def batched_gather(data, inds, dim=0, no_batch_dims=0): """https://github.com/aqlaboratory/openfold/blob/5037b3d029efcc9eeb3f5f33eedd4ecdd27ca962/openfold/utils/tensor_utils.py#L67""" ranges = [] for i, s in enumerate(data.shape[:no_batch_dims]): r = torch.arange(s) r = r.view(*(*((1,) * i), -1, *...
fb97551bbe0c84a540e78ca48762c599dc4cadfe
666,752
import subprocess def run_live(command): """Run a command with real-time output""" proc = subprocess.run( command, stderr=subprocess.PIPE, text=True ) results_dict = { 'status': proc.returncode, 'success': proc.returncode == 0, 'stderr': proc.stderr } return...
1d0cd8a3ee36a62f98a9b4f9d83764b483642653
666,753
def find_between(s, start, end): """ Return a string between two other strings """ return (s.split(start))[1].split(end)[0]
de7494240dec8202a61ac47e798cdac6f547966e
666,754
import requests def currency_data_last_n_days(currency = 'ETH', to = 'EUR', days = 14): """Get day by day price of a currency in respect to another one, using the APIs at "min-api.cryptocompare.com". Data are from the last "days" days.""" currencies = 'fsym={0}&tsym={1}'.format(currency, to) days...
05c4f626cce7d99fa1c6d7ce4de5ecbf61eaccb2
666,756
def row2dict(row): """Converts SQLAlchemy row to dict Args: row: A SQLAlchemy query result object Returns dict: Returns the row as dictionary """ d = {} for column in row.__table__.columns: d[column.name] = str(getattr(row, column.name)) return d
080f65b41539ad2ceb7622ea3b9c772bf258542a
666,757
def calc_term_overlap(termsA, termsB): """ Calculate the reciprocal overlap between two lists of HPO terms """ nA = len(termsA) nB = len(termsB) if nA == 0 or nB == 0: ro = 0 else: nOvr = len(set(termsA).intersection(set(termsB))) oA = nOvr / nA oB = nOvr / ...
0140cc9f31ede1cf8023040383dcd45a39738d0a
666,758
from typing import Union def is_palindrome(word: str) -> Union[bool, str]: """Function to check if word is a palindrome >>> from snakypy.helpers.checking import is_palindrome >>> is_palindrome("ana") True >>> from snakypy.helpers.checking import is_palindrome >>> is_palindrome("banana") Fa...
d44480a460a9fc99a136cae7ff601ca3684b9bd7
666,759
def sort_completions(completions_gen): """ sorts the completions """ def _get_weight(val): """ weights the completions with required things first the lexicographically""" priority = '' if val.display_meta and val.display_meta.startswith('[REQUIRED]'): priority = ' ' # a spa...
028c0e47d0bdb699d51045d9bb7b4601cd58bb10
666,760
import torch def compute_accuracy_for_train(output, labels, mask, score_threshold, num_type, num_relation): """ Compute: precision, recall, f1-score """ #compute precision, recall and f1-score preds = torch.gt(output, score_threshold) preds = torch.mul(preds, mask) preds_sum...
72755f534154f1153fdf0e0a295016ac24204309
666,761
from datetime import datetime def day_end(date: datetime) -> datetime: """ Calculates end of date Args: date (datetime): datetime object, for which to calculate the end of the day Returns: date_end (datetime): timestamp for end of the given date """ return datetime(date.year,...
3b21bd2f54bc4ab895ec0aab80def3c895e51ce2
666,762
def get_format_name_with_option_middle(first, last, middle = ''): """返回可选的中间名姓名""" if middle: full_name = first + ' ' + middle + ' ' + last else: full_name = first + ' ' + last return full_name.title()
98c06cb31b150cc2d16875fc8aa7dec334136709
666,763
import torch def quaternion_into_axis_angle(quaternion): """ Takes an quaternion rotation and converts into axis-angle rotation. https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles :param quaternion: 4-element tensor, containig quaternion (q0,q1,q2,q3). :return: (Axis of rotatio...
37569c34dbddacd5820171ebc5935c00b3e2bfb3
666,764
def read_side_and_obstacles_size(): """Function to read the first line of the input""" line = input().split() side = int(line[0]) obstacles_size = int(line[1]) return (side, obstacles_size)
4b406ce271ead553600bab12b55c6a1b3340e553
666,765
def get_offsprings(g, nodes): """ Find the offspring nodes in a DAG :param g: a directed acyclic graph :param nodes: targeted nodes :return: a set of offspring nodes """ return set.union(*[g.descendants(d) for d in nodes])
9da14e457ac402200aa18ebef90b18fba56379e6
666,766
import collections def rotated_range(start, stop, starting_value): """Produces a range of integers, then rotates so that the starting value is starting_value""" r = list(range(start, stop)) start_idx = r.index(starting_value) d = collections.deque(r) d.rotate(-start_idx) return list(d)
9a941e5dcd95b4dadf73e77cc50f6e4d12fe5885
666,767
import pathlib def assets_dir(): """Return the path of the directory with helper test files.""" return pathlib.Path(__file__).resolve().parent / 'assets'
6d2165f3e53901f1b75ce4d387c76d969d9dc7ad
666,768
def get_img(img_db, idx): """Get image from index. Parameters ---------- img_db : h5py.File image datasets idx : int The index of the image Returns ------- img_out : numpy.ndarray the output image """ if (idx < 60000): return img_db["CIFAR10"][id...
c3d34b4d9569b5da71422ea1958b769d1a621c51
666,769
import socket def _getdomainaddr(host_info): """ Return the domain address of the current network. For dual IP configuration the list of addresses may be returned by socket.gethostname(), like: [(10, 1, 6, '', ('2620:6a:0:8421::96', 0, 0, 0)), (10, 2, 17, '', ('2620:6a:0:8421::96', 0, 0, 0)), ...
69614a64f5b019408d47289c09e627fcf9c0df20
666,770
def lab2phonemes(labels): """Convert labels to phonemes. Args: labels (str): path to a label file Returns: List[str]: phoneme sequence """ phonemes = [] for c in labels.contexts: if "-" in c: ph = c.split("-")[1].split("+")[0] else: ph = ...
40f8a40a58a047db2870a478677b5369b559a595
666,771
import os def check_defaults(profile, sub_commands): """Check list of paths that should/not exist Parameters ---------- profile : dict A single profile (either global or named) created by load_config sub_commands : str A list of commands to verify correctness of within the profile...
b19c3c88f36a43c7cdab25640a6ea203795fcba6
666,772
import copy def modify_namespace(namespace, args): """Modify the specified arguments in the passed Namespace. namespace argparse.Namespace object args dict of argument: value pairs For most command-line tests, we define a base argparse.Namespace object, then change a few argumen...
65aee8eb630ee0b75b81b18234ea04b6ca888491
666,773
def parse_arguments_to_worker(args): """ Turns the list of argv arguments that is send to a com process (by the editor) into appropriate list of strings and lists (of topics). It is up to the com's start_worker function (in the *Com.start_worker functions) to create a list of argv that can be properly p...
53feaf370ab4bc34cd6c25453798321ceb989e3d
666,774
def xyY2XYZ(xyY): """ convert xyY to XYZ :param xyY: array-like :return: array like """ X = xyY[0] * xyY[2] / xyY[1] Y = xyY[2] Z = ((1 - xyY[0] - xyY[1]) * xyY[2]) / xyY[1] return [X, Y, Z]
c8a56adfa01e3f693b60f088a41807950c2368bc
666,775
def get_leader(units): """Return the leader unit for the array of units.""" for unit in units: out = unit.run('is-leader') if out[0] == 'True': return unit
fe36d216adac6687128459284e5136744d2a0a71
666,776
def vector_to_tuple(vector): """Converts a column vector into a tuple.""" return tuple(row[0] for row in vector)
b7a3a22a6a916801987f5d66347bfcd87742d540
666,777