content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def recall_pos_conf(conf): """compute recall of the positive class""" TN, FP, FN, TP = conf if (TN + FP) == 0: return float('nan') return TP/float(TP+FN)
333f0aec1a6e84e0affa340c8bfcaa44d153230c
574,820
import plistlib def read(f: str): """Read property list""" result: dict = dict() with open(f, 'rb') as _f: result = plistlib.load(_f) return result
a563dbf64acf4e066c7ee13e693db7fee2ec0076
574,822
def list_or_single(func, i, *args, **kwargs): """ 将单个对象或列表中的每个项传入给定的函数,并返回单个结果或列表结果,类似于 map 函数 :param func: 传入到的函数 :param i: 列表或单个对象 :param args: func 函数所需的 args :param kwargs: func 函数所需的 kwargs :return: 若传入的为列表,则以列表返回每个结果,反之为单个结果 """ if isinstance(i, list): return list(map(...
7321f0c08a6f06c1d5c1808c1e5ef15f1779553b
574,823
from bs4 import BeautifulSoup def crawl_url(input_url): """ Finds reddit post titles at a given url and returns a string containing them, separated as individual sentences. """ intitles = "" soup = BeautifulSoup(input_url.text, 'lxml') # Find all the titles on a single reddit page tit...
d4831583137494aef2a598a80f8b1aece745acbc
574,824
def warn_scraper_dir(tmp_path): """Set scraper directory.""" return str(tmp_path.joinpath("warn-scraper"))
a70513b2e72b30849173c87100f697cfe1348117
574,831
def addfive_getter(self): """A test getter function that just returns _value.""" return getattr(self, '_value', None)
1f3bc9130f1dc5ae6dc77ea5cae8dd82d207c787
574,832
import shutil def command_exists(cmd: str) -> bool: """Check if command exists Args: cmd: executable name """ if shutil.which(cmd) is None: return False else: return True
9a8356ee2c9703f33c244321308afc38053edf49
574,836
def remove_suffix(text, suffix): # type: (str, str) -> str """Remove suffix from text if any""" if text.endswith(suffix): return text[:len(text)-len(suffix)] return text
a2a94c78343a55bae4f0c3239db5880c87eb02d8
574,839
def check_mailing_list(sig_info, errors): """ Check mailing_list :param sig_info: content of sig-info.yaml :param errors: errors count :return: errors """ if 'mailing_list' not in sig_info.keys(): print('ERROR! mailing_list is a required field') errors += 1 else: ...
dec5a54e4d20c0873c5190f3ac02d44da6795b7d
574,843
def dict_from(iterable, from_func=lambda x, y: y, ignore=lambda k, v: False): """Generate a dict from (key, value) iterator. - iterable: a (key, value) iterator - from_func: a reduce function with same key for generation - ignore: a function to ignore key/value Return a generated dict. Exampl...
23320292d3deb2a24aeb452a9be2298f9263857e
574,848
from typing import List def canReach(arr: List[int], start: int) -> bool: """Return true iff you can reach any index in 'arr' with value 0, starting from the specified 'start' index.""" visited = set() leftBound = 0 rightBound = len(arr) - 1 def canReachViaDFS(curr: int) -> bool: """...
ee84aed2486fcd03545bea8302c0a331a04e5ce4
574,851
def rescale_ranges(n, range1, range2): """ Given a value n and the range which it belongs to, the function rescale the value, given a different range. Parameters ---------- n: int, float a value range1: tuple a certain range, e.g. (0, 1) or (10.5, 100). The value n shoul...
f553bf835771f834d520c84e6c26a7a0935c7283
574,857
from pathlib import Path def read_source_code(filepath: Path) -> str: """Reads python source code and returns it as a string Args: filepath: path to file Returns: source: a content of the file returned as single string """ with open(str(filepath), "r") as file: source_cod...
bb85c56b841a598885c8a083a120580723eb048b
574,858
def get_package_repo_name(package_info): """ The source repo name is stored with the package. The "From repo" line indicates where the package came from. Return the repo name or None if not found """ # should check that there is EXACTLY one line repo_lines = \ [line for line in pac...
f958c6aec0ab30dacf2fa7831f36936df0e7821e
574,859
import re def get_title(passenger: str) -> str: """Extracts the title (Mr, Ms, etc) from the name variable.""" line = passenger if re.search("Mrs", line): return "Mrs" elif re.search("Mr", line): return "Mr" elif re.search("Miss", line): return "Miss" elif re.search("Ma...
8928d546e8cdc01a8a9330435c4e22ac0ecb8970
574,861
def qc_curve_group_well(well, tests, keys=None, alias=None): """ Run tests on a cohort of curves. Args: well (welly.well.Well): Well object. tests (dict): a dictionary of tests, mapping mnemonics to lists of tests. Two special keys, `all` and `each` map tests to the set ...
ca745890714e4d58efd9ac8549b43f1fdc346db6
574,871
import torch from typing import Tuple def _keypoints_to_heatmap( keypoints: torch.Tensor, rois: torch.Tensor, heatmap_size: int ) -> Tuple[torch.Tensor, torch.Tensor]: """ Encode keypoint locations into a target heatmap for use in SoftmaxWithLoss across space. Maps keypoints from the half-open interv...
d160621371ed14224e2d6d1a0bda7bf89948a250
574,874
def ast_to_callable(ast_tree): """ Convert an ast containing a single function definition into a callable version of that function. This is the most magical part of this whole program. `compile` takes the AST tree and turns it into a code object which contains compiled python ready to execute b...
ab6765ad11d04a93cbe05ee3c31811a20a17a134
574,881
def _propagate_well_known_tags(tags = []): """Returns a list of tags filtered from the input set that only contains the ones that are considered "well known" These are listed in Bazel's documentation: https://docs.bazel.build/versions/main/test-encyclopedia.html#tag-conventions https://docs.bazel.build...
dc2ddfb680f76eff0c75cb806149df945f423ac2
574,883
def _convert_dataarray_attributes_xderivative(attrs,grid_location=None): """Return the dictionary of attributes corresponding to the spatial derivative of a scalar field in the x-direction Parameters ---------- attrs : dict-like object dictionnary of attributes grid_location : str ...
59939487868652bd4d30112101f127d93c2747ba
574,890
def post_res(response): """Hook for set Content-Type on all URLs.""" response.headers["Content-type"] = "json" return response
4aa5a68ee332ac37132a38eaf34e63041a992012
574,892
def find_series(name, obj, series_number): """return hdf5 group object if it corresponds to indicated series_number.""" target_group_name = 'series_{}'.format(str(series_number).zfill(3)) if target_group_name in name: return obj return None
e71edc9f8b092d382ed288292c0c0baa2558b8e3
574,893
import math def turan(n, r): """ Calculates the number of edges in a Turan graph https://en.wikipedia.org/wiki/Tur%C3%A1n_graph :param n: vertex (int) :param r: max clique (int) :return: number of edges :rtype: int """ mod = n % r upper = math.ceil(n / r) # ⌈n/r⌉ lower = m...
f579c535db52844f9bd08069b2b6dd9aeeaede39
574,897
from typing import Tuple def get_edge_line(node_1: Tuple[int, int], node_2: Tuple[int, int] ) -> Tuple[float, float]: """ This function returns the slope and intercept of a linear function between two given points in a 2-dimensional space Args: node_1 (Tup...
0f5b52ba46bea4a9c3387c11971f61ace7848761
574,898
import math def ap_dhp_damage(dhp, dmg): """Compute the AP needed to achieve the desired HP loss from the given damage. The input health loss *dhp* is always truncated before computations. Negative *dhp* and/or *dmg* are accepted. Note that some combinations of *dhp* and *dmg* do not admit a solu...
876f2621dcbf3cc3133cdb6c669f03953a74802c
574,899
from typing import Optional def fraction_description(fraction: Optional[float]) -> str: """ Return a string for describing a fraction (including a percent representation). """ if fraction is None: return "None" percent = fraction * 100 return f"{fraction:.4g} ({percent:.4g}%)"
c0c5a25ac5d9b5132ceb3c8b0f0bb1a89d92962d
574,900
def gen_calc_scans_n(inpt_data_dict, inpt_selected_samples): """Get the total number of scans that will be run (i.e., represented in both the Notebook data dict and in list[selected samples]). For single shot-per-image (non-ALC) datasets/Notebooks. Parameters ---------- inpt_data_dict : d...
59f76673c305027569b08ef368f11b1f8a730bd4
574,901
def unscale_mb(m, b, factor_x, factor_y): """Unscale the slope and intercept of a linear fit that was performed to data that was rescaled.""" # x * factor_x * m = y * factor_y --> y / x = ... m_real = m * factor_x / factor_y # b = y * factor_y --> y = ... b_real = b / factor_y return m_re...
4b22e3487eafd3c2cf9adcb8d0701ec2c8b2cd0b
574,902
def get_instructor_term_list_name(instructor_netid, year, quarter): """ Return the list address of UW instructor email list for the given year and quarter """ return "{uwnetid}_{quarter}{year}".format( uwnetid=instructor_netid, quarter=quarter.lower()[:2], year=str(year)[-2:]...
60f893ebb0b128a1a5272424107ee630def5e9b0
574,903
def use_operator_or_provided_hint_unless_contradicting( operator, hint_attr_name, provided_hint_value, message): """Get combined hint in the case where operator.hint should equal hint. Args: operator: LinearOperator that a meta-operator was initialized with. hint_attr_name: String name for the attrib...
1146e7a1a152c221e9dd552601aa1c512c817cad
574,905
def is_inc_monotonic(lst): """ Check whether the the elements in the list increase monotonically. Arguments --------- lst: list Returns -------- Bool, whether the elements of the list increase monotonically (True) or not (False) """ return all(x < y for x, y in zip(lst,...
9c3820816be4676d70bafa196ecfa605262eb079
574,908
def _is_txt_file(filename): """Is the given filename a text file?""" return len(filename) > 4 and filename[-4:] == '.txt'
c479480da999b93bf9a3a12ebfe1b199f9759e14
574,909
def listify(x): """ Example: >>> listify('a b c') ['a', 'b', 'c'] >>> listify('a, b, c') ['a', 'b', 'c'] >>> listify(3) [3] """ if isinstance(x, str): if ',' in x: return [x1.strip() for x1 in x.split(',')] else: r...
d7ed1484f498de7b9b71343437c85b96bf6b248c
574,912
from typing import Optional import torch def batch_eye( eye_dim: int, batch_size: int, device: Optional[torch.device] = None ) -> torch.Tensor: """Create a batch of identity matrices. Parameters ---------- eye_dim : int Desired eye dimension. batch_size : int Desired batch dim...
d1542fcc9a24a5a0306552cf47019891a26634e8
574,914
def symbol_winner(board, symbol): """ Decides if "symbol" has won the game """ dim = len(board) # Checking rows for i in range(dim): symbol_won = True for j in range(dim): if board[i][j] != symbol: symbol_won = False break if s...
38bdcde3a8f1e025b4898be5156a5a7ceee9cfea
574,916
import random def compute_walk(count, x0=0, step=1, seed=0): """Random walk count: number of steps x0 : initial position (default 0) step : step size (default 1) seed : seed for the initialization of the random generator (default 0) """ random.seed(seed) x = x0 ...
b0aa5842b2176e1e4ac743ea258eb519a3d9c0ef
574,918
from pathlib import Path def create_ouput_file(result_path: Path, k: int) -> Path: """Create path to print the resulting candidates.""" parent = result_path / f"batch_{k}" parent.mkdir(exist_ok=True) return parent / "candidates.csv"
0e93c27ea8f7c80d6ac862de0be2bbbf6e1e4116
574,921
def is_openapi3(openapi_version): """ Returns True if openapi_version is 3 """ return openapi_version and str(openapi_version).split('.')[0] == '3'
9a4022f5776ad161bb8ba1ba3ae8e94fd95314b1
574,926
def _stride_size(node): """Computes stride size given a TF node. Args: node: Tensorflow node (NodeDef proto). Returns: stride_x: Stride size for horizontal direction (integer). stride_y: Stride size for vertical direction (integer). """ strides_attr = node.attr["strides"] stride_y = strides_at...
9b90641b18bf4726563386ee0b782e0daedd2799
574,927
def normalize(x): """ Helper function for normalizing the inputs. Normalization is an affine transformation such that the minimal element of x maps to 0, and maximal element of x maps to 1 Args: x (``np.ndarray``): the array to be normalized Returns: ``np.ndarray``: a normali...
62c18aeecaf0672fa1c73e380c96723e8373510f
574,933
from pathlib import Path from typing import Any import pickle def load_pickle(p: Path) -> Any: """Load pickle from file""" with open(p, 'rb') as file: return pickle.load(file)
b7950b50d24b1e8e0cbb271f93bbf0e9974a485d
574,934
import glob def to_files_or_content(value): """File path/glob/content disambiguator. Check if the value passed is a glob, a set of files in a list or is string content. Args: value (str): Value to check. Returns: tuple: Two values being the first a boolean that indicates if ``va...
e704b0a02ab70ac3ee631e1530e146b8da8390f2
574,935
def _adr_params(inverter_params): """Return True if `inverter_params` includes parameters for the ADR inverter model.""" return {'ADRCoefficients'} <= inverter_params
140b6e18121d1e0132396e7dfb4895433cbe1ce9
574,937
def linesegmentsintersect(p1, p2, q1, q2): """Checks if two line segments intersect. Input: p1 : The start vertex of the first line segment. p2 : The end vertex of the first line segment. q1 : The start vertex of the second line segment. q2 : The end vertex of the second line se...
7b22687ee76b05632959654f8973fc902cca6ece
574,943
def CheckResponse(code): """ Analyze the given response code. :param code: Integer value :return: String response describing API response code """ response_codes = {200:'Success', 301:'Server Redirecting to new endpoint.', 401:'Credentials Not Authenticate...
51c2f558348dceb6e718da68b097c0c7456abde1
574,947
import random def randomly_sample_subset(dataset, size=500): """Randomly sample subset from a dataset""" random_indices = [random.randint(0, len(dataset) - 1) for i in range(size)] return [dataset[i] for i in random_indices]
87b4d070c835710d95d102a2ad6f644bfa1fd93f
574,952
def height_from_height_chest(segment_length): """ Calculates body height based on the height of the chest (equal to the nipples) from the ground args: segment_length (float): height of the chest (equal to the nipples) Returns: float: total body height """ if segment_length <= 0...
d0e787ae9f2782af72fc71fda61ed5d02408633e
574,953
def session_ended_request_handler(handler_input): """Handler for session end.""" return handler_input.response_builder.response
d297d95d3a2fc226da81fdc3d0eb43c21286e18a
574,960
import re def getEntities(data_all): """ This function contains a list of entitites from a supplied data frame. Input: data_all: data frame with entities Returns: List of entities """ data_replaced = [re.search('\|.*}', s) for s in data_all[0]] entities = list() fo...
86e9978d3e90185de93d4114f17ea82fcaabcc2b
574,961
def copy_with_meta(class_to_copy, meta_src): """ Return a copy of "class_to_copy" but with metadata (n_actions and n_obs) copied from meta_src. Usually class_to_copy is an agent-class and meta_src is an environment-class in whose instances instances of class_to_copy are to be run. """ cl...
1d2eb8fe03a5452407e39a40140e161b497a0524
574,964
def near(threshold, dist1, dist2): """Return true if distances is closes than threshold from each other. """ return abs(float(dist1) - float(dist2)) <= float(threshold)
8e043d706feacd8e12bb3e371960a8252d419999
574,965
import torch def get_model_mask_parameters(model, layers): """ Defines a dictionary of type {layer: tensor} containing for each layer of a model, the binary mask representing which parameters have a value of zero. :param model: PyTorch model. :param layers: Tuple of layers on which apply the thres...
aea57f6e00684c8e0e87f4ae4fd70e001508ff6f
574,968
def bookid2key(bookid): """ Simple unique encoding for each book id. Examples -------- >>> bookid2key("AZ1234") 71855628235572 """ return int(bookid.encode("hex"), 16)
dd2e260b65bddba09bc8b3e3e6099d0984cf45f5
574,971
import typing import inspect def method_names(cls: typing.Type) -> typing.List[str]: """Get a list of all method names of a Python class""" return [t[0] for t in inspect.getmembers(cls, predicate=inspect.isfunction)]
6384cba8cc15eab7948af8c076e47b80ddf9cb5f
574,972
def list_intersection(list_one, list_two): """ Compares two lists and returns a list of shared values between them. Parameters ---------- list_one: list list_two: list Returns ------- A list of matching items between the two given lists. """ return [entry for entry in lis...
cce977725eadef980702d792cd95a47946f36dc1
574,973
def find_median(arr): """ Finds the median of an array. """ len_of_list = len(arr) if len_of_list % 2 == 0: l = arr[len_of_list // 2] r = arr[(len_of_list // 2) - 1] return (l + r) / 2.0 elif len_of_list % 2 != 0: return float(arr[len_of_list // 2])
a432b096aff8bfc2a6ad9e00caeb2d4ab8ff848a
574,974
def contains(string, substring): """Boolean function detecting if substring is part of string.""" try: if string.index(substring) >= 0: return True except ValueError: return False
198ed2c489048896e4cd5259fbcf6de3ed19bc93
574,981
def isPerfect(x): """Returns whether or not the given number x is perfect. A number is said to be perfect if it is equal to the sum of all its factors (for obvious reasons the list of factors being considered does not include the number itself). Example: 6 = 3 + 2 + 1, hence 6 is perfect. Exam...
5b2d5a3d4566ce64be68679e496d812c0f726699
574,986
def match_list(list,bonus,score): """ check if there are one continuous sequence in the list which mach the bonus list :param list: origin input list etc [0xe9, 0x1c, 0xbd, 0xe9, 0x1c, 0x1c] :param bonus: bonus list [] :param score: rate for the bonus:1/3/5 :return: if match,return the score,els...
4e901a83416762f994c1c777c4cdf19819a1e705
574,990
import string def _generate_einsum_signature(n_trans_prob): """Generate the signature for :func:`numpy.einsum` to compute a Kronecker product. The ordering of the letters in the result is necessary so that the reshape to a square matrix does not fail. Example: >>> _generate_einsum_signature...
2eebcdadddd013b0209e83f2fd1b3e4e3ef947d1
574,991
def find_max_seat_id(seats): """ Return the max seat_id from a list of seats """ return max([x["seat_id"] for x in seats])
6abc204259e703528d88e44e1aaf0115caf4f092
574,993
import hashlib def calcule_hash_pass(login_info, password): """calcule_hash_pass(login_info, password) -> str Hash the password Params: login_info: array password: password from input_password() Return: The hashed password Example: calcule_hash_pass(login_info, '...
4b48e7c047f3ddf02f88c0b773c8c83b87c893c2
574,999
def argmax(lst, key=lambda x: x): """ Find the index 'i' in 'lst' with maximum lst[i] lst: list to search key: function to apply to each lst[i]. argmax(lst, key=func) --> argmax(map(key, lst)) """ it = iter(lst) top = 0 topval = key(it.next()) for i, item in enumerate(it, ...
5308ab7b0783f25afaa95d79027927baf6bb91e6
575,000
def validate_jobfile_format(jobfile): """Takes a jobfile dictionary and returns it if formatted properly. Args: jobfile: dictionary after file ingestion Returns: jobfile dictionary Raises: ValueError """ first_level_fields = [ 'job_name', 'job_type', 'creative_source_type', 'crea...
7d269d13d1bf5849aa0813cfcf2ea35c3413074b
575,002
def ap_from_ranks(ranks, nres): """ Computes Average Precision for retrieval results given by the retrieved ranks of the relevant documents. ranks - Ordered list of ranks of true positives (zero-based). nres = Total number of positives in dataset. Returns: Area under the precision-recall curv...
21d5fd94afbd5e565858ce1e39e835f421da3f2d
575,004
def handle_avro_errors(avro_output): """ Parse the output of `protocol.validate_parts` displaying only the fields that have the value `False` ------- Example ------- { 'problem': False, 'not_a_problem': True, 'nested': { 'problem': False, 'not_...
3255761ce728f7acb133427a48ec2d46b64f8460
575,008
def edge_matcher(graph1, graph2, node11, node12, node21, node22): """ Checks whether the resids for node11 and node12 in graph1 are the same, and whether that's also true for node21 and node22 in graph2. Parameters ---------- graph1: networkx.Graph graph2: networkx.Graph node11: collect...
0ccd7e02826683452244c3c5e054ea457fb9f6bf
575,010
def get_state_fips_code(fips_code): """ Returns the FIPS code of the state that the given fips_code belongs in. The first two chars of the fips code indicate the state. """ return fips_code[:2] + "000"
9785c17263ff8750805ca07a52b8799a78f59627
575,013
import re def create_user_tags(instring): """ Masks a string with `xxUSER` tags for Twitter-style mentions, IP Addresses, <USER> tags. :param instring: The input string. :return: Returns those masked version of the string. """ pattern = r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|<user>|<USER>|@[...
8796623ae29c22c98964262bfe5bf395b034141e
575,017
import requests def _check_env_status(test_url, expected_status, last_hash): """ Check the environment status by polling the report resource. Return True if the status matches the expected status, False otherwise. """ rsp = requests.get(test_url) assert rsp.status_code == 200 report_json =...
46f314dd88b9d8309a3cdf55c6013d9f3dfa5b82
575,023
def difference_sum_of_squares_square_of_sums(min, max): """Find the difference between (i) the sum of the squares of the numbers in a range and (ii) the square of the sum of the numbers in the same range. The `min` and `max` parameters define the minimum and maximum integers that make up the range in qu...
abe26784f180f242a406da042f22aef942cf5f60
575,025
def get_heatmap_cells_tickvals(max_mutations_per_pos_dict): """Get tickvals for the heatmap cells fig. :param max_mutations_per_pos_dict: See ``get_max_mutations_per_pos`` return value. :type max_mutations_per_pos_dict: dict :return: List of numerically indexed tickvals for heatmap cells fig ...
ebedeac420cc07dec681418da0d17c1d8ee62ac4
575,027
def load_vdata(filename): """Load vertice data into dict.""" vertices = {} with open(filename) as f: for line in f: l = [int(n) for n in line.split()] vertices[l[0]] = l[1:] return vertices
b84e7f26efa0972329a9d8d589ba8d2259f047ef
575,029
import re def max_repetitions(s, threshold=8): """Find the largest contiguous repeating substring in s, repeating itself at least `threshold` times. Example: >>> max_repetitions("blablasbla") # returns ['bla', 2].""" repetitions_re = re.compile(r'(.+?)\1{%d,}' % threshold) max_repeated = None for m...
04ea540a9cec1e937ba78f880f889b787f65b450
575,032
def get_textual_float(value, format = '%.2f'): """Get textual representation of floating point numbers and accept None as valid entry format is a string - default = '%.2f' """ if value is None: return 'None' else: try: float(value) except: # May ...
d15487c26d388377719088ef9ab1c63ea4686058
575,035
def concat_dataset(data, bdate, edate): """Concatenate pandas DataFrame with DateTimeIndex to the specified time period (bdate, edate). Args: data (pandas DataFrame): Air sensor dataset to concatenate. bdate (str): The beginning timestamp for the concatenated dataset. edate (str): T...
0f9109b013ed145b9ea8eea6830902aadac156ad
575,038
import json def getTokensInfo(ds): """ Get name of the token set and number of tokens used for tokenization of problem solutions Parameters: - ds - directory with tokenized dataset Returns: - Name of token set - Number of tokens """ _info_fn = f"{ds}/info.json" ...
e1b816ba4eb5e0f62ccccbc67bb5bea1cfb56788
575,039
import gzip import lzma def open_maybe_compressed_file(path): """Return a file object that possibly decompresses 'path' on the fly. Decompression occurs when argument `path` is a string and ends with '.gz' or '.xz'. """ if not isinstance(path, str): return path if path.endswith('.gz')...
dedf911ef92a3a6c007068949ddc57699e95321c
575,043
def get_number_covids_y(h_settings,covid_height): """Determines the number of covids in a column""" available_space_y = h_settings.screen_height - 2 * covid_height number_covids_y = int(available_space_y / (2 * covid_height)) return number_covids_y
53617a222ea59c354a728d9f2dc3a7a242f83fff
575,047
import six def _ListArg(arg): """Return a new list from arg. Args: arg: If a non-string iterable, return a new list with its contents. If None, return an empty list. Raises: TypeError: if arg is a string or non-iterable (except None). """ if isinstance(arg, six.string_types): raise TypeE...
6de8f5fa3ea4618aa3b80cb036c21f550d7a508c
575,049
def group5(message): """Turn a message into spaced groups of 5 characters""" result = "" for i in range(len(message)): ch = message[i] result += ch if (i+1) % 5 == 0 and i != len(message): result += ' ' return result
ec2f4bcfe2946e8aab0a6428207f0732635aaa4b
575,051
def check_format(input_row): """ Check if the row user input is the right format. :param input_row:(str) The row user input. :return: A string store all letters. """ lst = '' low = input_row.lower() if input_row[1] and input_row[3] and input_row[5] != ' ': print("Illegal input") else: if len(input_row) ==...
3bcd7045388b424930e610b35a13d2bdc701c8ce
575,054
def goal_reached(current_state, desired_state, precision=3): """ check if the current state is equal to the desired state with the user specified precision we define state as a list of centroid (array of size 2x1), theta (scalar), s1 (scalar), s2(scalar) state = [centroid, theta, s1, s2] """ # ...
9d555572fa12dd27d2aaa680f4b9bf85518432b0
575,057
import re def clean(s): """ Returns a cleaned, lowercased string """ out = " ".join(re.findall(r'\w+', s,flags = re.UNICODE | re.LOCALE)).lower() return out
5e1d5cc6d565e2f2e9c40d3cd209ff2ed49c42b3
575,058
def filter_by_abundance(data, abundance_column, high, low, taxonomy_column='Genus'): """ Return only rows where the specified taxonomy_column's set of rows have at least one value of abundance_column in range(low, high) :param data: dataframe to filter :param abundance_colum...
c8355d82d7b3608329529f894a2212ddbac5aad0
575,060
import glob def get_cppn_file_list(training_run, cppn_genome_folder=None): """ Get a list containing all files with cppn parameters in the run :param training_run: String, the name of the training run during which the cppns were saved :param cppn_genome_folder: String, full path of the folder contain...
14de3ee2886804fb951434d32e04863cbc320cc0
575,065
def restore_appliance_from_backup( self, ne_pk: str, appliance_backup_id: int, ) -> dict: """Restore appliance from the specified backup .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - applianceBackup - POST ...
2aad7b20df9a87804c1627877ad0bc6610383311
575,070
def read_file(number): """ Read puzzle by its number :param number: the number of the puzzle :return: the board """ missing_zeros = 3 - len(str(number)) filename = "puzzles/" + ("0" * missing_zeros) + str(number) + ".txt" file = open(filename, 'r') lines = file.readlines() board = ...
e2d3d9ef1e3dcc503ee9d234ce094fc08ff740f2
575,071
def by_days(entity): """ Used to group stat by days. For example, if state was created at 2022.10.14 12:15:54, then output of this function will be following: group_by_date('2022.10.14 12:15.54') -> 2022.10.14 00:00:00 """ return entity.created.replace(hour=0, minute=0, second=0, microseco...
3bdd9f6c42fa3f85562ccfed7a0d5e076924aa53
575,072
import torch def getGrid(input_shape, cell_map_shape): """Constructs a 2D grid with the cell center coordinates.""" cell_shape = input_shape / cell_map_shape cell_top_left = torch.meshgrid([torch.arange(start=0, end=cell_map_shape[0]*cell_shape[0], step=cell_shape[0], ...
eb965c3bcc58734e7379fbd040b5868b9a36e109
575,073
import re def postprocess_pages(field, pages, **options): """Convert a page range to a 2-element tuple.""" values = re.split(r'\-+', pages) if len(values) == 2: try: return (int(values[0]), int(values[1])) except (ValueError, TypeError): return pages else: ...
71c86e3e823169abdd9d2ad0e27416dda1dc30b3
575,076
def index_joins(df, downstream_col="downstream", upstream_col="upstream"): """Create an index of joins based on a given segment id. Returns a dataframe indexed by id, listing the id of the next segment upstream and the id of the next segment downstream. Segments that have 0 for both upstream and downst...
34816b4cd640e94cee810cc4716ab78e089e0359
575,081
def feet_to_meters(feet): """Converts feet to meters. Args: feet: A distance in feet. Returns: A distance in meters. """ return feet * 0.3048
468470e8bb922aa4ccf314d621fd27dabd324fbe
575,083
import re def services(filename="/etc/services"): # {{{1 """ Generate a dictionary of the available services from the services file, by default /etc/services. Arguments: filename: Name of the services file. Returns: A dict in the form of {25: 'smtp', 80: 'http', ...} """ ...
fa3e262746543bf563de55dce292ce5dcd8ae162
575,086
import struct def _convert_signed_hex(s): """Takes a signed hex string that begins with '0x' and converts it to a 16-character string representing an unsigned hex value. Examples: '0xd68adf75f4cfd13' => 'd68adf75f4cfd13' '-0x3ab5151d76fb85e1' => 'c54aeae289047a1f' """ if s.startswi...
8e056e1a3e872b6fcadca34868fd349ccf6ff46d
575,088
def recvall(sock, size): """ Receive data of given size from a socket connection """ data = b"" while len(data) < size: s = sock.recv(size - len(data)) data += s if not s: raise RuntimeError("did not receive data from socket " f"(siz...
3c5964772ed4f36220d72200fd0747f2d5abdb14
575,089
def ItemDedCap(e17500, e18400, e18500, e19200, e19800, e20100, e20400, g20500, c00100, ID_AmountCap_rt, ID_AmountCap_Switch, e17500_capped, e18400_capped, e18500_capped, e19200_capped, e19800_capped, e20100_capped, e20400_capped, g20500_capped): """ Applies a cap to ...
6416ba969b77fec57e070f4f837d8a9f8021d097
575,090
def num_add_commas(num): """ Adds commas to a numeric string for readability. Parameters ---------- num : int An int to have commas added to. Retruns ------- str_with_commas : str The original number with commas to make it more readable. """ num_...
c1da51505c9d442daa981c349f9bde426acef987
575,093
def Mc_M_eta(M, eta): """ Computes the chirp mass (Mc) from the total mass and symmetric-mass-ratio input: M, eta output: Mc """ return M * eta**(3./5.)
eb92c3dcb768f8bafffc75ac67999c1dea925492
575,094
def format_talon(abundance): """ Takes talon abundance file and produces dictionary with counts per transcript. :param abundance: File containing transcript counts :return: Dictionary: key = transcript id, value = counts """ talon_dict = {} with open(abundance, 'r') as file: # S...
28285dbb0c98a36cc305a6e359fb4ecdd48d7f8b
575,099