content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def args_expand_images(parser, nb_workers=1, overwrite=True): """ expand the parser by standard parameters related to images: * image paths * allow overwrite (optional) * number of jobs :param obj parser: existing parser :param int nb_workers: number threads by default :param bo...
56755f45ffc2c5dcaaecbd9e88f98fbbfb5ff86f
667,222
import random def choice_contry(): """ 国家,暂时默认为中国 :return: """ country = random.choice([ "CHN", "ALB", "DZA", "AFG", "ARG", "ARE", "ABW", "OMN", "AZE", "EGY", "ETH", "IRL", "EST", "AND", "AGO", "AIA", "ATG", "AUT", "ALA", "AUS", "MAC", "BRB", "PNG", "BHS", "PAK", "PRY", "PSE", "BHR...
c5964e3c5652da5dfa307050b56241d7d65992a3
667,223
def __get_tweet_content_from_res(gh_res): """From the response object returned by GitHub's API, this function builds the content to be tweeted Args: gh_res (dict): A dictionary of repository details Returns: str: The string to be tweeted. """ tweet_content = gh_res["name"] if gh_res["langua...
50db59f21bce3638217de4132f376acc44542b7b
667,224
import torch def float_to_wav(x): """ Input in range -1, 1 Output in range -2**15, 2**15 (or what is determined from dtype) """ assert x.dtype == torch.float max_value = torch.iinfo(torch.int16).max min_value = torch.iinfo(torch.int16).min x = x + 1.0 x = x * (max_value - min_valu...
2d3987cd3f0642727c196285130308e0d39fc55b
667,225
def verse(number): """Create a verse""" ordinal = { 1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", 6: "sixth", 7: "seventh", 8: "eighth", 9: "ninth", 10: "tenth", 11: "eleventh", 12: "twelfth" } ...
38c326d9528c8afdf61948bed128697b52f6eadb
667,226
def protocol_type(request): """ used to parametrized test cases on protocol type :param request: pytest request object :return: protocol type """ return request.param
d316ffa6724f34bc609e6fafb15a3f0ae308badd
667,227
def update_lines(num, ax, fargs): """define modification animation function""" dataLines, lines = fargs for line, data in zip(lines, dataLines): # NOTE: there is no .set_data() for 3 dim data... line.set_data(data[0:2, :num]) line.set_3d_properties(data[2, :num]) return line...
b6fc4758ba9af483565404503c42f4ace34c0a09
667,229
def calc_prelu(func, in_data, **kwargs): """[PReLUFunction](https://docs.chainer.org/en/v4.3.0/reference/generated/chainer.functions.prelu.html) Max operation can be executed by a single instruction. chainer-computational-cost considers it as one floating point operation. In case $W$ is neither scalar...
f12febda0ac00603318445beb66d7214fc64686d
667,230
def continuous_fraction_coefs (a, b): """ Continuous fraction coefficients of a/b """ ret = [] while a != 0: ret.append( int(b//a) ) a, b = b%a, a return ret
1903f74f9bd12c2e4dbed150c2eb24d93baa18b9
667,231
def countPrimes2(n: int) -> int: """厄拉多塞筛法:声明一个长度为最大限制数的布尔数组。用布尔值来区别筛选出的数和质数。""" cnt = 0 flags = [0] * n for i in range(2, n): if not flags[i]: cnt += 1 # 如果我们在进行顺序遍历时,每取得一个数(排除0、1),如果将它所有的倍数(排除0、1、本身)都清除,那么,剩下的数是不是必为素数? for j in range(i + i, n, i): ...
e990b71bcfdb56ffad1587b9bd9cfb385eaef4da
667,233
def GroupBuildsByConfig(builds_timings): """Turn a list of BuildTiming objects into a map based on config name. This is useful when looking at waterfall groups (cq, canary, etc), if you want stats per builder in that group. Args: builds_timings: List of BuildTiming objects to display stats for. Returns...
91c9c8b5d0323550244a6fc08d507340a4db2adf
667,234
import ntpath def get_relpath(path): """ gets the relative path without file Args: path (string): path to the file Returns: string: the relative path """ return ntpath.split(path)[0]
462a51d1b2239549c6ffa49325a1c21c0c9cb047
667,235
def get_db(entity): """ Returns the #pony.orm.Database backing the #Entity instance *entity*. """ return entity._database_
012f05c638b41ed21cf6d717fc3b55926264efb9
667,238
import numpy def table_K2(h): """Figure 11-30 Regression by Carl Sandrock""" a, b, c, d = 26.52258403, 0.76197575, 13.23116619, 33.1867269 return a + b*numpy.sqrt(numpy.sqrt((h - c)**2)) - (h - c)/d
78f11845824b76f57635d2a6248a9228b40f3c8b
667,239
import numpy as np def remove_dc_offset(ecg_smooth): """ This function will remove DC offsets that may be present in the data set. This is accomplished by subtracting the mean from the data :param: :return: """ ecgtotal = np.sum(ecg_smooth) ecgsize = len(ecg_smooth) ecgmea...
eabbce0e80991b4c395adb25e70a2843770ffc5a
667,240
def make_mission_id(mission_definition, specifics_hash): """ Returns the string mission_id which is composed from the mission_definition and specifics_hash. """ return "%s-%s" % (mission_definition, specifics_hash)
5b1d6817dfef08df61b7c372c921f5703186019f
667,241
from typing import Callable from typing import List from typing import Tuple import inspect def _get_dup_signature_tuples(fn: Callable) -> List[Tuple[str, str]]: """ Helper that inspects the arg signature of `fn` and returns a list of tuples, where each tuple is a pair of duplicated names which is used fo...
8d62ed3b0a03d5833d5d88312d43f31450405453
667,242
import math def work(force, displacement, theta): """ Calculates the work done by the force while displacing an object at an angle theta Parameters ---------- force : float displcement : float theta : float Returns ------- ...
989d44fe8f7e64a755484bc95db2e44abaaae3f5
667,243
def string_attributes(domain): """ Return all string attributes from the domain. """ return [attr for attr in domain.variables + domain.metas if attr.is_string]
fbc26a13eb445b25dac4a18d84c4ed109b118894
667,244
def wordcount(text): """ Return the number of words in the given text. """ if type(text) == str: return len(text.split(" ")) elif type(text) == list: return len(text) else: raise ValueError("Text to count words for must be of type str or of type list.")
fb9df95826565fc5bdbb8f13cd66179a08cea8e3
667,245
def get_neighbor_top_left_corner_from_explore(direction): """ Return the relative offsets where the top left corner of the neighbor card would be situated, from an exploration cell. Direction must be one of "up", "down", "left", or "right". """ return {"l": (-2, -4), "d": (1, -2), "u": (-4, -1), "r": (-...
1f561be3e9ca5f47f388a967b6c9073a52c7931f
667,246
import imaplib def get_mail_by_uid(imap, uid): """ The full email as determined by the UID. Note: Must have used imap.select(<mailbox>) before running this function. Args: imap <imaplib.IMAP4_SSL>: the server to fetch Returns: Dictionary, with the keys 'flags', 'date_time', ...
d8ded0dedf04fb55ba33a6dd493055f745f52264
667,247
import decimal def round_int(dec): """Round float to nearest int using expected rounding.""" return int(decimal.Decimal(dec).quantize(decimal.Decimal('0'), decimal.ROUND_HALF_DOWN))
0b6d0b48203e4c3d660bc5d6abd75b290af12c1a
667,248
import torch def euclidean_correspond_dist(x, y): """ Args: x: pytorch tensor, with shape [m, d] y: pytorch tensor, with shape [m, d] Returns: dist: pytorch tensor, with shape [m, 1] """ m, n = x.size(0), y.size(0) xx = torch.pow(x, 2).sum(1, keepdim=True).squeeze() ...
f7bac6cff544da54b93137aa2826424c396f7d4f
667,249
import numpy def choose_features(nof_features, max_features): """ function randomly selects the features that will be examined for each split """ features_indices = numpy.arange(nof_features) #numpy.random.seed() #features_chosen = numpy.random.choice(features_indices, size=max_features, repla...
02e74922816a93d8e4429cb6dab30e94929363f3
667,251
def cli_usage(usage): """Decorator to provide usage examples""" def wrap(func): """Decorator internal wrapper""" if not hasattr(func, 'cli_args'): func.cli_args = list() func.cli_usage = usage return func return wrap
63813f4ceae6e078a4e78e063ae957dcab78b4f5
667,252
import os def read_environ(): """read environment variables and store into local map""" environ = {} environ['BASEDIR'] = os.environ['TS_BASEDIR'] environ['CONFIG_NL'] = os.environ['TS_CONFIG_NL'] environ['NL_TS_SWITCH'] = os.environ['TS_NL_TS_SWITCH'] environ['DT_FILE'] = os.environ['TS_DT_F...
3591432c0007b0ea11c490c20bc79fc9ef14d3c7
667,253
def replace_dict_value(d, bad_val, good_val): """ Replaces Dictionary Values whenver bad_val is encountered with good_val """ for k,v in d.items(): if v == bad_val: d[k] = good_val return d
c2831e3f26cfde4c26859114ff3b64bf6fa6ace9
667,255
def collect_package_stats(packages, cwes, filter): """ Collects coverage statistics for packages matching the given filter. `filter` is a `lambda` that for example (i) matches packages to frameworks, or (2) matches packages that were previously not processed. The returned statistics are used to generat...
99f5c1ba4dcf9e040d1152026d7af63f5297bd4f
667,256
def empty_config_path(tmp_path_factory): """Create an empty config.ini file.""" config_path = tmp_path_factory.getbasetemp() / "config.ini" config_path.touch() return config_path
67a783279b572e86dba615f68b48dc8e05331338
667,257
def _is_flat(item): """Measures if object is flat""" for k, v in item.items(): if isinstance(v, tuple) or isinstance(v, list): return False elif isinstance(v, dict): if not _is_flat(v): return False return True
e1a520fb4ab00b8d3581585ae08380ccf67dda4d
667,259
def resta_complejos(num1:list,num2:list) -> list: """ Funcion que realiza la resta de dos numeros complejos. :param num1: lista que representa primer numero complejo :param num2: lista que representa segundo numero complejo :return: lista que representa la resta de los numeros complejos. """ ...
9d7cc64b3e418494b2cd6c85180d379ed9384b1e
667,260
def Main(a, b): """ :param a: an integer :param b: an integer :return: a + b :rtype: int """ c = a + b return c
17228d0d17bb3f41c301ff3334d02eac709300bf
667,261
def channelMaxSortKey(node): """ Use in .sort() when you want to sort a list of nodes by maxChannels :param node: node :return: channelCount """ return node.maxChannels
88abeef8a98011d96b59e27880a9b0dce9dab3d5
667,262
from typing import List from typing import Dict import numpy import pandas def _k_way_cross_plan_y_stratified( *, n_rows: int, k_folds: int, y ) -> List[Dict[str, List[int]]]: """ :param n_rows: number of input rows :param k_folds: number of cross folds desired :param y: values to stratify on ...
3946deb1ba24e86981bb2fd0cb61f60ea5d894f9
667,263
from typing import Mapping from typing import List def _mapping_to_mlflow_hyper_params(mp: Mapping) -> List[str]: """ Transform mapping to param-list arguments for `mlflow run ...` command Used to pass hyper-parameters to mlflow entry point (See MLFlow reference for more information) All mapping value...
c0d1fe9083ddf6fce29b98bd88de209a06a47f02
667,264
def get_us_letter_equivalent_score(score: float) -> str: """Get the letter equivalent in the US grading system for a given score.""" str_score = "F" if score == -1: # RPL: score is not applicable str_score = "N/A" elif score >= 93: str_score = "A" elif score >= 90: str_s...
44729801016db3b6953ddc0bd7b3efedcba77d5f
667,265
def query_database(conn, query, params=None, commit=False, returning=False): """Query a database. Takes a database connection, query represented by a string, query parameters represented by a list, and a boolean representing whether the query makes changes to the database, and returns the results o...
39e417180eeea8b3b19db8b0925d2019d7c3c155
667,266
import os def file_exists(path): """ Return ``True`` if the given ``path`` string points to an existing file. :param string path: the file path :rtype: bool """ if (path is None) or (not os.path.isfile(path)): return False return True
50337c4e1ea5f99a9eaa8d770287ab4606de299d
667,267
import os def collect_data(config_loc): """include everything in config_loc as package data.""" configs = [] for f in sorted(os.listdir(config_loc)): configs.append(os.path.join(config_loc, f)) return configs
3df611ca5b50045d7749a5727964e6685f01dc3d
667,269
import click def confirm_yesno(text, *args, **kwargs): """Like ``click.confirm`` but returns ``Y`` or ``N`` character instead of boolean. """ default = "[N]" # Default is always N unless default is set in kwargs if "default" in kwargs and kwargs["default"]: default = "[Y]" confirm...
fad4c93214d06036769cf3da9d0060e43d759c99
667,271
def addView(s:str): """ addView(s) -> None Deprecated. Use the Root node. Adds a new view to the list of views. @param s: View name. @return: None """ return None
f4d19f8370b9a3750c2701efb8c9066753347ee6
667,272
def threshold_filter(elevation_series, threshold=5.0): """Filter elevation series by breaking it into vertical increments. Args: elevation_series (pd.Series): elevation coordinates along a path. threshold (float): Threshold beyond which a change in elevation is registered by the algorithm, in the u...
dce4f4f8e9c5d4eec02cedac72bb93cefe7ed502
667,273
def parse(cleaned): """ Return list of words beginning with wss """ ret = [url for url in cleaned.split() if url.startswith("wss")] # print (ret) return ret
83989d329596bece7b69876b539d5a46b23cc5d0
667,274
import os def IsExecutable(filename): """Checks whether a file exists and is executable. @type filename: string @param filename: Filename @rtype: bool """ return os.path.isfile(filename) and os.access(filename, os.X_OK)
19bf4a8b18b6e067f98d69299580a75a2f515d86
667,275
def test_datadir(request, datadir): """ Inject the datadir with resources for the specific test function. If the test function is declared in a class then datadir is ClassName/FunctionName otherwise it is only FunctionName. """ function_name = request.function.__name__ if not request.cls: ...
1f27d8fd131f2d88b60e1c7a463c2f2876020550
667,276
def displacement_Compute(point, pointf): """Computes displacement between two image point arrays""" assert len(point) == len(pointf) values = [] for i, pt0 in enumerate(point): pt1 = pointf[i] values.append((pt1[0] - pt0[0], pt1[1] - pt0[1])) return values
3c79d030cb4ec2aac72a935c63a42c3ccf41778b
667,277
def _l(self, paper, **_): """Display long form of the paper (all details)""" print("=" * 80) paper.format_term_long() print("=" * 80) return None
99c9611fe3f1f20a019b3dd03951b68f47cd078f
667,279
import functools def log_exception(logger): """decorator for logging exception""" def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: args_str = ",".join(map(str, args)) ...
9f2a1e8206f0d1e7ae3043366b5715b5cb543dee
667,280
import asyncio def getLoop(): """ :return: the current asyncio loop """ return asyncio.get_event_loop()
fefebf48abc3a9fb84ae0717e61d76fb716a6779
667,281
import argparse def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Choose the article', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('word', metavar='word', help='T...
16dcfac5ecaf77c58f814e12b074ee7cd4c21d57
667,282
import inspect def sage_getvariablename(self, omit_underscore_names=True): """ Attempt to get the name of a Sage object. INPUT: - ``self`` -- any object. - ``omit_underscore_names`` -- boolean, default ``True``. OUTPUT: If the user has assigned an object ``obj`` to a variable name, ...
a4ef5e23a21266314917f3d20d6eafeb753b1b61
667,284
def _build_requested_filter(requested_filter): """ Returns requested filter_params string. """ # Files and Uploads type filter values all_filters = { "Images": ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/tiff', 'image/tif', 'image/x-icon'], "Documents": [ ...
c5283bba12e6cefc4a4d764343805faf275a3225
667,285
import json def serialize_json_data(data, ver): """ Serialize json data to cassandra by adding a version and dumping it to a string """ dataOut = data.copy() dataOut["_ver"] = ver return json.dumps(dataOut)
1e2bdc63204c7b64044056c15c34e7a4bb62e919
667,286
import os import warnings def savepath (nameOfPath): """ Shortcut to create a folder :param nameOfPath: Path name to save file :type nameOfPath: str :return: New folder created. If the `nameOfPath` exists, will return ``None`` :rtype:str """ try : s...
f21f4946c83c7a7a296f4da810e3627187b089de
667,287
from typing import Callable def enforce_state(property_name: str, expected_value): """ A decorator meant for class member functions. On calling a member, it will first check if the given property matches the given value. If it does not, a value error will be thrown. """ def dec(func: Callable)...
58545341e29d13b9e4fd89a56bde0d8512546976
667,288
def get_headers(referer): """Returns the headers needed for the transfer request.""" return { "Content-Type": "application/json; charset=UTF-8", "X-Requested-With": "XMLHttpRequest", "Referer": referer }
3e7470a6344cd7b97f682974e8497bce0edc08cb
667,289
def revoke_token(self, subid): """revoke a presently active token, meaning append _revoked to it.""" return self.finish_user(subid, ext="revoked")
0ffb7088b99ae11c5ee3f773ac38691416116ae1
667,290
def maximoEncabezado(nombreEncabezado,numDecisiones): """ maximo encabezado funcion que nos permite hacer un numero maximo de encabezados. @param nombre encabezado string @param numDecision int """ nombre="" lista=[] for i in range(numDecisiones): nombre=nombreEncabezado + "...
5d8dcc5fdd20c4dd2cf3f692fe38d0e1c193d52e
667,291
def getPointCoords(row, geom, coord_type): """Calculates coordinates ('x' or 'y') of a Point geometry""" if coord_type == 'x': return row[geom].x elif coord_type == 'y': return row[geom].y
35d15cebe418238e0826e272a670a4b3af701ae3
667,292
def are_users_same(users): """True if all users are the same and not Nones""" x = set(u.get('seq') for u in users) return len(x) == 1 and None not in x
0e58dbcaaa9fc9b9449efbf4454ceebb4de607a2
667,293
def efit_transform(object, data): """Fit-Transform an object on data.""" return object.fit_transform(data)
589481cdd716cd454ce287cddc38b3b2404f91da
667,294
from typing import List def count_total_keywords(keywords: List[str]) -> int: """ Returns the count of total keywords of a list of keywords as a integer. Parameters: keywords (List[str]): list with all keywords as strings. """ return len(keywords)
ba4fff81fddd82487aca121f458d68d3d793af9a
667,295
def linearise(entry, peak1_value, peak2_value, range_1to2, range_2to1): """ Converts a phase entry (rotating 360 degrees with an arbitrary 0 point) into a float between 0 and 1, given the values of the two extremes, and the ranges between them Parameters ---------- entry : int or float ...
d6faa6537c5e2ccde30ce903e90a24280dba43fe
667,296
import re def search_for_perf_sections(txt): """ Returns all matches in txt for performance counter configuration sections """ perf_src_srch_str = r'\n<source>\n type oms_omi.*?object_name "(.*?)".*?instance_regex "(.*?)".*?counter_name_regex "(.*?)".*?interval ([0-9]+[a-z])(.*?)</source>\n' ...
fbeb505ffcadb3f3cf5d4985da1af8ceb5225b25
667,297
def get_old_password(accounts, username): """ """ old_password = accounts.old_hashpass(username) return old_password
3d59f2a0b06425d7f90a5b3aef218f2d47814cec
667,298
def xemm_signal(prices, fees): """ Signal generation to bakctest a Cross-Exchange Market Maker strategy. Parameters ---------- prices: dict with the historical ticks or prices, must be a dictionary with the following structure: {'origin_exchange: {timestamp: {}}, 'destination_e...
02fcae63822321dbb55a2292a92232b07315c148
667,299
def getLocation( min_point: tuple, max_point: tuple ) -> tuple: """Gets the bottom center location from the bounding box of an occupant.""" # Unpack the tuples into min/max values xmin, ymin = min_point xmax, ymax = max_point # Take midpoint of x-coordinate and ymax for bottom middle of box x_re...
3195507038dd5ae6e746ce4163b646f5765fc334
667,300
import copy def wrap_grant(grant_details): """Utility function wrapping grant details for return from a POST.""" details_list = [copy.deepcopy(grant_details)] if grant_details else [] return {'results': details_list}
7c1803f2d749d65ed475fec21f6abc2d8ffc614f
667,301
def ocurs_words_length( message: str, *, percent: bool = False, reverse: bool = False ) -> dict[int, int | float]: """Count all occurences of words length in the message. Returns: dict[str, int | float]: the dict of all occurences. """ word_lengths = [len(word) for word in message.split(' ')] word_length_ocurs...
1e67c46ccafae0b4956b77962380339d3d54e58c
667,302
def get_dom_np(sents, pos): """ Finds the position of the NP that immediately dominates the pronoun. Args: sents: list of trees (or tree) to search pos: the tree position of the pronoun to be resolved Returns: tree: the tree containing the pronoun dom_pos: the position ...
c8e6a06ea07ee18afe051c676acd070aef282fcb
667,303
def check_filters(filters): """Checks that the filters are valid :param filters: A string of filters :returns: Nothing, but can modify ``filters`` in place, and raises ``ValueError``s if the filters are badly formatted. This functions conducts minimal parsing, to make sure that the relationship exist...
724bfbce98c734fe253bb2e77100fb8588f6a3da
667,304
def decodeMsg(aStr): """Decode a message received from the hub such that multiple lines are restored. """ return aStr.replace("\v", "\n")
f84cb538bc86df7f24ffeb375d3ddc42b7a9b80f
667,305
from datetime import datetime def get_logdir(): """Return unique logdir based on datetime""" now = datetime.utcnow().strftime("%m%d%H%M%S") logdir = "run-{}/".format(now) return logdir
20afef9ce176f5f4c6e36b60687787fef818c53f
667,306
def make_freq_table(stream): """ Given an input stream, will construct a frequency table (i.e. mapping of each byte to the number of times it occurs in the stream). The frequency table is actually a dictionary. """ freq_dict = {} bsize = 512 # Use variable, to make FakeStrea...
9ddb486405ef862107fd66fd3bf20a7074d100d1
667,307
import torch def zero_out_row_span(xfft, row, start_col, end_col=None): """ Zero out values for all data points, channels, in the given row and column span. :param xfft: input complex tensor :param row: the row number to zero out value :param start_col: the start col (inclusive, its value is ...
e5c8b15af451e3b14ecca4d5576eed63beff26fd
667,308
def count_factors(n): """Return the number of positive factors that n has. >>> count_factors(6) # 1, 2, 3, 6 4 >>> count_factors(4) # 1, 2, 4 3 """ i, count = 1, 0 while i <= n: if n % i == 0: count += 1 i += 1 return count
6515778b9bd3be74a30ce4b32c418357dd000150
667,309
from typing import List from typing import Dict def get_author(author_list: List[Dict]) -> str: """Parse ChemRxiv dump entry to extract author list Args: author_list (list): List of dicts, one per author. Returns: str: ;-concatenated author list. """ return "; ".join( ["...
22c9c7acba7a243592d9054eb6b811847d7bfd25
667,310
from typing import Iterable def flat_map(f, xs: Iterable): """ :param f: a mapping function :param xs: (Iterable) :return: list """ return [item for element in xs for item in f(element)]
dc7d0980ae0c4b88c63907a0e6766377acedc750
667,311
def read_conll_pos_file(path): """ Takes a path to a file and returns a list of word/tag pairs (This code is adopted from the exercises) """ sents = [] with open(path, 'r') as f: curr = [] for line in f: line = line.strip() if line == "": s...
a5b27deac877d42d759b64d97837c89ff2277546
667,312
def is_keymap_dir(keymap, c=True, json=True, additional_files=None): """Return True if Path object `keymap` has a keymap file inside. Args: keymap A Path() object for the keymap directory you want to check. c When true include `keymap.c` keymaps. json ...
9cb54853ebdda2f1e77b705c35d9a2af21029827
667,313
def get_transcript_score(ort_scores_file): """Read orthology scores.""" result = {} f = open(ort_scores_file, "r") _ = f.__next__() # skip header for line in f: line_data = line.rstrip().split("\t") transcript = line_data[0] chain = line_data[1] score = float(line_da...
4dc3942b9c2a77645cacd5662eea3a45f6334642
667,315
import torch def recall(cm, mode='pos'): """ Recall: What fraction of ground truth labels was correct? Of all ground truth positive samples, what fraction was predicted positive? sensitivity = recall_pos = TP / (TP + FN) Similarly, of all ground truth negatives, what fraction was predicted ...
bcd8437b5b1c5e2dbc7291deed06c541410aa0ce
667,316
def unformatted_item_spec(): """A specification for an unformatted string item.""" return { 'weirdName-Cool_stuff lol': { 'required': True, 'format_env': False, 'format_cli': False, } }
2da407a195436d8fbbd4332dc30625d875b62f6e
667,317
def concatenate_datasets(datasets): """/ concatenate single cell datasets Parameters ---------- datasets: list List of AnnData objects to be concatenate. Returns ------- :class:`~anndata.AnnData` adata """ adata = datasets[0].concatenate(datasets[1]) for i in range(2, len(datasets)): adata = adata.c...
379d2cca842945621c74e14bd5270f19876e509b
667,318
def load_config(file_location): """ Load config file and parse it to suitable config format for renderer. Requires config file location as argument. """ print("loading config " + file_location) config = [] # Load file(without newline at the end) f = open(file_location, "r") data = ...
82a0d0d696262f5371e3a1c0f731f8b107531924
667,319
import random def randomize_sleep_time(sleep_time): """sleep time +- 50%""" return sleep_time / 2 + random.random() * sleep_time
004a7ce98b8e8a5f5e6200bde4481be33450f836
667,320
import subprocess def run(command): """Run a bash command from python and returns the output, splitted line by line. :param command: command to run. :type command: string :return: list of the stdout lines. :rtype: list[string] """ result = subprocess.run([command], stdout=subprocess....
37dd9639cc1086928e4c6e1c4bb8f815a5bc6cff
667,321
import math def svp_from_t(t): """ Estimate saturation vapour pressure (*es*) from air temperature. Based on equations 11 and 12 in Allen et al (1998). :param t: Temperature [deg C] :return: Saturation vapour pressure [kPa] :rtype: float """ return 0.6108 * math.exp((17.27 * t) / (t ...
50e2a2f8c5222efd9e36bfba787e9ed56da04a57
667,322
import re def format_condition_value(conditions): """ @summary: ['111', '222'] -> ['111', '222'] ['111', '222\n333'] -> ['111', '222', '333'] ['111', '222\\n333'] -> ['111', '222', '333'] ['', '222\n', ' 333 '] -> ['222', '333'] [111, 222, 333] -> [111, 222, 333] @...
778b4b2369df9c7de46e2a22490408b1b9a86cac
667,323
def csv(options): """Format TikZ options. Parameters ---------- options : dict TikZ options, where spaces in keys are represented by underscores. Returns ------- str Comma-separated key-value pairs in TikZ format. """ return ', '.join(key.replace('_', ' ') +...
138f7fe0f23bd6ab09f1038c583da389f9a28162
667,324
def calculate_alphabet_from_order(ORDER): """ Generates aplhabet from order """ LOWERCASE = "abcdefghijklmnopqrstuvwxyz" UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ALPHABET = "" for CHAR in ORDER: if CHAR.islower(): ALPHABET = "%s%s" % (ALPHABET, LOWERCASE) elif CHAR.isupper(): ALPHABET...
66a0be580bded0e1fafe56e6d2e0436b58dd990e
667,325
from typing import Tuple from typing import Dict import os def get_user_click(rating_file: str) -> Tuple[Dict, Dict]: """ 获取用户点击链表 Args: rating_file:点击率文件 Return: 字典 """ if not os.path.exists(rating_file): return {}, {} fp = open(rating_file) line_num = 0 ...
eb0b1ea6c547a89b7be5fc7cdd4af6c3bd002c60
667,326
def get_filter_fixed(patch, size): """ Get filter with fixed size :param patch: :param size: :return: """ samples = [] for i in range(patch.shape[0] - size + 1): for j in range(patch.shape[1] - size + 1): sample = [] for h in range(size): f...
64f969b5bdd168cf029c3080edf14c7a9f63afc7
667,327
import numpy def get_dof_neighbours(V): """ Given a DG function space find, for each dof, the indices of the cells with dofs at the same locations """ dm = V.dofmap() gdim = V.mesh().geometry().dim() num_cells_all = V.mesh().num_cells() dof_coordinates = V.tabulate_dof_coordinates().re...
ac27fbfdac839209aaf562cf1103458498cc8f0b
667,328
def formatColor3i(r,g,b): """3 ints to #rrggbb""" return '#%02x%02x%02x' % (r,g,b)
19791626efad2bfa7795522c3d0d37fd91c63289
667,329
def read_string(file_pth): """ read in a file as a string """ with open(file_pth, encoding='utf8', errors='ignore') as file_obj: string = file_obj.read() return string
ce1cfc8149be034acd4d3d4fdd59700c7fbff217
667,330
def _map_bins_to_labels(bins): """ Maps integers 0-99 to a label according to the distribution specified in `bins`. Example: bins = [10, 20] # implies bin sizes of 10 - 20 - 70 maps to => [0]*10 + [1]*20 + [2]*70 Note that if the integers in `bins` don't add up to 100, this function will ...
37e0327f5cdb2d42f4368f22a2966be4ac4a4729
667,331
def get_supressed_alarms( self, ) -> dict: """Get configured supressed alarms .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - alarm - GET - /alarm/suppress :return: Returns dictionary of appliances and alarm t...
bb83658d9646e75d14364a62e6f31eaf934e5960
667,332
import os def modtime(path): """Returns the modification time of the file at the given path, or None if the time could not be determined for any reason. """ try: return os.stat(path).st_mtime except EnvironmentError: return None
4dd40ef7f2253e162eac3e8c1406288ecafbee53
667,333