content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def flip_v(grid): """Flip grid vertically.""" return '\n'.join(reversed(grid.split('\n')))
ee5096714a0f1916a8ec2ff5dfa35b2edc839585
625,392
import ipaddress def parse_ip(ip_bytes): """ Convert an IPv4/IPv6 address in bytes to a valid IP address in string format, if it is indeed valid. :param bytes ip_bytes: bytes of IPv4/IPv6 address. :returns: IP address in string format, None if input invalid. """ try: retu...
0a6f48281da50d89418f6f48b22b2e5ddfd53adb
625,393
import struct import socket import fcntl def get_interface_IP(interface_name): """Retrieve IP address of the specified network interface. Args: interface_name (str): Name of the interace. Returns: str: Standard dotted-quad string representation of the IP address. """ IFNAMSIZ = 1...
0191e325447dfe9b6a7dcb330fdb3f2fe8329454
625,396
def mlo(i, j): # pragma: no cover """Auxiliary function for La Budde's algorithm. See `arXiv:1104.3769 <https://arxiv.org/abs/1104.3769v1>`_. .. note:: The La Budde paper uses indices that start counting at 1 so this function lowers them to start counting at 0. Args: matrix (...
6d3a6279dde492d260675f9f2c9300db46a2b3c4
625,398
import textwrap def format_tooltip(text, *args, **kwargs): """ Wrapper around textwrap.fill that preserves newline characters """ return '\n'.join(textwrap.fill(t, *args, **kwargs) \ for t in text.splitlines())
231ee50f092e6fc29b88bb36ed13458e67c1d193
625,400
def months_interval(start_date, end_date): """ Generate the monthly intervals between a start date and an end date """ months_num = [str(i+1).zfill(2) for i in range(12)] start_year = int(start_date[0:4]) start_month = int(start_date[4:6]) end_year = int(end_date[0:4]) end_month = int(en...
2e25ec3d129993c50c39a167b58eddf7d84dcd40
625,401
from typing import Sequence from typing import Tuple def named_range(name, stop: int) -> Sequence[Tuple[str, int]]: """Equivalent to `range()` but suitable for use with ``named_parameters``.""" return tuple(((f"{name}_{i}", i) for i in range(stop)))
dab4b7c8f4fec0717e98608f1b7277c207797727
625,406
from typing import Any from typing import Iterable def stringify(value: Any) -> Any: """Creates an equivalent data structure representing data values as string Parameters ---------- value Value to be stringified Returns ------- stringified_value """ if value is None or is...
87504cd807af6ed50e610c8676d51e3037e0f673
625,407
def filter_kwargs(keywords, **kwargs): """ Filter provided keyword arguments and remove all but those matching a provided list of relevant keywords. Parameters ---------- keywords : list of string Keywords to search for within the provided keyword arguments kwargs : dict Diction...
5bf8493e81a0e3e0db18cd94e152d65f691817ca
625,408
def elementwise_list_addition(increment, list_to_increment): """ Simple method to element-wise increment a list by the values in another list of the same length. """ if not list_to_increment: return increment assert len(increment) == len(list_to_increment), 'Attempted to add two lists of di...
7e7020604ebeb3ab227e3d64999bb0e8cf255986
625,412
def utc_iso8601(datetime): """Convert a UTC datetime into an ISO8601 timestamp string.""" return datetime.strftime("%Y-%m-%dT%H:%M:%S.%f+00:00")
985f6333f7977f9709b652fe992dc06cfba3403d
625,431
import torch def proj(x, epsilon=0.00001): """ Projects a matrix of vectors in hyperbolic geometry back into the unit ball Parameters ---------- x the matrix with each row representing a vector epsilon the small difference to subtract to ensure that vectors remain in the unit b...
79cf720790d325f811888ff9e93fd1c489a9cd53
625,433
import socket def get_host_name() -> str: # pragma: no cover - we're just proxying """Get hostname of the machine Returns: str: host name """ return socket.gethostname()
e060a7a0efe1a5cf327aa36219091cb249bbd27f
625,435
def reverse_complement(dna, reverse=True, complement=True): """ Make the reverse complement of a DNA sequence. You can also just make the complement or the reverse strand (see options). Input: A DNA sequence containing 'ATGC' base pairs and wild card letters Output: DNA sequence as a string. ...
a7e651721df61241200fe50e8006956b2c982dba
625,436
def predict(x_tst, model): """ The method predicts labels for testing data samples by using trained learning model. Parameters ---------- x_tst: features of testing data model: trained learning model """ predictions = model.predict(x_tst) return predictions
ef0e23bbd70a1d8340b5893b42f7fd72f0ee17d0
625,438
from typing import Any import re def __is_condition_met(condition_type: str, condition_value: Any, value: Any) -> bool: """ Checks if given value meets the given condition Args: condition_type: condition type, could be "equal" or "regex" condition_value: the value of the condition, in case...
1bf7a80df9c12bedc6e843851947bf94c64ae120
625,439
def y_coordinate(block): """Returns the y-coordinate component in block as a string.""" start = block.find(',')+1 # Skip the first space end = block.find(' ', block.find(' ')+1) return block[start:end]
4714d9646d9f80a9218c9d8b3f85e17ca205e4f3
625,440
def write_coord(coord): """ Adjusts whitespace for coordinates """ return "{:06.8f}".format(coord) if coord < 0.0 else " " + "{:06.8f}".format(coord)
4782c6ab2940dd35516d7c373a3f2e6d93ad3671
625,444
import torch def compute_batch_accuracy(output, target): """Computes the accuracy for a batch""" with torch.no_grad(): batch_size = target.size(0) _, pred = output.max(1) correct = pred.eq(target).sum() return correct * 100.0 / batch_size
c264a863cbf45afaddbf3c5a9e1cad23f515cff9
625,446
def twitter_auth_required(view_func): """ Decorator for views that requires the authenicated user to have authorized the site on Twitter. If no credentials are on record, user will be directed to a page to authorize the site. """ view_func.twitter_auth_required = True return view_func
6f39b325f876af8d4b499c88324152b7caed545e
625,450
def lsum (inlist): """ Returns the sum of the items in the passed list. Usage: lsum(inlist) """ s = 0 for item in inlist: s = s + item return s
24907db4a001b66974adb9702e816b531cf78d84
625,451
def TETChromaticScale(frequency, octaveDivider): """creates an even tempered scale with a given starting frequency and a number for how many divisions you want the octave to be divided into. Returns an Array""" i = 0 scale = [] while i < octaveDivider: i += 1 note = round(frequency *...
c01dc7a3e1dbbf2a146327dfbc6d73fb877259b6
625,456
def GetParentNodeWhereTrue(node_id, tree, stop_function): """walk up in gene tree and stop where stop_function is true. The walk finishes at the root. returns tuple of node and distance. """ node = tree.node(node_id) distance = 0 while node.prev is not None: if stop_function(node...
bdc79abd5a8171f821102e5d8f74f95952a5157b
625,461
def setBit(num, n): """ Return num with the nth bit set to 1. """ # Make a mask of all 0s with the nth bit set to 1. mask = 1 << n return num | mask
42ec57a67b37171171ef929c5355e3de368ec63c
625,462
import time def display_timestamp(t): """Takes a Unix timestamp as a an arg, returns a text string with '<unix timestamp> (<equivalent time>)'.""" return '%s (%s)' % (t, time.strftime('%d/%m/%Y %H:%M', time.gmtime(t)))
e5a435ec39afc114d532846a01b407c5cfad2df2
625,464
def create_valid_bigquery_field_name(field_name): """ Clean up / prettify field names, make sure they match BigQuery naming conventions. Fields must: • contain only -letters, -numbers, and -underscores, • start with a -letter or ...
413b62566f0f1034335f43237229f02195947368
625,465
def uniq(iterable, key=lambda x: x): """ Remove duplicates from an iterable. Preserves order. :type iterable: Iterable[Ord => A] :param iterable: an iterable of objects of any orderable type :type key: Callable[A] -> (Ord => B) :param key: optional argument; by default an item (A) is discarded ...
219cba5494198fc806b503e9000a7e491fe2a7c5
625,466
def make_cached_ssd_store_options( cache_budget_mb, persistent_path, capacity=None, size_factor=1, physical_block_size=512, host_cache_budget_mb=0, ): """make SSD use GPU and host as cache store_options param of MultiTableEmbedding. If cache_budget_mb > 0 and host_cache_budget_mb > 0, use GP...
fd701a01ceca0efff3efb9ac27e46d683f67eb1a
625,468
import re def is_match(regex, string, ignore_case=False): """Check if regex matches string.""" regex_flags = re.DOTALL if ignore_case: regex_flags = re.DOTALL | re.IGNORECASE return re.match(regex, string, regex_flags) is not None
52b7efb1569531f1e0b1e5717f021d5e2b08e924
625,469
def classify_token(w): """ Function for feature augmentation. Improves the network's results by generating the information that will be fed into the feature-augmentend embedding layer Parameters ---------- w : str Word Returns ------- str Class to which a token ...
78757650191388204e942ac02a4950316bbefd6d
625,470
def _get_global_variable_names(name, tuple_path): """Get the global variables names for ground truth. Args: name: Python `str`. Name of the sample transformation. tuple_path: Tuple path of the part of the ground truth we're saving. See `nest.flatten_with_tuple_paths`. Returns: mean_name: Varia...
33b02ca0907f5e5d2a026cf1a56811107c38025c
625,472
def _parse_file_move(file_move): """Return the (old_filename, new_filename) tuple for a file move.""" _, old_filename, new_filename = file_move.split() return (old_filename, new_filename)
02815dde04578fcc63cb5033bb29729d4dfb9fd1
625,473
import hashlib def getETag(data): """Gets the ETag for the specified data. Args: data: The data for which the ETag should be generated. """ md5 = hashlib.md5() md5.update(data) return md5.hexdigest()[-16:]
db7578c74551f5c507c3d7c0bcbf3cab2768ff1e
625,474
def njoiner(inbox, n=None, join=""): """ String joins and returns the first "n" inputs. Arguments: - n(``int``) [default: ``None``] All elements in the inbox smaller then this number will be joined. - join(``str``) [default: ``""``] String which will join the elements of the ...
1541c192bb379657027ef93eebd2c01287756df8
625,477
import traceback def format_exception(e): """ Format the traceback of the exception ``e`` in a string. """ elements = traceback.format_exception(type(e), e, e.__traceback__) return ''.join(elements)
f83ccb7da334e24c90887412211c1ca9eba1e66d
625,478
def est_majeure(nom: str, prenom : str, age: int) -> bool: """ Renvoie True si la personne est majeure, ou False sinon. Précondition : nom != "" and prenom != "" and age > 0 """ return age >= 18
eebd9d58c8280e8ce857a753b2108eb3e5ea5c0c
625,482
def optimizerModel2wts(model): """Convert an optimizer model file into a flat weight vector.""" wts = [] with open(model) as f: for line in f: wts.append(float(line.partition(' ')[2])) return wts
6960ed9172a72190bf11c9e1ea7e8eaf98ee18ec
625,483
def convert_wavelength_vacuum2air(wavelength_vacuum): """ Convert vacuum wavelength to air wavelength Parameters ----------- wavelength_vacuum: float Vacuum wavelength in Angstroms Returns -------- float Air wavelength in Angstroms """ sigma2 = (1e4/wavelength_va...
c6448f8043c4cc1b603743cf12a766edeefdbbef
625,486
def is_sorted( s, strict = True ): """Test if a sequence is sorted""" prev_elem = None for x in s: if prev_elem != None and x < prev_elem or ( x == prev_elem and strict ): return False prev_elem = x return True
174e0824e45964fd41027e08801e54b9c260cb1b
625,491
from PIL import Image def _to_pil_rgb_image(image): """Returns an PIL Image converted to the RGB color space. If the image has an alpha channel (transparency), it will be overlaid on a black background. :param image: the PIL image to convert :returns: The input image if it was already in RGB mode, o...
b4590b12f38899ca5552805287fc753d050079a8
625,495
def get_bfield_name(name): """Sanitize the name of bitfields.""" return name.replace(' ', '') + 'Bits'
8df32b8b6f0eb439ac8f3cf9e8fb7810324e854b
625,500
def get_refdes(anno_record): """ Build and return a reference designator from the subsite, node and sensor fields in record supplied. """ subsite = anno_record.get('subsite', None) node = anno_record.get('node', None) sensor = anno_record.get('sensor', None) if node is None: return subsi...
d210ef0a57214c04d8f72348fca9d40388d19d29
625,503
def _is_comment(line): """ Assert if line is a comment or a line to ignore. Expects striped lines. """ is_comment = \ line.startswith('#') \ or not bool(line) return is_comment
04494ee84fff24a6a88e0d4838a3bcd351cffee9
625,505
def calc_3d_bbox(xs, ys, zs): """Calculates 3D bounding box of the given set of 3D points. :param xs: 1D ndarray with x-coordinates of 3D points. :param ys: 1D ndarray with y-coordinates of 3D points. :param zs: 1D ndarray with z-coordinates of 3D points. :return: 3D bounding box (x, y, z, w, h, d)...
5e4f2c6197addae67816844f6764b16c031d3d29
625,506
def add_mask_if_none(f, clip, *a, **k): """ Add a mask to the clip if there is none. """ if clip.mask is None: clip = clip.add_mask() return f(clip, *a, **k)
bc277aaacf175299dd95856ecccb1b2476e52dfd
625,510
from pathlib import Path def add_stem_suffix(p: Path, s: str) -> Path: """ eg. ("/path/to/file.ext","-suffix") -> ("/path/to/file-suffix.ext")""" return p.parent / Path(p.stem + s + p.suffix)
18f0741bb73bd77b4585b450d84bb9e6c54ebd13
625,512
def compare_version(lhs, rhs): """Compare two versions. Parameters ---------- lhs : tuple tuple of three integers (major, minor, patch) rhs : tuple tuple of three integers (major, minor, patch) Returns ------- int Returns 0 if lhs and rhs are equal, 1 if lhs is bigger than rhs, otherwise...
fd61215efa578b31d4c14502b16b8793a3fa7a28
625,514
def default_to_list(value): """ Ensures non-list objects are add to a list for easy parsing. Args: value(object): value to be returned as is if it is a list or encapsulated in a list if not. """ if not isinstance(value, list) and value is not None: value = [value] el...
128709c0d999cd80d0009d4aec31c2ec34755493
625,516
def _to_list(obj): """Make object into a list""" return [obj] if not isinstance(obj, list) else obj
acdc52335a4e536446d6d1ff7666ce8122f98011
625,518
import functools import time def timed(func): """ Time the execution of a wrapped function and print the output :param func: Function to be wrapped :return: function to be wrapped """ @functools.wraps(func) def wrap(*args, **kwargs): start = time.perf_counter() func(*args,...
3b85277f928064fed081165d5925b13f447e7860
625,520
def shorten_task_names(configs, common_task_prefix): """ Shorten the task names of the configs by remove the common task prefix. """ new_configs = [] for config in configs: config.task_name = config.task_name.replace(common_task_prefix, "") new_configs += [config] return new_conf...
b73ce8be7adece6da1f6ed218f3d78c52c5b1d94
625,522
def percentile(n): """Create function that calculates percentile for list""" return lambda xs: sorted(xs)[int(len(xs)*n)]
6760213cfd57e8d93948c4215bb0d7785a25860a
625,524
from typing import Set def _extract_args(input_str: str) -> Set[str]: """Extract the argument names from a string representation of a lambda function. Args: input_str: The string to be inspected. Something like 'x, opt=5:". Returns: The argument names from the `input_str`. Something like...
cdfe59dbee131490cb940560417b0202302d27f6
625,525
from typing import Sequence from typing import Any from typing import Tuple from typing import Optional def validate_provided_image_paths(image_paths: Sequence[Any]) -> Tuple[Optional[str], bool]: """Given a list of image_paths (list length at least 1), validate them and determine if metadata is available. ...
b50f9114d9f940943f61f4b8f85e0125673769c2
625,529
from typing import Union from typing import Optional from datetime import datetime def epoch_to_timestamp(epoch: Union[int, str]) -> Optional[str]: """Converts epoch timestamp to a string. Args: epoch: Time to convert Returns: A formatted string if succeeded. if not, returns None. ""...
910049acef550f638d5d8bcb50a21209fd5fff30
625,531
def parse_timestamp(my_dt): """ Param my_dt (datetime.datetime) like status.created_at Converts datetime to string, formatted for Google BigQuery as YYYY-MM-DD HH:MM[:SS[.SSSSSS]] """ return my_dt.strftime("%Y-%m-%d %H:%M:%S")
439e446bb6ac0ef0b7f3a49bb333868304cbb4b8
625,532
def chooseHighestFromTuple(arr): """ Pick the id of the highest element of a list of tuples of the form (id, key), where they key determines which value is the highest :param arr: The array of elements :return: A tuple of the form (id, key) of the element with the highest key """ high = ...
58a0a8606149dd8ba579d663ed6451f2fabb9bd0
625,535
def replace_string(metadata, field, from_str, to_str): """Replace part of a string in given metadata field""" new = None if from_str in metadata[field]: new = metadata[field].replace(from_str, to_str) return new
8ab2a22bd6623217deda59d54044c6bdfa9a3d21
625,536
def great_circle_pole_pts(lon_p, lat_p): """Find two orthogonal points on the great circle from its polar axis. Parameters ---------- lon_p: float Polar axis west longitude (degree). lat_p: float Polar axis latitude (degree). Returns ------- float West longitude...
fc479bc75a623ff752b19e24fe164d885c3d251e
625,538
def _mkUniq(collection, candidate, ignorcase = False, postfix = None): """ Repeatedly changes `candidate` so that it is not found in the `collection`. Useful when choosing a unique column name to add to a data frame. """ if ignorcase: col_cmp = [i.lower() for i in collection] can_cmp...
6c9d840104b91134ac8a623e3ed85aad967e6a65
625,543
def _assertable(queryset, list_item='name'): """ From a Django queryset return a list of one attribute that can be passed to an assert statement. The default model attribute to compare is name. :param django.db.models.query.QuerySet queryset: :returns: A list of the specified attrributes from each ...
9cd93aff431e3ea9779b228b3319b1891df726a3
625,544
import torch def create_loss_function(loss_name): """ Create a loss function from its name by creating a wrapper to the corresponding torch.nn.functional function (e.g. torch.nn.functional.mse_loss for 'MSE') and preparing the targets if necessary. Args: loss_name: The name of the loss functi...
4e6ef2b4d7dd3c5ad1142e987252826adaaccc4b
625,548
from bs4 import BeautifulSoup def __parsePageFilings(page_parsed: BeautifulSoup) -> list: """Function to extract filings from a parsed HTML EDGAR listings page. Arguments: page_parsed {BeautifulSoup} -- Parsed HTML for filing extraction. Returns: list -- Structured list of dictio...
1f533d3a1bfce1a543aaf1d5a74075b213356f02
625,551
def convert_process(x): """ Converts process column in wikipedia transistor count table to numeric. """ # NANs are floats if isinstance(x, float): return x else: return x.replace('nm', '').replace(',', '').strip()
2bd43bdd1b952602087ee74aaf9ef11179ec06ac
625,554
import re def read_fb_file(fb_fname): """Return the total number of simulations covered by the folder from a fb file. The actual simulation is written by Matlab. The first part of the simulation code is to provide the total number of simulations the code will calculate. The function read the outp...
9d7b2da89f548809a3927cfb79d70ce0525832b1
625,556
def get_file_contents(file_path): """Return a string containing the file contents of the file located at the specified file path """ with open(file_path, encoding="utf-8") as f: file_contents = f.read() return file_contents
4e00422c05de3b90e3457b8d468514957c28b5f3
625,560
def find_faces_at_index(layer_qs, coord_val, index): """Find all the faces that intersect `coord_val` along `index` Example Slice a list of faces along the x-axis so that you can tell where to fill the shape in, by drawing lines across the polygon. """ return [face for face_q in layer_qs for fa...
da2e4c24da0dde66b6c40b0ff552840995b3a51e
625,565
def is_password_parameter(data_model, source_type: str, parameter: str) -> bool: """Return whether the parameter of the source type is a password.""" # If the parameter key can't be found (this can happen when the parameter is removed from the data model), # err on the safe side and assume it was a password...
60694ef889f9f2ed7afe069196391beab15dd6d8
625,566
def dropIdColumn(train, test): """Detaches Id column from both datasets Parameters: train (pd.Dataset): Training set test (pd.Dataset): Testing set Returns: train (pd.Dataset): Training set without Id test (pd.Dataset): Testing set without Id trainId (pd.Dataset) : Training Id fields ...
7566c130dc3edc66601fb7ade185026de55dea3a
625,568
def rbg_to_hex(c): """Convert an rgb-formatted color to hex, ignoring alpha values.""" return f"#{c[0]:02x}{c[1]:02x}{c[2]:02x}"
4b8061dee948e0bbbfe4e58c42b37f4b66ab29cf
625,569
def DetectEncoding(data, default_encoding='UTF-8'): """Detects the encoding used by |data| from the Byte-Order-Mark if present. Args: data: string whose encoding needs to be detected default_encoding: encoding returned if no BOM is found. Returns: The encoding determined from the BOM if present or |...
43670fd234453a703dd18521b6dc655507448664
625,570
def append_pkcs7_padding(s): """ Function to return s padded to a multiple of 16-bytes by PKCS7 padding. :param s: string to apply padding to :return: padded string """ # numpads = 16 - (len(s) % 16) return s + numpads * chr(numpads)
c2b9dd0a473ea599b963cdab1bc612a8d8b63bb9
625,572
import re def atomwise_tokenizer(smi, exclusive_tokens = None): """ Tokenize a SMILES molecule at atom-level: (1) 'Br' and 'Cl' are two-character tokens (2) Symbols with bracket are considered as tokens exclusive_tokens: A list of specifical symbols with bracket you want to keep. e.g., ['...
245aa4b98329f55d2acffc562b922846f1d9f785
625,573
def reverse_loop(value): """Reverse string using a loop.""" result = "" for char in value: result = char + result return result
609447b4b0c7dd449f5cbeb2d9e7e0bbca675574
625,576
def downsample_image(image, n): """Downsample 2D input image n x n. Parameters ---------- image : ndarray 2D input image. n : int Downsampling factor, applied to both image dimensions. Returns ------- result : ndarray Resampled image with shape = image.shape//n. ...
c85ccde52f0502cf8b097111865fc04b5c735448
625,582
def text_to_int(text): """ Converts text into an integer for use in encryption. input: text - a plaintext message output: integer - an integer encoding text """ integer = 0 for char in text: if integer > 0: integer = integer*256 integer = integer + ord(char) r...
f22d2ba29c36c6a803294a3c284ef8a9cc068ea3
625,583
def underscore_to_dash(name: str) -> str: """Convert underscore to dash and drop final dash if present.""" converted = name.replace('_', '-') return converted if converted[-1] != '-' else converted[:-1]
de84984deb58a3f6e815f43bea8fcee667d2bc47
625,587
import requests import json def update_network(platform, key, client, net_id, new_name): """ Updates the name of a network via the API. :param platform: URL of the RiskSense Platform to be queried. :type platform: str :param key: API Key. :type key: str :param c...
a84a8dc10ff48dba6a9083bfddb4eccf3af44457
625,588
import torch def create_the_slices(image, label, slices: int = 5, dim: int = 0): """ Splitting raw input image into slices Args: image (torch.tensor): Input image label (torch.tensor): Target label slices (int, optional): Split size. Defaults to 5. dim (int, optional): Dimensi...
17257aef2dd7eded4943a3e3c462d9ba2c65dad4
625,589
def make_python_name(name): """ Convert Transmission RPC name to python compatible name. """ return name.replace('-', '_')
e5a97eab62507f21b70da8367240b773c4107ea3
625,594
def from_tensor(tensor_item): """ Transform from tensor to a single numerical value. :param tensor_item: tensor with a single value :return: a single numerical value extracted from the tensor """ value = tensor_item.item() if value == -1: return None return value
9981215be4eb6d40838a50d147af2368ca854cd8
625,595
from typing import List import re def excluded_pattern(root: str, excludes: List[str]) -> bool: """ Check if the given path or filename matches any of the provided exclude patterns. """ for pattern in excludes: if re.search(pattern, root): return True return False
c511ac66426ace4432ba74f660b3dcb16ee4335e
625,596
def _endswith(value): """ Maps to `string.endswith`. """ return lambda v: v.endswith(value)
1cf3fda2e87f0dfa507d18c88552e6d3d463b688
625,598
def lstm_mask_layer(proj, mask): """ Removes any spurious output from the LSTM that's not covered by a label or doesn't correspond to any real input. :param proj: Output of the LSTM layer :param mask: 1 if the position is valid, 0 otherwise :return: The masked values """ return proj * m...
4b8d50f9362a9b870ac2f55365747cfc5f89d675
625,600
def user_info_query(user_id: str) -> dict: """ Build User information query. :param user_id: User id :return: Query """ return { "operationName": "ProfileGet", "query": """query ProfileGet($user_id: ID!) { userprofile { get(user_id: $user_id) { ...
da79d9f2f81c7583115f27d6ca86e98008969372
625,602
import string import random def generateRandomString(length): """Generate a random string of a specified length. To be used in rpc information. Args: length (int): Length of string to be generated. Returns: String: String that was generated. """ choice = string.ascii_...
856eacce58521a30806ebc752e30622457b68a43
625,605
def knot2ms(ws_knot): """ Convert unit of wind speed from knots to meter per seconds. Examples --------- >>> ws_ms = kkpy.util.knot2ms(ws_knot) Parameters ---------- ws_knot : array_like Array containing wind speed in **knots**. Returns --------- ws...
7333b5bfdb78ee6fee0adb3cc79c64cd5c3caffd
625,611
import struct def encode_varint(number): """ Write a VarInt to a string. :param number: Number to encode as a VarInt. :return: The encoded VarInt. """ # Python ints are variable length, which means there's no fixed size. # Typical programming language implementation exploits the sign bit moving # when doing...
a12efcaf2c636058297ae3b23c0f8ca2c49ee66a
625,616
import hashlib def str_md5(_str): """ 字符串MD5 :param _str:字符串 :return:字符串的MD5值 """ m = hashlib.md5() m.update(_str.encode()) return m.hexdigest()
e5f69c78215bde2292193eb1b2ec961829336fc7
625,617
def _polygon_area(x, y): """ Function to compute the area of a polygon by giving its coordinates in counter-clockwise order. """ area = 0 j = len(x)-1; for i in range (0, len(x)): area += (x[j]+x[i]) * (y[i]-y[j]); j = i return area/2;
88f7127f412bc3b332951730ddbbcf64355b3f31
625,618
import torch def top_k_ranking(embeddings, labels, prototypes, prototype_labels, top_k=3): """Compute top-k accuracy based on embeddings and prototypes affinity. Args: embeddings: An N-D float tensor with last dimension as `num_c...
f443b137c39737927cfe3af404ef32dcfb789a8d
625,619
def make_empty_table(row_count, column_count): """ Make an empty table Parameters ---------- row_count : int The number of rows in the new table column_count : int The number of columns in the new table Returns ------- table : list of lists of str Each cell ...
7fdda33e73475df7051a4117dd2aaffe5193f9a0
625,622
def _try_convert_str_to_float(value, label): """ Try to convert input value to float value. """ try: return float(value) except Exception: msg = 'Invalid parameter: {} cannot cast string to float.'.format(label) raise ValueError(msg)
484738b1b76545c10031905a71a9534de3f4f646
625,623
def _validate_arg(value, expected): """Returns whether or not ``value`` is the ``expected`` type. """ if type(value) == expected: return True return False
e296ebdc51a4e441494074f5a8f5bb1e066c16e5
625,624
def parse_requirements(path): """ Return the contents of a requirements file as a string separated by spaces. """ with open(path, 'r') as fp: return ' '.join(line.strip() for line in fp)
c220effeddfc819a1d584b575dbba997caab6e6d
625,632
def enum_names_aslist(c, lower=True): """Get an Enum class as a list of enum names. Args: c (:class:`Enum`): Enum class. lower (bool): True to get names as lower case; defaults to True for easier comparison with other strings. Returns: List: List of enum names. """...
8ff40185b07dc6e4c0d1fe0ee469b9b470bcff0a
625,634
def min_length(word, thresh): """ Predicate for the length of a word """ return len(word) >= thresh
5f6eff3e06726294a64ef7705e3797ab188202f3
625,640
def build_lstm_vocab(tokens): """ Builds vocab from list of sequences :param sentences: list of sequences, each a list of tokens :return: tuple of (dictionary: word --> unique index, pad_token_idx) """ all_tokens = list(set(tokens)) vocab = {token: i for i, token in enumerate(all_tokens)...
f35a2bcc65a46e2c224886ed93b62e47bec90aa5
625,646
def _parse_gcs_path(path: str): """Parses the provided GCS path into bucket name and blob name Args: path (str): Path to the GCS object Returns: bucket_name, blob_name: Strings denoting the bucket name and blob name """ header, rest = path.strip().split('//') if header != '...
ab77a7bbe41b7e6da4e1bd75e44fe006706a7a93
625,647
def object_sort_key(obj): """ Define a predictable sort ordering for Kubernetes objects. This should be the same ordering that Kubernetes itself imposes. """ return ( # Not all objects have a namespace. getattr(obj.metadata, "namespace", None), obj.metadata.name, )
49ed089de8b8b8442fd39faf9f6d97f15186d220
625,650