content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import itertools def getdates(yr1=2009, yr2=2016, month1=1, month2=12, day1=1, day2=31): """Returns a list of all possible dates as a set of tuples: E.G. date1 = (2009, 01, 01) or datex = (2011, 12, 06) The form is therefore a [(yyyy, mm, dd), ... (yyyy, mm, dd)] This function is set up to return all possible...
b6329add7199be6ab2ea57e623b12f09533d79f1
637,524
from typing import List from typing import Dict def _add_annotation(objs: List[Dict], annotation_key: str) -> List[Dict]: """ Adds a boolean annotation (set to True) to a list of rich text objects (https://developers.notion.com/reference/rich-text) """ for obj in objs: if 'annotations' in ...
9f3f465cd88ebdfa6e5adbc909c0be9a77836bf7
637,525
def read_and_pre_process_xml(file_name): """ Read XML file with the name specified in the argument and pre process the xml so that it can be parsed. Pre Processing removes line retune characters (i.e. "\n"). Arguments: file_name (str): Name of the XML file. Returns: (str): Pre Pr...
e3dbfaf7320d74a58698a61c6e463c08d9bb0e03
637,527
def _normalize_header_name(name: str) -> str: """ According to rfc https://www.ietf.org/rfc/rfc2616.txt header names are case insensitive, thus they can be normalized to ease usage of Headers class. :param name: :return: """ name = name.lower() if name.startswith("http_"): name =...
694087c9af89bca5652bc43fcaeaaa4ccbe86ad0
637,528
def center_text(text, page_width, char_width): """Helper function for calcuating the start x value for centered text.""" text_width = len(text) * char_width return (page_width - text_width) // 2
fb545d39315467606ed08e4aa93ce3159870c68b
637,530
def _stripReverse(s): """Returns the string s, with reverse-video removed.""" return s.replace('\x16', '')
38e1c202b0e38b15caf677dba922ff1b669705c8
637,531
import logging def GetLogger(name: str) -> logging.Logger: """Return a logger. This is a wrapper around logging.getLogger that is intended to be used by the other modules so that they don't have to import the logging module + this module. Args: name (str); The name for the logger. Returns: logg...
d0991494a1b49cc302f110af233878288d424d22
637,539
def secondsToHms(seconds): """Convert seconds to hours, mins, secs seconds - seconds to be converted, >= 0 return hours, mins, secs """ assert seconds >= 0, 'seconds validation failed' hours = int(seconds / 3600) mins = int((seconds - hours * 3600) / 60) secs = seconds - hours * 3600 - mins * 60 return hour...
baf1618e0bd4f72619328ed1bb412dbc039e6438
637,541
def palindromic(s: str) -> bool: """ Checks whether a string is a palindrome. """ size = len(s) for i in range(size // 2): if s[i] != s[size - 1 - i]: return False return True
9695821733b4b6042916a884eb8416eeca9f4483
637,546
def _compute_ANN_row(tree, x): """ For a given survival tree and a feature vector, traverse down the tree to find the feature vector's adaptive nearest neighbors. Parameters ---------- tree : dictionary Tree node of a decision tree. We traverse down the tree taking branches that...
75970eb70c8088b5c021ae9bc60f4efc5175265c
637,548
def text_mention(text_content): """ 处理微博正文中的用户@ :param text_content: 处理对象文本 :return: 是否含有@(1:有,0:无),@数量 """ mention_nums = text_content.count("@") if(mention_nums > 0): return 1,mention_nums else: return 0,0
42506ed5cc438327a71176505efd629895d830b8
637,551
def classname(cls): """Return the full qualified name of a class""" mod = cls.__module__ return cls.__name__ if mod is None else f"{mod}.{cls.__name__}"
2883e5cdb0f3d307cd18c9ce17ac5c9396aba226
637,553
def overlap(a1, a2): """ Check if the given arrays have common elements """ return len(set(a1).intersection(set(a2))) > 0
75d40ab32b56db942c4ba84d3bac852a7619df07
637,556
def transpose(matrix): """return the transpose of a matrix stored as a 9-element tuple""" return (matrix[0], matrix[3], matrix[6], matrix[1], matrix[4], matrix[7], matrix[2], matrix[5], matrix[8])
25c6f6ac09ff1d0305102721963d53282e9b80f3
637,558
def propagate_taxids(res, ranks): """ Transfer taxonomy ids to unassigned ranks based on best known taxonomy Example: {'species': -1, 'family': -171549, 'genus': -171549, 'order': 171549, 'phylum': 976, 'class': 200643, 'superkingdom': 2} should become {'species': -171549, 'family': -171549, '...
4f6495e1c9d19f86b1d3eceffa9eb4c748717d2d
637,560
def flat_clfs(params) -> dict: """Flatten the classifiers for easier access.""" flat = {} for clfs in params["classifiers"].values(): flat.update(clfs) return flat
bb3fbad8f9866848648f6e8a323553534727b9e3
637,564
def getStringForVariables(variables, wordsize): """ Takes as input the variable name, number of variables and the wordsize and constructs for instance a string of the form: x00, x01, ..., x30: BITVECTOR(wordsize); """ command = "" for var in variables: command += var + "," comma...
1710ec9d8f71a48849df2548d4ff936ff909a43c
637,565
import json def get_predictions(file): """ Returns prediction_list (class probabilities) and predicted_final_classes :param file: file produced by save_json() :return: prediction_list (class probabilities) and predicted_final_classes """ with open(file) as json_file: data = json.load(j...
05c10e27eb1537ed045e76d9beb6d060e202f525
637,567
import inspect def get_num_args(f): """ Find the number of arguments a function or method takes (excluding ``self``). """ if inspect.ismethod(f): return f.__func__.__code__.co_argcount - 1 elif inspect.isfunction(f): return f.__code__.co_argcount else: raise TypeError("...
b5620d3fa8501f452e3c520888725f09a131c799
637,568
def getBiggestArea(freePlaceValues, place=1): """ Returns the biggest requested area from the freeMap. If place is 1, the biggest will be returned If place is 2, the second biggest will be returned Etc :param freePlaceValues: Whole map with free places :param place: x biggest area (1./2./3./...
943b4462b33d70bcdda4a0c2d818c17505eaec3b
637,569
def red(x): """Format a string red. Returns: The string `x` made red by terminal escape sequence. """ return f"\033[31m{x}\033[0m"
a48cd1be565e7361c80e9cc7b35298248c2a5af2
637,574
def raster_ds_shape(raster_ds): """Return the number of rows and columns in an opened raster dataset Args: raster_ds: opened raster dataset Returns: tuple of raster rows and columns """ return raster_ds.RasterYSize, raster_ds.RasterXSize
6069c50be27361b4fa896027d022a82b87440de2
637,575
def get_ethertype_value(ethertype): """Convert string representation of ethertype to the numerical.""" if ethertype is None: return None mapping = { 'ipv4': 0x0800, 'ipv6': 0x86DD, 'arp': 0x806 } return mapping.get(ethertype.lower())
8cc3861ed94dc640521a8378905b3e05d749b6f3
637,577
import random def rand_suffix(length=7): """Generate a random suffix of `length` chars""" charset = '0123456789abcdefghijklmnopqrstuvwxyz' return ''.join(random.choice(charset) for i in range(length))
7af309ccb9e2ba477d491209e441208f9dd8bcc8
637,580
def rename_columns_with_data_schema(dfx, data_schema): """ Renaming columns based on a specified data schema :param dfx (dataframe): df with the columns that will be cleaned :param data_schema (dictionary): data schema containing the clean column names :return dfx (dataframe): df after renaming the...
1ec1790b72763736372413a227d8389b61333d06
637,582
def default_wd_filter(x): """default weight decay filter.""" parameter_name = x.name if parameter_name.endswith('.bias'): # all bias not using weight decay return False if parameter_name.endswith('.gamma'): # bn weight bias not using weight decay, be carefully for now x not inclu...
defd970e4bcb589f48011dfb23a4af10fc9c0b50
637,590
def get_row_coords(horiz_line_coords): """Get top-left and bottom-right coordinates for each row from a list of horizontal lines""" row_coords = [] for i in range(1, len(horiz_line_coords)): if horiz_line_coords[i][1] - horiz_line_coords[i-1][3] > 1: row_coords.append((horiz_line_coords[...
7a4949a4fe713c9eb9c2c3079fea09186c05a258
637,591
from typing import Any from typing import List def ensure_list(item: Any) -> List: """Ensure string is converted to a Path. Args: item (Any): Anything. Returns: The item inside a list if it is not already a list. """ if not isinstance(item, list): item = [item] return...
c7895c87121f0265080cac42ab9b3ca1c23cca23
637,593
from pathlib import Path def join_analysis_path(data_path: Path, analysis_id: str, sample_id: str) -> Path: """ Returns the path to an analysis JSON output file. :param data_path: the application data path :param analysis_id: the id of the NuVs analysis :param sample_id: the id of the parent samp...
f698239fa576082a8af2ff2b98d1571abdf59526
637,596
def get_value(deep_dict, path): """Return deep_dict[path[0]][path[1]...""" value = deep_dict for key in path: value = value[key] return value
8d99b28917c028a31199c0411f59ed19900f11f5
637,597
def is_draft(catalog_record): """ Is the catalog record a draft or not. Args: catalog_record (dict): A catalog record Returns: bool: True if record is a draft """ if catalog_record.get('state') == 'draft': return True return False
aa61fccf2678582394632ce8fb0e52e28d527ba3
637,602
def full_rb_decay(A, B, C, lambda_1, lambda_2, m): """Eq. (15) of Wood Gambetta 2018.""" return A + B * lambda_1 ** m + C * lambda_2 ** m
602f425025add047ee3502e73f7a5487be4da425
637,604
def translate_list(dictionary, list_to_be_translated): """For a given list with entries and a dictionary, it return a new list with the translated entries""" translated = [] for i in list_to_be_translated: translated.append(dictionary[i]) return translated
20874aba3b03e11d9386d8fd425f2751c19163d2
637,606
def get_message_id(timestamp, topic): """Unify the way to get a unique identifier for the given message""" return '{}{}'.format(timestamp, topic.replace('/', '_'))
072d03347ce44d30ebbe28ad6ff2559c021784db
637,608
def _services_around_node(node_geometry, services_gdf, services_gdf_sindex, radius): """ It supports the weight_nodes function. Parameters ---------- node_geometry: Point geometry the street services_gdf: Point GeoDataFrame services_gdf_sindex: Rtree Spatial Index radius: f...
7782734c56f1dc8c24427543765f5a5e3ab61868
637,612
import networkx as nx import pickle import codecs def plot_aces_conversion_graph(graph, filename, prog="dot", args=""): """ Plot given *aces-dev* conversion graph using `Graphviz <https://www.graphviz.org/>`__ and `pyraphviz <https://pygraphviz.github.io>`__. Parameters ---------- graph :...
7039de32067874f131dbedd8ae11f11c64c3a47a
637,617
def perform_group_by(h2oFrame, na): """ Given a H2OFrame h2oFrame, and the na treatment, perform chained group by aggregation and return the results of aggregations in an H2OFrame. :param h2oFrame: :param na: :return: """ grouped = h2oFrame.group_by("class") grouped.count(na=na).min...
440c61e437785a04147bc5afd9f252d6ce72c0eb
637,618
def get_requirements(path): """ Import user's requirement file and save as a variable """ user_requirements_list = [] with open(path, 'r') as filehandler: user_requirements_list = [package_name.rstrip() for package_name in filehandler.readlines()] return user_requirements_list
b0eb1738cd26da9a83177c430297f83dc7e17e17
637,621
def _CreateExceptionRetryHandler(exception): """Returns a retry handler for given exception(s). Please see WithRetry class document for details. """ if not (isinstance(exception, type) and issubclass(exception, Exception) or (isinstance(exception, tuple) and all(issubclass(e, Exception) fo...
a7d3c5d095de3ac65eb1ad22fe92b86cde00c4e3
637,623
def land(*fns): """ Functionally logical ands the given functions. >>> lor(starts_with('123'), ends_with('asd'))('123asd') True >>> land(starts_with('123'), ends_with('asd'))('asd') False >>> land(starts_with('123'), ends_with('asd'))('123') False :param fns: Functions to and :...
8b48e5862704548515593d8183aa88b82392da51
637,624
def p_w_from_rh_p_and_ws(rh, p_ws): """ Calculate water vapor pressure from relative humidity and water vapor saturation pressure Eq(6) in "CHAPTER 6 - PSYCHROMETRICS" in "2001 ASHRAE Fundamentals Handbook (SI)" :param rh: relative humidity [-] :type rh: double :param p_ws: water vapor saturati...
62ba0ab8ced023899e58817a31a3a08d434d94bb
637,625
def getUser(ctx, *arg): """ returns a user id from either the arguments or if None is passed the sender """ if arg == (): # if no argument is passed go with sender return(ctx.author.id) else: return(arg[0].strip('<!@> '))
61bd3b47d9b3553349530d5292804d703f1dc5ed
637,626
def entuple(x,n=2): """ Make sure given value is a tuple. It is useful, for example, when you want to provide dimentions of an image either as a tuple, or as an int - in which case you can use `(w,h) = entuple(x)`. :param x: Either atomic value or a tuple. If the value is atomic, it is converted to a tu...
c5e8ca94d552b746b45342b803dd267cd7c481f3
637,628
def get_func_code_details(my_F): """Extract co_code, co_consts, co_argcount, func_defaults """ bytecode = my_F.__code__.co_code consts = my_F.__code__.co_consts argcount = my_F.__code__.co_argcount defaults = my_F.__defaults__ return bytecode, consts, argcount, defaults
3ce4ed957d142eb79ec5c65ac101c636324103fa
637,629
def connection_table_to_matrix(conn_df, group_cols='bodyId', weight_col='weight', sort_by=None): """ Given a weighted connection table, produce a weighted adjacency matrix. Args: conn_df: A DataFrame with columns for pre- and post- identifiers (e.g. bodyId, type or instance)...
a12819057e6d9c9d7d2df94485a211babaf20989
637,634
def _SkipTreeCheck(input_api, output_api): """Check the env var whether we want to skip tree check. Only skip if include/v8-version.h has been updated.""" src_version = 'include/v8-version.h' if not input_api.AffectedSourceFiles( lambda file: file.LocalPath() == src_version): return False return ...
b3d577e6b72f22208af22f174f2479afbb1e4570
637,637
def translate_to_slack(datum, casa): """ For a single entry in the query results, create a dict with the relevant information. """ if datum['ementa'] == 'None': resumo_tipo0 = 'Excerto' resumo0 = datum['resumo'] else: resumo_tipo0 = 'Ementa' resumo0 = datum['emen...
aaaa028779da41d6d436f04b0a9796632f12d1e6
637,638
def _clip(value, lower, upper): """ Helper function to clip a given value based on a lower/upper bound. """ return lower if value < lower else upper if value > upper else value
a84395414ca4fd6739ecebc6c2e0c1ee4716f506
637,639
def parse_relative_year_value(relative_year: str) -> int: """ Parses a relative year value such as "去年" :param relative_year: The year to parse :return: An integer representing the relative value of the year, for example -1 """ if relative_year == "去年": return -1 if relative_year == ...
c530ec09a57753c08db0e121228fdf64554a18e9
637,640
import pkg_resources def package_version(name=''): """ Get version of arbitrary package. The function relies on introspection using :mod:`pkg_resources`. Parameters ---------- name : :class:`str` Name of package the version should be obtained for Returns ------- version ...
27d787cd3ed51f9105dce4d8eb1915579883bbdf
637,642
import re def findVars(expression): """Finds and extracts the variables in an expression using regex pattern matching. Returns a list of matches in the given string.""" variableRegex = re.compile('[a-zA-Z][a-zA-Z0-9]*') variables = re.findall(variableRegex, str(expression)) return variables
c794ec2f5e49d0c5cf006d8bbc5718bd28161e49
637,646
def cif2float(cifnum): """ Convert a cif-floating point number that may include an uncertainty indication to a proper floating point number. In a .cif file the value "0.4254(4)" is a floating point number where the digit in brackets gives the uncertainty. To convert this number to a regular Pyt...
ecac9f0aeff17da6b38355cf87c9fcc35a6a025f
637,649
import re def splitCIGAR(CIGAR): """ Takes CIGAR string from SAM and splits it into two lists: one with capital letters (match operators), and one with the number of bases """ matchTypes = re.sub('[0-9]', " ", CIGAR).split() matchCounts = re.sub('[A-Z]', " ", CIGAR).split() matchCounts = [in...
e579bb6254ff1edf9378a0fbddd61975f38456d9
637,650
def extend_padding(ls_of_ls, padding=''): """ Takes in a lists of lists, returns a new list of lists where each list is padded up to the length of the longest list by [padding] (defaults to the empty string) """ maxlen = max(map(len, ls_of_ls)) newls = [] for ls in ls_of_ls: if l...
f9316ae9853f5ced56cf9dbb80abd00b18a72fe3
637,652
def _crawl(name, mapping): """ ``name`` of ``'a.b.c'`` => ``mapping['a']['b']['c']`` """ key, _, rest = name.partition('.') value = mapping[key] if not rest: return value return _crawl(rest, value)
ac82ab46cce5187ae50c3943b24aa42657f1ffc4
637,653
def get_enum(key_list, enum_dict): """Returns the mcf format of enum dcid list that represents a given value(s). Used to convert a list of values which map to enums to their appropriate enum dcid, as given by the enum_dict. For this import, enum_dict is either ASSOCIATION_ENUM_DICT or EVIDENCE_ENUM_DIC...
defacb5a052459e4d085a3d4c5ec2922fb042542
637,654
import re def loxi_name(ident): """ Return the LOXI name of an openflow.h identifier """ # Order at the outer level matters as super strings are listed first rules = [ # The following are for #define macros and have highest precedence dict(OFP_MAX_TABLE_NAME_LEN = "OF_MAX_TABLE_NAME_LEN")...
3c9a0e369a6368b105fefc04869ebe7d730866bd
637,656
def rotate_list(alist): """Pop the last element of list out then put it into the first of list. :param alist: A list that want to rotated. :return alist: A rotated list. """ assert type(alist) == list last = alist.pop() alist.insert(0, last) return alist
d3fefe92870aea63e51fff82c274990a0d9151f6
637,657
def downgrade_sample_rate_of_labels(labels, original_sample_rate, needed_sample_rate): """This function downgrades sample rate of provided labels to needed_sample_rate It is worked through calculating ratio between original_sample_rate and needed_sample_rate and then thinning provided labels :par...
658d97557ae11c9d3b7514f03c309a3cbfe9e18a
637,660
def fullname(o): """ Gives a full name (package_name.class_name) for a class / object in Python. Will be used to load the correct classes from JSON files """ module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ # Avoid reporting __built...
134d50e292967c89e03b5e8708b6015dba2485a6
637,665
def Status2Int(protect_status): """ returns the int-value related to the input-str Read / Write := 0 Write protect := 1 """ rtn_value = 0 if 'yes' in protect_status.lower(): rtn_value = 1 return rtn_value
827736cf11981d7fc239cab59444b3b21dc246a5
637,666
def compute_normalized_rho_pars(u, b): """Compute normalized rho_0, rho_min given b, u=rho_min/rho_0 Parameters ---------- u : `float` u = rho_min/rho_0 parameter. b : `float` b parameter Returns ------- rho_0, rho_min : (`float`, `float`) """ rho_0 = ((b + 2)/(...
186aa4c62812d216edbe2bd2ca309cfbd2c668cd
637,667
def return_success(data=None): """ Generates JSON for a successful API request """ if data is None: return {"success": True} return {"success": True, **data}
f780a1e2d9c1c6e3b2be20db3b97717d3836adee
637,671
def on_whitespace(s): """ Returns tokens taking whitespace as word boundaries >>> on_whitespace('This is not a test.') ['This', 'is', 'not', 'a', 'test.'] Args: s: a string Returns: list: a list of strings """ return s.split()
25960ed620d77dcc0b4eb723f585a2d4a5d5734e
637,676
def get_user_id(user_id: str) -> str: """ Formats the user_id to a plain format removing any <, < or @ :param user_id: slack id format :type user_id: str :return: plain user id :rtype: str """ return user_id.strip("<>@")
7e69ecf3e67607aba947a7980703f50f23d10c5f
637,677
def converter(temperatures, convert): """Returns a sequence that converts each Celsius temperature to Fahrenheit >>> def convert(x): ... return 9.0*x/5.0 + 32 >>> temperatures = [10, 20, 30, 40, 50] >>> converter(temperatures, convert) [50.0, 68.0, 86.0, 104.0, 122.0] """ return [co...
09ca4bff8999b6721e4f9c28767db01016bf0974
637,679
def clean_specie_name(specie_str: str) -> str: """ Clean up the species name from '<element>\xa0<roman number for oxidation state>' to '<element>' """ return specie_str.split("\xa0")[0]
fd5f435982fca9471b08cf02b217fd849c38fee6
637,682
def is_integer(value, cast=False): """Indicates whether the given value is an integer. Saves a little typing. :param value: The value to be checked. :param cast: Indicates whether the value (when given as a string) should be cast to an integer. :type cast: bool :rtype: bool .. code-block:: p...
c2fd05d572be8cd799480e953b0282c59b24c649
637,683
def ConvertPrivateIpv6GoogleAccess(choice): """Return PrivateIpv6GoogleAccess enum defined in mixer. Args: choice: Enum value of PrivateIpv6GoogleAccess defined in gcloud. """ choices_to_enum = { 'DISABLE': 'DISABLE_GOOGLE_ACCESS', 'ENABLE_BIDIRECTIONAL_ACCESS': 'ENABLE_BIDI...
fa7520e364d7b489c04015acc88637c1c92571cd
637,685
def _bitcmp(bit, bit_ref, wildcard='x'): """ Compares the string representation of a binary number ignoring any bits on the reference string 'bit_ref' marked with a wildcard. """ bit = bit.replace('0b', '') bit, bit_ref = list(bit), list(bit_ref) bit.reverse(); bit_ref.reverse() # Start comp...
0f14022f369e5bf4dd9dbb292c95082a795c894f
637,686
import random def random_saturation(im, lower=0.5, upper=1.5): """Random change saturation Args: im(numpy.array): one H,W,3 image lower(float): change lower limit upper(float): change upper limit """ if random.random() < 0.5: im[:, :, 1] *= random.uniform(lower, u...
f81fe55559afc28a727622426f90475fea5d0fa5
637,687
def make_complex_matrix(m): """ Transforms a block 2x2 matrix of real and imaginary part into a complex matrix :param m: block 2x2 real matrix as numpy/scipy array :return: complex matrix as numpy/scipy array """ return m[:m.shape[0]/2, :m.shape[1]/2] + 1j * m[m.shape[0]/2:, :m.shape[1]/2]
143db8755d2cf5258bc7bae4786bc6c4edd9230d
637,689
from datetime import datetime def fmt_timestamp(ts=None): """ Jinja filter to format date/time from timestamp. """ if ts is None: return 'no-timestamp' dt = datetime.fromtimestamp(int(ts)) pretty_time = dt.strftime('%m/%d/%y %I:%M %p') return pretty_time
ccd30f229532ff1f26d35a79a44526e606c87e13
637,690
import codecs def load_utf8(filename): """Load UTF8 file.""" with codecs.open(filename, 'r', encoding='utf-8') as f: return f.read()
9ce0f51879b2bc4b83690fb06a0353c3c73235cb
637,694
def build_info(file_name, meta_features): """Builds the info of a dataset in a presentable manner""" info = {'dataset': int(file_name[:-5])} for feat_name, value in meta_features.items(): new_name = feat_name.replace("_", " ") info[new_name] = value return info
8e8291fb17034afe14274e4955e48a630c03dfe7
637,695
def train_test_split(features, target, split_ts): """ Splits all provided TimeSeries instances into train and test sets according to the provided timestamp. Parameters ---------- features : TimeSeries Feature TimeSeries instances to be split. target : TimeSeries Target TimeSerie...
0d803476cc53f35f9b1171e1835366e408741442
637,700
import colorsys def hs_to_hex(hue: float, saturation: float) -> str: """Convert hue and saturation to a string hex color.""" rgb = colorsys.hsv_to_rgb(hue / 100, saturation / 100, 100) return "#{:02x}{:02x}{:02x}".format( round(rgb[0]), round(rgb[1]), round(rgb[2]) ).upper()
ad47cb84c4d656584b2051a66281aeb858bc7b80
637,702
def phi(x, y, ck, i): """ The linear basis functions Parameters ---------- x : np.array x-values. y : np.array y-values. ck : np.array basis function coef. matrix. i : int which basis function to use. Returns ------- numpy.array basis...
0277396c935ca9af555d9f253808227cf295c647
637,703
def performance_measure(y_true, y_pred): """ Compute the performance metrics: TP, FP, FN, TN Args: y_true : 2d array. Ground truth (correct) target values. y_pred : 2d array. Estimated targets as returned by a tagger. Returns: performance_dict : dict Example: >>> f...
83d2382cc35836275ebfc4badfbc023bb9a9340c
637,707
import torch def prep_images(images): """ preprocess images Args: images: pytorch tensor """ images = images.div(255.0) images = torch.sub(images,0.5) images = torch.mul(images,2.0) return images
5faa9cc5f5fe33b56719437329fd213b5325fab5
637,708
def source_type_normalize(source_type): """ Make it easier to ignore small inconsistencies in these key word arguments. >>> source_type_normalize("journals") 'journal' >>> source_type_normalize("Journal") 'journal' """ ret_val = None normal = {"journals": "journal", "...
e4aa0a5e59eca8498f318f8f7204da9cb864475a
637,709
def csdele(self, kcn1="", kcn2="", kcinc="", **kwargs): """Deletes local coordinate systems. APDL Command: CSDELE Parameters ---------- kcn1, kcn2, kcinc Delete coordinate systems from KCN1 (must be greater than 10) to KCN2 (defaults to KCN1) in steps of KCINC (defaults to 1). If ...
6a6847079506af51cd7fa3e5c1c17ab59f6c93df
637,715
import itertools def nth(iterable, n, default=None): """ Returns the nth item or a default value. This code is mildly adapted from the documentation. N.B. This returns the *base-0* nth item in the iterator. For example, nth(range(10), 1) returns 1. """ return next(itertools.islice(iterable,...
c55431eaaee29c323e5f05d3049572b65813b029
637,717
import asyncio async def compute_fancy_greeting(name: str, seen: int): """ Compute a personalized greeting, based on the number of times this @name had been seen before. """ templates = ["", "Welcome %s", "Nice to see you again %s", "Third time is a charm %s"] if seen < len(templates): gre...
45c9159e4ac724c6df4c4e86807c3fd8d2397eee
637,722
def transform(data, median, var_25_75): """Scale data using robust estimators. Scale the data by subtracting the median and dividing by the variance, i.e. the difference between the 75th and 25th percentiles. Parameters ---------- data : pandas DataFrame, shape (n_spectra, n_freq_point...
91b74ec87ec9cf65e4accb7a3ebd02d3ab7a7e5e
637,723
def get_tags(entities): """ Args: entities (Iterable[Entity]): the entities in a sentence Returns: Set[str]: a set of their tags, excluding 'O' """ return {entity.tag for entity in entities} - {'O'}
21cbdeca18d9c8a3dc367db33b41e47c7e6905c6
637,725
def g(x, y): """ A multivariate function for testing on. """ return -x**2 + y
a134054e8731bd81c2f91980e71ede051dfc305f
637,728
def verb_check(tag): """ :param tag: a string representing a POS-TAG :return: boolean if the given tag belongs to the verb class """ return tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']
3aeafc50f854c8a630c0702d2221d87315e6bc40
637,729
def parse_connector_version(version): """Parse a connector version string into a tuple (hadoop version, major version, minor version, patch version, release candidate).""" hadoop_version, version = version.split("-", maxsplit=1) hadoop_version = int(hadoop_version[6:]) release_candidate = None if "...
60a8c817e7d725d9b07201e2e4276c52e2932d39
637,732
def vertices_generation(number_of_vertices): """ Generate the vertices list :param number_of_vertices: :return: vertices list in format [0, 1, 2, 3...] """ # here, the list is much more efficient than set return [s for s in range(1, number_of_vertices + 1)]
3b05d7711092bb094bf214d94c4237b0a8c12ccc
637,736
def get_E_pump_hs_d_t(E_pump_SW_d_t, E_pump_gsRW_d_t): """日付dの時刻tにおける1時間当たりのポンプの消費電力量 (8) Args: E_pump_SW_d_t(ndarray): 日付dの時刻tにおける1時間当たりの送水ポンプの消費電力量(kWh/h) E_pump_gsRW_d_t(ndarray): 日付dの時刻tにおける1時間当たりの熱源水ポンプの消費電力量(kWh/h) Returns: ndarray: 日付dの時刻tにおける1時間当たりのポンプの消費電力量(kWh/h) """ ...
d99d537afed9e06ba5fa87f41340301d2f9d9900
637,741
def txt_category_to_dict(category_str): """ Parameters ---------- category_str: str of nominal values from dataset meta information Returns ------- dict of the nominal values and their one letter encoding Example ------- "bell=b, convex=x" -> {"bell": "b", "convex": "x"} ""...
d7a4e6c0e3e08fcc3af56d3408b722f99e522a07
637,743
import logging def get_logger(name): """Returns a customized logging object. Multiple calls to with the same name will always return a reference to the same Logger object. Args: name (str): Dot-separated hierarchical name for the logger. Returns: Logger: An instance of :any:`logging...
44996c138119696ec0f9ae5a3f659bfee4efa168
637,745
def derive_http_method(method, data): """Derives the HTTP method from Data, etc :param method: Method to check :type method: `str` :param data: Data to check :type data: `str` :return: Method found :rtype: `str` """ d_method = method # Method not provided: Determine method from ...
9fd1941c2de86fdf3a06eb05a6e7046705cb4cd3
637,746
import time def encode_tag(prefix, time_tuple, time_format): """ Create a [prefix:time] playlist tag using specified time formatting. Args: prefix ::: (str) unique identifier for playlist series time_tuple ::: (`time.struct_time` instance) time to encode in tag time_format ::: (str) f...
66dbf81bc424bdb2f8abed47c8cab527c034c6ee
637,750
def drop_dupes(sequence): """Drop duplicate elements from a list or other sequence. C.f. https://stackoverflow.com/a/7961390 """ orig_type = type(sequence) return orig_type(list(dict.fromkeys(sequence)))
ff8380212264eb2fa4aa3f3fbc747c9e41f22984
637,752
def kcalc(self, kplan="", mat="", kcsym="", klocpr="", **kwargs): """Calculates stress intensity factors in fracture mechanics analyses. APDL Command: KCALC Parameters ---------- kplan Key to indicate stress state for calculation of stress intensity factors: 0 - Plane stra...
7c8b1cd90c756878590ffadad397f5bd760c560d
637,755
from pathlib import Path def _get_activity_names_path(data_processed_dir: str) -> Path: """Returns path to the file with activity names. """ return Path(data_processed_dir, "activity_names.json")
a9b9224aaefb4b170cd8b2c539e353ac4f0c8d54
637,764
import typing async def pagify_commands(coms: typing.List[str]) -> typing.List[str]: """Takes a list of command names and returns a pagified list It will return a page of 15 commands Parameters ---------- coms: List[:class:`str`] The list of commands to iterate over Returns ----...
21b1acb5b56a6ced7ce49eea93b0a8ca665a8061
637,766
import sympy def symbolize(pair): """Turn a pair of symbol names into a pair of symbols.""" return (sympy.Symbol('x' + str(pair[0])),sympy.Symbol('x' + str(pair[1])))
78953374868ecd10989e796881003bb7ef38b036
637,768