content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Any from typing import List def convert_list(x: Any) -> List: """Convert int / float to list. Parameters ---------- x : Any Input to convert. Returns ------- x : Iterable Converted value. """ if isinstance(x, (int, float)): return [x] ...
a57491daefb5f0b7fdd5628130e810bff3c76d9e
613,982
def get_db_access_token(db, user_id): """Get the OAuth access token for the specified user""" row = db.execute("SELECT access_token FROM users WHERE id = ?", [user_id]).fetchone() return None if row is None else row[0]
d812ba589f5454a845ad9eb716d94a3e3d4058a8
613,990
def _extract_n_bits(value: int, num_bits: int) -> int: """Extracts n bits from a number""" limit_bit = 1 << num_bits result = value & (limit_bit - 1) if value >= limit_bit: result |= limit_bit return result
7757d2530fd04e55f61c1983c48603ba85a1f338
613,993
import six def is_string_type(value): """ 判断value是否字符类型,兼容python2、python3 :param value: 输入值 :type value: any :returns: 判断结果 :rtype: bool """ if six.PY3: return isinstance(value, (str, bytes))
c76d6088c14e02812472839e720eb0d06cbeb4c0
613,996
def state(s: int) -> int: """Get the index of compressed fish from the living state of fish.""" return s + 1
ca2fb8b3d17525b851300818cedaca6e45e72351
614,004
import ntpath def get_log_file_name(myfile): """ This function obtains the name of file without filename extension """ path, filename = ntpath.split(myfile) name = str(filename.split(".")[0]) #remove .log return name
604fe6c9afefd899e4ceb972c7a0d0b1692396fb
614,008
def get_custom_param_value(content_dict, param_key, default_value='null'): """ Looks through a content_dict's custom params and returns the value of the given key or default_value if not found """ value = None for entry in content_dict['programmed_custom_params']: if entry['key'] == para...
807a60f6f3429955682f870d2a18e032a20c33e1
614,011
def try_int(num_string): """ short hand cast to number :param num_string: :return: int or None """ if num_string is not None: try: return int(num_string) except ValueError: pass return None
d97482dc3180ec061082f1515016d135639b7800
614,012
def itofm(i): """Converts midi interval to frequency multiplier.""" return 2 ** (i / 12.0)
eea7e26e63b5b8e56af41b34444440ebe5b2b4bb
614,015
import random def random_choice(sequence): """Return a random element from the non-empty sequence.""" return random.SystemRandom().choice(sequence)
942e9e2a7967a02863c76c84b2a2b6228fad35b0
614,016
def coor(n,a,b): """ Calculates a list of coordinates using a for loop Parameters ---------- n: integer number of coordinates to use between endpoints a: float starting point b: float ending point Returns ------- coordinates: ...
31a3531ef964906e775daf6a70d4dda2558ec655
614,018
def get_aspect(image, base_scale=10): """ Generate suitable plot resolution based on image or network output dimensions :param image: any 2+ dimensional shape :param base_scale: base scale to generate image aspect :return: aspect ratio for plots """ ratio = float(image.shape[0])/float(image...
d71b157e99d74367072dd4c01e98ebd321c1d26b
614,020
def find_commit_in_prs(needle, commit_data, prs): """Finds the commit `needle` PR in the commit_data dictionary If found, returns the pr the needle commit is in. If the commit was not part of the PRs in the dictionary, returns None. """ for pr_id in commit_data: commits = commit_data[pr_id]...
1d79e810fbe0118dff5c9b75cbd894fc0ef58b49
614,022
import random def getinsight(arn, action, count): """ Calculates insight for CloudTrail tuple <<UserIdentity -> arn, eventName, Count of EventName> :param arn: CloudTrail UserIdentity -> arn :param action: CloudTrail eventName :param count: Count of eventName aggregated by ProactiveExploratio...
ca70a194f828d78307172a42dc8119c6c98bd4b1
614,024
def K_wall_discretization_error(dt, dx, n_c): """ Best fit to error ratio of thermal conductivity for finite dt, dx, n_c. Parameters: dt: normalized timestep dx: normalized cell size n_c: particles per cell Returns: K_wall(dt, dx, n_c) / K(0, 0, infty) Rader, D...
cb8f9ef92d906e991cd4a80f9e00565882d83cc5
614,025
def _is_empty_axes(ax): """Return if axes is empty.""" return ( not any([ ax.lines, ax.collections, ax.patches, ax.texts, ax.images, ]) )
90a976d6d3cc0f651d00a8dc9afe7441aefd1336
614,027
def difference(a, b): """ returns what's in b and not in a """ return [item for item in b if not item in a]
12582532547668a6091535caf265c896b233ae61
614,028
def keyfunc(ekey): """ Extract the name before the colons: >>> keyfunc(('agg_loss_table', 'csv')) ('agg_loss_table', 'csv') >>> keyfunc(('agg_loss_table/1', 'csv')) ('agg_loss_table', 'csv') >>> keyfunc(('agg_loss_table/1/0', 'csv')) ('agg_loss_table', 'csv') """ fullname, ext =...
63a7e0d2f815eacaa80cac6028daea843bd6956d
614,031
def getAlias(column, alias = ''): """ Composes an alias for the column specified. """ if alias: return column + ' AS ' + alias return column
98ead822b60d567d1f17d401c2c9800a86f00adf
614,034
def letter_check(letter_guessed, guessed_letters): """ letter_guessed: string, letter user have just guessed guessed_letters: list, with all letters user have used return: boolean, True if letter_guessed already exists in guessed_letters otherwise False """ if letter_guessed in guessed_letters: ...
fa2322c4f156edbb503f44848cab0a2f94169035
614,037
def simulate_multiline(string): """Return simulated multiline input for given string.""" counter = 0 strings = string.split("\n") def simulated_input(*args): nonlocal counter if counter == len(strings): return "" value = strings[counter] counter += 1 ...
06e9f2b73e736809ad2569bf44c8b36fa2c6bfc7
614,039
def _tup_mult(t1, t2): """Multiply tuples :t1: Tuple 1 :t2: Tuple 2 :returns: Tuple sum """ return (t1[0]*t2[0],t1[1]*t2[1])
6d734f9f9feea1c229c32ef41cf4df2fe1338045
614,040
def transform_output_arg(dir: str) -> str: """ Build youtube-dl '--output' option from directory selected by user. """ dir = dir.strip('"') return rf'{dir}\%(title)s.%(ext)s'
74fbae940c47253dbe55c3262e7bb68d4e06e85a
614,041
def remove_underline(params): """Remove the underline in reserved words. The parameters def and type are python reserved words so it is necessary to add a underline to use this words, this method remove the underline before make a http request. Args: params (dict): Url query parameters. ...
18350abc8284c529de78ec871c25bc0d3908f42b
614,042
from typing import Any def logging_filter_log_records_for_chat(record: Any) -> bool: """Filters log records suitable for interactive chat.""" return ( record.msg.startswith("decoded") or record.msg.startswith(" ->") or record.msg.startswith("Restoring parameters from") )
fae587aa8a6985667a24429db618da0b93743882
614,044
def wavelen2wavenum(l): """Converts from wavelength in nm to wavenumber in cm^-1""" return 1 / l * 1.0e7
b86297fba698ec69e819e5b2fd9a318728069401
614,051
import sympy def symequal(a, b): """Check if two symbolic numbers or vectors are equal.""" if isinstance(a, (list, tuple)): for i, j in zip(a, b): if not symequal(i, j): return False return True return sympy.expand(sympy.simplify(a)) == sympy.expand(sympy.simpli...
f17e9cc3da201c38bf4fa44786468f6a1510c8eb
614,054
def nint(x, n=0): """Returns x rounded to the nearast multiple of 10**-n. Values of n > 0 are treated as 0, so that the result is an integer. In other words, just like the built in function round, but returns an integer and treats n > 0 as 0. Inputs: - x: the value to round - n: negative o...
9f46767bb36e3b0422fa4ca11c66509befb84d08
614,055
def formatBuckets(buckets): """ Formats buckets into a list of strings :param buckets: buckets to be formatted """ timeList = [] for i, bucket in enumerate(buckets): formatStr = '{0:4,.3g}' if i < len(buckets) -1 else '>>{0:4,.3g}' timeList.append(formatStr.format(bucket)) return timeList
005115b4092993a8cde8415fc014b264ed55d1a5
614,058
def get_distinct_edge(edge_array): """ Return Distinct edges from edge array of multiple graphs >>> sorted(get_distinct_edge(edge_array)) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] """ distinct_edge = set() for row in edge_array: for item in row: distinct_edge.add(item[0]) ...
84105ea2e08ec4909c7effea2e3b8a11ae4d23a4
614,066
def _shorten_name(name): """Format asset name to ensure they match the backend requirements.""" if len(name) < 100: return name return name[:75] + '...' + name[:20]
a8d17317075ad15b2c02ae95d8c257a01d6ef869
614,068
def construct_common_line(avg_line_params, image_shape): """ This method constructs common line from the average of slope and intercept of the respective lanes Parameters ---------- avg_line_params : list list containing average of slope and intercept image_shape : tuple tuple o...
5b743e5c85200ae31c3172152ce06cfc9c3bc7b3
614,071
def writing_duration_overall(sample_wrapper): """ Returns overall writing duration. :param sample_wrapper: sample wrapper object :type sample_wrapper: HandwritingSampleWrapper :return: overall writing duration :rtype: float """ return float(sample_wrapper.sample_time[-1] - sample_wrappe...
b91a77e834aa96b785f1d07ea189dd9ee03dcf37
614,073
def crc_calc(input_string): """ Calculates cumulative XOR CRC of inputted string :param input_string: Str to CRC :return: 2 char CRC str """ crc = 0 for next_char in input_string: ascii_val = ord(next_char) crc ^= ascii_val hex_crc = hex(crc) if crc <= 0xF: ...
551dd3f04ff1f1c0c069cd4d9aa40085f4ca723e
614,077
def paramError(s1, s2): """Add together s1 and s2 with the right delimiter \pm and surroundings $$ Inputs ------ s1 : pandas Series A pandas Series with main parameter, e.g. Teff s2 : pandas Series A pandas Series with error, e.g. Tefferr Output ------ sout : pandas Series ...
65e67b9081adc5e1a405c7e52d44f30e243a5e8a
614,080
import random def _get_privacy_secret(privacy_secret): """Gets the passed privacy secret (or 128 random bits if None).""" secret = privacy_secret if secret is None: secret = random.getrandbits(128) return secret
764b6a8178cb506cc66e032ac5d921422bbc88dd
614,082
def tuple_add(t1, t2): """ Add two tupples, elementwise. """ return tuple(map(sum, zip(t1, t2)))
58cd05039e7351a411bb5b4f93d1ba535cc75d77
614,085
import torch def get_legal_action_mask_torch(n_actions, legal_actions_list, device, dtype=torch.uint8): """ Args: legal_actions_list (list): List of legal actions as integers, where 0 is always FOLD, 1 is CHECK/CALL. 2 is BET/RAISE for continuous PokerEnvs, and for...
acd0d5497b16a1c72fd5f04e43301f2d0766d2bf
614,086
def convert_SE3_to_arr(SE3_dict, timestamps=None): """Convert SE3 dictionary to array dictionary Args: SE3_dict (dict): a dictionary containing SE3s timestamps (list): a list of timestamps Returns: poses_dict (dict): each pose contains a [4x4] array """ poses_dict = {} ...
16a811e924aae5d03aedf944d34e0c6c5810fa6e
614,099
def get_post_data(request): """ get request.POST, if POST is empty return None """ if request.method == 'POST': return request.POST return None
d3dd8feddab940e06f523c586fa9c28bd3ade458
614,104
def utf8(x: str): """ Returns the UTF8 encoding of the given string. """ return x.encode('UTF8')
cd6c3626773e7e4bf1dd480a654f8ac996ad5991
614,105
from datetime import datetime def get_today_date(the_date=datetime.now()): """Return today's date (no time) as string.""" return the_date.strftime("%Y-%m-%d")
e506d2735e66c0bfaa4fd5572147c0669a935190
614,108
def gcd(numbers): """Calculates greatest common divisor of a list of numbers.""" aa = numbers[0] for bb in numbers[1:]: while bb: aa, bb = bb, aa % bb return aa
3227747c4c501a98ec27910e600f00b4a5f7d86e
614,111
import decimal def is_number(number): """ check if a string is number @param number: string to evaluate @return: false if not numeric, else returns digit(long or float) >>> is_number("233.33") 233.33 >>> is_number("233") 233L >>> is_number("foobar") False """ try: ...
13c0ea7faa1dad2fc8c6f02b1507f4392793a9c7
614,112
def mandel(x0, y0): """ Iterate the Mandelbrot function, returns the number of iterations until x^2 + y^2 > 4 or 200 iterations. """ x = 0 y = 0 iteration = 0 max_iteration = 200 while ( x*x + y*y <= (2*2) and iteration < max_iteration ): xtemp = x*x - y*y + x0 y = 2*x*y + y0 x = xtemp iteration += ...
f920d3b6e35ca54529496349679a4c0233afe97c
614,118
import json def parameters(tmp_path): """Create a dummy parameter file.""" parameter = { "input_ds": { "clustering": { "neighbors": 10, "res": 0.15 }, "filtering": { "min_cells": 3, "min_genes": 10 ...
5dbf7402b19c89ce953b0d0f9d9f755f1e556947
614,119
def normalizeKerningValue(value): """ Normalizes kerning value. * **value** must be an :ref:`type-int-float`. * Returned value is the same type as input value. """ if not isinstance(value, (int, float)): raise TypeError("Kerning value must be a int or a float, not %s." ...
04f9de27f52e265ae75e9d10583cb2dc94bec9cb
614,120
def vector_index(row_idx, col_idx, matrix_size): """ Return vector index (vector of Cls in healpy diagonal-major order) corresponding to matrix indices (of Wishart scale matrix). Args: row_idx (int): Row index for matrix. col_idx (int): Column index for matrix. matrix_size (int)...
d514c5a078dbedea38a5b14dc8011d3ff55c8c10
614,121
def read_ssh_pubkey(ssh_key: str) -> str: """ Read the public key of the generated ssh-key and returns it in a format acceptable for instance Metadata. """ with open(ssh_key + '.pub') as key_file: pub_key = key_file.read() user = pub_key.rsplit(' ', 1)[1].split('@')[0] return f"{user...
2a51d89a23229f4c761bef8c55de3c5c8a5b772a
614,122
from typing import Dict from typing import Any def merge_dicts(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]: """Return the union of two dicts, raise an error if keys are non-unique.""" # Resolve None types. if a is None: if b is None: return {} return b if b is None: return a d...
30e02ae53d3b6e2a696a776cf076439c1131cdd0
614,123
def generate_cipher_response(cipher: str, key_size: int) -> str: """Generate a response message :param cipher: chosen cipher :param key_size: chosen key size :return: (cipher, key_size) selection as a string """ return "ChosenCipher:{},{}".format(cipher, key_size)
207e692c15d7c2be6040a632ac7a3fa5d996564b
614,124
def _flatten(li): """ Flatten nested list and remove None values """ li = [i for i in li if i is not None] return [item for sublist in li for item in sublist]
7698d9224290f80065f29a41a87c40e98557e0fd
614,125
import re def is_ticker_symbol(value): """Checks whether a string is a possibly valid stock ticker symbol. Examples: 'GOOG', 'BRK/B', '263750 KS', 'EMBRAC B SS' :param value: A string to evaluate. :returns: True if string is in the form of a valid stock ticker symbol. """ return re.match(r'^...
a43f030845b2a5e611fd5410f8eb541a7d6d5295
614,129
def get_ends(bed3): """Get the BED coordinates of the last nucleotide of each record.""" ends = bed3.copy() ends['chrom_start'] = ends['chrom_end'] - 1 return ends.sort_values(by=['chrom', 'chrom_start'])
c67b4b1a220fa9c0ed71191d5cd7da29acf429f0
614,133
import random def split_dataFrames(df, trimmedRUL, splittingRatio): """Split the dataframes according to the indicated splitting ratio""" num_engines = df['Unit Number'].max() shuffledEngines = list(range(1,num_engines+1)) random.shuffle(shuffledEngines) i = int(splittingRatio*num_engines) ...
1190d9bb55c307daa753956eae88eb4806c52eb8
614,136
def samples_overlap(samplesA, samplesB, upper_thresh=0.5, lower_thresh=0.5): """ Report if the samples called in two VCF records overlap sufficiently. The fraction of each record's samples which are shared with the other record is calculated. The record with a greater fraction of shared samples must...
ecb08d2ff93fccd93641348e97624359b570880b
614,137
def get_manifest_out_of_files(files): """ Parses `files` for a file that ends with `androidmanifest.xml`. :param Set[str] files: list of paths to files as absolute paths :return: manifest string if in `files`, else None """ for file_name in files: if file_name.lower().endswith("androidma...
6e9e209920a7bc1a810679ab3d20eb7e2a2048ef
614,140
from bs4 import BeautifulSoup def find_job_post_summary_indeed(card: BeautifulSoup) -> str: """ Scrapes the summary of the job from an individual job card. Args: card (BeautifulSoup object): A BS4 object consisting of the section of the HTML doc result for a si...
9996b2e0a2f5cdf10f30a96b785f5287dea11acd
614,141
def get_solution_file_name(file_name): """ Return the name of the file in which save the solution :param file_name: the name of the file. :return: A .sol filename :rtype: str """ if file_name is None: return None if file_name.endswith('.sol'): return file_name else:...
6eb986e3312e745d29dacadc517e86d640e81431
614,143
def getValue( x ): """ If x is a tuple return the first entry, else return x. Arguments: x: The object to get the value of. """ if isinstance( x, tuple ): return x[ 0 ] else: return x
973920d38e54d71c309f330cb0fb48fe4881bdf4
614,145
def parseReferences(dStr): """ Parse comma separated list of component references to a list """ return [x.strip() for x in dStr.split(",") if len(x.strip()) > 0]
a1e89a7e08897dd5b5271135a24b47a034896916
614,147
import pathlib import configparser def load_cfg(config_path: pathlib.Path) -> configparser.ConfigParser: """ loads library config file :return: loaded `ConfigParser` object """ config = configparser.ConfigParser() config.read(str(config_path)) return config
60ee0c4fac12e13f01005e4babb936db926e2ea8
614,148
def clip(val): """Standard clamping of a value into a fixed range (in this case -4.0 to 4.0) Parameters ---------- val: float The value to be clamped. Returns ------- The clamped value, now fixed to be in the range -4.0 to 4.0. """ return max(min(val, 4.0), -4.0)
96651cff52098c0c87c98b8d4c0ee193fad17a23
614,149
def matMulti(A,D): """ Matrix multiplication A@D where A is herimitian matrix, and D is a diagonal matrix """ return A@D
be70c723629ec0f2cf4998ec85ee76466efecc68
614,154
def text_presence(job_desc, lan_list): """ Parameters ---------- job_desc : str Job Description. lan_list : list List of languages. Returns ------- dic : dictionary Dictionary of if each language was in description. """ dic = {} for langua...
ff8ba80523aa408dedc5e712eee2b45790b62f50
614,161
def CheckDomain(domain, fatal=True): """ Reports statistics and performs quality checks of the domain: - number of blocks is divisible by `nproc` Returns list of failed checks or aborts if fatal=True. """ checks = [ "(domain.bx * domain.by * domain.bz) % domain.nproc == 0", ] ...
5eb44c692054698e4477d0a27fe26d8f50c29a53
614,162
import typing def part2(func: typing.Callable[[str, typing.Any], None]): """ Decorator to wrap around the solution method for Part 2. The first positional argument is the puzzle input. The second argument is the return value from Part 1's solution function. Example; ``` @utils.part2 ...
9a2689dd625c6ed953e7da60396a5742a06071df
614,165
def find_cross(pair, unique_ents): """ Find if the pair is in cross or non-cross sentence. Args: pair: (tuple) target pair unique_ents: (dic) entities based on grounded IDs Returns: (str) cross/non-cross """ non_cross = False for m1 in unique_ents[pair[0]]: for m2 in ...
7dcd8958880e2a10095f14b8b2831c498892f763
614,174
def capitalise(input_string: str) -> str: """Convert the first character of the string to uppercase.""" return input_string[0].upper() + input_string[1:]
eb5dd6a2208ed626bac496b456c7b1f45770a1d5
614,177
def is_no_log(**kwargs): """ Return true is no_log value = True or 1 """ if "no_log" in kwargs: no_log = kwargs["no_log"] if no_log or no_log == 1: return True return False
7f571a2c205d4816645dc675394e1e71e1c1fcdb
614,179
def _find_extension(asn1, extn_id): """Find an extension from a certificate's ASN.1 representation Args: asn1: x509.Certificate instance. extn_id: OID of the extension to look for. Returns: The decoded value of the extension, or None if not found. This is a reference and ca...
e7965cda9ba36d2cbc13c6596cb0fc3f74b9b512
614,180
def uuid_representer(dumper, data): """Represent a uuid.UUID object as a scalar YAML node.""" return dumper.represent_scalar('!uuid', '%s' % data)
ee1e02acebb876849388cc0251178c76961e0b0c
614,183
def _get_matching_keys(*query_filters_list, model): """Returns all the keys matching any of the `query_filters` given `model`.""" entity_keys = set() for query_filters in query_filters_list: query = model.query(*query_filters) ekeys = model.all(query=query, keys_only=True, order=False) ...
5d6f4056097790e745c7274e64546e0533293bc9
614,186
def average(total, day): """ :param total: The sum of temperature data. :param day: The sum of days. :return: The average temperature. """ avg = total/day return avg
14d6a7e4f0c577778303b5e41910186d5b9c89c0
614,195
from typing import Dict import io def render_docstring(parsed: Dict[str, str], indent=""): """ Renders parsed docstring returned from parse_docstring. Args: parsed: A dictionary returned from parse_docstring() indent: An optional prefix to include in each line of t...
b32f34b09ed6316397a0f208fa39ee729838fb60
614,197
import requests def get_status_code(host, path="/", auth=None): """ This function retreives the status code of a website by requesting HEAD data from the host. This means that it only requests the headers. If the host cannot be reached or something else goes wrong, it returns None instead....
cdb0c2fd46c0f5cae6252cf13cf13670b62f0370
614,198
def serialize_libfuzzer_args(args): """Serialize a dict to libfuzzer's args, e.g. -dict=something.""" args_list = [] for key, value in args.iteritems(): args_list.append('-%s=%s' % (key, value)) return ' '.join(sorted(args_list))
ed0dbefb35448112c770765296a2999c800b0f1b
614,201
import re def strip_multiple_whitespaces(s): """ Remove repeating whitespace characters (spaces, tabs, line breaks) from `s` using RE_WHITESPACE """ RE_WHITESPACE = re.compile(r"(\s)+", re.UNICODE) return RE_WHITESPACE.sub(" ", s)
c27effcb59dd6ebd3c79eeb4d09c41fb111b51c1
614,202
def is_overlap(s1, e1, s2, e2): """True: if (s2,e2) is sufficient overlap on (s1,e1)""" if s2 >= s1 and e2 <= e1: # winthin (s1, e1) return True elif (s2 < s1 and e2 > s1) and (s1 - s2) < (e2 - s1): # s1 within (s2, e2) return True elif (s2 < e1 and e2 > e1) and (e1 - s2) > (e2 - e1): # ...
3553a58a493f50282f91db1add28f025d85e5011
614,205
from typing import Callable from typing import Set import inspect def get_mandatory_args(func: Callable) -> Set[str]: """Returns the mandatory args for a function as a set Returns the set of arguments names of a functions that are mandatory, i.e. does not have a default value. `**kwargs` type arguments a...
0dd25afc8a5b465d2ae464c029860c9febb0743f
614,206
def filter_columns(data,column_names): """Keep selected columns in the dataframe.""" selected_columns = data[column_names] return selected_columns
c6056aaff62201f6a6e666f82613aa5cd95de369
614,208
def _get_scores(model, feat): """Get the scores from a model We want to use the `decision_function` method if it is available, but fall back to the `predict_proba` method if it isn't. In sklearn, `predict_proba` for a binary classifier returns a two-column numpy array, where the second column is th...
4965ae4b33ba7fb23b8184d561e8efe96d55c9dd
614,209
import random import torch def sample_random_batch(dataset, batch_size=32): """ * inputs: - dataset (torch.utils.data.Dataset, required) An instance of torch.utils.data.Dataset. - batch_size (int, optional) Batch size. * returns: A mini-batch ran...
fcad09349731dfc9485ddc934705d85a10b3f2ac
614,215
import math def lightcurve_metrics(src_list): """ Calculates various metrics for a lightcurve made up of source extractions These are normally calculated internally in the database - this function serves as a sanity check, and is used for unit-testing purposes. Returns a list of dictionaries, th...
08a32cd0fe91c0276df875715e885d5a6caa49e4
614,218
def RK4(f, y, t, h): """ One step of the numerical solution to the DE (dy/dt = f). :param f: Time-derivative of y :param y: Previous value of y, used in finding the next :param t: Time :param h: Time-step length :return: Value of y at time t+h """ k1 = h*f(t,y) ...
00730ff86f63da643d1fbe401d103122726c87d8
614,221
def fix_missing_keys(json_data): """Fill in missing data fields with default values.""" default_data = { "name": "Sample", "description": "Add a description ...", "spin_systems": [], "methods": [], "config": { "integration_density": 70, "integratio...
b11133a870112f14f269492d4bc36f9923af9dfc
614,224
import pickle import pkg_resources from pathlib import Path def load_model(model): """Loads the model from the passed path or name""" if isinstance(model, Path): return pickle.loads(model.read_bytes()) model = 'models/' + model + '.pkl' model = pkg_resources.resource_string('botrecon', model...
7b416e39a740a25f360fcbd4371d76213de3e2ef
614,225
def translate_cmap(yourchoice): """ Convert readable colormap to a matplotlib cmap entity """ cmap_transposer = {'red_yellow_green': 'RdYlGn_r', 'yellow_orange_brown' : 'YlOrBr', 'blue_green' : 'winter'} return cmap_transposer[yourchoice]
698ae175c6aeab87c972f55d4bc351a3c4654f1a
614,228
def _build_schema_resource(fields): """Generate a resource fragment for a schema. Args: fields [Sequence[:class:`~google.cloud.bigquery.schema.SchemaField`]): schema to be dumped Returns: (Sequence[dict]) mappings describing the schema of the supplied fields. """ return...
1f39153aec88f98f6c53812f3bc8ec861294403b
614,231
def check_for_choice_col_based_on_return_long_probs(return_long_probs, choice_col): """ Ensure that if return_long_probs is False then choice_col is not None. Raise a helpful ValueError if otherwise. Parameters ---------- return_long_probs : b...
ef110091a6d3e22a18259a9eee3cab9f43bb1f6c
614,232
def GetCoordinates(file,atom_ref_ids, atom_name): """ This function returns the coordinates of a PDB file. PARAMETERS ---------- file : string PDB filename atom_ref_ids : list of strings the residue number of the reference atoms atom_name : string the PDB atom name of the reference PDB file RETU...
d6e910c3a0355f0b6f0c0b2bf19220281729fa6e
614,233
def remove_suffix(string: str, suffix: str): """ Removes a suffix from a string if present. Args: string (`str`): The string to remove the suffix from. suffix (`str`): The suffix to remove. Returns: The string without the suffix. """ return string[: -len(suffix)] if str...
f6fed4cc0eb280241a91aa699bc8fcfc7b61b59a
614,234
def get_run_info_miseq( instrument_model, application_version, tree ): """ Helper function to get some info about the sequencing runs. Args: tree: xml tree Returns: dict: basic statistics about run, like date, instrument, number of lanes, flowcell ID, read lengths, etc. """ run_...
cb1146a0276d55018bd05ea5aab0f97bda2bdd87
614,235
def make_odd(number): """ Return the input number if its odd, or return input number + 1 if its even or zero. """ if number == 0: number += 1 if number % 2 == 0: number += -1 return number
5c074d0cb981eda1d380126865714babea2c96cc
614,236
def shorten( text: str, width: int, placeholder: str = "...", front: bool = False ) -> str: """Truncate exceeded characters. Args: text (str): Target string. width (int): Limit length. placeholder (str): Placeholder string. Defaults to "..." front (bool): Head hidden or tail...
3dc4cacc9d82e0063f1dd5cd3ac993063a5758cf
614,243
def check_stmt(stmt, conditions, evid_policy='any'): """Decide whether a statement meets the conditions. Parameters ---------- stmt : indra.statements.Statement INDRA Statement that should be checked for conditions. conditions : dict Conditions represented as key-value pairs that st...
045e9c5fec6681f0c90fcb0df2b4b924b72e12f9
614,245
from datetime import datetime def utc_timestamp(time: datetime) -> float: """Return timestamp in UTC. Parameters -------------- time : datetime datetime object in UTC Returns --------- float Timestamp in UTC """ epoch = datetime(1970, 1, 1) # get timestamp in...
21502a94453284d2eaf3361abb6c8fbfaa0976b6
614,248
import torch def attention_list_to_matrix(coding_tuple, dim=2): """[summary] Args: coding_tuple (list((torch.Tensor, torch.Tensor))): iterable of (outputs, att_weights) tuples coming from the attention function dim (int, optional): The dimension along which expansion takes place t...
0cbb2e5a6792466140998c419059226ed34ff8f0
614,256
def dss_is_geo(dss_schema): """ Check if the input dataset contains a geopoint (DSS storage type) column If so, specific processing will be applied later on :param dss_schema: schema of a dss dataset >>> dss_schema = {"columns": [{"name": "customer_id", "type": "bigint"}]} :return Boolean{input...
ae90babcbba8f7815485ce78ea6e97e531249057
614,257
import requests def _retry_on_connection_error(exception: BaseException) -> bool: """Helper for retrying connections.""" return isinstance(exception, requests.ConnectionError)
28dcf9854238cd94a99f13cc9b54386fc856e70c
614,258