content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import logging def all_transceivers_detected(dut, asic_index, interfaces, xcvr_skip_list): """ Check if transceiver information of all the specified interfaces have been detected. """ cmd = "redis-cli --raw -n 6 keys TRANSCEIVER_INFO\*" asichost = dut.asic_instance(asic_index) docker_cmd = asi...
59b6b8329972f7f262a579faa4c4fd3cf0d16b07
665,726
import pathlib def get_version(rel_path): """Get the version of the library Args: rel_path (str): Relative path to __init__.py with version. Returns: str: Version of library """ for line in pathlib.Path(rel_path).open('r').read().splitlines(): if line.startswith('__version_...
5570a521737aac58bda6ac7a85ce21a5cba8fb44
665,727
def should_be_deactivated(message): """ Determines whether a message stands for an option to be turned off. Args: message(str): A message to test Returns: bool: True if the message is negative, False otherwise """ NEGATIVE_TERMS = ["deactivated", "disabled", "false", "no", "none"...
f0b9bae84fe196c8af58620cb8501dd7f91df64f
665,729
import hmac import hashlib import time def verify_access_token(token, key): """Verify that the given access token is still valid. Returns true if it is, false if it either failed to validate or has expired. A token is a combination of a unix timestamp and a signature""" t = token[:15] signature =...
158ea66dd4f57507336f749b5e2a104450909d21
665,734
def get_fake_context(**config): """Generates a fake context description for testing.""" fake_credential = { "user": "fake_user", "host": "fake_host", "port": -1, "key": "fake_key", "password": "fake_password", } return { "task": { "uuid": "fa...
e8484b13aad2f10f060bf928d4928100fd141475
665,741
def expand_window(data, window_set=1): """ :param data: the original list :param window_set: int or list of int :return: a list of lists shifted by the bias which is specified by window_set """ if isinstance(window_set, int): window_set = [window_set] window_list = [] for bias in...
191736346c536443b938382a49f3f80911b73549
665,743
def dirname(path): """Return the directory portion of a file path.""" if path == "/": return "/" parts = path.split("/") if len(parts) > 1: return "/".join(parts[:-1]) return "."
8ae910d8a8ee5a213b75b404355e2155a70b8bff
665,746
import functools def drain(predicate=lambda x: True): """ Drains a generator function into a list, optionally filtering using predicate """ def wrapper(func): @functools.wraps(func) def inner(*args, **kwargs) -> list: return [x for x in func(*args, **kwargs) if predicate(x...
4d9b5505b168b4caa28c3efe474bf9f25e714f3d
665,747
import pathlib def sanitize_path(path): """Sanitize a path. Returns a pathlib.PurePath object. If a path string is given, a PurePath object will be returned. All relative paths will be converted to absolute paths. """ pure_path = pathlib.Path(path).resolve() return pure_path
3a34af2bcea83172047217ebc8274aac38a55d8a
665,748
import time def server_time(request): """ Includes the server time as a millisecond accuracy timestamp """ return {"server_time": int(round(time.time() * 1000))}
171cfae6ad9ae214bac17fc3dbff25738cae9067
665,750
def clearsky(three_days_hourly, albuquerque): """Clearsky at `three_days_hourly` in `albuquerque`.""" return albuquerque.get_clearsky( three_days_hourly, model='simplified_solis' )
9068bed1de581cca9794047b1b7c033a23633950
665,751
import requests def object_store_change_ownership(api_key, object_type, object_id, owner_id): """ Changes the ownership of an object (Extractor or Crawl Run) in the object store. NOTE: The API KEY must be from an account that has SUPPORT role :param api_key: Import.io API Key :param object_type: S...
89ee3e1b0a5823cd1e433b6c0e1029426b9e6f74
665,763
def lower_clean_string(string): """ Function used to make string lowercase filter out punctuation :param string: Text string to strip clean and make lower case. :return: String in lowercase with all punctuation stripped. """ punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~[\n]' lowercase_...
27d7331215e513efad61d695ae5198a6dfd10cd3
665,766
def find_first_common_ancestor(node1, node2): """ Find the first common ancestor for two nodes in the same tree. Parameters ---------- node1 : nltk.tree.ParentedTree The first node. node2 : nltk.tree.ParentedTree The second node. Returns ------- ancestor_node : nltk...
37748766c76e3fd1d2b1f15202637536147a7a5c
665,770
async def get_hmms_referenced_in_db(db) -> set: """ Returns a set of all HMM ids referenced in NuVs analysis documents :param db: the application database object :return: set of all HMM ids referenced in analysis documents """ cursor = db.analyses.aggregate([ {"$match": { "...
aca44ad11eaff0c734503701f943cb8394db15a5
665,772
import asyncio async def call(args, *, cwd, env=None, shell=False): """ Similar to subprocess.call but adapted for asyncio. Please add new arguments as needed. cwd is added as an explicit argument because asyncio will not work well with os.chdir, which is not bound to the context of the running corout...
63063b8d9577287bcd5ad3a934899354c2a70cf0
665,773
def _pad_data(data: bytes, n: int = 16) -> bytes: """ Adds padding to the data according to the PKCS7 standard. Note that at least one byte of padding is guaranteed to be added. :param data: the data to pad :param n: the length to pad the data to, defaults to 16 :return: the padded data """ ...
c4241816fca3e180f793e464e36d7931aa3eb23f
665,778
def add_segment_final_space(segments): """ >>> segments = ['Hi there!', 'Here... ', 'My name is Peter. '] >>> add_segment_final_space(segments) ['Hi there! ', 'Here... ', 'My name is Peter.'] """ r = [] for segment in segments[:-1]: r.append(segment.rstrip()+' ') r.append(segment...
6593cbd325cac7a102ec21a7bfc16e22e74dc31f
665,780
def construct_publish_comands(additional_steps=None): """Get the shell commands we'll use to actually build and publish a package to PyPI. Returns: List[str]: List of shell commands needed to publish a module. """ return (additional_steps or []) + [ "python setup.py sdist bdist_wheel",...
ec1a1512e47a9839ea9d23ba7c23a44485a2c503
665,781
def n_lexemes_for_lemma(conn, language_code, lemma) -> int: """Get the number of dictionary entries with ``lemma`` as headword. :param conn: The database connection for the dictionary. :param str language_code: ISO 639-3 language code of the language of interest. :param lemma: A dictionary that con...
9b66d78931921127afa5d0739d86f00d649f9b21
665,785
def _get_binary_op_bcast_shape(lhs_shape, rhs_shape): """Get the shape after binary broadcasting. We will strictly follow the broadcasting rule in numpy. Parameters ---------- lhs_shape : tuple rhs_shape : tuple Returns ------- ret_shape : tuple """ ret_shape = [] if l...
2461caa4a720bf178f0aef85d74ca783db6e6cce
665,786
def _sort_key_max_confidence_sd(sample, labels): """Samples sort key by the maximum confidence_sd.""" max_confidence_sd = float("-inf") for inference in sample["inferences"]: if labels and inference["label"] not in labels: continue confidence_sd = inference.get("confidence_sd", f...
f0be3921c40edbe7648c580874424b065b0c1dde
665,789
def reassemble_addresses(seq): """Takes a sequence of strings and combines any sub-sequence that looks like an IPv4 address into a single string. Example: ['listener', '0', '0', '0', '0_80', downstream_cx_total'] -> ['listener', '0.0.0.0:80', 'downstream_cx_total'] """ reassembled =...
93395113428c5d905917593f59c6bf2b3361b506
665,792
import operator def best_assembly(assembly_list): """Based on assembly summaries find the one with the highest scaffold N50""" if assembly_list: return sorted(assembly_list, key=operator.itemgetter('scaffoldn50'))[-1]
44aab301c2eba9c8caa24134a4f75606d2eb0d54
665,794
import math def compute_distance(x1, y1, x2, y2): """Compute the distance between 2 points. Parameters ---------- x1 : float x coordinate of the first point. y1 : float y coordinate of the first point. x2 : float x coordinate of the second point. y2 : float ...
38cbf3ee7c94daf7b241b8907328b971fc3eea49
665,795
def get_version_integer(version): """Get an integer of the OGC version value x.y.z""" if version is not None: # split and make integer xyz = version.split('.') if len(xyz) != 3: return -1 try: return int(xyz[0]) * 10000 + int(xyz[1]) * 100 + int(xyz[2]) e...
a371a43bff4977fbdf068a0b1801c61b3b6c8b22
665,796
import requests def download(url: str) -> bytes: """ Download a file from the internet using a GET request. If it fails for any reason, an exception is raised. For more complicated behavior, use an HttpAgent object. Returns the bytes of the downloaded object. """ resp = requests.get(url, stream=True) if not...
b36925edb5ad79ffcc412ab09dd096662e15761c
665,798
def _get_headers(data): """ get headers from data :param data: parsed message :return: headers """ headers = {} data = str(data, encoding="utf-8") header_str, body = data.split("\r\n\r\n", 1) header_list = header_str.split("\r\n") headers['method'], headers['protocol'] = header_l...
58aaca44ef84d73c0ab0bdbedfbe9697a27f2576
665,800
def convertFromRavenComment(msg): """ Converts fake comment nodes back into real comments @ In, msg, converted file contents as a string (with line seperators) @ Out, string, string contents of a file """ msg=msg.replace('<ravenTEMPcomment>','<!--') msg=msg.replace('</ravenTEMPcomment>','-->') ret...
ac7f8495471ce491889799961163b584518c0fed
665,803
def text_objects(text, font, color, pos): """Return text surface and rect""" text_surface = font.render(text, True, color) text_rect = text_surface.get_rect(center=pos) return text_surface, text_rect
f51a15805383b9d013e98b5913122517bc090d7c
665,806
def hms2deg(h, m, s): """Convert from hour, minutes, seconds to degrees Args: h (int) m (int) s (float) Return: float """ return h * 360 / 24 + m / 60.0 + s / 3600.0
e231896ad56d8c7be6ebaea5f5379b00d32464c3
665,807
def missing_char(str_: str, n: int) -> str: """Remove character at index n.""" return f'{str_[:n]}{str_[n+1:]}'
d3705835e07d83429a9103d6c7fce49ee19451fb
665,810
import math def f_slow(X): """ slow function """ a = X[0] b = X[1] c = X[2] s = 0 for i in range(10000): s += math.sin(a * i) + math.sin(b * i) + math.cos(c * i) return s
b271c782e05bc3430ce17d4ca6323356dfe914b4
665,816
import json def get_pg_params(json_file): """ Takes the path to the json file specifying database connection information and returns formatted information. Parameters ---------- json_file : 'str' The path to the json file specifying database connection information. Returns...
b0097b2201962b4bc2d516a919459459a5afdbdc
665,819
from typing import OrderedDict def update_src_dict(key, item_dict, src_dict=None): """ updates existing or non existing src dict with key values of item dict @param key: search key in item dict @type key: str @param item_dict: the dictionary to search for key @type item_dict: dict @param ...
b22683fa2c7f2f3958a200be3c3d4bd1bdd4ce88
665,820
def str_format(text, data, enc_char): """This takes a text template, and formats the encapsulated occurences with data keys Example: if text = 'My name is $$name$$', provided data = 'Bob' and enc_char = '$$'. the returned text will be 'My name is Bob'. """ for key in data: val = data[key] text = tex...
207024659439a6f1fb920312d7256fc107ebd97a
665,821
def factorial(n: int) -> int: """Return n! (0! is 1).""" if n <= 1: return 1 result = 2 for x in range(3, n + 1): result *= x return result
8e4139bb5a227ddfbd46164e6fb0f092fdd8dfcd
665,823
def inherited_branches(bases): """Returns a dictionary of combined branches for all the given bases. Bases are evaluated in reverse order (right to left), mimicking Python's method resolution order. This means that branches defined on multiple bases will take the value from the leftmost base. """ ...
28b20ca471736361e03b38d9e1e2f8d5246be0f3
665,826
def massage_link(linkstring): """Don't allow html in the link string. Prepend http:// if there isn't already a protocol.""" for c in "<>'\"": linkstring = linkstring.replace(c, '') if linkstring and linkstring.find(':') == -1: linkstring = 'http://' + linkstring return linkstring
e624ba8ce489f3a9c82430e1d3ef1af820ba113a
665,828
def construct_instance_market_options(instancemarket, spotinterruptionbehavior, spotmaxprice): """ construct the dictionary necessary to configure instance market selection (on-demand vs spot) See: https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances ...
03daf402bfbd5e0f2d39c56f39e15441fd03a2b1
665,829
def tau_column(tau, k, j): """ Determine the column index for the non-zero elements of the matrix for a particular row `k` and the value of `j` from the Dicke space. Parameters ---------- tau: str The tau function to check for this `k` and `j`. k: int The row of the matrix ...
26e390f4d8c3d13d57e4cb470b3169e493eb3915
665,830
from pathlib import Path def configure_output_dir(output_dir: str): """ Create a directory (recursively) and ignore errors if they already exist. :param output_dir: path to the output directory :return: output_path """ output_path = Path(output_dir) output_path.mkdir(parents=True, exist_o...
e5bc9b176cade54a99bc6bdc9e3da4f240e37307
665,831
def simple_transfer(type, file_path, out_path=None): """ simple_transfer [summary] Args: type (str): File's encoding type file_path (str): Path to the file out_path (str, optional): Path to the output file. Defaults to None. Returns: [bool]: whether transfer the encoding type successfully. """ with ope...
d6ddb1beed83e8082415379bf9ff9f0811461897
665,832
import plistlib import xml def read_manifest_plist(path): """Given a path to a ProfileCreator manifest plist, return the contents of the plist.""" with open(path, "rb") as openfile: try: return plistlib.load(openfile) except xml.parsers.expat.ExpatError: print("Erro...
d9710b9bdf38af10a285f06e714692938ea5306d
665,834
import six def get_dict_from_output(output): """Parse list of dictionaries, return a dictionary. :param output: list of dictionaries """ obj = {} for item in output: obj[item['Property']] = six.text_type(item['Value']) return obj
a71fe78f131887e35ccea1406da93b0d15bf73d2
665,839
import torch def pack_tensors(tensors, use_cuda=False): """ Packs a list of tensors into one 1-dimensional tensor. Args: tensors (list[torch.Tensor]): The tensors to pack use_cuda (bool): Whether the resulting tensor should be on cuda Returns: (torch.Tensor, list[int], list[(...
c5656c701a4eeeb0920471bc9831b1b284034441
665,842
def SFR(z): """ returns the cosmic star formation rate in M_\odot/yr/Mpc^3 following Strolger+15""" A = 0.015 #M_\odot/yr/Mpc^3 B = 1.5 C = 5.0 D = 6.1 return A*(1+z)**C/( ((1+z)/B)**D + 1 )
5736e3034fb4d1da8b69e40f1926209f184df52a
665,848
def private_repo_count(self): """count of private repositories of `org`""" return len(self.get_repos('private'))
e6d1a66d17cf862574e1a223ebb119b4614c5abb
665,852
def dobra(x): """ Dobra o valor da entrada Parâmetros ---------- x : número O valor a ser dobrado Retorno ------- número O dobro da entrada """ return 2*x
00431c5fb8a1ab056252b5d8389868f71c872c62
665,853
def get_called_variants(var_list, cn_prob_processed, starting_index=0): """ Return called variants based on called copy number and list of variant names """ total_callset = [] if starting_index != 0: assert len(var_list) == len(cn_prob_processed) + starting_index for i, cn_called in enum...
46e6dbce20d9e004872999bee220558d4446ac8d
665,854
def add_deviations_from_sample_mean(data): """ Adds columns in which [profitability, inv_rate] are demeaned at the firm-level and then the full-sample mean is added again. Args ---- data (pandas.DataFrame): dataframe with 4 columns: firm, year, profitability, inv_rate Returns ---...
0eda4c5526e238b80fc9eabb4a071f410f1af103
665,855
def get_normal_vector(hkl, Astar): """ Get normal vector to real-space Miller plane, hkl. Note ---- The normal vector to a real-space Miller plane is collinear with the reciprocal dHKL vector. As such, we can use this simpler formula in the reciprocal lattice basis to get the c...
34cf8f02acfb6c88f92022831f5e310221977b46
665,856
from datetime import datetime def get_alert_values(root): """Finds important alert info, returned in this order: 1. Alert header 2. Alert type 3. Alert status 4. Alert confidence 5. Alert latitude (of radiative center) 6. Alert longitude (of radiative center) 7. Alert date and time (da...
c6b54a42f8ad4ec79d990e7b8139b7f3ea8bdef6
665,859
def convert_types(type_dict): """ Check dictionary on nested dictionaries, convert it into one dictionary without nested dictionaries :param type_dict: dictionary that can contain nested dictionaries :type: dict :return: dictionary contained data from type_dict without nested dictionary in it ...
6291244ed1eb1062fe8e3fc5662f0a8676c434ff
665,866
def host_data(fqdn): """ Splits input FQDN to usable elements: domain_attr = { "fqdn": "name.example.com", "domain": "example.com", "host": "name", } Takes into account multiple subdomains (i.e., name1.name2.example.com). """ hosts = fqdn.split(".") domain_at...
ca6c4ac77a42070ba6740c0eefaf703e1dbdca30
665,869
def manhattan_distance(pos1, pos2): """Returns manhattan distance between two points in (x, y) format""" return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
c239e75605088c6a061c5c25b1b47676ccd619ae
665,871
def is_linear_perpetual(trading_pair: str) -> bool: """ Returns True if trading_pair is in USDT(Linear) Perpetual """ _, quote_asset = trading_pair.split("-") return quote_asset == "USDT"
945029d75191056172cceeb8304a3461e4e704c4
665,874
def _f2r(v, depth): """\ _f2r(floatval,depth) -> (numerator, denominator) Generates a rational fraction representation of a *positive* floating point value using the continuous fractions technique to the specified depth. Used rational() in preference, to get the most optional match. This function ...
e3986b608a949d1b60a834fc56b53ec21b32af6e
665,875
def tableName(line): """ Generate the name of the table. """ words = line.split() tableNum = words[1].replace(":", "") tname = "Table" + tableNum for w in words[2:]: tname += "-" + w tname += ".csv" return tname
5626704fe2fd1e8ba28c7c22292a9a4a1c0618a2
665,878
def validate_parameters(params): """Validate event counter parameters and return an error, if any.""" # Sanitize input to correct numeric types for key in ('start_year', 'end_year'): if params.get(key): try: params[key] = int(params[key]) except ValueError: return "%s must be an in...
693d0974d95abc6a8067700fc709aaddde19b7d9
665,879
from datetime import datetime def to_datetime(datetime_str: str, sep: str = ":") -> datetime: """Convert datetime formatted string to datetime object. Arguments: --- datetime_str: datetime value in string sep: separator for time in datetime string returns: --- return datetime objec...
b31ef7a8d4d679e193a2786ae8c0c2861746acdc
665,880
def w_binary_to_hex(word): """Converts binary word to hex (word is a list) >>> w_binary_to_hex("111") '0x7' >>> w_binary_to_hex([1,1,1,1]) '0xf' >>> w_binary_to_hex([0,0,0,0,1,1,1,1]) '0xf' >>> w_binary_to_hex([0,1,1,1,1,1,0,0]) '0x7c' """ if isinstance(word, str): ...
1fd5c6f84e8a19ee16dc191f333d46202f2049a2
665,882
import logging import json def connect_and_get_output(device): """ Helper function which get LLDP data from specified device Positional argument: - device -- NAPALM driver object Returns: - json_output -- LLDP device data serialized to JSON """ try: device.open() outp...
41403b46728f63ac34d7c8f42f8e3bd076d20ddf
665,883
def denormalize(features, mean, std): """ Normalizes features with the specificed mean and std """ return features * std + mean
e17006012ab61f056e2094cb973b1f98bb31d359
665,885
def num_sections(course: tuple[str, str, set]) -> int: """Return the number of sections for the given course. Preconditions: - The input matches the format for a course described by the assignment handout. """ return len(course[2])
bc0120a451ea2c771b20e65224e3dacce47bba2d
665,886
def _sort_circle(the_dict): """ Each item in the dictionary has a list. Return a new dict with each of those lists sorted by key. """ new_dict = {} for k, v in the_dict.items(): new_dict[k] = sorted(v) return new_dict
0491dad0ff05e03b9775ccb5b9774e53b5960761
665,887
def make_anchor(type): """Takes a type name in CamelCase and returns the label (anchor) equivalent which is all lower case, as the labels Sphinx generates for headers. """ return type.lower()
b88d615a904ca9cecc64287f48fae7072deb7965
665,888
import pickle def read_data(infile): """Read data array. Args: infile (str): path to file Returns: np.ndarray: numpy arrays for features and labels """ print(f'Reading data from {infile}') with open(infile, 'rb') as f_read: obj = pickle.load(f_read) array_ordered ...
89b3ef2b081701789e3cfe6f33559078b5cadfee
665,896
def load_input_data(input_path, do_lowercase): """Load input data.""" examples = [] lc = 0 with open(input_path, "r") as f: for line in f: lc += 1 line_split = line.strip().split("\t") print(line_split) if len(line_split) != 2: raise Exception("Each line is expect to only hav...
32ba298b930db730634c7853db06e9dddbfc122f
665,899
def get_controller_index_by_typename(net, typename, idx=[], case_sensitive=False): """ Returns controller indices of a given name of type as list. """ idx = idx if len(idx) else net.controller.index if case_sensitive: return [i for i in idx if str(net.controller.object.at[i]).split(" ")[0] =...
0ec63ed37114be6b764dc2de880a98c313ad0df5
665,900
def cap(v, l): """Shortens string is above certain length.""" s = str(v) return s if len(s) <= l else s[-l:]
8683d647f12aaf82880df8fe2f373a19ad24c674
665,902
import sqlite3 def openDatabase(file,inMemory=False): """Open SQLite db and return tuple (connection,cursor)""" if inMemory==True: conn=sqlite3.connect(':memory:') else: conn=sqlite3.connect(file) conn.row_factory = sqlite3.Row cursor=conn.cursor() return (conn,cursor)
5982508d8240c276a91d6118180b869d9e90de52
665,904
from typing import Any def __wrap_boolean_value(value: Any) -> str: """ If `value` is Python's native True, returns 'true'. If `value` is Python's native False, returns 'false'. Otherwise returns 'null'. """ if value is True: return 'true' if value is False: return 'false' ...
ef21b91d533e7d0d47cd2d1acb5a170d10a99779
665,906
from datetime import datetime def datetime_helper( datetime_str ): """try to convert datetime for comparison Args: datetime_str (str): datetime str (%Y-%m-%d) or (%Y-%m-%dT%H:%M:S) Returns: datetime.datetime """ try: return_datetime = datetime.strptime(datetime_s...
b38988e5d64289197ecfe98537340ad91ef45874
665,908
def merge_lists(*lists): """Merges the given lists, ignoring duplicate entries. Args: *lists: lists of strings to merge Returns: A list of strings """ result = {} for x in lists: for elem in x: result[elem] = 1 return result.keys()
9d10de0f9ed07a6afd593979e4756ead017ae54b
665,909
def sqr(x): """Return the square of x. """ return x*x
de543fbf626b2837781d7606c02147ddc8924af9
665,912
import asyncio async def gather_with_concurrency(n, *tasks): """ Execute tasks concurrently with a max amount of tasks running at the same time. Retrieved from https://stackoverflow.com/a/61478547/7868972. """ semaphore = asyncio.Semaphore(n) async def sem_task(task): async with semap...
c3241909b37d965391ad4a3e5809368a50544dd2
665,914
import functools import warnings def deprecated(msg=""): """Decorator factory to mark functions as deprecated with given message. >>> @deprecated("Enough!") ... def some_function(): ... "I just print 'hello world'." ... print("hello world") >>> some_function() hello world >>> so...
9617d6a8e5448f324b9f557e902c6e51c3f66a57
665,915
import torch def l1norm(X, dim, eps=1e-8): """L1-normalize columns of X""" norm = torch.abs(X).sum(dim=dim, keepdim=True) + eps X = torch.div(X, norm) return X
6e3e9796f97403a4bf1513c8738ad343a2481392
665,916
def s2_index_to_band_id(band_index): """s2_index_toBand_id returns the band_id from the band index :param band_index: band index (0-12 inclusive) referencing sensors in ESA's metadata :return: band_id for the band_index """ return { 0: '1', 1: '2', 2: '3', 3: '4', 4: '5', 5: '6', 6: '7', ...
8e79e3f6c162656f7884feb0eeb8aa5e8d5055dd
665,928
def ppm_to_dalton(mass:float, prec_tol:int)->float: """Function to convert ppm tolerances to Dalton. Args: mass (float): Base mass. prec_tol (int): Tolerance. Returns: float: Tolerance in Dalton. """ return mass / 1e6 * prec_tol
384eee4cf267dcd1ada8011bba70191ee2715c8e
665,929
def listsplit(liststr=u''): """Return a split and stripped list.""" ret = [] for e in liststr.split(u','): ret.append(e.strip()) return ret
1619917aeb57b1245e321dd48d2d32db5e2a3824
665,932
def matrix_matrix_product(A, B): """Compute the matrix-matrix product AB as a list of lists.""" m, n, p = len(A), len(B), len(B[0]) return [[sum([A[i][k] * B[k][j] for k in range(n)]) for j in range(p) ] for i in range(m) ]
ac4657df9efaf3bf903e818dfdef118590349300
665,936
def raw_input_default(prompt, default=None): """prompts the user for a string, proposing a default value in brackets.""" if default: prompt = "%s [%s]: " % (prompt, default) res = input(prompt) if not res and default: return default return res
801dc3b3e8a5d54cb9a500461d9296650f2c4e22
665,937
def lls_predict(A, X): """Given X and A, compute predicted value Y = A.T@X """ if X.ndim == 1: return A * X else: return A.T @ X
d70dfba5bb5c911382efc373ac0a4b405c1490ea
665,938
def md_headline(title, level): """ Format a markdown header line based on the level argument """ level_char_list = ['=', '-'] try: level_char = level_char_list[level] except IndexError: level_char = '=' return '\n%s\n%s\n' % (title, (level_char * len(title)))
25ae97fbee0d356dbffca268b4a7f5fec67631f2
665,940
def get_issue_info(payload): """Extract all information we need when handling webhooks for issues.""" # Extract the title and the body title = payload.get('issue')['title'] # Create the issue dictionary return {'action': payload.get('action'), 'number': payload.get('issue')['number'], ...
fd3836a94dbd93a387cd9d38b81c37c2a73be4ba
665,942
from typing import Type from enum import Enum from typing import List def enum_values(enum_cls: Type[Enum]) -> List: """List enum values.""" return [v.value for v in enum_cls]
6ca7856af9abfbeae8bbdf7dec10db0b238f8e63
665,951
def get_txtfilename(ID, era): """ Return the txtfilename given by station ID and era in correct format.""" return era+'_'+ID+'.txt'
54497cf696b543a3d1b4da66c2adaea2cc23e078
665,954
def popcount(n=0): """ Computes the popcount (binary Hamming weight) of integer `n`. Arguments --------- n : a base-10 integer Returns ------- int Popcount (binary Hamming weight) of `n` """ return bin(n).count('1')
fb44bbae77e0223196e2eb1352f3126605510bfb
665,956
from typing import Tuple def get_neighbors( cell: Tuple[int, int], shape: Tuple[int, int, int], with_start_position: bool = False, ): """ :param cell: :param shape: :param with_start_position :return: The neighbor cells of the given cell, respecting the map shape """ p, q = sha...
613638d13d0a3dd9b4b2e2dd8f03b232fb47f85c
665,960
import xmltodict def gen_query(search_ligand, search_protein=None, querymode=None): """ Args: search_ligand: the Chem_ID of the FDA-approved inhibitor of interest search_protein: UniProt Accession ID for the approved target for the inhibitor querymode: string indicating whether searchi...
4a70162f61bed0818cea7029aed71e178d55e1d1
665,961
def hamming_distance(str1, str2): """ Computes the number of different characters in the same position for two given strings. Typically the inputs are binary, but it needs not be the case. Parameters: ---------- str1: str str2: str Returns: ------- int: hamming distance Exampl...
6c487d875c0a6a9ca87e45a6f9b7d944af2b1d4a
665,962
import torch def regulate_len(durations, enc_out, pace=1.0, mel_max_len=None): """A function that takes predicted durations per encoded token, and repeats enc_out according to the duration. NOTE: durations.shape[1] == enc_out.shape[1] Args: durations (torch.tensor): A tensor of shape (batch x enc...
cfe975c3f9e2580421584421c0667e153833df54
665,964
def mix_targets(preds, targets, target_name1, target_name2, weight1=0.5, weight2=0.5, skip_missing=False, new_name=None): """ Linearly combines two targets into one, optionally with custom weights, storing it under the name of the first one, unless `new_name` is given. `weight1` and `wei...
048341c365cc7166027e3aa46f805c14d233c227
665,966
def ext2str(ext, compact=False, default_extver=1): """ Return a string representation of an extension specification. Parameters ---------- ext : tuple, int, str Extension specification can be a tuple of the form (str,int), e.g., ('sci',1), an integer (extension number), or a string ...
845a20832765f4c82357e7555c44f37cc0659393
665,968
def way(routing, start, end): """Return the route from the start to the end as a list""" route = [] current_node = end while current_node != start: route.insert(0, current_node) current_node = routing[current_node] return route
924d5546db62aa799eb7bcf62acb6452d49f1caa
665,970
def parse_info_cfg(filename): """ Extracts information contained in the Info.cfg file given as input. :param filename: path/to/patient/folder/Info.cfg :return: values for: ed, es, group, h, nf, w """ ed, es, group, h, nf, w = None, None, None, None, None, None with open(filename, 'r') as f: ...
92769fc607c925c86a1d52802de31227c17123c9
665,974
import math def safe_is_nan(x): """Is the value NaN (not a number). Returns True for np.nan and nan python float. Returns False for anything else, including None and non-numeric types. Called safe because it won't raise a TypeError for non-numerics. Args: x: Object to check for NaN. ...
2371352b9975c22130ecba83ea738b0e35ee07ac
665,977
def c_to_k(temp): """ Converts Celsius to Kelvin. """ return temp + 273.15
1d52f9989fd4ea0eec59041e98993018c54ec31d
665,981