content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def divide_LeftRight(img): """ Divide bi-camera image into left image and right image bi-camera image shape:(720,2560,3); left and right image shape:(720,1280,3) :param img: CV2 mat image :return: ;left_img, right_img """ divide_index = img.shape[1] // 2 right_img = img[:, 0:divide_index...
2ffbbdb8ea166f4221e4a0722146faa6a432c8b1
636,784
def extract_scores(transcript): """Extract scores of different types from a grading job's output, starting from the bottom of the output :param transcript: the grading output :type transcript: str :return: a list of (key, score) pairs """ score_lines = [] found_score = False for l...
7232e63b19ae7d302e31259258632b0dac645964
636,786
def _make_fasta( num_proteins, peptides, peptides_per_protein, random_state, prefix="" ): """Create a FASTA string from a set of peptides Parameters ---------- num_proteins : int The number of proteins to generate. peptides : list of str A list of peptide sequences. peptides...
bf2439afce4cda8b603e04fc4186a6660bba2edb
636,789
def extract_signal(s): """ Returns the portion of s between the (first) pair of parentheses, or the whole of s if there are no parentheses. """ loc0 = s.find("(") if loc0 >= 0: loc1 = s.find(")") if loc1 >= 0: return s[loc0 + 1 : s.find(")")] return s
38d695e8e42f385a14b1a392aaf5d3dfd9d6f55b
636,792
def nice_time(sec_in): """ Pretty formatting for time stamps """ seconds = int(sec_in) % 60 minutes = int((sec_in / 60)) % 60 hours = int(sec_in / 3600) return "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds)
47df5b5b1b10f8d0f831e4707df30872dae712c1
636,794
def is_tag(elm): """ True if the passed object is a HTML/XML tag * **elm**: * **return**: >>> from bs4 import BeautifulSoup as bs >>> doc = bs("<span></span><p>bubu</p>", "html.parser") >>> span = doc.span >>> is_tag(doc.span) True >>> is_tag(doc.p) True >>> is_tag(list...
5cdbbea685a9b1030dbeb5d83aa32df3d20b121b
636,795
def get_value(specs, name): """ Unpack metric specification Parameters ---------- specs: dict a dict with keys value and name name: str the spec name Return ------ value: float or None value of the spec if exists, None otherwise """ value = None for ...
06a83cdb70f891235f773eda28ec0fc59bc86e79
636,796
def get_default_arrow(scale=1): """Get the default arrow """ return { 'cylinder_radius': scale*0.05, 'cylinder_height': scale*0.75, 'cone_radius': scale*0.125, 'cone_height': scale*0.25 }
10276185aad3710315a477a07e38c05049371984
636,800
def query_templater( table_name, columns=None, conds=None, db_name="darpa_data" ): """ Generates an appropriate SQL query for db_name Params: table_name : str Some darpa_data table columns : [str] or None A list of column names to fetch...
b8f7bd3423407fe4be47a0f136375cafb0f97582
636,802
import string def sanitize_channel_name(name: str) -> str: """Filter out characters that aren't allowed by Discord for guild channels. Args: name: Channel name. Returns: Sanitized channel name. """ whitelist = string.ascii_lowercase + string.digits + "-_" name = name.lower()....
2f0b246cbecfcf8a39ea6810da836c9d469bc0f1
636,804
from operator import mul def multiplyLists(lst1, lst2): """Return the elementwise product of lst1 and lst2.""" assert len(lst1) == len(lst2), "The lists have to be the same length." return list(map(mul, lst1, lst2))
fe26b0d143a1beec53c7ed771e383e7edff6154a
636,815
def serialize_uint256(n: int) -> bytes: """ Serialize an unsigned integer ``n`` as 32 bytes (256 bits) in big-endian order. Corresponds directly to the "ser_256(p)" function in BIP32 (https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#conventions). :param n: The integer to be seria...
e8987a9a59843bc5cac22d11c3222abe5ccd7f6b
636,817
def add_mask_to_image(img, mask, x, y): """Paste a mask at specific position on image""" if y + mask.shape[0] > img.shape[0]: max_height = img.shape[0] - y mask = mask[: max_height, :] if x + mask.shape[1] > img.shape[1]: max_width = img.shape[1] - x mask = mask[: , :max_wid...
093b0410c0a0dfc46c4f4b717b34932b9672c05d
636,819
def dSquaredLoss(a, y): """ :param a: vector of activations output from the network :param y: the corresponding correct label :return: the vector of partial derivatives of the squared loss with respect to the output activations """ # assuming that we measure the L(a, y) by sum(1/2*square(y_i - a...
9793bd5bd9e9f5190b0868466a8716a5ce82c653
636,826
def get_cmd_arg(arg, cmd_tree): """ Return the indicated command argument from command parse tree. If arg is a str it is a keyword. If arg is an int it is a positional index. If the argument is not found, return None. Args: arg: Command argument to look up cmd_tree: Parsed command t...
b90c24bbc387ddc0158a3d5d000126d844be2be8
636,828
def get_notes_by_song(song, notes_map): """ Iterate over all labels for a given song. Same note have different midi codes in different octaves. For example the note C has the following codes: 12, 24, 36, 48, 60, 72, 84, 96, 108, 120 For this representation, we transform all these code only t...
311666e0f72fad8c8c10c7128a633c7ae18653d2
636,829
import torch def get_bert_embeddings(tokens_tensor, segments_tensors, model): """Get embeddings from an embedding model Args: tokens_tensor (obj): Torch tensor size [n_tokens] with token ids for each token in text segments_tensors (obj): Torch tensor size [n_tokens] ...
6b9ddd69f6f61d5667bc321ae3628485a9a2fa47
636,832
def parse_dependencies_windows(data): """ Parses the given output from dumpbin /dependents to determine the list of dll's this executable file depends on. """ lines = data.splitlines() li = 0 while li < len(lines): line = lines[li] li += 1 if line.find(' has the following de...
4e3f6ed46171d2861d68e1bf06302652cb5b5103
636,834
def get_datetime_str(dt): """ >>> dt = datetime.datetime.now() >>> def get_datetime_str(dt): ... return dt.strftime("%Y-%m-%d %H:%M:%S") >>> get_datetime_str(dt) '2021-04-11 17:19:10' """ return dt.strftime("%Y-%m-%d %H:%M:%S")
5c657ab1d43879cb16c80b4c89061864f6827d18
636,838
import gc import time def measure(func, inner_iterations=1, repeats=5): """ Runs func ``repeats`` times and returns the fastest speed (inner loop iterations per second). Use ``inner_iterations`` to specify the number of inner loop iterations. Use this function for long-running functions. """ ...
65bbf304eb8d2e3db5fbc3e56cb118503339ccb9
636,839
def calculateBoxInertia(mass, size): """Returns upper diagonal of inertia tensor of a box as tuple. Args: mass(float): The box' mass. size(iterable): The box' size. Returns: : tuple(6) """ i = mass / 12 ixx = i * (size[1] ** 2 + size[2] ** 2) ixy = 0 ixz = 0 iyy ...
e8634f8079a002a0c96876dcb12ec3d29ed1b58e
636,840
def get_suspecious_items(_items): """Items with libraryCatalog==Zotero These items are suspecious, cause they were imported from pdf files and maybe Zotero did not import the metadata properly. :param _items: Zotero library items :type _items: list containing dicts :returns: list containing di...
d067dc2756630b814552b461927c31530cb67e4f
636,843
def validate_change_dict_for_blog_post(change_dict): """Validates change_dict required for updating values of blog post. Args: change_dict: dict. Data that needs to be validated. Returns: dict. Returns the change_dict after validation. """ if 'title' in change_dict: blog_do...
926e145cefaced48e662ee31b219c9176a98bd6c
636,846
def covxy(x, y): """ Covariance => average of pair products. """ N = x.shape[0] psum = 0 for i in range(N): psum = psum + x[i] * y[i] return psum / N
bf315cabb6d2af97a508d981dd3af24c74ebd21f
636,848
def overlaps(low1: int, high1: int, low2: int, high2: int) -> bool: """ Returns true if the two regions [low1, high1] and [low2, high2] overlap. """ return high1 >= low2 and high2 >= low1
c44a5dd3ebfb3ce8cebb531d0da2778d650e5a29
636,849
def uniq(seq): """return uniq elements of a list, preserving order :param seq: an iterable to be analyzed """ seen = set() return [x for x in seq if not (x in seen or seen.add(x))]
111efd8305b618bad380052883bf5ccbecb4d1ba
636,850
from typing import Any def import_class(name: str) -> Any: """Import from a module specified by a string""" components = name.split(".") mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod
a69ecbf83d7df82537a7c261da3a412acc69234c
636,852
def pos_mask(row: int, col: int) -> int: """Return the bit mask for (row, col) on a bitboard.""" assert 0 <= row < 8 assert 0 <= col < 8 return 0x8000000000000000 >> col >> row * 8
11e374843026bb50a3d6ca0cd58c52d6ec1924b4
636,858
def find_vswitch_uri_for_id(k2_id, vswitch_map): """ Returns the vSwitch href URI for a given K2 id. :param k2_id: The K2 vSwitch ID :param vswitch_map: The vSwitch map from the HMC Topo :returns: vSwitch URI """ k2_obj = vswitch_map.get(k2_id) if not k2_obj: return None retu...
e8e9fbaa16061f207a0d9f49afe5ffb534cf409a
636,859
def get_leftmost_end_point(linestring): """ extracts leftmost end point of linestring :param linestring: shapely.geometry.LineString :return: shapely.geometry.Point """ point_0_x = linestring.xy[0][0] point_1_x = linestring.xy[0][-1] if point_0_x <= point_1_x: return point_0_x ...
e23014df16f09f6d60e3f3af66b5ef04ee5ca0bb
636,861
def getKey(myDict, value): """ Finds key associated with a value in dictionary """ for key, val in myDict.items(): if val == value: return key return -1
ac0c1eaa8fec797ac1e4db9c1e0886cc5cffd99d
636,862
def _worker_fn(url, dataset_fn, sampler_fn): """Function to generate the dataset and sampler for each worker.""" dataset = dataset_fn(url) sampler = sampler_fn(dataset) return (dataset, sampler)
4ddafee02420eca6731ab75e60172c023c953eef
636,863
def summary_global_quantities(ods, update=True): """ Calculates global quantities for each time slice and stores them in the summary ods: - Greenwald Fraction - Energy confinement time estimated from the IPB98(y,2) scaling - Integrate power densities to the totals - Generate summary.global_q...
f70e9d233fc457e495e3ebb5ee46faaec38ad98a
636,865
def get_resume_name(stage_name): """return a new name with resume and an increasing index""" split_stage_name = stage_name.split("_") if len(split_stage_name) > 2 and split_stage_name[-2] == "resume": resume_index = int(split_stage_name[-1]) + 1 return "_".join(split_stage_name[:-2] + ["resu...
a1aea3021b33c1c39b5671979eaab13c91ecaf26
636,866
import yaml def extract(mdtext): """ Extract a yaml text blob from markdown text and parse the blob. Returns a tuple (yaml_obj, markdown_text) """ lines = mdtext.split("\n") n = 0 ylines = [] mlines = [] for line in lines: if (line == "---"): n = n + 1 else: if n == 1: y...
7bfb9affa1b24af321f7558d01edbce86dfc80a9
636,872
import torch def binary_accuracy(prediction, target): """Calculates accuracy between two classes using probabilities Parameters ---------- prediction : torch.Tensor or torch.autograd.Variable Vector of probabilities of class 1 target : torch.Tensor Vector containing the class indices 0 or 1 """ ...
4f101992de444af744c06b361146feeee917b682
636,874
import inspect def listens_to(name): # noqa: D401 """Decorator to register a method of a :class:`Handler` as a listener. The method must be a coroutine. Arguments --------- name: :class:`str` The name of the event to listen to. Raises ------ TypeError The name was n...
e3c8f4bc365cfe4ee60a09297741335a4640272d
636,875
def correlate_dicts(dicts, key): """Correlate several dicts under one superdict. If you have several dicts each with a 'name' key, this puts them in a container dict keyed by name. Example:: >>> d1 = {"name": "Fred", "age": 41} >>> d2 = {"name": "Barney", "age": 31} >>> flint...
2f4c03f5d976115ea14746a1acf243fff635bdb8
636,880
import functools def as_list(f): """Decorator that changes a generator into a function that returns a list.""" @functools.wraps(f) def wrapper(*args, **kwargs): return list(f(*args, **kwargs)) return wrapper
28b0de884a06f4a0933ef7afe9940e449cfb2144
636,884
def is_overlapped(end1, start2): """Returns True if the two segments overlap Arguments --------- end1 : float End time of the first segment. start2 : float Start time of the second segment. """ if start2 > end1: return False else: return True
421148cd3dfbb9ea5accaa6f5792c48beee09334
636,885
def _delta(x,y): """ Returns 1 if x and y differ, 0 otherwise. """ return x != y
69b3d1eca28678685d9d135b091affd1d6dcff00
636,888
def matrix_relative_rotation(r0, r1): """ Find the relative rotation to go from r0 to r1. """ return r1 @ r0.T
83f675dda63a8120662b2b840b40e74f51580173
636,889
import tempfile def makeTempDir() -> str: """Make a temporary directory. :rtype: str :return: The path to the temporary directory. """ return tempfile.mkdtemp()
cede067b0cc720ab37859d4ea590429778edbcf9
636,891
def parse_header(line): """Returns dict {'field': (start, length), ...}""" fields = [f.strip() for f in line.split(' ') if f.strip()] return {field: (line.index(field), len(field) + 1) for field in fields}
cb0f5bfec6540a573455ef6b4ee9de39a8809a74
636,896
import warnings def deprecate_arg(old_arg, new_arg, old_value, new_value): """Helper to raise warnings when a deprecated arg is used. Args: old_arg (str): Name of old/deprecated argument. new_arg (str): Name of new argument. old_value (Any): Value the user passed in for the old argume...
2d1a9a05ec65d364f26449423b540093c4c44167
636,897
def readfile(filename): """ Reads and returns file contents """ with open(filename) as docfile: return docfile.read()
ac17395b05e501673718b1110c3ebbedcee4e60c
636,899
import math def get_learning_rate(lr_schedule, tot_epoch, cur_epoch): """ Compuate learning rate based on the initialized learning schedule, e.g., cosine, 1.5e-4,90,6e-5,150,0 -> ('cosine', [1.5e-4,90,6e-5,150,0]). Args: lr_schedule: the learning schedu...
a6ee1d202d846094243baa120f1486e33016a174
636,900
def topic_ref_transform(ref_string, topic): """ Converts a topic string with forward-slashes into a JSON reference-friendly format ("/" becomes "~1"), then places the new string into the provided base reference path. :param ref_string: The base reference path :param topic: The DXL topic string to c...
b80071faed0e9bc3a4c8b06453e84c385012b532
636,901
import re def check_date_format(date_str): """ Check the date to ensure that it's in the proper format """ pattern = re.compile("^\d{4}-+\d{2}-+\d{2}T+\d{2}:+\d{2}:+\d{2}.+\d{1,}Z+$") matched = pattern.match(date_str) return matched
4c82090bd463e71683ec8cc599e2f34515a6ce4f
636,905
def compute_standard_walking_time(length_m: float, elevation_gain_m: float, elevation_loss_m: float) -> float: """Estimate the hiking time in seconds Parameters ---------- :param: length_m: Length of the hike in meters :param: elevation_gain_m: Elevation gain of the hike in meters :...
c6c1c6896f1c9b5188d3b65bf32880f6071b92e1
636,906
def sort_dict(data: dict, key_type=None, reverse=False): """ Returns a sorted dictionary by keys :param data: the input dictionary :param key_type: type of key (if keys are not str for example) :param reverse: sort in reverse order :return: sorted dictionary """ res = {} if len(data)...
b7cb416ebf6c572d09838ade105c5229a5be2e99
636,907
def bounds_to_geojson(bounds): """ Convert a rio BoundingBox to geojson with optional buffer :param bounds: BoundingBox :return: geojson with applied buffer """ return { "type": "Polygon", "coordinates": [ [ [bounds.left, bounds.top], [...
6aab2f3b44ff79eb30681b4f9d7aefc99679c0d6
636,912
def _get_dataset_length(dset, default=1): """Return the dataset's training data length and in case the dataset is uncountable return a defalt value.""" try: return len(dset.train_data) except RuntimeError: return default
b2c46e652d425b920406a3a534d55886c555e0a5
636,915
def attribution() -> str: """Returns data attribution string""" return '\u0026copy; <a href="https://usafacts.org">USAFacts</a>. '
556d0f74bc35a4e7cbc597d1a9190d8c8b936683
636,917
def _filter_core_state_space(df, options): """Applies filters to the core state space. Sometimes, we want to apply filters to a group of choices. Thus, use the following shortcuts. - ``i`` is replaced with every choice with experience. - ``j`` is replaced with every choice without experience. ...
296c25879a2e30d8260efdf28ada02c6e5e69ff9
636,918
def get_output_file(dataset, output_dir): """ Compute the output metadata file name for the given dataset. """ out_file_name = str(dataset.id) + '-metadata.yaml' return output_dir / out_file_name
34086bb664a5e1527391ad1d606196e0b63f3453
636,920
import warnings def _split_sections(lines): """ Split rigaku file into sections Returns a list of sections [(name, body, index)] where name is the section type, body is the list of lines between *RAS_name_START and *RAS_name_END and index is the 1-origin index of *RAS_name_START (or the 0-origin ...
b80678d654a91b6703dc490b930dff59f116ad29
636,922
import zipfile def list_files_in_zip(filename, endswith=None): """ List files in zip archive :param filename: path of the zip :param endswith: optional, end of filename to be matched :return: list of the filepaths """ with zipfile.ZipFile(filename) as zip_file: filelist = zip_file.name...
51aeefd0c14223d65f84bbf95e7676fe27e46297
636,926
def producer_config(config): """Filter the producer config""" for field in ["group.id", "partition.assignment.strategy", "session.timeout.ms", "default.topic.config"]: if field in config: del config[field] return config
3245c62f26288ab58a992494a4d0e87b772fcc81
636,930
def label_filter(label_key, label_value): """Return a valid label filter for operations.list().""" return 'labels."{}" = "{}"'.format(label_key, label_value)
fe6efe0fdce70a1c36e3f070205c3b0d4279dd62
636,932
from datetime import datetime def utc_folder(x): """ Convert a UTC timestamp to a folder string """ return datetime.utcfromtimestamp(x).strftime('%Y/%j/%H')
a153a06d07600420bbbcfa846eb144b0cceddf13
636,933
def short_state(state: str) -> str: """Return a short version of query state. >>> short_state("active") 'active' >>> short_state("idle in transaction") 'idle in trans' >>> short_state("idle in transaction (aborted)") 'idle in trans (a)' """ return { "idle in transaction": "i...
1559c3e97314607d96954793a9b253ef252dd04c
636,936
import re def _extract_sentence_tags(tagged_sentence): """Given a tagged sentence, extracts a dictionary mapping tags to the words or phrases that they tag. Parameters ---------- tagged_sentence : str The sentence with Medscan annotations and tags Returns ------- tags : dict ...
2a913707d2f48736f70df2141779c00a0068ee54
636,939
def find_median(a: int, b: int, c: int) -> int: """Find median of three elements""" x = a - b y = b - c z = a - c if x * y > 0: return b if x * z > 0: return c return a
97816d215c11fc158f800fe47d5b89941fd356fd
636,940
def get_updater(api, resource_type): """Returns the method to update a given resource type """ updaters = { "source": api.update_source, "dataset": api.update_dataset, "model": api.update_model, "ensemble": api.update_ensemble, "batchprediction": api.update_batch_pre...
3cbdad0376940724783134734b521e802da2ea60
636,944
import torch def get_complete_dataset(dataloaders, key="train", region="region1"): """ Load complete dataset to memory. Args: dataloaders (OrderedDict): dictionary of dictionaries where the first level keys are 'train', 'validation', and 'test', and second level keys are r...
8e952cd8458884160ee51f46a21feebc1af6c87c
636,946
def converter_tuple(obj) -> tuple: """ Convert input to a tuple. ``None`` will be converted to an empty tuple. Parameters ---------- obj: Any Object to convert. Returns ------- obj: Tuple[Any] Tuple. """ if obj is None: return () elif hasattr(obj, "_...
0e08563fc0f8253d1f81d1de90fdafd70cbe387b
636,947
def tupilate(source, val): """Broadcasts val to be a tuple of same size as source""" if isinstance(val, tuple): assert(len(val) == len(source)) return val else: return (val,)*len(source)
6047a14148aa22c32a2caa43f8ea2015ba69bd8c
636,948
def convert_eq(list_of_eq): """ Convert equality constraints in the right format to be used by unification library. """ lhs = [] rhs = [] for eq in list_of_eq: lhs.append(eq.lhs) rhs.append(eq.rhs) return tuple(lhs), tuple(rhs)
1366c0fa26b690cace85cb4feb2a646600850543
636,950
def split_filtStr(filtStr): """ ...doctest: >>> split_filtStr('a>b;c<=d; e == f; bc=[0,1]') ['a>b', 'c<=d', 'e == f', 'bc=[0,1]'] >>> split_filtStr('a>b AND c<=d AND e == f') ['a>b', 'c<=d', 'e == f'] >>> split_filtStr('bc=[0,1]') ['bc=[0,1]'] >>> split_f...
2f2221afeb53ac4bfa626dfb4b7ad3082fc2c7c1
636,951
def coord2pix(cx, cy, cdim, imgdim, origin="upper"): """Converts coordinate x/y to image pixel locations. Parameters ---------- cx : float or ndarray Coordinate x. cy : float or ndarray Coordinate y. cdim : list-like Coordinate limits (x_min, x_max, y_min, y_max) of imag...
e750aaf8350826aa22af58e20622182a9a209b97
636,952
def multiply(a,b): """ multiply two numbers """ return a*b
90580db394d6e6021e3fbf969d8de8e5e789fcff
636,954
def get_public_key(remote, realm_url): """Get the realm's public key with the ID kid from Keycloak.""" certs_resp = remote.get(realm_url).data return certs_resp["public_key"]
2d4de952101901a862d14b8e13514f5f17c7d0dd
636,955
def triple(n): """ (number) -> number Returns triple a given number. >>> triple(9) 27 >>> triple(-5) -15 >>> triple(1.1) 3.3 """ one = n * 3 return (one)
0f10a8026aba22ce9a1905c5d445984c7310763d
636,956
import hashlib def md5_bytes(data: bytes): """ generate md5 hash of binary. """ return hashlib.md5(data).hexdigest()
9cfbea28556dae41e3eff3e9b480a48c39a47a3d
636,957
import shlex def expand_file_arguments(argv): """ Any argument starting with "@" gets replaced with all values read from a text file. Text file arguments can be split by newline or by space. Values are added "as-is", as if they were specified in this order on the command line. """ new_args = [] ...
70645b57b303092450cff60c7c4608633d48167f
636,958
def hosts_loader(filename: str) -> dict: """ Loads host mapping file :param str filename: path to file :return: mapping as dictionary """ return_dict = {} with open(filename) as mapfile: lines = [ line.strip() for line in mapfile if not line.startswith('#') and l...
2d271ce94f68eb36237d397678857b6654938f52
636,959
from zlib import crc32 def safe_crc(string): """64 bit safe crc computation. See http://docs.python.org/library/zlib.html#zlib.crc32: To generate the same numeric value across all Python versions and platforms use crc32(data) & 0xffffffff. """ return crc32(string) & 0xffffffff
43c6693c7d30ef19be7cda3d270f5c1225d70778
636,960
def iterator_strategy(cube, axis=None): """ Guess the most efficient iteration strategy for iterating over a cube, given its size and layout Parameters ---------- cube : SpectralCube instance The cube to iterate over axis : [0, 1, 2] For reduction methods, the axis that is ...
a6769396d2fe2a0ca60419dcdc16cb0b454e4e38
636,961
def format_number(num): """Return a number representation with comma separators.""" snum = str(num) parts = [] while snum: snum, part = snum[:-3], snum[-3:] parts.append(part) parts.reverse() return ",".join(parts)
2de1b12c0703f1d5b1ed981f636b4db0cd00707b
636,964
def invert_dict(dct: dict) -> dict: """Invert dictionary, i.e. reverse keys and values. Args: dct: Dictionary Returns: Dictionary with reversed keys and values. Raises: :class:`ValueError` if values are not unique. """ if not len(set(dct.values())) == len(dct.values())...
380ed6b769526c08eecb4f33c58f350c54ccc18f
636,965
def sort_list(coord_list): """ Return a sorted list of coordinates, by y, then x """ return sorted(coord_list, key=lambda k: [k[1], k[0]])
70d5c26e183c483adfe8013c6f60b4865e0f12d9
636,966
def space_list(line: str) -> list: """"Given a string, return a list of index positions where a blank space occurs. >>> space_list(" abc ") [0, 1, 2, 3, 7] """ spaces = [] for idx, car in enumerate(list(line)): if car == " ": spaces.append(idx) return spaces
968fbd2a4cacbd8fda110855677ba10d6bdacd00
636,967
import itertools def _get_coord_mapping( dims, output, out_indices, numblocks, argpairs, concatenate, ): """Calculate coordinate mapping for graph construction. This function handles the high-level logic behind Blockwise graph construction. The output is a tuple containing: The ma...
6cfa507b4bb2ebb50053d71c6947553196114f9a
636,969
def xr_average_across_days_of_year(da): """ Collapses an array across days of each year. Parameters ---------- da: xr.DataArray with 'time' dimension Returns ------- xr.DataArray with a 'year' dimension instead of 'time' """ return da.groupby("time.year").mean()
15f4aa6cab514bf2a609f46f06a7b4d406fbdbfd
636,973
def prompt_for_yes_no(msg): """returns a bool based on whether the user presses y/n.""" choice = None while not choice or choice.lower() not in ['y', 'n', 'yes', 'no']: choice = input('%s (y/n) ' % msg).lower() return choice.lower() in ['y', 'yes']
b6c31055be5accdb62a4dcd6ecc5234955b43845
636,976
def divide(x, y): """ Idiomatic / Pythonic recursive division with remainder """ if x == 0: return (0,0) q, r = divide(x / 2, y) q *= 2 r *= 2 if x & 1: r += 1 if r >= y: r -= y q += 1 return (q,r)
e056e7749b5a8661e966b8723b8f667605b92de3
636,978
def evaluate_mva(df, mva): """ Evaluate the response of a trained classifier. Parameters ---------- df : DataFrame, shape= [n_training_samples, n_features] DataFrame containing features. mva Trained classifier. Returns ------- Series or array Classifier resp...
94432f3d374ba2d34e0cb120cba70b62c33ea464
636,979
def add_50(x): """ Adds 50 to the input value x. """ return x + 50
26a36e12ad38617efc904359729313c430a017c1
636,983
def is_descriptor_schema(data): """Return ``True`` if passed object is DescriptorSchema and ``False`` otherwise.""" return type(data).__name__ == 'DescriptorSchema'
46337d0837f86ff9c6500d6e101844f968e724a3
636,986
def serialize_curve(fcurve): """Returns a list of dictionaries representing each of the keys in the given FCurve.""" key_data_list = [] for key in fcurve.Keys: key_data = { 'time': key.Time.Get(), 'value': key.Value, 'interpolation': int(key.Interpolation), ...
1af5aea6ca0aa8c9ae309ba9b178fa1ecce19493
636,987
def valid_year(year): """Check if number is a valid year""" return 1920 <= year < 2030
3f060ee33de3fd29b89d958386142f6717327524
636,988
def add_reprompt(response): """ Adds a response message to tell the user to ask their question again. """ response['response']['reprompt'] = { "outputSpeech": { "type": "PlainText", "text": "Please ask your crypto price question" } } return response
64fa9f057e84d7332a7c3273a6d1940bcbe03d36
636,991
import math def rotation_matrix_to_euler_angle(R): """ Converts a rotation matrix to [yaw, pitch, roll] """ yaw = math.atan2(R[1, 0], R[0, 0]) pitch = math.atan2(-R[2, 0], math.sqrt(R[2, 1] ** 2 + R[2, 2] ** 2)) roll = math.atan2(R[2, 1], R[2, 2]) return yaw, pitch, roll
8e1f7c77496fabbb0478454940c6cb336d19a0ce
636,994
def arc(equity_array, scale=252): """ Annualized Return Ratio :param equity_array: equity line :param scale: number of days required for normalization. By default in a year there are 252 trading days. :return: ARC as percentage """ return (equity_array[-1] / equity_array[0]) ** (scale / len(...
d7f9ea620d91b8833570cb7bdb9e60b7af49a143
636,996
import re def normalize_directors(s: str) -> str: """Restore proper first-last name order and use a uniform separator between multiple names.""" flip = lambda name: ' '.join(reversed(name.split(', '))) return ' & '.join(map(flip, re.split(' & |/', s)))
1dcb31f0475bb2c307ca790f0a8b25da79393ede
637,002
def string_to_number(s): """Input stringified number and return integer.""" return int(s)
ed74783348d85d06cd8afe72feda5d9872398705
637,003
def sparrow_url_helper(*, build_url, config, **_): """ This helper function uses the "build_url" input from flowbyactivity.py, which is a base url for data imports that requires parts of the url text string to be replaced with info specific to the data year. This function does not parse the data, on...
02aedd2e2755da86f714b5de3ea5ad625831bae2
637,005
def translated_geometry(assets): """Returns the translated geometry assets folder.""" return assets / "translated_geometry"
a2b87ad86ee276b57594afc1db6f3ed217fd7526
637,006
def valida_input(msg, respostas_validas, erro): """ Cria um laço de repetição "while True" que só é encerrado quando o usuário fornece uma resposta válida. enquanto isso não acontece, uma mensagem de "erro" é mostrada na tela. param msg(str): mensagem mostrada ao úsuario no input param respostas_va...
b6bae9d077a77aa0c74432ea69cbc1de27b0d7b3
637,011