content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import List from typing import Optional from typing import Tuple def split_by(items: List[str], separator: Optional[str] = None) -> Tuple[List[str], List[str]]: """If the separator is present in the list, returns a 2-tuple of - the items before the separator, - all items after the sepa...
947219eaed147800b54480696fb751134d5eacd8
687,428
import math def computeGoodMax(totalTimes, noerrs): """Find a good value for the maximum on the Y axis""" # Could allow a small amount of space above the top, but it's annnoying for percentages! # return None factor = 1.00 maxReading = factor * max( [max([v for v in l if v != None]) for l ...
a71ad553716d709d4a21d0973ccd226879fc1189
687,429
def value_of_ace(hand_value): """ :param hand_value: int - current hand value. :return: int - value of the upcoming ace card (either 1 or 11). """ if hand_value + 11 > 21: value = 1 else: value = 11 return value
f57a2f630340b864c759bdd2f7600e44e895b599
687,430
def add_char_labels(instance): """ 将word_lst中的数据按照下面的方式设置label 比如"复旦大学 位于 ", 对应的分词是"B M M E B E", 则对应的dependency是"复(dep)->旦(head)", "旦(dep)->大(head)".. 对应的label是'app', 'app', 'app', , 而学的label就是复旦大学这个词的dependency label :param instance: :return: """ words = instance['word_lst'] ...
981fc34e55339e5838d07b0771e20641f57a264f
687,431
def _parse_ports(ports_text): """ Handle the case where the entry represents a range of ports. Parameters ---------- ports_text: str The text of the given port table entry. Returns ------- tuple A tuple of all ports the text represents. """ ports = p...
eb6eed9a5f8ea91d448be9c0eede9f5b258cf358
687,432
def operation_consumes_ref_bases(operation): """ Returns true if this is a cigar operation that consumes reference bases """ return operation == 0 or operation == 2 or operation == 3 or operation == 7
e6c31b9ce796ee690a2b5e076c1e9ff9665996e0
687,433
from pathlib import Path import os def get_path_fixture(path_from_tests: str) -> Path: """retrieves path to fixture""" file_dir = os.path.dirname(__file__) fixture_path = Path(file_dir) / ".." / path_from_tests return fixture_path
5be91a784947ca26cd85f31f527f2a0aa0811b5a
687,434
import socket import struct def long2ip(l): """Convert big-endian long representation of IP address to string """ return socket.inet_ntoa(struct.pack("!L", l))
57c3653a3e8748a6d8461d1b89f4c3a0fa6a4d3c
687,435
def credentials(db_url): """Parse the database string""" transit1 = db_url.split('/') transit2 = transit1[2].split('@') name = transit1[-1] user, password = transit2[0].split(':') host, port = transit2[1].split(':') return {'NAME': name, 'USER': user, 'PASSWORD': password, 'HOST': hos...
31fcb6c1b4befce86c47ee87840f8a3553f88937
687,437
import os import re def get_runs_list(path): """ This function returns the list of run folders in the path, by verifying that they are in the right format :param path: :return: """ assert os.path.exists(path), "The path {} does not exists!".format(path) r = re.compile(".{4}_.{2}_.{2}_.{2}:.{2}_.{6}") ...
a857b4d925f58a65aa80d3b7de67ada370a66742
687,438
from bs4 import BeautifulSoup def get_soup(html): """ Get the Beautiful Soup tree from HTML. """ # return BeautifulSoup(req.content, "html.parser") # return BeautifulSoup(req.text, "html5lib") # Haven't tested this yet return BeautifulSoup(html, "html.parser")
500915855594ab722cf63ecae29190e9dc907954
687,439
def registry_file_url(): """ return the url for the plugins.json file """ return 'https://raw.github.com/aiidateam/aiida-registry/master/plugins.json'
75964395d7a3d227a4a7bb29c3bfcd22307ad247
687,440
import os def get_themes(templates_path): """Returns available themes list.""" themes = os.listdir(templates_path) if '__common__' in themes: themes.remove('__common__') return themes
fc72f95b40a3510e4b187cc9729247fb3fc6011f
687,441
def judgeCircle(moves): """ :type moves: str :rtype: bool """ return moves.count("L") == moves.count("R") and moves.count("U") == moves.count("D")
2a76050d1b14cca1880e6b02be1d0b6ceeed97be
687,442
import re def replacenth(string, sub, wanted, n): """Replace nth word in a sentence string: Complete string sub: Substring to be replaced wanted: Replace by wanted n: index of the occurence of sub to be replaced """ where = [m.start() for m in re.finditer(sub, string)][n-1] before...
a3987b6f0c248cac6a01ae9a4a1912d88d52d630
687,443
def _SNR(coef): """ Return the signal-to-noise ratio for each constituent. """ if "Lsmaj" in coef: SNR = (coef["Lsmaj"] ** 2 + coef["Lsmin"] ** 2) / ( (coef["Lsmaj_ci"] / 1.96) ** 2 + (coef["Lsmin_ci"] / 1.96) ** 2 ) else: SNR = (coef["A"] ** 2) / (coef["A_ci"] / ...
ac3bdd752d062a72ffc64fb9171e3f636d0e26e8
687,444
def construct_utf_8_symbol_mask(codepoint, length): """ construct mask for encoding codepoint """ assert length >= 2 mask = bytearray() d = codepoint while d != 0: d, m = divmod(d, 64) mask.insert(0, m) for _ in range(length - len(mask)): mask.insert(0, 0) return mask
4f661c7d68966142b6c46259e0bce25d53096931
687,445
def ask_for_value(question): """The solution for asking for a integer value without using exceptions """ answer = "" while not answer.isdigit(): answer = input(question) # Error message if not answer.isdigit(): print("Input must be a number!") else: ...
ad9d83c61b888db02793ce3e99eab78e61b58ee7
687,446
from typing import Dict from typing import Any import subprocess import os from typing import cast import json def _load_pbxproj_as_json(path: str) -> Dict[str, Any]: """Load a pbxproj as JSON. :param path: The path to the pbxproj :returns: A deserialized representation of the pbxproj """ conte...
b70b96c621385fdfac805ab55d0175981fef8957
687,447
def get_container(context, container): """Return the container.""" reports = context.get("reports") container_instance = [report for report in reports["reports"] if report["report_uuid"] == context.uuid["report"]][0] if container != "report": container_instance = container_instance["subjects"][c...
f667375c4c96d2df5673f0d5e968f5a5efb0ab92
687,448
from typing import Counter import re def is_valid_sentence(str): """ Check if a sentence is valid: - Does not contain mismatched brackets - Does not start with 'and' or 'but' - Ends with a punctuation [.?!] - Has a minimum length of 5 """ start_pattern = r"^\"*[A-Z]+" end_pattern ...
192a60a5a4cc3e26d9b04cbe5a0df82a4fe72187
687,449
def prepend(base, prefix): """Prepend a prefix to a string""" return f"{prefix}{base}"
7d9d240a10405d7e404b46a4f0cfbc968cd3af18
687,451
def point_touches_rectangle(point, rect): """Returns ``True`` (``1``) if the point is in the rectangle or touches it's boundary, otherwise ``False`` (``0``). Parameters ---------- point : {libpysal.cg.Point, tuple} A point or point coordinates. rect : libpysal.cg.Rectangle A rec...
11b2f3b672cf32aa7dd66290362a206fc9e8c010
687,452
import glob def get_photos(folder_path, pics_extension): """Function create a list of photos from given folder""" pics_path = folder_path + "/*." + pics_extension return glob.glob(pics_path)
3d32d5b173d74a2425f1229ee5e45784c1283053
687,453
def generate_zip_code_dcids(zipcode): """ Args: zipcode: a zip code Returns: the matching dcid for the zip code """ dcid = "dcid:zip/" + str(zipcode).zfill(5) return dcid
f87634fc33e6dd7b7a10b1a2199f71e2bff243ac
687,454
def match_in_index(node, index): """ :param node: str :param index: int :return: Node """ result = None if node.short_name() in index: nodes = index[node.short_name()] if nodes: for node_found in nodes: if node.name().endswith(node_found.name()) o...
9f5df3bd9aeef9ed575d48745960a38f1d2224f7
687,455
def _full_index(sample_id_col): """Return all columns necessary to uniquely specify a junction""" return [sample_id_col, 'chrom', 'intron_start', 'intron_stop', 'strand']
db2bc661e0faef0234216c7426f23780ea25dd4d
687,456
def apply2nuc (seq, query, ref, keepIns=False, keepDel=False): """ Apply results from amino acid sequence alignment to the original nucleotide sequence by padding insertions with gaps, omitting deletions. """ newseq = '' qpos, rpos = 0, 0 # query, reference a.a. positions for i in range...
63274ecfbfb9988ec1f121f14d541d47117bbc07
687,457
import math def bbox_resize(bb,hr,wr,ar=0): """ Resize the bbs (without moving their centers). If wr>0 or hr>0, the w/h of each bb is adjusted in the following order: if hr!=0: h=h*hr if wr1=0: w=w*wr if hr==0: h=w/ar if wr==0: w=h*ar Only one o...
750c0f66dbbb40d4bf3387717045f8b81141e6e2
687,458
import json import struct def length_encode_json(data): """ Produces a length-encoded representation of JSON. """ json_bytes = json.dumps(data).encode('utf-8') length_header = struct.pack('H', len(json_bytes)) return length_header + json_bytes
c863e17f4348ae85b7c5e3a09d81a0ed28cf2970
687,459
import argparse def parse_arguments(): """ Parse command-line options """ parser = argparse.ArgumentParser(description="Exports data from a BBP " "simulation to a flat file.") parser.add_argument("--sim_id", dest="sim_id", type=int, requ...
3af3f8c2be314cca5c38c254e1482f1132af366a
687,460
def chain(*args): """Applies a list of chainable update transformations. Given a sequence of chainable transforms, `chain` returns an `init_fn` that constructs a `state` by concatenating the states of the individual transforms, and returns an `update_fn` which chains the update transformations feeding the ap...
74643ddf7d88e05640c9549048ddd19f9616c2c2
687,461
def NaturalVentilation(ShaftATop, ShaftABottom, ShaftBTop, ShaftBBottom): """ The purpose of this function is to calculate the Natural Ventilation Head in Inches Water Gage. Inputs required: Lists in the following format: [DryBulbTemp, WetBulbTemp, Elevation, Pressure (in Hg) Method 2, page 297 in Raman...
ccdf88b0fd40028d981c30e3cd96cab4a103e492
687,462
def _solve_method_3(arr): """ https://github.com/JaredLGillespie/HackerRank/blob/master/Python/minimum-swaps-2.py Couldn't really figure it out via my method, but I found this solution that was very small and I understand. One thing I did was factor out a portion of it into a function call, for ...
fca3a8ace9f026eed0d56a1b80c56073842f3249
687,463
import re def _lookup_key_parse(table_keys): """Return the order in which the stacks should be executed. Args: dependencies (dict): a dictionary where each key should be the fully qualified name of a stack whose value is an array of fully qualified stack names that the stack d...
98f1476e8cd31c974906118fe38e8cc80eadf0d7
687,464
def _calculate_build_timeout(features): """Return maximum allowed time for build (in seconds).""" timeout = 60 if 'mysql' in features: timeout += 60 timeout *= 60 return timeout
710bacd0332b0dc4a1f9a50efe2121c7e7d45b1f
687,465
def calc_checksum(data): """This function does not want the checksum byte in the input data. jeep chrysler canbus checksum from http://illmatics.com/Remote%20Car%20Hacking.pdf """ end_index = len(data) index = 0 checksum = 0xFF temp_chk = 0; bit_sum = 0; if(end_index <= index): return False for...
2c49caf546c82bdedd054acf241064c8174e5f9a
687,466
import io def trim_spaces_and_tabs_from_lines_in_txt(txt: str) -> str: """ This function will remove leading spaces and tabs from lines of text. :param txt: a str containing the text to be cleaned up. :return: a str containing text with all of the leading spaces removed from each line. """ clean...
a935af2954335c4c37b7d75fefcca435d38460b7
687,467
from operator import add def vadd(V1,V2): """ add the components of 2 vectors <div class=jython> VADD (V1, V2) = [ u1+u2, v1+v2 ] </div> """ return add(V1,V2)
5e050c5fb7864194d751faeff7112a2c338e4bfc
687,468
import os import subprocess def segment_image(img_path): """ Segment leaf from an image and create new segmented image file Args: img_path: filesystem path of an image Returns: segmented image file name """ image_name, extension = os.path.splitext(img_path) segmented_image_...
6f56204ac70a3fbd1dd4dca622abb986c64becb8
687,469
def log_mean_exp(ops, x, axis=None, keepdims=False): """ Compute :math:`\\log \\frac{1}{K} \\sum_{k=1}^K \\exp(x_k)`. .. math:: \\begin{align*} \\log \\frac{1}{K} \\sum_{k=1}^K \\exp(x_k) &= \\log \\left[\\exp(x_{max}) \\frac{1}{K} \\sum_{k=1}^K \\ex...
20c76480839839e26dd7cc4cb566da44158a26ee
687,470
def _use_and_del(d, k, v): """ Use a values from a dict and remove it. """ if k in d: v = d[k] del d[k] return v
01cb79df4787402415d21cbb792198b26267406e
687,471
import re def canonical(value): """Replace anything but 'a-z', 'A-Z' and '0-9' with '_'. """ return re.sub(r'[^a-zA-Z0-9]', '_', value)
dfd9b324a9c9ec273750e95a4bd7b1548af37108
687,472
def channel_shuffle(x, groups): """shuffle channels of a 4-D Tensor""" batch_size, channels, height, width = x.size() assert channels % groups == 0 channels_per_group = channels // groups # split into groups x = x.view(batch_size, groups, channels_per_group, height, width) # transpose 1, 2 a...
22d386728fac21c34932d0a64ce169bc7c5540f1
687,473
import click import sys def create_repo_body(repo_type=None, compress=True, concurrent_streams=None, chunk_size=None, max_restore_bytes_per_sec=None, max_snapshot_bytes_per_sec=None, location=None, bucket=None, re...
056e4d5a33e2d69365db621a958c99603e0f7747
687,474
import re def language(text, wtl): """Return language from given text and using the provided language classifier and regex""" words = [ "recomendo", "amei", "entrega", "otim[ao]", "excelente", "rapida", "celular", "gostei", "facil", "lindo", "bonito", "comprei", "legal", "perfume", "preco", "...
8b5ecd781825b3ad7217c144cf70796a6ebde8d3
687,475
import json def readParams(control_file): """Reads a JSON control file for the paramaters. List of parameters: trajectoryFolder : string, folder where the trajectory data is trajectoryBasename : string, names of the trajectory files is numClusters : int, number of clusters to partition...
3d287f59c7939c2801f38a4686daf76c3c60f837
687,476
def operatingexpenses(taxes, insurance, pmi, managementfee, hoafee): """Annual expenses occured through normal cost of business. :param taxes: Annual taxes. :type taxes: double :param insurance: Annual insurance. :type insurance: double :param pmi: Annual pmi payment. :type pmi: double ...
b1b2e5b4e90c62e18c1b8dcbe81027c335c28b9d
687,477
import subprocess def get_version(cmd): """ Returns the compiler version as string. """ lines = subprocess.check_output([cmd, '-v'], stderr=subprocess.STDOUT) return lines.decode('ascii').splitlines()[0]
5cc03c88b03b6ebba883c1269eca1a7de2983a4a
687,478
def getDjangoURLPatterns(params): """Retrieves a list of sidebar entries for this View. Params usage: The params dictionary is passed to the getKeyFieldsPatterns method, see it's docstring on how it is used. django_patterns: The django_patterns value is returned directly if it is non-False. ...
e8e9fbbeed6aeb4dc7f3ea472b7da603efafa9f9
687,479
from typing import Dict from typing import Any import json def parse_json(path: str) -> Dict[str, Any]: """ Parse a json file. Args: path (str): Json file path. Returns: Dict: Dictionary of parsed data. """ with open(path, "r") as stream: return json.load(stream)
b4c1d80aad7427f9f91e6ef26eff95053f509a9b
687,480
import json def find_ground_truth(sim_reads, json_locs): """Counts the raw read counts present in the simulated reads parameters ---------- sim_reads fasta file, contains the simulated reads json_locs bedfile, contains the cluster gene locations returns ---------- ret =...
32c6885186172015956656335a0ad58a58474222
687,481
async def create_simulator(server, egta, name, version): """Create a simulator that's semi configured""" sim = await egta.get_simulator(server.create_simulator( name, version, conf={'key': 'value'})) await sim.add_strategies({ 'a': ['1', '2', '3', '4'], 'b': ['5', '6', '7'], }) ...
cd9e74069878847569c3e27188810600b8fa58f6
687,482
import base64 import six def UrlSafeB64Encode(message): """wrapper of base64.urlsafe_b64encode. Helper method to avoid calling six multiple times for preparing b64 strings. Args: message: string or binary to encode Returns: encoded data in string format. """ data = base64.urlsafe_b64encode(six.e...
7078d3257ebd968dd205dd73395149d22eddc21f
687,483
def mmcc(ds, xs, ys): """Fit a straight line (x, y) = (mx, my) * d + (cx, cy) to ordinates x, y in xs, ys as a function of d in ds.""" assert len(ds) == len(xs) assert len(ds) == len(ys) ds = [float(i) for i in ds] xs = [float(i) for i in xs] ys = [float(i) for i in ys] _d = su...
40d6d718f1e278110ac6fa7c405b63c9b470e5eb
687,484
from typing import Tuple def ego_coordinate_to_world_coordinate( egocentric_x: float, egocentric_y: float, current_location_x: float, current_location_y: float, current_forward_x: float, current_forward_y: float, ) -> Tuple[float, float]: """ :param location_x: The x-component of an eg...
f78065f1dcf3e6c9e989530f14fbb579dd49660e
687,485
def _unique_list(df_col): """Return a list of unique values without NA.""" return list(df_col.unique().dropna())
fac06777d1b7e6abbe7aa8daf491e4171b5ef713
687,486
def get_stripped_data(data): """ Return data after removing unnecessary special character """ for strippable in ("'",'"', '{', '}', '[', ']', '%q',): data = data.replace(strippable, '') return data.strip()
2ee6eb1a445790867e92d2bad5a0a1f829f5f709
687,487
def normalize(text: str) -> str: """Remove whitespace, lowercase, convert spaces to underscores""" return text.strip().lower().replace(' ', '_')
e2e14317e7a2ab66d6f70b362a1d9d6bc445b1ce
687,488
def unique_slug(manager, slug_field, slug): """ Ensure slug is unique for the given manager, appending a digit if it isn't. """ i = 0 while True: if i > 0: if i > 1: slug = slug.rsplit("-", 1)[0] slug = "%s-%s" % (slug, i) if not manager.fi...
247fe133cced76f89ebaf9b06fe3349bf4704e0d
687,489
def AddAuthFieldMask(unused_ref, args, request): """Adds auth-specific fieldmask entries.""" if args.auth_type is None: # Not set, not the 'none' choice return request if request.updateMask: request.updateMask += ',authentication' else: request.updateMask = 'authentication' return request
221ac3287c9f0a85cb1f8ff4a5d2b6241c5e88c6
687,490
import torch def box_convex_hull_tensor(boxes1, boxes2): """ Arguments: boxes1, boxes2 (Tensor[N, 8], Tensor[M, 8]): boxes to compute convex hull area. They are expected to be in (x0, y0, ..., x3, y3) format, where the corners are sorted counterclockwise. Returns: ...
6218550bc77a3aafe40af4e86e5f01fde429468c
687,491
def bdev_error_delete(client, name): """Remove error bdev from the system. Args: bdev_name: name of error bdev to delete """ params = {'name': name} return client.call('bdev_error_delete', params)
299e210739afea99444ad5c5b21655d654868aff
687,492
import logging def loggers(): """get list of all loggers""" root = logging.root existing = root.manager.loggerDict.keys() return [logging.getLogger(name) for name in existing]
f34849e2a4f781070cb0d7114fa7bb203bd7b8f7
687,493
import re import ipaddress def mac2eui64(mac, prefix=None): """Convert a MAC address to a EUI64 address or, with prefix provided, a full IPv6 address.""" # http://tools.ietf.org/html/rfc4291#section-2.5.1 eui64 = re.sub(r"[.:-]", "", mac).lower() eui64 = eui64[0:6] + "fffe" + eui64[6:] eui64 = hex...
c7540da6c21f32237b81bd0c36f5c00385a8e7c2
687,494
def _flip_masks_up_down(masks): """Up-down flip masks. Args: masks: rank 3 float32 tensor with shape [num_instances, height, width] representing instance masks. Returns: flipped masks: rank 3 float32 tensor with shape [num_instances, height, width] representing instance masks. """ return...
d83d2273f4a936c3e1e526af8db78a08e494ca75
687,495
def import_modules_with_check(module_names): """Check if a given set of modules exists.""" success = True failed_modules = [] for module_name in module_names: try: map(__import__, [module_name]) except ImportError: success = False failed_modules.append...
99fe9339df03bd07cefb9b89c9c92567d5ec789e
687,496
def find_cell_index(x, lower, upper, delta): """Find the local index in 1D so that lower + i * delta <= x < lower + (i + 1) * delta. Arguments --------- x : float The target coordinate. """ if x < lower or x >= upper: return None return int((x-lower)//delta)
8087cf7c9fdf2a76265c690caf5d01988cbc934c
687,497
import argparse def create_parser(): """Create the argument parser.""" parser = argparse.ArgumentParser( description="Bridge a serial port over zmq pub/sub" ) parser.add_argument( "--serial-port", dest="serial_port", type=str, default="", help="Set the s...
8d2261aacf308a1e24e00b4fdbad406a0076e785
687,498
import torch def get_scorenet_input(x, idx, k): """(neighbor, neighbor-center)""" batch_size = x.size(0) num_points = x.size(2) x = x.view(batch_size, -1, num_points) device = torch.device('cuda') idx_base = torch.arange(0, batch_size, device=device).view(-1, 1, 1) * num_points idx = id...
54fbb8c4fc96a8caa2db342908ede0a007e8d349
687,499
import requests import json def _get_sid() -> str: """ XHR 监听 sid 需要动态获取sid, 拼接后访问 https://www.jb51.net/article/149738.htm 用轮询获取 sid 用 sid 请求 :return: sid 内容 :rtype: str """ url = "https://sshhbhekjf.jin10.com:9081/socket.io/?EIO=3&transport=polling" r = requests.get(url) d...
b441623a35505f535d7ec12a2e408a1fbf93e7d9
687,500
def if_int_entirely(value): """Фильтр проверки на целое число""" return int(value/2) == float(value/2)
26ec3b3ace6dfd047cb7215d94b8e097de900830
687,501
import re def tamper(payload, **kwargs): """ Replaces greater than operator ('>') with 'NOT BETWEEN 0 AND #' and equals operator ('=') with 'BETWEEN # AND #' Tested against: * Microsoft SQL Server 2005 * MySQL 4, 5.0 and 5.5 * Oracle 10g * PostgreSQL 8.3, 8.4, 9.0 Not...
a660b0a6b1176fd7d7377c50a29ff04620b46b2d
687,502
from typing import List import json def read_geometries(file_geometries: str) -> List[str]: """Read a list of geometries.""" with open(file_geometries, 'r') as f: data = json.load(f) return data
93632ff61f192251abc3ca1e6083dc4347761155
687,503
def extract_annealing_log(log): """ Parses a VPR log line by line. Extracts the table with simulated annealing data. Returns the table header and data line lists as separate. """ # Find a line starting with "# Placement" for i, line in enumerate(log): if line.startswith("# Placement"): ...
ef9c4ca8e907f956efa3dc965237893fd589b684
687,504
def get_subscribed_reports_addresses(location_reports): # workds """returns list of string addresses for given LocationReports""" addresses = [] for lr in location_reports: addresses.append(lr.address) return addresses
e580f607d30ca60d1dec5834c0945631a8508e49
687,505
from typing import Counter def wordle_judge(input_word: str, answer_word: str)-> int: """ Judge input word based on the wordle rule We assume input_word and answer_word are of the same length (but no check is conducted) Judge results are defined as a sequence of {0, 1, 2}, where 2: exact, ...
ebf545f44fe34425d938a4ab09a3418810c244f8
687,506
def kelvtocels(kelvin): """ This function converts kelvin to celsius, with kelvin as parameter.""" celsius = kelvin - 273.15 return celsius
b2ca3f4f4d7cd1125ec42a5ed2d8641378c6f1c1
687,507
def ak_expected(): """ Fixture to create example cosine coefficients """ return [6, -1]
705f580cbc2bd7f1a3e4346385e5ab084032cc6c
687,508
import random def scheme_d_number_random(min_value=0, max_value=255): """Generate list of random integers in a given range Args: min_value (int): Minimum random integer to return max_value (int): Maximum random integer to return Returns: lambda: generates a list of random integer...
35da99001b155d173027316c2b9a76251b52f185
687,510
def is_list_match(item, value): """Check if a item match a value or (if it is a list) if it contains only one item and the item matches the value """ if isinstance(item, list): if len(item) == 1 and item[0] == value: return True else: return False else: ...
12c881ce311ea5237f35810cfe2058988ff11d26
687,511
from typing import List def collatz(number: int) -> List[int]: """Проверка гипотезы Коллатца Подробнее: https://en.wikipedia.org/wiki/Collatz_conjecture Параметры: :param number: число для которого проверяется гипотеза :type number: int :return: Сипсок чисел, соответствующих шагам п...
ee7e08c023d09f6e874aef05e76fc6cad63b3d78
687,512
import torch def expected_sin(x, x_var): """Estimates mean and variance of sin(z), z ~ N(x, var).""" # When the variance is wide, shrink sin towards zero. y = torch.exp(-0.5 * x_var) * torch.sin(x) y_var = (0.5 * (1 - torch.exp(-2 * x_var) * torch.cos(2 * x)) - y**2).clamp(min=0.0) return ...
eb219c8b1d6554e2201d10a0844ee52e7f25c28a
687,513
def choose_unit_from_multiple_time_units_series(time_serie, time_key="seconds"): """Given a time series in the form [(x, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0}), (y, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0}), (z, {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 0...
98f9e57eeeafd951ffc19826573174ff44318fec
687,514
import torch import logging def accuracy(yhat, y, print_scores=False): """ Compute accuracy """ scores = torch.argmax(yhat, dim=1) if print_scores: logging.info(scores) num_correct = torch.sum(scores == y).item() return num_correct/float(len(y))
c136653bccf4b526507dd1f329e07deeffb2555a
687,515
def roll(I_x, S_gross_w, density, velocity, span, Cl_p): """ This calculates the approximate time constant for the roll mode Assumptions: Only the rolling moment equation is needed from the Lateral-Directional equations Sideslip and yaw angle are being neglected and thus set to be zero. ...
4eef01e318884c015837cfd10defb1fe9fa9e8da
687,516
def write_set_userhook(model_name,base_pythia_version): """ Adds a specialised SetHooks class to the PyCollider routines in SetHooks.hpp and getPy8Collider.hpp. """ # Forming the code to write into the getPy8Collider.hpp class towrite = ( '\n' ' /// In the case that th...
6d666ffa45e24d4e7c908728610f624dcf181177
687,517
from typing import List def read_lines_from_file(path: str, strip: bool = False) -> List[str]: """Read file into stripped lines.""" with open(path, "r") as f: lines = f.readlines() if not strip: return lines return list([line.strip() for line in lines])
299466534b9d1646f42b5a3137794bde309f500d
687,519
import os def get_world_size(): """Replace linklink.get_world_size""" return int(os.environ.get('SLURM_NTASKS', 1))
978f2505775073c70ae2a26d5124d852ee8c3ffe
687,520
def read_hc_tape(file_path, order=2): """ read_hc_tape :Read Hilbert Curve command from the table Read Hilbert Curve command from the table in this package. The command including these English alphabet {'o', 'u', 'd', 'l', 'r'} :param file_path: a path of HC table :type file_path: string ...
1ba682abf0f898ea9c2b16d363877af4dd96118f
687,521
def records_match(record, other): """ Test if two records are same SV: check chromosome, position, stop, SVTYPE, SVLEN (for insertions), STRANDS (for BNDS and INVs), and (if they exist) CHR2/END2 for multi-chromosomal events """ return (record.chrom == other.chrom and record.pos == other...
6b041129e77fe69e45b5a81996c05b028b309161
687,522
import torch def from_flattened_numpy(x, shape): """Form a torch tensor with the given `shape` from a flattened numpy array `x`.""" return torch.from_numpy(x.reshape(shape))
3dc8fb7fb0240b82104f1a0fe6d1fa5681a5b2d2
687,523
import html import re def clean_text(s): """Function to remove control characters and escape invalid HTML characters <>&""" if s is None or not s: return None return html.escape(re.sub(r'[\u0000-\u001F\u007F-\u009F]', '', html.unescape(s)))
cd6b0aef78bf02c63605d2a28638e2e0e4f431e0
687,524
def create_bit_mask(data_array, valid_bits, no_data=-9999): """Create a boolean bit mask from a list of valid bits Args: data_array: xarray data array to extract bit information for. valid_bits: array of ints representing what bits should be considered valid. no_data: no_data value for ...
198db8fed64a8c6143f245dc620eb59e711d900f
687,525
def calculate_len_get(headers): """ # Desc : Function to calculate total length of data received for a get request. # Calculated as sum of header length and the content length # Input : Header from a get request # Output: Returns the total length of data received """ sock_header_len = 0 sock_c...
076067efe0e2a68b12ded4bcc4890380434d6e2f
687,526
def test_sub_grids(board: list) -> bool: """ test each of the nine 3x3 sub-grids (also known as blocks) """ sub_grids = [ board[0][0:3] + board[1][0:3] + board[2][0:3], board[0][3:6] + board[1][3:6] + board[2][3:6], board[0][6:] + board[1][6:] + board[2][6:], board[3][0:3] + board[4][0:3] + board[5][0:3]...
7844df3f5e01b04f92b504c8e457393698db2cad
687,527
def get_samples_panfamilies(families, sample2family2presence): """Get the sorted list of all the families present in the samples Can be a subset of the pangenome's set of families""" panfamilies = set() for f in families: for s in sample2family2presence: if sample2family2presence[s][...
2ef12a0bb51e547171a61225333a2ebd91a3e9a2
687,530
def olar(nome='bb'): """Diz olá para o bb!""" return f'Olar {nome}!'
1b7f75e7ab4bab7dd7dc8edef29cf27c018bc064
687,531
def parse_rank_score(rank_score_entry, case_id): """Parse the rank score Args: rank_score_entry(str): The raw rank score entry case_id(str) Returns: rank_score(float) """ rank_score = None if rank_score_entry: for family_info in rank_score_entry.split(","): ...
e8b89593477cfebef331e89ff5addf81e2b8038f
687,532
def str2bool(s): """Convert string to bool for argparse""" if isinstance(s, bool): return s values = { "true": True, "t": True, "yes": True, "y": True, "false": False, "f": False, "no": False, "n": False, } if s.lower() not in ...
9b8c369652dea20181e60c9fb336af280b4e0e8d
687,533