content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def list_pairs(validation_dates): """ For a set of ndates dates, return a list of indexes and IDs for all possible unique pairs. For example, for ndates=3 -> [(0, 1), (0,2), (1,2)] """ ndates = len(validation_dates) indexes = [] pair_ids = [] for k1 in range(ndates): for k2 in r...
ab0826c43f5c85f40c3be7b63218bacc5225a503
675,781
def _right_child(node): """ Args: node: index of a binary tree node Returns: index of node's right child """ return 2 * node + 2
183682b4218ac00f22c1e7f82c2606bbea4f91e1
675,783
def have_program(c, name): """ Returns whether connected user has program ``name`` in their ``$PATH``. """ return c.run("which {}".format(name), hide=True, warn=True)
a1b1bcb446aebef3cad9c530b557eb0c9b41e527
675,786
def has_remote(repo, remote_name): """Returns true if the given repository already has the named remote. Args: repo: The git.Repo object representing the repository. remote_name: The remote name to be looked for. """ return remote_name in [x.name for x in repo.remotes]
4e64ed34d6bdb699dbffe35c77a33c187e86394c
675,787
def count_format_specifiers(format_string): """Return the number of format specifiers in string format_string. >>> count_format_specifiers("foo bar foo") 0 >>> count_format_specifiers("foo %d bar foo") 1 >>> count_format_specifiers("foo %d bar %i foo") 2 >>> count_format_specifiers("foo...
f958d96b24ddebc8d90ea5a3d5678cbcee1c9067
675,788
import functools def cached_property(fun): """A memoize decorator for class properties. Adapted from: http://code.activestate.com/recipes/576563-cached-property/ """ @functools.wraps(fun) def get(self): try: return self._cache[fun] except AttributeError: se...
a0fec3b0df310e0d74dd40d23f992749f2e52173
675,791
def merge(source1, source2): """Merge two dicts, source2 could override existing keys based on source1""" return {**source1, **source2}
bdb046ebd4e5c422667add9e342901fcffff1d7e
675,796
import itertools def make_multidim(col, ndim): """Take a col with length=2 and make it N-d by repeating elements. For the special case of ndim==1 just return the original. The output has shape [3] * ndim. By using 3 we can be sure that repeating the two input elements gives an output that is suffici...
268598a1f02deb4b924724dae584cb1f7c7366de
675,798
import csv def get_image_value_list(csv_file_name): """ Expects a csv file with header/structure: filename, TE, mean_background skips the first (header) line returns a list of tuples with (filename, TE) """ image_value_list = [] with open(csv_file_name) as csvfile: ...
7802ba5a0cd787e52c22e7cab267222539bf046c
675,804
import json def load_json_from_file(file_path): """Load json from a json file""" with open(file_path) as json_data: return json.load(json_data)
0f800eba604245c3e907bcb42d58da7de3a7a9b0
675,805
async def in_voice_channel(ctx): """Checks that the command sender is in the same voice channel as the bot.""" voice = ctx.author.voice bot_voice = ctx.guild.voice_client if voice and bot_voice and voice.channel and bot_voice.channel and voice.channel == bot_voice.channel: return True else: ...
b1bd347db349ac3d6c35427ab41ef08231fb373c
675,806
def place(cards, pos, card): """ Replaces the card at a given position in a list. Example: > place([1,4,7,10,12], 2, 9) [1,4,9,10,12] """ result = cards[:] result[pos] = card return result
ee301ea71eb94cc3446736adf8124100aa756d72
675,807
def text_of_list(t): """ Convert a string list to multiline text. """ return '\n'.join(t)
526ca23f6fbca6780238ae71ccf581290b92037b
675,808
def trapmf(x, a, b, c, d): """ Trapezoidal membership function generator. Parameters ======== x : single element array like abcd : 1d array, length 4 Four-element vector. Ensure a <= b <= c <= d. Returns ======== y : 1d array Trapezoidal membership function. """ ...
6a7a8a50cf83194d072055054d71db4b0398bb2d
675,810
from typing import Set def import_declarations(import_set: Set[str]) -> str: """ Generate the import declaration(s) given the import specs. :param import_set: import specs :return: Go import declaration >>> import_declarations(set()) '' >>> import_declarations({'time'}) 'import "tim...
6cef7b84701caa59eef1fde4b23c0ba176596c53
675,816
def get_version(fname): """Reads PKG-INFO file generated by setuptools and extracts the Version number.""" res = "UNK" with open(fname, "r") as f: for line in f.readlines(): line = line[:-1] if line.startswith("Version:"): res = line.replace("Version:", ""...
503d28ba0bea43dbbd5164acd2f6804a8a7c479b
675,817
def to_subscription_key(uid, event): """Build the Subscription primary key for the given guid and event""" return u'{}_{}'.format(uid, event)
55edbc3a6a8af5e68133e18170c682e7fb7995a3
675,820
def format_pathname( pathname, max_length): """ Format a pathname :param str pathname: Pathname to format :param int max_length: Maximum length of result pathname (> 3) :return: Formatted pathname :rtype: str :raises ValueError: If *max_length* is not larger than 3 This...
add9a4fa5e82e6f99821fc8d623a8417a5ad737b
675,824
def encode_binary(x, width): """Convert integer x to binary with at least width digits.""" assert isinstance(x, int) xb = bin(x)[2:] if width == 0: assert x == 0 return '' else: assert len(xb) <= width pad = width - len(xb) return '0' * pad + xb
61a5c1e933f495f4347e0d89490a02b6e9630f6e
675,828
def dist(pt1, pt2): """Distance between two points""" return ((pt2[0] - pt1[0])**2 + (pt2[1] - pt1[1])**2 + (pt2[2] - pt1[2])**2)**0.5
7277c8984a4c1c10223fb0cd481b7ac7b4868f9d
675,831
def filter_by_bidder_id(bids, bidder_id): """ >>> bids = [ ... {"bidder_id": "1", "amount": 100}, ... {"bidder_id": "1", "amount": 200}, ... {"bidder_id": "2", "amount": 101} ... ] >>> filter_by_bidder_id(bids, "1") [{'amount': 100, 'bidder_id': '1'}, {'amount': 200, 'bidder...
887e44b2a8b71b4e9b37c50defea0eba37fc7afb
675,833
def get_distance(pt1, pt2): """ Finds the distance between two points. """ x1 = pt1[0] y1 = pt1[1] x2 = pt2[0] y2 = pt2[1] return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** (1 / 2)
814a8904e17f4f2fd91738664f711d2bc0a98566
675,834
from typing import Optional from typing import Callable def docfill( *args, template: Optional[str] = None, **kwargs ): """Format the decorated function's docstring using given args and kwargs This is useful if some functions share many common inputs or if the range of valid values for a para...
ae3ab484d18bfb41e232f191163955e2c2e829f4
675,836
def app_request_type_label(app, request_type) -> str: """Format a label based on the application name and request type.""" return f"{app}\n({request_type})"
8f7545842b7c342d0d7cf18ab45afddb48297aee
675,837
import torch def scalar_mult(x, y): """A function that does complex scalar multiplication between two complex scalars, x and y. :param x: A complex scalar. (x[0], x[1]) = (real part, imaginary part). :type x: torch.doubleTensor :param y: A complex scalar. (x[0], x[1]) = (real part, imaginary part). ...
751ab77346995d339d037c62d533a47107b85f15
675,839
def decode_text(value): """ Decode a text-like value for display. Unicode values are returned unchanged. Byte strings will be decoded with a text-safe replacement for unrecognized characters. """ if isinstance(value, bytes): return value.decode('ascii', 'replace') else: ...
ba2f37b2b16d6810799f85ff8026228d9af9cd72
675,842
def znes_colors(n=None): """Return dict with ZNES colors. Examples -------- >>> znes_colors().keys() # doctest: +ELLIPSIS dict_keys(['darkblue', 'red', 'lightblue', 'orange', 'grey',... Original author: @ckaldemeyer """ colors = { 'darkblue': '#00395B', 'red': '#B54036...
16a5c06b898bc58bc046c8a1cd9137846b0d9097
675,845
def get_tags_string(tags): """ Returns a comma-delimited k=v string Args: tags (dict): A dictionary of key/value pairs Returns: str """ return ','.join([f'{k}={v}' for k, v in tags.items()])
561876d35739de5032465536f667caac9eb0cc6f
675,851
def is_dataset(dataset): """ Check if input is a hdf dataset e.g. is_dataset(hdf_group.get(address)) """ return hasattr(dataset, 'size')
e7eb6392c7347792fdd0371d5c7b057a193e8b1d
675,857
def get_last_completed_launch(fw): """ Given a Firework object returns the last completed launch """ return next((l for l in reversed(fw.archived_launches + fw.launches) if l.state == 'COMPLETED'), None)
ec9c2f6c55a367451ca6df9a187c22111d227a68
675,865
def _check_value(item, allowed_values, item_name=None, extra=None): """ Check the value of a parameter against a list of valid options. Parameters ---------- item : object Item to check. allowed_values : tuple of objects Allowed values to be checked against. item_name : str ...
1cecf190d83a14573d93ca73de070f98dbf7c57f
675,866
def play_tictactoe_turn(action, board_state, turn): """ Input: action: 0-8 an index into the board array board_state: (0,1,0,None,None,None,None,None,None) a tuple of the board's state turn: 1/0 the player's who's turn i...
e50c0ed69bfcef45f72b763e7133935636f047b2
675,867
def filter_startswith_prefix(dataframe, prefix="TALON"): """Filter out rows where 'annot_gene_id' column value starts with prefix. Args: dataframe: pandas DataFrame prefix: string Returns: pandas DataFrame """ not_starts_with_prefix = dataframe["annot_gene_id"].apply( ...
9e8f61d4c603099da0a2adf5dce4b4d043925992
675,868
def int_to_varint_hex(int_value): """ VARINT <= 0xfc example: 12 <= 0xffff example: fd1234 Prefix is fd and the next 2 bytes are the VarInt (in little-endian). <= 0xffffffff example: fe12345678 Prefix is fe and the next 4 bytes are the VarI...
7b0aa099987097effc922a78e1100eaac0686cbf
675,876
from typing import Any from typing import List def validate_entry_context(entry_context: Any, keys: List[str], unpack_nested_elements: bool): """ Validate entry context structure is valid, should be: - For unpack_nested_elements==False: 1. List[Dict[str, str/bool/int/float]] 2. Lis...
49e1f0a8a5b57066cf6bacdb564883600193f38c
675,877
def progessbar(new, tot): """Builds progressbar Args: new: current progress tot: total length of the download Returns: progressbar as a string of length 20 """ length = 20 progress = int(round(length * new / float(tot))) percent = round(new/float(tot) * 100.0, 1) ...
119cec7121167c5bcb23571cab4f33e4a816e521
675,881
def p1_for(input_list): """Compute some of numbers in list with for loop.""" out = 0 for i in input_list: out += i return out
7691bc14e10eab3a7fbda46091dcb62773704f1a
675,882
def precision(c, tweets): """Computes precision for class `c` on the specified test data.""" tp = 0 fp = 0 for tweet in tweets: if c in tweet['predictions']: if c in tweet['tags']: tp+=1 else: fp+=1 if(tp+fp == 0): return floa...
d5012859f14e114258d05552cc0edac2af998f3f
675,885
def getBondedNeighborLists(atoms, bondProxies): """ Helper function to produce a dictionary of lists that contain all bonded neighbors for each atom in a set of atoms. :param atoms: Flex array of atoms (could be obtained using model.get_atoms() if there are no chains with multiple conformations, must ...
cbf2250642cf388c37645fee936306867acf737e
675,886
def format_fasta(title, sequence): """ This formats a fasta sequence Input: title - String - Title of the sequence sequence - String - Actual sequence Output: String - Fully formatted fasta sequence """ fasta_width = 70 # Number of characters in one line n_lines = 1 + le...
3c6ac0f1472aa3a8409c9f9c36978eb329491fab
675,888
def vecBetweenBoxes(obj1, obj2): """A distance function between two TextBoxes. Consider the bounding rectangle for obj1 and obj2. Return vector between 2 boxes boundaries if they don't overlap, otherwise returns vector betweeen boxes centers +------+..........+ (x1, y1) | obj1 | ...
e6f794ff14625072f83442b8557ee29eb2981601
675,897
def clip(string: str, length: int, suffix = "...") -> str: """Clip string to max length If input `string` has less than `length` characters, then return the original string. If `length` is less than the number of charecters in `suffix`, then return `string` truncated to `length`. Oth...
52522785fea0d52c706f202d0b521b66401b2651
675,900
def normalize(string): """Returns a string without outer quotes or whitespace.""" return string.strip("'\" ")
a8f716f259175ac7ba2e5a5c004cfd95f4410302
675,903
import ast def is_ast_equal(node_a: ast.AST, node_b: ast.AST) -> bool: """ Compare two ast tree using ast dump """ return ast.dump(node_a) == ast.dump(node_b)
0a1866e72f454af6d4429ea8cd68b3cb087aeab7
675,904
def decode_text_field(buf): """ Convert char[] string in buffer to python str object :param buf: bytearray with array of chars :return: string """ return buf.decode().strip(b'\x00'.decode())
d144000057830fa62a6a28caa0f1d61e410e02ba
675,905
def is_prime(number): """Check if a number is prime.""" if number < 2: return False if number == 2: return True if number % 2 == 0: return False for _ in range(3, int(number ** 0.5) + 1, 2): if number % _ == 0: return False return True
b37c84314d45abd5a2a4105d2c93d4fdd0b8e722
675,906
import torch def subtract_pose(pose_a, pose_b): """ Compute pose of pose_b in the egocentric coordinate frame of pose_a. Inputs: pose_a - (bs, 3) --- (x, y, theta) pose_b - (bs, 3) --- (x, y, theta) Conventions: The origin is at the center of the map. X is upward with ...
c6c759297a6cef19349a19abc1dd598cc5ba0a9b
675,907
from pathlib import Path def setup(opts): """Set up directory for this GenomeHubs instance and handle reset.""" Path(opts["hub-path"]).mkdir(parents=True, exist_ok=True) return True
ce0c1e6dfb378a313dc4ac8630099ff1e9fcfdd0
675,910
def accuracy(true_positives, true_negatives, false_positives, false_negatives, description=None): """Returns the accuracy, calculated as: (true_positives+true_negatives)/(true_positives+false_positives+true_negatives+false_negatives) """ true_positives = float(true_positives) true_...
99a1a8d7a1b59c3f72b711aeb733ea6f32c9c3f2
675,911
def rate_color(rate: int, units: str = '') -> str: """ Get color schema for percentage value. Color schema looks like red-yellow-green scale for values 0-50-100. """ color = '[red]' if 30 > rate > 20: color = '[orange_red1]' if 50 > rate > 30: color = '[dark_orange]' if 7...
0dd1174c9c5d333cad44c5892a8dd32cb6239176
675,914
import time def get_duration_timestamp(day=7): """ 获取当前时间和7天前的时间戳 :param day: :return: """ # 当前时间对应的时间戳 end = int(round(time.time() * 1000)) # 7天前的时间戳 start = end - day * 24 * 60 * 60 * 1000 return start, end
034bd89e9d70b9804c14073ec109d07a6fa2ebb1
675,916
def pass_through_filter(cloud, filter_axis='z', axis_limit=(0.6, 1.1)): """ Cut off filter Params: cloud: pcl.PCLPointCloud2 filter_axis: 'z'|'y'|'x' axis axis_limit: range Returns: filtered cloud: pcl.PCLPointCloud2 """ # Create a PassThrough filter object. ...
0dacdb13d0b47ff80e61f2b8f25549472ce98c92
675,919
def clean_text_up(text: str) -> str: """ Remove duplicate spaces from str and strip it. """ return ' '.join(text.split()).strip()
04799b0c22b48b118fdf14efd7b58971eaf35885
675,921
def case_convert(snakecase_string: str) -> str: """Converts snake case string to pascal string Args: snakecase_string (str): snakecase string Returns: str: Pascal string """ return snakecase_string.replace("_", " ").title().replace("Cnn", "CNN")
40b79d4455406c8a3c8bc9324b3b42abf32cf754
675,927
def current_ratio(current_assets, current_liabilities, inventory = 0): """Computes current ratio. Parameters ---------- current_assets : int or float Current assets current_liabilities : int or float Current liabilities inventory: int or float Inventory Returns ...
716ef196df285c6dda2b369b5db24a6bc350ad3a
675,929
def ci(_tuple): """ Combine indices """ return "-".join([str(i) for i in _tuple])
4f3f66731bea3d9cde0ec085dce0ccbe66438a23
675,931
def base_point_finder(line1, line2, y=720): """ This function calculates the base point of the suggested path by averaging the x coordinates of both detected lines at the highest y value. :param line1: Coefficients of equation of first line in standard form as a tuple. :param line2: Coefficients of ...
c2a7b198f1e76739391efc8fadf00c98c20dcfc0
675,932
def expand_var(v, env): """ If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env. """ if len(v...
eeeb8ef250cc1fc5f9829f91b3dc0290b6c6fb83
675,934
from typing import List def is_primary_stressed(syllable: List[str]) -> bool: """ Checks if a syllables is primary stressed or not. :param syllable: represented as a list of phonemes :return: True or False """ return True if any(phoneme.endswith('1') for phoneme in syllable) else False
054b85a49a2f4ddc426ce074314be4d319853002
675,936
def count_bad_pixels_per_block(x, y, bad_bins_x, bad_bins_y): """ Calculate number of "bad" pixels per rectangular block of a contact map "Bad" pixels are inferred from the balancing weight column `weight_name` or provided directly in the form of an array `bad_bins`. Setting `weight_name` and `bad...
33668d6d1efc16a436560171f54647f8e01c2040
675,937
import io def csv_parseln( p_line, delim=',', quote='\"', esc='\\'): """ Given a sample CSV line, this function will parse the line into a list of cells representing that CSV row. If the given `p_line` contains newline characters, only the content present before the first newline character is parsed. ...
b1aefa153c33788435513e32052b0c9a765e4cf3
675,946
def rechunk_da(da, sample_chunks): """ Args: da: xarray DataArray sample_chunks: Chunk size in sample dimensions Returns: da: xarray DataArray rechunked """ lev_str = [s for s in list(da.coords) if 'lev' in s][0] return da.chunk({'sample': sample_chunks, lev_str: da.coo...
5818863205c2d5cf468426fe1678bd8f95fce12b
675,951
from typing import List def denormalize_identity(texts: List[str], verbose=False) -> List[str]: """ Identity function. Returns input unchanged Args: texts: input strings Returns input strings """ return texts
21dca95b74832c4afca2fcaa5e0cd2a750b352fd
675,952
import math def calculate_fuel_requirement_plus(fuel): """Calculates the fuel requirement based on the given fuel mass. (Part 2) Parameters: fuel (int): mass of the fuel Returns: int:Additional fuel required """ add = math.floor(fuel / 3) - 2 if add > 0: return add + ca...
602df3358a1315f683483e2268ce2c7513a3dcde
675,955
def assumed_metric(y_true, y_pred, metric, assume_unlabeled=0, **kwargs): """ This will wrap a metric so that you can pass it in and it will compute it on labeled and unlabeled instances converting unlabeled to assume_unlabeled Assumption: label -1 == unlabled, 0 == negative, 1 == positive """ ...
96451aa28d87880dc291c32d8ac8f52310755562
675,959
def _HELP_convert_RMSD_nm2angstrom(RMSD_nm): """ Helpfunction for plot_HEATMAP_REX_RMSD(): convert RMSD values: RMSD_nm -> RMSD_anstrom Args: RMSD_nm (list): rmsd values in nm Returns: RMSD (list) rmsd values in angstrom """ RMSD = [x*10 for x in RMSD_nm] re...
12c564378f92b571059763c325fe52e82d53b4c1
675,964
from pathlib import Path import json def read_features(corpus_folder): """Read the dictionary of each poem in "corpus_folder" and return the list of python dictionaries :param corpus_folder: Local folder where the corpus is located :return: List of python dictionaries with the poems features """ ...
2c156317b649ab5c952c47e84e81e4686c63a9e1
675,965
def static_vars(**kwargs): """ Attach static variables to a function. Usage: @static_vars(k1=v1, k2=k2, ...) def myfunc(...): myfunc.k1... Parameters: **kwargs Keyword=value pairs converted to static variables in decorated function. Returns: decorate """ def decor...
ee6690d76ca21efd682ef2ade0aa8b8046ec6a51
675,968
def flatten(iter_of_iters): """ Flatten an iterator of iterators into a single, long iterator, exhausting each subiterator in turn. >>> flatten([[1, 2], [3, 4]]) [1, 2, 3, 4] """ retval = [] for val in iter_of_iters: retval.extend(val) return retval
0a2132fc2c9e1dc1aef6268412a44de699e05a99
675,974
def is_number(s): """ Checks if the variable is a number. :param s: the variable :return: True if it is, otherwise False """ try: # Don't need to check for int, if it can pass as a float then it's a number float(s) return True except ValueError: return False
2d3fa464246833041ac5018afe23f9fbec2989e1
675,976
import math def cond_loglik_bpd(model, x, context): """Compute the log-likelihood in bits per dim.""" return - model.log_prob(x, context).sum() / (math.log(2) * x.shape.numel())
26e1dc0e525b76fc402a5b70ebf02f9547673278
675,980
import threading def create_thread(func, args): """Creates a thread with specified function and arguments""" thread = threading.Thread(target=func, args=args) thread.start() return thread
08244612bd467d0d8b8217e07705d9c41670cd4a
675,981
def calculate_stretch_factor(array_length_samples, overlap_ms, sr): """Determine stretch factor to add `overlap_ms` to length of signal.""" length_ms = array_length_samples / sr * 1000 return (length_ms + overlap_ms) / length_ms
66c3b5fadf7998b6ecbd58761242ec4c253fd2f5
675,982
def nothing(text: str, expression: str) -> bool: # pylint: disable=unused-argument """Always returns False""" return False
dccfbed553f8178469c2920b09c916c90127e57f
675,985
import requests def read_build_cause(job_url, build_id): """Read cause why the e2e job has been started.""" api_query = job_url + "/" + str(build_id) + "/api/json" response = requests.get(api_query) actions = response.json()["actions"] cause = None for action in actions: if "_class" i...
80c3aafc29ae9eed1a7e4165962c4a50281779dd
675,989
import re def to_valid_filename(filename: str) -> str: """Given any string, return a valid filename. For this purpose, filenames are expected to be all lower-cased, and we err on the side of being more restrictive with allowed characters, including not allowing space. Args: filename (str...
e3fa7a84c4ed8c57042d3c2564c064380e6d2abd
675,995
def shapes(tensors): """Get the static shapes of tensors in a list. Arguments: tensors: an iterable of `tf.Tensor`. Returns: a `list` of `tf.TensorShape`, one for each tensor in `tensors`, representing their static shape (via `tf.Tensor.get_shape()`). """ return [t.get_shape() ...
d5958286782a3ce73621831e5b69d205feeb74d8
675,998
def get_4d_idx(day): """ A small utility function for indexing into a 4D dataset represented as a 3D dataset. [month, level, y, x], where level contains 37 levels, and day contains 28, 29, 30 or 31 days. """ start = 1 + 37 * (day - 1) stop = start + 37 return list(range(start, stop, ...
7434d734e106ceb32a6ac4c0fc13800ef0245df9
676,000
def cookielaw(request): """Add cookielaw context variable to the context.""" cookie = request.COOKIES.get('cookielaw_accepted') return { 'cookielaw': { 'notset': cookie is None, 'accepted': cookie == '1', 'rejected': cookie == '0', } }
22f72b6399389b43b1093543e6f65e0c804d7144
676,001
def calculate_offset(address, base, shadow_base=0): """ Calculates an offset between two addresses, taking optional shadow base into consideration. Args: address (int): first address base (int): second address shadow_base (int): mask of shadow address that is applied to `base` ...
7614a1263c2d73cacf509c769e53503b80052839
676,004
import yaml def get_yaml_dict(yaml_file): """Return a yaml_dict from reading yaml_file. If yaml_file is empty or doesn't exist, return an empty dict instead.""" try: with open(yaml_file, "r") as file_: yaml_dict = yaml.safe_load(file_.read()) or {} return yaml_dict except FileNotFoundError: return {}
bf290735bc3d30f8517d8513f8d2679a1383e718
676,005
import math def tand(v): """Return the tangent of x (measured in in degrees).""" return math.tan(math.radians(v))
a3023dcdf19bb7b235ac5389011c0243498b7128
676,008
def cartesian(coords): """ Convert 2D homogeneus/projective coordinates to cartesian. """ return coords[:, :2]
36566982c7d2aa9cb3fda1aeab8de1d0ee2fb115
676,013
def getObjectKey(rpcObject): """Given a rpc object, get a unique key that in the form 'class.id' @type rpcObject: grpc.Message @param rpcObject: Rpc object to get a key for @rtype: str @return: String key in the form <class>.<id> """ objectClass = rpcObject.__class__.__name__ object...
dcd1af06fcbe6022d5382eee79878ad6a222a3c5
676,014
import calendar def sort_months(months): """Sort a sequence of months by their calendar order""" month_ref = list(calendar.month_name)[1:] return sorted(months, key=lambda month: month_ref.index(month))
71c465901149f3a7dac325d3f3e97d495a245c94
676,015
from pathlib import Path import tempfile import venv def create_new_venv() -> Path: """Create a new venv. Returns: path to created venv """ # Create venv venv_dir = Path(tempfile.mkdtemp()) venv.main([str(venv_dir)]) return venv_dir
077dd1318d579ccdb3333849b092555c54297903
676,018
def total_seconds(td): """ Return total seconds in timedelta object :param td: timedelta :type td: datetime.timedelta :return: seconds :rtype: float """ return (td.microseconds + (td.seconds + td.days * 86400) * 1000000) / 1000000.0
8aab761d946bee240e2c49d5de0885f021d82ba6
676,024
import getpass def get_mysql_pwd(config): """Get the MySQL password from the config file or an interactive prompt.""" # Two ways to get the password are supported. # # 1. Read clear-text password from config file. (least secure) # 2. Read password as entered manually from a console prompt. (most s...
3077fca733739d1d0648e555fa2a485a31cc3d8a
676,026
def resolve_attribute(name, bases, default=None): """Find the first definition of an attribute according to MRO order.""" for base in bases: if hasattr(base, name): return getattr(base, name) return default
ed358e230da7ca7bb2a413caee151f344c111b25
676,034
def _get_date_and_time_strings(date): """Return string of YYYYMMDD and time in HHMM format for file access.""" y, m, d, h = [str(i) for i in [date.year, date.month, date.day, date.hour]] # add zeros if needed if len(m) == 1: m = '0' + m if len(d) == 1: d = '0' + d if len(h) == 1...
da60c58bd6c13e104caf2d01d479675d7d7a7b8a
676,037
import typing def format_scopes(scopes: typing.List[str]) -> str: """Format a list of scopes.""" return " ".join(scopes)
5776e849ff96ab250f2b957309c6b1829ac54383
676,039
import re def get_size_from_tags(tags): """Searches a tags string for a size tag and returns the size tag. Size tags: spacesuit, extrasmall, small, medium, large, extralarge. """ match = re.search( r'\b(spacesuit|extrasmall|small|medium|large|extralarge)\b', tags ) if match: re...
8d406d237a7249b6d3807af6375f56b5c124ca8b
676,040
def distance_from_camera(bbox, image_shape, real_life_size): """ Calculates the distance of the object from the camera. PARMS bbox: Bounding box [px] image_shape: Size of the image (width, height) [px] real_life_size: Height of the object in real world [cms] """ ## REFERENCE FOR GOPRO ...
037adbaba89ae13ed74ac5fc1d1cfc080c5107d1
676,041
def get_occurences(node, root): """ Count occurences of root in node. """ count = 0 for c in node: if c == root: count += 1 return count
7df5e3e1c5fbcdca482a297e38b5e09be1b3d8e1
676,042
def snd(tpl): """ >>> snd((0, 1)) 1 """ return tpl[1]
d002211609082a2c14f49b826643c774dd6205c3
676,048
from pathlib import Path from typing import List def get_regions_data(path: Path) -> List[dict]: """Gets base data for a region in a page. :param path: Path to the region directory. :return: List of dictionaries holding base region data. """ regions = list() for region in sorted(path.glob("....
b5e4d10f58815eaec23104ec37ac6c9beaa45c43
676,050
def get_members_name(member): """Check if member has a nickname on server. Args: member (Union[discord.member.Member, list]): Info about member of guild Returns: str: User's name, if user doesn't have a nickname and otherwise list: List of names of user's nicknames """ if i...
4b8798a98dc6064b775a72e44c1189408e7a0073
676,051
def find_layer_idx(model, layer_name): """Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise. """ ...
ab5c8bcde11e22aa0081a2bb60c9b99c324b6525
676,058
def _start_time_from_groupdict(groupdict): """Convert the argument hour/minute/seconds minute into a millisecond value. """ if groupdict['hours'] is None: groupdict['hours'] = 0 return (int(groupdict['hours']) * 3600 + int(groupdict['minutes']) * 60 + int(groupdict['seco...
0f09960f3cb482931445d304a963236db11c2228
676,059
def frame_to_pattern(frame_path): """Convert frame count to frame pattern in an image file path. Args: frame_path (str): Path of an image file with frame count. Returns: str: Path of an image sequence with frame pattern. """ name_list = frame_path.split('.') name_list[-2] = '%...
bfd1c973281b11295d4c17752c5ae1b2c221fad7
676,060