content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Optional from typing import Tuple from pathlib import Path def get_adress( adress_archive_root: Optional[str], corpus_name: str, variant_type: str, archive_name: str, ) -> Tuple[str, Path]: """Get the adress of a archive file and a contents directory of the corpus. Args...
ea33539532fe762a2e044e4519283c6be1c69d88
677,885
import hashlib def hash_file(f): """Finds the MD5 hash of a file. File must be opened in bytes mode. """ h = hashlib.md5() chunk_size = 65536 # 64 KiB for chunk in iter(lambda: f.read(chunk_size), b''): h.update(chunk) return h.hexdigest()
7c6f4660961a5bf45d38e918ee82e5c5a2bcb132
677,887
def kev2ang(energy): """ Convert energy [keV] to wavelength [Å] """ wlen = 12.398/energy return wlen
3bb0a19865199a277490f39a96516cd649cb98dd
677,888
def listify(x): """If x is already a list, do nothing. Otherwise, wrap x in a list.""" if isinstance(x, list): return x else: return [x]
751d518c64f19f9a6640717ddd8cd0949edf4d37
677,889
def em_complete(job): """Verify that energy minimization has completed""" return job.isfile('em.gro')
b96ef1eebac69b426ee44eae72847bb8dd661a2f
677,891
def world_to_index(x, y, origin, resolution, width): """ Convert World coordinates to index """ x = (x - origin[0]) / resolution y = (y - origin[1]) / resolution return y * width + x
23c8a769236afd1bc92f8bb00db44d97a5227a86
677,893
def wait_for_button_press(button): """ Wait for a button to be pressed and released. Parameter: - `button` (Button): an instance of the EV3 Button() class return the Button name that was pressed. """ pressed = None while True: allpressed = button.buttons_pressed if bool(a...
2b119fb637580104fa79f43f8c72ec76182f31fa
677,895
def is_valid_field_content(s: str) -> bool: """ Returns True if string s can be stored in a SubStation field. Fields are written in CSV-like manner, thus commas and/or newlines are not acceptable in the string. """ return "\n" not in s and "," not in s
6de29796766d672cdb27044135378167564f1c76
677,900
import builtins def is_a_builtin(word) -> bool: """ Returns True if a word is a builtin python object Args: word: word to check Returns: True if word is builtin python object """ return str(word) in dir(builtins)
5dd2eed08273d8fc5a4bba1e67cc681f3a2488ca
677,906
def invalidate_cols(platemap, cols, valid=False): """Returns updated plate map with specified columns invalidated. :param platemap: Plate map to use :type platemap: pandas dataframe :param wells: Columns to invalidate, e.g. [1, 2, 3] :type wells: int or list of ints :param valid: Sets the s...
114a15fd452a49f2c5e3a23421a6181ce2d142d6
677,908
import getpass def get_current_user() -> str: """Return the name of the current user""" return getpass.getuser()
cc21a6aafd5cbbd8a02b0b6e62f8318311a6ed59
677,910
def increase_threshold(thresh, thresh_inc): """ Increase the threshold based on a string Inputs: - thresh Initial threshold - thresh_inc How the threshold should be increased. "xN": multiply by N "+N": increase by N ...
c5d7281acb85e27a6ada104b336bb6a05ed1b24c
677,916
import math def hd(inc, sd): """ Calculate horizontal distance. :param inc: (float) inclination angle in degrees :param sd: (float) slope distance in any units """ return sd * math.cos(math.radians(inc))
76de48925810c399632d80fa799d4bbf94ff0069
677,918
def get_symbol_name(*args): """Return fully-qualified symbol name given path args. Example usage: >>> get_symbol_name('ZenPacks.example.Name') 'ZenPacks.example.Name' >>> get_symbol_name('ZenPacks.example.Name', 'schema') 'ZenPacks.example.Name.schema' >>> get_symbol_...
b0c97157f8121e5bb6f32f8bb9253b5a723cfde8
677,919
from typing import Set import re def solidity_unresolved_symbols(hex_code: str) -> Set[str]: """ Return the unresolved symbols contained in the `hex_code`. Note: The binary representation should not be provided since this function relies on the fact that the '_' is invalid in hex encoding. ...
496f120c0dc6c49b45eedd4a6004e773d5a3e88e
677,921
def remove_comment(content): """Remove comment from the content.""" lines = content.split('\n') return '\n'.join([line for line in lines if not line.startswith('#')]).strip()
6efb3ae4376eb16cc14c3c1a8f210420e807a250
677,925
def person(request): """ A dummy fixture, parametrized so that it has two instances """ if request.param == 0: return "world" elif request.param == 1: return "self"
5c34b2a87c2db01d93d4f2e32e07c80cb2a06459
677,926
import re def clean_tag(tag, allow_none=False, mytype='string', default=None, max_len=254): """ Clean the given `tag` instance depending of its `mytype`.""" if default is None and allow_none is False: if mytype == 'string': default = 'unknown' elif mytype == 'integer': ...
69416f4c1f4230434eac17e983fb460df371b125
677,930
def calculate_square(num): """ Returns the square of a given number """ return num * num
5bac73090aaf92cd97659343a64513470f81e8c2
677,932
def fmt_color(text: str, color: str) -> str: """Format a string in a certain color (`<span>`). Args: text: The text to format. color: Any valid CSS color. Returns: A `<span>` that contains the colored text. """ return u'<span style="color:{color}">{text}</span>'.format( ...
2bb3a83fa278e5a48335e43d048fdda6029c9afb
677,933
def RIGHT(text, n): """Slices string(s) a specified number of characters from right. Parameters ---------- text : list or string string(s) to be sliced from right. n : integer number of characters to slice from right. Must be greater than zero. Returns ------- list or s...
d5a31641754213a41da74114bd09010a9ea23e62
677,934
def _stringify_int(integer): """Convert an integer into a string formatted with thousand separators. Parameters ---------- integer : int The integer. Returns ------- str The integer turned into a string. """ return "{:,}".format(integer)
8f797819ef166a3cb726565f9d329d154ebb44dc
677,940
def calc_percent(per, cent): """Takes the parameters "per" and "cent" and returns the calculated percent.""" return (per / cent) * 100
aeb7cf4a5ba243847ccd638bd8c89dbfa3b5195f
677,944
from typing import Union from typing import List from typing import Tuple def edge_has_empty_node( edge: Union[List[str], Tuple[str, str]], node_ids_with_labels ) -> bool: """Check if edge contains an empty node.""" return not str(node_ids_with_labels[edge[0]]) or not str( node_ids_with_labels[edg...
18fd4784484403aaa7859f249b61776da95cb9a7
677,948
def cli(ctx, state="", history_id="", invocation_id="", tool_id="", workflow_id="", user_id="", date_range_min="", date_range_max="", limit=500, offset=0, user_details=False): """Get all jobs, or select a subset by specifying optional arguments for filtering (e.g. a state). Output: Summary information for eac...
cf6702581a7f4870c105aab763a8b5b5a89a1bc6
677,959
def build_table(x, perceiver, cache, cache_emb, topk, return_images=False, index_dir=None): """ Maps each image to a linearized row in a table. Each entry in a row is delimited by "|". Each entry comes from the t...
5822dbe6f54a0d582bc19785cf9b1d49a4ac5eda
677,960
def match_pattern(resource: bytes, pattern: bytes, mask: bytes, ignored: bytes): """ Implementation of algorithm in:x https://mimesniff.spec.whatwg.org/#matching-a-mime-type-pattern True if pattern matches the resource. False otherwise. """ resource = bytearray(resource) pattern = bytearray(...
8e6652c2593317d6c75e2f30eaedb25377504962
677,966
import torch def mse(target, predicted): """Mean Squared Error""" return torch.mean((target - predicted)**2)
27b60d509f4cddac3e06f8cb76ee3221f60e8d0b
677,968
def min_scalar_type(a): """ min_scalar_type(a) For scalar ``a``, returns the data type with the smallest size and smallest scalar kind which can hold its value. For non-scalar array ``a``, returns the vector's dtype unmodified. Floating point values are not demoted to integers, and comple...
d9a69b900c2b7ab8e600447fa42058bb17a574fc
677,969
from typing import Any def force_list(value: Any) -> list: """ Convert `value` to list or return `value` if it is already a list. :param value: Value to convert to list. """ return list(value) if isinstance(value, (list, tuple)) else [value]
2151eefef55a280c6c7cc0a5a7520a774750ecb2
677,970
def get_frameshift_lengths(num_bins): """Simple function that returns the lengths for each frameshift category if `num_bins` number of frameshift categories are requested. """ fs_len = [] i = 1 tmp_bins = 0 while(tmp_bins<num_bins): if i%3: fs_len.append(i) tm...
dde6f0d2264754727384c82792e56dacaadb84c9
677,974
def set_appliance_discovery_emails( self, email_list: list[str], ) -> bool: """Update email addresses configured to be notified for discovery of new appliances. .. warning:: Replaces the current configured list with the new list. To add an email, first retrieve the current emails an...
62872b47ebdd2c9129c379348ea763666262f17e
677,975
def _check_not_none(value, name): """Checks that value is not None.""" if value is None: raise ValueError(f"`{name}` must be specified.") return value
bfded56ca8e86463d3d20ceebe252605bfe6319b
677,976
def fill_point(x, y, z, _): """ Returns a string defining a set of minecraft fill coordinates relative to the actor. In minecraft, the y axis denotes the vertical (non-intuitively). """ return f'~{int(x)} ~{int(z)} ~{int(y)}'
25cdf38627ea6f2dc612484f9ffb2c54e0d08d64
677,979
import operator def advance_permutation(a, increasing=True, forward=True): """ Advance a list of unique, ordered elements in-place, lexicographically increasing or backward, by rightmost or leftmost digit. Returns False if the permutation wrapped around - i.e. went from lexicographically greatest...
d5d2740e9b173c3277843411f1b5c05427d785ce
677,981
def prompt(msg): """Prompt the user for input.""" value = "" while not value: value = input(msg+" ").strip() return value
edf2fa00d99b96d8ad25e9af40c1020eb39c6fe6
677,986
import math def p_sequence(expected_value, days_a_week, upper_bound, step): """Calcualtes the capacity values to test.""" lower_p = math.ceil(days_a_week*expected_value/0.99) # PSEQ per week, pseq per day PSEQ = sorted(list(set([int(lower_p + step*i) for i in range(upper_bound)]))) pseq = [round(i...
c3122ec315aa190f9ad7ca3c53c9c02c380cb634
677,987
import torch def jitter(X, ox, oy): """ Helper function to randomly jitter an image. Inputs - X: PyTorch Tensor of shape (N, C, H, W) - ox, oy: Integers giving number of pixels to jitter along W and H axes Returns: A new PyTorch Tensor of shape (N, C, H, W) """ if ox != 0: left = X[:, :, :, ...
6807ff6b7010d2684c4a737568e475a1695dcbf1
677,988
import time def add_timer(func_name): """Decorator to add timing to run commands """ def decorator(func): def wrapper(*args, **kwargs): start = time.time() func(*args, **kwargs) end = time.time() line_len = 88 print("") print...
63e330fda8146c14613ba60feab7cde8daf6a4b9
677,990
import re def to_slug(value): """ Convert a string to a URL slug. """ value = value.lower() # Space to dashes value = re.sub(r'[\s_]+', '-', value) # Special characters value = re.sub(r'[^a-z0-9\-]+', '', value, flags=re.I) # Extra dashes value = re.sub(r'\-{2,}', '-', value) va...
27a1524f94324c83bd5fe763133bd2b2f65c5984
677,995
def get_digits_by_length(patterns, length): """Find all digits of a given length.""" return [pattern for pattern in patterns if len(pattern) == length]
d35b73c4ba9710a2a7d4f681ed02a7cfaac7d234
677,996
def calculate_fantasy_points(player) -> float: """ Calculate the fantasy points this player earned from the formula Kill = 0.3 Death = -0.3 Assist = 0.15 Last Hit = 0.003 Gold per minute = 0.002 EXP per minute = 0.002 Seconds of enemy stuns = 0.07 Every 1000 allied healing done ...
a2a0c91a69720904a81fee58d5a5ecf236f32bdc
677,997
from typing import List from functools import reduce from operator import mul def multiples_of(numbers: List[int]): """ Calculate the number of numbers multiples in the range being their product. Eg for 3, 5 compute amount of 3 & 5 multiples in frame size 3 * 5 """ frame_size = reduce(mul, numbers...
47cbcc7c23287c3863373ab1189ab8ef93a980a6
677,999
def positive_percent(df): """ compute the percentage of positive Tweets: 2 is positive :param df: a tweet dataframe :return: percentage of positive tweets """ assert 'sentiment_vader_percent' in df, "The pandas dataframe should contain the sentiment of each tweet" positive = 0 for sentim...
39c0b1a9ec86bf91256728e7321fcd5c1896b8c9
678,008
def gcd(a, b): """ Find the greatest common divisor of two integers a, b. This uses Euclid's algorithm. For integer a, b, it holds that a * b = LCM(a, b) * GCD(a, b). Starting from range(1, 21), we replace two head elements x, y to LCM(x, y). """ dividend = max(a, b) divisor = min(a, b)...
7d5ec6818e73015d46c4d00e6842e81d48d3e4f0
678,012
def rot(c, n): """ This function rotates a single character c forward by n spots in the alphabet. """ # check to ensure that c is a single character assert(type(c) == str and len(c) == 1) if 'a' <= c <= 'z': new_ord = ord(c) + n if new_ord > ord('z'): new_ord = ord(c) + ...
23923faa7aa96419152e0b9673f7a0d21b36d2e6
678,013
def format_headers(headers): """ Return a list of column names formatted as headers :param headers: :return list: """ new_headers = [] for h in headers: h: str = h if '_' in h: h = h.replace('_', ' ') # if 'id' in h: # h = h.replace('id', '') ...
59c66c9edac91eea0e59889312c67cedda9f5fa9
678,015
import yaml def build_content(csvdict): """ Construct a new dictionary that will be used to populate the template. """ yamlkeys = ['title', 'excerpt', 'tags', 'mentors', 'badge', 'level'] #yamlkeys = ['title', 'excerpt', 'tags'] yamldict = {} content = csvdict.copy() #sidekeys = ['me...
283a102c83377e8e48e4a26c6d1ea1dd987290a4
678,017
def _kern_class(class_definition, coverage_glyphs): """Transpose a ttx classDef {glyph_name: idx, glyph_name: idx} --> {idx: [glyph_name, glyph_name]} Classdef 0 is not defined in the font. It is created by subtracting the glyphs found in the lookup coverage against all the glyphs used to define t...
7ad1d9b84ec9a4af58e8aaed951d25030ceef82b
678,019
import torch from typing import Union def normalize( data: torch.Tensor, mean: Union[float, torch.Tensor], stddev: Union[float, torch.Tensor], eps: Union[float, torch.Tensor] = 0.0, ) -> torch.Tensor: """ Normalize the given tensor. Applies the formula (data - mean) / (stddev + eps). ...
cb0ad521d87a1a39c7cf9156c8dc79365c92df5b
678,020
def get_xarray_subset( dataset, variable_name, time_step_indices, xy_slice_indices ): """ Returns a subset of the provided dataset. The source dataset is restricted to the variable and indices supplied. When contiguous time step and XY slice indices are supplied, the resulting DataArray is a view of t...
649b77fad686cfc61ea17d7d0fb35cdb5ef27f44
678,022
def encrypt_letter(letter): """Encrypt a single letter Arguments: letter {char} -- The character to encrypt Returns: char -- The encrypted character """ inc_ord_char = ord(letter) + 3 if letter.isupper(): if inc_ord_char > 90: inc_ord_char = inc_ord_c...
db25dd20f144a87317e064fabec276b68145fc51
678,023
def float_to_pcnt(x): """Convert a float to a percentage string, e.g. 0.4 -> '40%'.""" return '{}%'.format(round(x * 100))
7fd3fc10f5e4f9de99264908207f8588c269b1c0
678,024
def resolve_integer_or_float(*numbers): """Cast float values as integers if their fractional parts are close to zero. Parameters ---------- numbers : sequence Number(s) to process. Returns ------- A number or list of numbers, appropriately transformed. """ if len(number...
e8f3545afdebfda3028844c941eb331f3f9257fa
678,029
def test_module(client): """ Returning 'ok' indicates that the integration works like it suppose to. Connection to the service is successful. Args: client: HelloWorld client Returns: 'ok' if test passed, anything else will fail the test """ result = client.say_hello('DBot') ...
77d9e604a4c42850753e81056a851a7dbdd83697
678,030
from typing import OrderedDict def groupby_name(bindings, tier=0): """ Groups bindings by the name fragment specified by tier. Input bindings can be not sorted. The order of the bindings remains initial in scope of its group. Yields: (name, [binding(s)...]) tuples. """ res = Order...
3bdb7286ba7f3f54d7ffe279f048efe54c9764f6
678,032
def get_location(datetime, position_df): """Create a tuple of the date_time, latitude and longitude of a location in a dataframe from a given date_time.""" latitude = position_df[position_df.date_time == datetime].latitude.item() longitude = position_df[position_df.date_time == datetime].longitude.item() ...
bea3dc5cb58fb6965f263e95c56f510ffe7f413f
678,034
import math def gen_abd_params(N, f, dummy=None): """ Generate possible values of n, q1, q2 """ quorum_params = [] quorum_params_append = quorum_params.append for n in range(2*f+1, N+1): for q1 in range(math.ceil((N-1)/2), n-f+1): for q2 in range(math.ceil((N-1)/2), n-f+1): ...
25b90d06ae6f6b5b4a9d2af443db815b1c9181cc
678,039
def is_close(a, b, rel_tol=1e-09, abs_tol=0): """Determines whether two numbers are nearly equal. The maximum of the relative-based and absolute tolerances is used to test equality. This function is taken from `math.isclose` in Python 3 but is explicitly implemented here for Python 2 compatibility...
fa9ea5a8c2e7088d1eb2d3223dd6b29d2d5dfefa
678,043
import pickle def load_pickle_file(file_name, encoding='latin1'): """Loads a pickle file. :param file_name: File name (extension included). :type file_name: pathlib.Path :param encoding: Encoding of the file. :type encoding: str :return: Loaded object. :rtype: object | list | dict | numpy....
1dca3fbf08bdd5e8982097a4e56561811d5207e3
678,044
def _give_default_names(list_of_objects, name): """Helper function to give default names to objects for error messages.""" return [name + '_' + str(index) for index in range(len(list_of_objects))]
6f608ad70db21ba2b8154e06b4e756324df105f8
678,045
def translate (vector, obj): """ Function translate return openscad translate command @param vector: [x, y, z] translation matrix @param obj: text object to translate """ return "translate({}){{{}}}".format(vector, obj)
f2e745f4fa3eabf9f7934ce56826658805ea918d
678,046
import ipaddress def hops_to_str(hops): """Concatenate together a list of (host, port) hops into a string such as '127.0.0.1:9001|192.168.1.1:9002|[::1]:9000' appropriate for printing or passing to a zeromq connect() call (does not include the 'tcp://'' prefix)""" formatted_hops = [] for host, por...
01e958d84813604acbaf4c1beb37ee35ff844c8b
678,049
def _parse_package_name(name: str) -> str: """ Force lower case and replace underscore with dash to compare environment packages (see https://www.python.org/dev/peps/pep-0426/#name) Args: name: Unformatted package name Returns: Formatted package name """ return name.lower()...
0257cbae7d8c25b31d089c983a0185c67cff6e2d
678,053
import json import codecs def encode_blob(data): """ Encode a dictionary to a base64-encoded compressed binary blob. :param data: data to encode into a blob :type data: dict :returns: The data as a compressed base64-encoded binary blob """ blob_data = json.dumps(data).encode('utf...
266f0b6440adfae165a9d8d6877a111736e22488
678,060
def intro(secret): """ Returns opening instructions to player. """ return 1
c5af34c1729f23e4b491f0f7b590022498266dbb
678,070
import struct def readLEFloat(f): """Read 4 bytes as *little endian* float in file f""" read_bytes = f.read(4) return struct.unpack('<f', read_bytes)[0]
f7a27102da1fb941d15537821443f4d7b682a7a7
678,076
from typing import Dict def _compute_metrics(hits_or_lcs: int, pred_len: int, target_len: int) -> Dict[str, float]: """This computes precision, recall and F1 score based on hits/lcs, and the length of lists of tokenizer predicted and target sentences. Args: hits_or_lcs: A number of ma...
630801f5c0821e774b9b2ac95c3d408afd5380a8
678,081
def string_diff_column(str1, str2): """ >>> string_diff_column("ab1", "ab2") 3 >>> string_diff_column("ab1c3e", "ab2c4e") 3 >>> string_diff_column("abc", "abcd") 3 >>> string_diff_column("abcd", "abc") 3 >>> string_diff_column("a", "") 1 >>> string_diff_column("", "a") ...
7672aca6a74ed5496f5d1bb1f9b9da58f11ec4c5
678,082
def _set_type(values, new_type): """Transforms a list of values into the specified new type. If the value has zero length, returns none Args: values: A list of values new_type: A type class to modify the list to Returns: The values list modified to the new_type. If an element is em...
d95aac651374a658e204da58094a4a0a56fea276
678,084
def first_true_pred(predicates, value): """ Given a list of predicates and a value, return the index of first predicate, s.t. predicate(value) == True. If no such predicate found, raises IndexError. >>> first_true_pred([lambda x: x%2==0, lambda x: x%2==1], 13) 1 """ for num, pred in enu...
bf72ce96833e1f501599aa7091de727f9eea4974
678,085
def check_x_lim(x_lim, max_x): """ Checks the specified x_limits are valid and sets default if None. """ if x_lim is None: x_lim = (None, None) if len(x_lim) != 2: raise ValueError("The x_lim parameter must be a list of length 2, or None") try: if x_lim[0] is not None and...
6dda696f4a001d021c8074675e0905f049e88e70
678,090
def get_model_device(model): """Return the device on which a model is.""" return next(model.parameters()).device
2fb10d37811cfd86cf1500561b13befe6465fa05
678,094
def distx2(x1,x2): """ Calculate the square of the distance between two coordinates. Returns a float """ distx2 = (x1[0]-x2[0])**2 + (x1[1]-x2[1])**2 + (x1[2]-x2[2])**2 return distx2
ec54779bc477088c08be512dbb1a7a5cdeefb18b
678,095
def sp(dividend, divisor): """Returns the percentage for dividend/divisor, safely.""" if not divisor: return 0. return 100. * float(dividend) / float(divisor)
ca027d5637738f3a268e24d329d2d876f855e794
678,098
def bdev_delay_create(client, base_bdev_name, name, avg_read_latency, p99_read_latency, avg_write_latency, p99_write_latency): """Construct a delay block device. Args: base_bdev_name: name of the existing bdev name: name of block device avg_read_latency: complete 99% of read ops with th...
6625574dd46788eb2136ab06745ceadf5b167247
678,107
def get_scan_indices(data): """Get the line numbers where scans start This finds all the lines starting with the word 'Scan'. Although some of these lines have a source name, it appears to be correct only for the first scans in the file. Notes ===== This is specific to Tid ASCII files @param data : l...
447a123f9db2b65469e3c72918e40d8ee70391ba
678,111
from typing import Sequence def _lcs(pred_tokens: Sequence[str], target_tokens: Sequence[str]) -> int: """Common DP algorithm to compute the length of the longest common subsequence. Args: pred_tokens: A tokenized predicted sentence. target_tokens: A tokenized target s...
7189136a6ceeb3079c3d34bdacf2ee4c37b519ad
678,112
import torch def load_io_dataset(dataset_path: str, device=None): """ Load the saved dataset, map the data location to `device`. Args: dataset_path: Path to the checkpoint (.pt format) device: Device for the data. Returns: The loaded IO dataset """ data = torch.load(dataset_...
181dc0dc3c2cb0615068bc6620af9af4d86d1274
678,114
def dice_similarity_coefficient(inter, union): """Computes the dice similarity coefficient. Args: inter (iterable): iterable of the intersections union (iterable): iterable of the unions """ return 2 * sum(inter) / (sum(union) + sum(inter))
ae58310528b7c24b7289cb3bcf76c72745c8bacc
678,115
def rint(f: float) -> int: """ Rounds to an int. rint(-0.5) = 0 rint(0.5) = 0 rint(0.6) = 1 :param f: number :return: int """ return int(round(f, 0))
82f89c49135e0081db7ac4615a51d3dd24665309
678,117
def merge_with(f, *dicts): """Returns a dict that consists of the rest of the dicts merged with the first. If a key occurs in more than one map, the value from the latter (left-to-right) will be the combined with the value in the former by calling f(former_val, latter_val). Calling with no dicts retur...
1ddb503b6a000932d115f8045676c409e05abe5c
678,119
def ok(results): """Return whether or not all results are status 200 OK.""" return all([result['data'].ok for result in results])
42e61dc39110b196837a3ac353c1996d32fa434c
678,120
from io import StringIO def write_tgf(graph, key_tag=None): """ Export a graph in Trivial Graph Format .. note:: TGF graph export uses the Graph iternodes and iteredges methods to retrieve nodes and edges and 'get' the data labels. The behaviour of this process is determined by the single...
580dd0da85e580e3cb6864aa0bcd28d78f4bbee1
678,124
def valid_elements(symbols,reference): """Tests a list for elements that are not in the reference. Args: symbols (list): The list whose elements to check. reference (list): The list containing all allowed elements. Returns: valid (bool): True if symbols only contains elements from ...
a6fb3a6c09e76da865a76e4ae320f9cfef55a91c
678,127
import torch def collate_fn(batch): """Collate batches of images together. """ imgs, targets = list(zip(*batch)) imgs = torch.stack(imgs) targets = torch.LongTensor(targets) return imgs, targets
e2979b3e335c8c3aef3d18612705e7fd1e4331d0
678,128
import torch def any(input_, axis=None, keepdims=False): """Wrapper of `torch.any`. Parameters ---------- input_ : DTensor Input tensor. axis : None or int or tuple of ints, optional Axis or axes to operate on, by default None keepdims : bool, optional If true, the axe...
76d6ca1c662215d068f168989ea36f68fd113b6e
678,129
import hashlib def file_hash_sha256(file): """Return SHA-256 hash of file as hexadecimal string.""" with open(file, 'rb') as hf: hfstuff = hf.read() ho = hashlib.sha256() ho.update(hfstuff) return ho.hexdigest()
46db04556269113a31d3850e5bd44096b52832fc
678,132
def percent_change(d1, d2): """Calculate percent change between two numbers. :param d1: Starting number :type d1: float :param d2: Ending number :type d2: float :return: Percent change :rtype: float """ return (d2 - d1) / d1
45a8de67340432eff3cd3c9fee695b1f1db7d46a
678,133
import re def isvowel(char): """Check whether char is tibetan vowel or not. Args: char (str): char to be checked Returns: boolean: true for vowel and false for otherwise """ flag = False vowels = ["\u0F74", "\u0F72", "\u0F7A", "\u0F7C"] for pattern in vowels: if r...
3476271b9109a2d42d404c20ebebade95549af9a
678,134
def _indent(string, width=0): #pragma: no cover """ Helper function to indent lines in printouts """ return '{0:>{1}}{2}'.format('', width, string)
9a77537d2562834a3acb2f746ef397b17cbc8333
678,141
def is_list(node: dict) -> bool: """Check whether a node is a list node.""" return 'listItem' in node
ad01033afe51391db2e5966247080e7263baa5e4
678,146
def _is_using_intel_oneapi(compiler_version): """Check if the Intel compiler to be used belongs to Intel oneAPI Note: Intel oneAPI Toolkit first version is 2021.1 """ return int(compiler_version.split(".")[0]) >= 2021
ceaa0ebe12112e3106071f6af2e4b51809c7a0b1
678,148
def celsius_to_fahrenheit(temperature_in_c): """Convert temperature from celsius to fahrenheit PARAMETERS ---------- temperature_in_c : float A temperature in degrees Celsius RETURNS ------- temperature_in_f : float A temperature in degrees Fahrenheit """ temperatur...
d3589f7e87aae4b03d3184baf6db7c2c2602b54e
678,152
def path_probability(trans_mat, quad_to_matrix_index, path): """ Computes the probability of a given path :param trans_mat: trained transition matrix (numpy matrix) :param quad_to_matrix_index: dictionary to keep track of indicies :param path: input path of neo4j types :return: float representing probability of s...
c0c078e7fc16ff787c805779746ace939e8db0d4
678,153
def frameToCell(frame, info): """ Convert a frame and game info to a cell representation """ return str((info['x']//32,info['y']//32,info['act'],info['zone']))
f20c4132001d7a754221c311d866b707f7375b1a
678,156
def usage(wf): """CLI usage instructions.""" return __doc__
4825dc18eb22e83fcf4d14e7a0dea1ce1457a9e7
678,157
from typing import List import torch def conv( in_channels: int, out_channels: int, stride: int = 1, groups: int = 1, kernel_size: int = 3, padding: int = 1, ) -> List[torch.nn.Module]: """ 3x3 convolution with padding.""" return [ torch.nn.Conv2d( in_channels, ...
6b69392050747be39b9a4a15da60a08e64647df8
678,159
def join_hostname_index(hostname, index): """Joins a hostname with an index, reversing splti_hostname_index().""" return "{}~{}".format(hostname, index)
7e7dc902c9c47cae5c8a930f6979b97a5e7e3f2c
678,160
def t03_SharingIsPassByReference(C, pks, crypto, server): """Verifies that updates to a file are sent to all other users who have that file.""" alice = C("alice") bob = C("bob") alice.upload("k", "v") m = alice.share("bob", "k") bob.receive_share("alice", "k", m) score = bob.download("k"...
ffdcde1c6dd9fcb6053715789287efabbe7ed6f1
678,163