content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re from functools import reduce def remove_access_letter_from_menu(string): """ Remove any ampersand that is not followed by another ampersand """ result = re.split(re.compile("&(?!&)"), string) return reduce(lambda x,y : x+y, result, "")
01cbded33743494b5ebd9957451392cb509bd75c
578,104
def format_equivariance_error(errors: dict) -> str: """Format the dictionary returned by ``equivariance_error`` into a readable string. Parameters ---------- errors : dict A dictionary of errors returned by ``equivariance_error``. Returns ------- A string. """ ret...
c66d1da40453af396392f9637289e5494c79449d
578,107
import torch def generate_newdataset(train_dataset, test_dataset, split=0.7): """ Generate the new dataset containing a mix of the train_dataset and the test_dataset. A target will have value '1' if the original data is from the train set, '0' if it is from the test set. Args: -train_dataset:...
a4599d705fa3accb544855b5be92c88b634009d8
578,109
import string def encrypt(txt, encode=True, rotation=21): """ by Daniel Bezerra dos Santos... dbsantos1981@gmail.com This function implements a simple version of "Caesar's Cryptography" :param txt: text to be encrypted or decrypted :param encode: if encode is true, it will encrypt. Otherwise it ...
f7f4f2e7dc4cf2c7b3c5b4d62311b7c4a6e6ecab
578,110
import string def is_alnum(a_string, okchars=None): """ Checks if the *a_string* contains alnum characters (i.e like string.alnum) but allows you to also include specific characters which you want to allow. Returns false if a character in *a_string* is not alphanumeric and not one of *okchars* """...
10cd7dbce1ff3a0bc66fe9b8c393753198a121cc
578,124
def no_blank_options(_option): """ :param _option: (delivery_api_client.Model.option.Option) :return: (bool) True if option contains type and content, False otherwise """ return _option.type and _option.content
3142cc1540ecfe92a3fe38a72d73824d95c4613c
578,129
import re def get_example_line(s): """ Get the example line. :param s: A line of text. :return: The example line if it exists. """ reg = re.compile(r'^\[[^\(]*\]\(([^)]*)') if reg.match(s): return [''.join(reg.findall(s))] return ['']
ff3e8fc4b4169c6c166bc993d2fd900505a05e90
578,131
def remove_empty_tags(s, tags=('p', 'i', 'em', 'span')): """ >>> remove_empty_tags('Hi there') 'Hi there' >>> remove_empty_tags('<p>Hi there</p>') '<p>Hi there</p>' >>> remove_empty_tags('Hi there<p> </p>') 'Hi there ' >>> remove_empty_tags('Hi <span> </span>there') 'Hi there' ...
eb7f78fe6f1cab6358bab427e74d12ebeb8eabf6
578,133
def wrap_index(idx, dim): """ Helper function that wraps index when greater than maximum dimension. Args: idx (int): Unwrapped index dim (int): Maximum dimension Returns: idx (int): idx if idx < dim or idx - dim """ if idx < dim: return idx else: ret...
90c3ec85d129c5462c3781fa15ef9132ce061149
578,135
def in_time_frame(sim_start_epoch, sim_end_epoch, rec_start_epoch, rec_end_epoch): """ Check wheter record is inside the simulation time frame. :param sim_start_epoch: simluation start. :param sim_end_epoch: simulation end. :param rec_start_epoch: record start. :param rec_end_e...
2f33b4ac944f1be3224a259c218dd4c87f8d990a
578,136
from pathlib import Path import yaml def check_toc_integrity(doc_folder, output_dir): """ Checks all the MDX files obtained after building the documentation are present in the table of contents. Args: doc_folder (`str` or `os.PathLike`): The folder where the source files of the documentation lie....
fdc3dc43f92a6fb32979596c42cb35fa424cbef7
578,137
def heat_index(tdb, rh, **kwargs): """ Calculates the Heat Index (HI). It combines air temperature and relative humidity to determine an apparent temperature. The HI equation [12]_ is derived by multiple regression analysis in temperature and relative humidity from the first version of Steadman’s (1...
a96d04ccc8616f5e4987ea4bdb3c3f4294949488
578,139
def get_hyperlink(path): """Convert file path into clickable form.""" text = "Click to open in new tab" # convert the url into link return f'<a href="{path}" target="_blank">{text}</a>'
22d70a423a8f02bbfa62e93f4a89f80cdc08d12d
578,143
def output_list(masterlist): """ Helper function that removes the extra brackets when outputting a list of lists into a csv file. Stackoverflow link: https://stackoverflow.com/questions/31587784/python-list-write-to-csv-without-the-square-brackets Keywords: masterList (list): input list of lists ...
532430e50a1860867c1e05440b2b359ec9c855cc
578,150
def get_filename_in_second_line(cpp_txt): """ From the second line of cpp_txt, get the filename Expected input argument: // ``` // Begin file_name.cpp // ... Expected output argument in this case: file_name.cpp """ result = "" for line in cpp_txt.splitlines(): if ...
b0e3e3efe7af0af667b20c74c1334c3d61f74ebf
578,152
def prob_of_transmission_within_household(Ph, Pt, Pf): """ Get the probability of transmission of infection within household Parameters ---------- Ph: Probability for members of each household to contract from their housemates Pt: Probability for members of each household to contract du...
6ecf317888e1369377a42041b94dc45a35149edc
578,153
def atof(text): """ Function to test whether a str can be rendered as a float. Useful when retreiving experimental parameters that were stored within the filename. Parameters: text (str) Returns: float or text """ try: retval = float(text) except ValueError:...
5276411bfa6967fde441b023fe3a30f5146a23c8
578,154
import yaml def read_vibdata(vib_file): """Reads a yaml file containing the vribational frequencies from a DFT calculation. Parameters ---------- vib_file : (:py:attr:`str`): File name Returns ------- vib_prop : :py:attr:`dict` Dictionary of vibrational freqencies. ...
31006173c40b9ad5edc27688aaad330bc7335bb9
578,156
import re def get_hash_for_filename(filename: str, hashfile_path: str) -> str: """Return hash for filename in the hashfile.""" filehash = "" with open(hashfile_path, "r", encoding="utf-8") as stream: for _cnt, line in enumerate(stream): if line.rstrip().endswith(filename): ...
0704355489d72ad002d3a18cf897cee1e47d587f
578,157
def copytree_ignore_backup(src, names): """ Returns files to ignore when doing a backup of the rules. """ return [".cache"]
c6972dd983f0ac83b3ed17154e006edafeeec515
578,159
def safe_div(a, b): """ returns a / b, unless b is zero, in which case returns 0 this is primarily for usage in cases where b might be systemtically zero, eg because comms are disabled or similar """ return 0 if b == 0 else a / b
8c425ef9f3e1fa735a7664ef7bfc043dbd1f6349
578,160
import math import time def ut2isofs(ut, sep=' ', ndd=4): """UTC UT -> 'YYYY-MM-DD HH:MM:SS.1234'. No TZ or offset.""" b, a = math.modf(ut) # Fractional part, whole part. tm = time.gmtime(a) fs = (('%%.%df' % ndd) % b)[1:] return '%04d-%02d-%02d%s%02d:%02d:%02d%s' % \ (tm.tm_year, tm.tm_...
1577f604dbe28ce3741ec763f02f3d84527f833d
578,161
def index_from_address(level, address): """Computes TLR Index from Address vector. Returns the TLR index of a point with certain address vector in a graph of SG at some fixed level. For point F_{w1} F_{w2} ... F_{wm} q_{k} (0<=wi<=2, 0<=k<=2), we can represent it in two ways: 1. ...
ceef884b364fd55eb21d8eb2c1cad4c6a30372d3
578,162
def cstr(v): """Convert Python 3.x string to C compatible char *.""" return v.encode('utf8')
f2b594538b20150f334d1372b5c65d716289cda7
578,167
def lambda_function_generator(lambda_client): """ Iterates over Lambda functions in a specific region :param lambda_client: Client :return: Generator """ next_marker = None try: response = lambda_client.list_functions() except Exception: print('Could not scan region') ...
69bf753c436d3e073dbc54a3c0fd77a5e85abf7d
578,168
def convert_color(color): """Convert color tupel(r, g, b) to string("rgb({r}, {g}, {b}"). Args: color (tupel): RGB color. e.g. (134, 8, 45) Returns: string: "rgb({r}, {g}, {b}" """ return "rgb({}, {}, {})".format(color[0], color[1], color[2])
df689996a5adb5d9ab10ae096c75546a4f9041ba
578,169
def deep_update(cfg, other): """deep_update recursively mutates `cfg`, copying items from `other`, recursing when both values are dictionaries and overriding otherwise""" for key in other.keys(): if ( isinstance(other[key], dict) and key in cfg and isinstance(cfg[...
2665d0174a03d74b3933e15746c9b320f8c44243
578,175
def cp2np(u): """Identity function.""" return u
37a6840263f748c9a3ddab9a45f9926872fa2f14
578,181
def lc_prefix(prefix, s): """return the longest common prefix of prefix and s""" if prefix is None: return s n = 0 for i, j in zip(prefix, s): if i != j: break n += 1 return prefix[:n]
f3d6545c47128631a48b3b4b466f704bf9a6742c
578,193
def parse_header(field): """Parses a single header key and converts it to the way it appears on a HTTP classified_request. This function is necessary because the headers' keys are provided in the environment variables not as they appear in a HTTP classified_request. For example, it converts HTTP_USER_AG...
42007140e1eb2922485785e1213eeac859b50348
578,196
def dms2dd(d: float, m: float = 0, s: float = 0) -> float: """Convert degree, minutes, seconds into decimal degrees. """ dd = d + float(m) / 60 + float(s) / 3600 return dd
a60d2d1d144729dff9145a65f813e642e8ab2a3d
578,199
from typing import Mapping from typing import Any from typing import Dict def added_double_hyphen(contents: Mapping[str, Any]) -> Dict[str, Any]: """add double hyphen ('--') to all keys and return it""" target: Dict[str, Any] = dict() for key, val in contents.items(): new_key = '--' + key ...
182cd60be9fbc8b87c7ef243f6840fd76f30498c
578,201
import torch def makePDM(matA): """ Make Positive Definite Matrix from a given matrix matA has a size (batch_size x N x N) """ AL = torch.tril(matA, 0) AU = torch.triu(matA, 1) Aant = AU - torch.transpose(AU, 1, 2) Asym = torch.bmm(AL, torch.transpose(AL, 1, 2)) return Asym, Aant
9e0954ab395af0a9572b55adbdbc0e8501cb2de5
578,204
def inventree_credits_url(*args, **kwargs): """ Return URL for InvenTree credits site """ return "https://inventree.readthedocs.io/en/latest/credits/"
a928ced280aee0fc8857b837fcabac505e214228
578,207
def convert_error_dict_to_list(error_dict, error_code=None): """ Given an error dict (returned by Marshmallow), convert into a list of errors """ return_value = [] for f, errors in error_dict.items(): # error can be a string, a dictionary, list of string or a list of dictionary if is...
b8ee64d561ae18facd58f280c8e654d730e75379
578,210
def list_to_entry_type(cls): """ Return the entry type for a list """ slen = len("of_list_") return "of_" + cls[slen:]
9ff295b773109ec47573ee528fde674fcb8e4cfb
578,211
import re def isslug(value): """ Validate whether or not given value is valid slug. Valid slug can contain only alphanumeric characters, hyphens and underscores. If the value is a slug, this function returns ``True``, otherwise ``False``. Examples:: >>> isslug('my-slug-2134') Tru...
e8f79351d7ec6939344cdcb278a22e2316ed592f
578,212
def check_bounds(fit_result): """ Check if the obtained fit result is within bounds""" for param in fit_result.model.params: value = fit_result.params[param.name] if value < param.min: return False elif value > param.max: return False return True
d2b40665c7265c0acf1ca933411b31f661ec76c0
578,213
from typing import Optional def nseconds(t1: float, t2: Optional[float] = None) -> str: """Formats time string Formats t1 if t2 is None as a string; Calculates the time and formats the time t2-t1 if t2 is not None. :param t1: time 1/initial in seconds :type t1: double :param t2: time 2 (Defa...
e0433e50c3b4dc98924fa024c962c7889c1b0c07
578,217
def test_single_processor(recipe): """Test for recipe having a single processor. Args: recipe: Recipe object. Returns: Tuple of Bool: Failure or success, and a string describing the test and result. """ description = "Recipe has only a single processor, of type 'JSSImporter'...
c0404794ce87f4fd1aee8f8f9d7105f377461988
578,219
def chunks_to_string(chunks): """ Parameters ---------- chunks : list of strings A list of single entities in order Returns ------- string : A LaTeX-parsable string Examples -------- >>> chunks_to_string(['\\\\sum', '_', 'i', '^', 'n', 'i', '^', '2']) '\\\\s...
a7b5579fe2f68e3d5245d5a55ed771d51882bf3e
578,220
from typing import Optional from typing import Callable from typing import Any from typing import List def as_list(ans: str, sep: str = ',', f: Optional[Callable[[str], Any]] = None) -> List[Any]: """ Parse list elements and optionally apply a transformer to each element. This allows you to parse things d...
d7b63032ef31cf44af155b1bbadb5408af2fd1a6
578,226
import torch def compute_fw_loss(flo_diff, mask=None): """ compute forward-backward flow consistency loss :param flo_diff: difference of flow and warped-flow :param mask: disocclusion mask :return: loss """ if mask == None: return torch.mean(torch.abs(flo_diff)) else: ...
d18f084e90fe9c5c7ea50ed3be5979054cf91f94
578,228
def intensitymodel( amp, k_rad, a=0, b=0, c=0): """Radial dependence of spot calibration\n intensity = amp**2*(a*k_rad**2 + b*k_rad + c)""" return amp**2*(a*k_rad**2 + b*k_rad + c)
57985409b24753a73186fce9a3670f988d72cbb8
578,229
def _escape_filename(filename): """Turns a file into a string representation with correctly escaped backslashes""" str_repr = str(filename) str_repr = str_repr.replace("\\", "\\\\") return str_repr
55bf2ee754ca61a52f0e2a7bf199186962e8e463
578,230
def remove_multiple_newlines(content): """ mdoc format gives a warning if multiple newlines are put into a document. To suppress this warning, we strip multiple newlines :returns: str """ flt = content # remove double newlines flt = flt.replace('\n\n\n\n', '\n') flt = flt.repl...
fc28f90667e10984c82e3eb687613c2d5d229f1a
578,231
def write_journal(journal_file_path, journal_template, full_model_path, command): """ Writes a journal to be used with revit, based on :param journal_file_path: journal output path. :param journal_template: journal template to be used as base. :param full_model_path: file path to the model. :par...
685430d1a09fe8a3804e3777b7a2d8bf17129969
578,233
def netatmo_pressure_correction(p0, h): """Convert SLP reported by Netatmo to Surface pressure. Necessary because Netatmo uses a very crude formula. Parameters ---------- p0 : float Netatmo SLP in hPa h : float Altitude of station in meters Returns ------- ps : floa...
e5fff6c21c89bf507c0d55aae92062e9ac41e4d6
578,234
def normalize(x: float, x_min: float, x_max: float) -> float: """ Rescaling data to have values between 0 and 1 """ return (x - x_min) / (x_max - x_min)
2e6dd1c8488f34c53799d9a379cd0722b48a15cd
578,235
import torch def partial_distance_matrix(x: torch.Tensor, partial_idx: torch.Tensor) -> torch.Tensor: """Calculates the partial distance matrix given the indices. For a low memory footprint (small computation graph) it is essential to avoid duplicated computation of the distances. Parameters --------...
c8b813e93681498913c2a17cae0fb3967bf209d0
578,241
async def id_exists(collection, id_: str) -> bool: """ Check if the document id exists in the collection. :param collection: the Mongo collection to check the _id against :param id_: the _id to check for :return: does the id exist """ return bool(await collection.count_documents({"_id": id_...
2c3355227b7d24133dc1383e47a26c03c468e2a4
578,243
def GetProblemIoSetByName(problem, io_set_name): """Get a problem's index given its key and a problem list. Args: problem: Problem whose I/O set must be retrieved. io_set_name: String with the name of the I/O set to retrieve. Returns: The problem I/O set with the specified name, or None if no I/O se...
70ea9d0ac826ef4866316f3b509e24075e441017
578,245
import importlib def load_from_package(name, attr): """Load `attr` from the package `name`.""" try: module = importlib.import_module(name) if module is None: return None return getattr(module, attr, None) except ImportError: pass return None
95942db4a0ff5cd8f8e3dc6f0f7985a3345b869f
578,246
def trim(line): """Remove everything following comment # characters in line. >>> from sympy.physics.quantum.qasm import trim >>> trim('nothing happens here') 'nothing happens here' >>> trim('something #happens here') 'something ' """ if not '#' in line: return line return li...
80902aeefc55877dc903ebdf2eb38783f3e3b7da
578,248
def _hasvalue(obj, attr): """True if the attribute `attr` of `obj` exists and is not None.""" return getattr(obj, attr, None) != None
186f9856766a72db850154e681d80148486d9449
578,249
def flow_to_linkdict(flows): """ Convert LinkFlow object from parse_flow_file to dict { (from,to) : LinkFlow } mapping a link indexed by (from,to) tuple to LinkFlow data Parameters: flows - list of LinkFlow objects as returned by parse_flow_file() Return value: dict {(from,to...
8c0419d91e78458f37cea679b872eff1eb8ef9cd
578,252
from typing import Dict def get_string_with_spacing(data: Dict[str, str]) -> str: """ Gets a string representation of a list of key/value pairs (as OrderedDictionary) with proper spacing between key/values. :param data: A Dictionary containing key/value pairs. :return: A string representation of the D...
bd5d6fc6eabe5047e28b89eeaaec4acbce2510c9
578,253
from datetime import datetime def parse_date(date_str): """Turns a report date from the FEC disclosures into a Python datetime""" try: return datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S') except ValueError: try: return datetime.strptime(date_str, '%Y-%m-%dT%H:%M:%S.%f') ...
dff141f7ea6ef7c08cc539df732e26fe20ef72af
578,258
def labelling(row): """Labelling samples in which random_baseline result is >= 0.5 as 1 (Actives) and the rest as 0 (inactives)""" if row["random_baseline"] >= 0.5: return 1 else: return 0
c88c4103d3e6ea01f76e89f3f7695241751176a0
578,259
from datetime import datetime from typing import List def parse_month(now: datetime, key: str, group: List[str]) -> str: """ Handles the Month presentation https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#month """ if key != "M": raise Exception(f"Unknown character...
8ca38504fe9e339f700fde49c14082a55a00fd83
578,262
def overlap(bbox1, bbox2): """ Given two bboxes, return whether the two bboxes overlap """ x1, y1, w1, h1 = bbox1 x2, y2, w2, h2 = bbox2 return (x1 < x2 + w2) and (y1 < y2 + h2) and (x2 < x1 + w1) and (y2 < y1 + h1)
1c2f7b562823e4c13341ab4eea40c905d7f72f63
578,263
def get_data_dir(config): """Returns the root directory containing serialized fedora objects based on the configuration.""" return config.dir if not config.bag else config.dir + "/data"
15af20aa6c5deaa6c3d0007e9faa267f03d71c70
578,264
def attribute(method): """Decorator for parsing element attributes. Methods with this decorator must return a dictionary with interested attributes. The dictionary will then be passed to corresponded generator method as parameters. """ def inner(*args, **kwargs): self = args[0] ...
64832920fa787a4cfdb066451b11670a6eece75b
578,267
def split_data(data, validation_rate=0.2, test_rate=0.1, shuffle=True): """ 데이터를 train, validation, test 데이터로 쪼개어 csv로 저장 :param data: split할 데이터. type은 pandas.DataFrame :param validation_rate: validation데이터 비율, 0~1사이의 실수여야하며 기본값은 0.2 (20%의 데이터를 validation에 사용) :param test_rate: ...
dea99300c696a8599fce2e79b8260d3119f2cf33
578,272
def ishasbody(method): """ check if the method can have an body: e.g. put, post and patch :param method: (get, put, post, ....) :return: """ if method in ["put", "post", "patch"]: return True return False
b1a268a6d7872951a10e5be163d25ea9036e9b52
578,279
def template_var(template_file, template_vars, template_lookup_module): """ Run Ansible Template Lookup Plugin The result is forced into a string and leading/trailing newlines and whitespaces are removed. Parameters ---------- template_file : str Filename to pass to template_lookup_mod...
f825356b2940d6d664fcc80e8e25307ac92e0ef8
578,281
def _filter_points_to_get_convex_hull(points_sorted): """Find the upper convex hull. Parameters ---------- points_sorted : pandas.DataFrame Points represented as rows with 'x' and 'y' columns, sorted by 'x'. Returns ------- result : pandas.DataFrame Points that make the upp...
e556e29306f14f39bfb40b42bf16b1cd72c793b6
578,282
from typing import List from typing import Callable def find_pattern(patterns: List[str], filter_func: Callable[[str], bool]) -> str: """Find the pattern defined by `filter_func` in the list of `patterns`""" find_result = [*filter(filter_func, patterns)] assert len(find_result) == 1 return find_result...
1ae077fde9e1a38926f2969f1e737bfc8d0d5f05
578,283
def camelCaseIt(snake_case_string): """ Format a string in camel case """ titleCaseVersion = snake_case_string.title().replace("_", "") camelCaseVersion = titleCaseVersion[0].lower() + titleCaseVersion[1:] return camelCaseVersion
0e9353118f50c2bbd758f0bb7b4f12793b8eba82
578,293
import string def _substitute(template, substitution): """Substitutes elements in template based on a given substitution. This method can be thought of as a shorthand for t = string.Template(template) return t.substitute(substitution) Args: template: A template. substitution: A s...
b398a6b614dbd9aac341f86f71e9c50a290fccb6
578,303
def plzz(self, rotvel="", deltarotvel="", **kwargs): """Plots the interference diagram from a cyclic modal analysis. APDL Command: PLZZ Parameters ---------- rotvel Rotational speed in revolutions per minute (RPM) used to define the speed line. If blank, use the rotational speed (f...
8bdd7745f9c9c5cab8ef3825bef3be6296bf8faa
578,305
def detect_and_reject_outliers(df, y): """Detects and rejects outliers in the distribution of within effect sizes. Studies with a within effect size out of the bounds are excluded. Parameters ---------- df: pandas.DataFrame Dataframe containing all observations in rows, factors and also va...
50a409f507f85e37973f0deda1d009fe56cccabc
578,306
import itertools def safe_max(sequence, default=None): """ Return the max value from sequence, if sequence is empty, return the default value. :param sequence: iterable sequence :param default: default value """ i_seq = iter(sequence) try: value = next(i_seq) except StopIt...
3e5eaaea6795f3bb8309bd70a455a399dba26b45
578,308
def fancy_format(in_str, **kwargs): """ A format command for strings that already have lots of curly brackets (ha!) :param in_str: :param kwargs: the arguments to substitute :return: >>> fancy_format('{haha} {dan} {bob}', dan = 1, bob = 2) '{haha} 1 2' """ new_str = in_str.replace('{...
6ee8c08cbe41967e32d89231b95a90c0d9bc4590
578,318
import requests def get_best_variant(variants): """ Returns the best variant for a video :param variants: Array with video variants :return: A URL with the best variant """ bitrate = 0 url = "" for v in variants: if ("bitrate" not in v and bitrate == 0) or ("bitrate" in v and v...
18afd64b4d97ee73f62b55d968459f3285e0c0fa
578,320
from pathlib import Path def get_parent_dir(path: Path) -> Path: """ Get the parent directory of the given path. :param path: a Path :return: a Path """ return path.parents[0]
98191642868d7b2d4c04f6be4760831f3f08e19e
578,321
def get_critical_process_from_monit(duthost, container_name): """Gets command lines of critical processes by parsing the Monit configration file of each container. Args: duthost: Hostname of DuT. container_name: Name of container. Returns: A list contains command lines of criti...
c26b4b788252b4e6273fb77fd14c22619fe2d125
578,322
import json def _parse_dict(token, default=None): """Returns a dict from a string token Returns the default value if the token cannot be converted to dict""" try: result = json.loads(token) return result except ValueError: return default or {}
10110d85357cb5a615862aa2321d073d316d7b07
578,324
import re def is_valid_run_date(date): """ Validates date in ISO8601 format according to BAM specification :param date: str to validate :return: True if valid and False if invalid """ regex = r'^(\d{4})-?(1[0-2]|0[1-9])-?(3[01]|0[1-9]|[12][0-9])' \ r'(T(2[0-3]|[01][0-9]):?[0-5][0-9...
bd6432d46f3e7470908d7ef9ba70b43d5e67cb37
578,327
def valid_integer(to_check): """ Check if the value in to_check is actually an integer. to_check can be a string or already an integer. returns True or False """ try: int(to_check) return True except ValueError: return False
6df6ecf39c115d9cac4a84d30e05e6d58b8c9e9b
578,329
def _mask_border_keypoints(image_shape, keypoints, distance): """Mask coordinates that are within certain distance from the image border. Parameters ---------- image_shape : (2, ) array_like Shape of the image as ``(rows, cols)``. keypoints : (N, 2) array Keypoint coordinates as ``(...
020db082cc62b3903985321a7e35eaea3b87a4d1
578,332
def sat_ip_to_text(sat_point, rows_vars): """Converts a satisfying input point into lines of text, one row per line""" text = "" for row_var in rows_vars: for var in row_var: if sat_point[var]: text += "▓▓" else: text += " " text += "\...
4b1c83efeb43d4e6a99f2074aaee7fed77174d87
578,334
def str2bool(value): """Parse a string into a boolean value""" return value.lower() in ("yes", "y", "true", "t", "1")
76b078822bac4f706cc6e6b1e730128e0f656185
578,335
def in_favorites(user, recipe): """Check if a recipe is in favorites.""" return recipe.favourites.filter(user=user).exists()
accb1c05b6f7e3366232be90ff736b2028e00614
578,341
def is_stronghold(replay_json): """ Returns whether the replay is from a stronghold battle """ return replay_json['first']['battleType'] == 11
157bbdfc8a8ac15b1832a965b5584b687f418b69
578,342
def print_board(board): """ Input: takes a xo board as a list from values of a 3x3 board Returns: a tic-tac-toe board in a visual manner """ return print("\n{} | {} | {}\n--+---+--\n{} | {} | {}\n--+---+--\n{} | {} | {}\n" .format( board[1],board[2],board[3],board[4], board[5],b...
9968895a5c25a50644c4577c7f38654dcf5f9748
578,343
def sort_decls(structs): """Generate the set of all (uninterpreted) sort declarations from a set of predefined structures. Return (possibly empty) dictionary of sort declarations suitable for z3 python API.""" sorts = [struct.sort.ref for struct in structs if struct.sort.to_declare()] retu...
268f789942915600c058a027c05d3a60c125dc32
578,345
from typing import List def space_tok(text: str) -> List[str]: """Tokenizes string on spaces """ return text.split(" ")
1f14fd86838f25de30740aeb00870aa30a0c9777
578,346
def prefix(string1, string2): """Return the prefix, if any, that appears in both string1 and string2. In other words, return a string of the characters that appear at the beginning of both string1 and string2. For example, if string1 is "inconceivable" and string2 is "inconvenient", this function wi...
247677ed2f684518ab2f7f1a2663aa75e2c2e27e
578,347
def bounds_tuple(start, stop): """ Standardize the given start/stop into a tuple-of-ints, suitable for a dictionary key. """ start = tuple(int(x) if x is not None else None for x in start) stop = tuple(int(x) if x is not None else None for x in stop) return (start, stop)
08b095b25aef26628bbb53299cdf18473188595b
578,349
from pathlib import Path def save_options_to_config(filepath, opt, unknown=None): """ Saves the parsed options to a config file to be used as arguments. Args: filepath: path to write the config file to. opt: parsed known options. unknown: unknown options (only safe for non-command...
2b6fd2e9590f87c5c168d41e52cd168b22e78747
578,353
def stringify_credentials(access_key, secret_key, token=None): """Serialize the credentials into a format accepted by redshift Args: access_key(str): The public AWS credential secret_key(str): The secret AWS credential token(str): A token needed for temporary AWS credentials Return...
c55f9b67b0d53eae1673fee8d2013227e3b73d97
578,360
def annotations_to_ytbb_labels(annotations, label_list, reverse_ytbb_map): """Convert annotations from labeling UI to match YTBB index labels. Args: annotations (List[Dict]): Contains list of annotation objects with keys 'key', 'notes', 'labels'. label_list (List[str]): List of label...
c228c77f75a99f568b5674e125e5c66cad2c656b
578,362
import csv def load_directory_data(csvfile): """ Read student & family data from the CSV export of Maria's directory spreadsheet. This function returns a list of dicts - one for each student - where the keys are just the column names from the spreadsheet. """ records = [] # a li...
b93c1f7acefacb1156fb23097da22127197d9793
578,370
def ComputeEditDistanceMatrix(hyp_words, ref_words): """Compute edit distance between two list of strings. Args: hyp_words: the list of words in the hypothesis sentence ref_words: the list of words in the reference sentence Returns: Edit distance matrix (in the format of list of lists), where the fi...
eb2ff6ec7adca7d469f72bbbf33d4a949a5c114e
578,372
def select_qualityscore(structures, qualityscore_min): """ Filter structures for structures with a quality score equal or greater than a given value. Parameters ---------- structures : pandas.DataFrame Structures DataFrame from opencadd.databases.klifs module. qualityscore_min : int or ...
c2bf257143f38018d07d7ce6c7c9587a22675b37
578,373
import functools import warnings def deprecated(replacement=None): """A decorator which can be used to mark functions as deprecated. replacement is a callable that will be called with the same args as the decorated function. """ def outer(fun): msg = "{} is deprecated".format(fun.__name__)...
b5400d73a10d2ac7885bf7c5a53b30b2f0d6847b
578,374
def excess(topic_srs, ref_srs): """Calculates the excess of a topic series vs. a reference series. Excess is simply the difference between the topic series and a reference series. If passing returns, log returns should be used since the function simply subtracts to calculate the difference. Args...
44742a36297a76607f2777398e5e6203e8516b6b
578,375
def try_import(mod_name, attr_name=None, attr_default=None): """Try to import a module and get an attribute from it. Parameters ---------- mod_name : str Module name. attr_name : str, optional Name of an attribute in the module. attr_default : optional Default value if t...
9523ac58174c1494eb8803ae075bb77061de746e
578,376
import random def mutate(individual, m, k): """ This function apply the mutation operator :param k:Number of genes that were chosen to maybe mutate :param individual:list :param m:Mutation Rate :return:Return the individual after the mutation """ lst = random.sample(range(0, len(indiv...
ad6da81d134ba83c4b464f42924f343ea871cb3c
578,377