content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def parse_arn(arn): """ Parses an ARN (Amazon Resource Identififier). :param arn: The arn as a string :returns: A dictionary with all as entries """ parts = arn.split(':') sections = { 'owner': parts[1], 'service': parts[2], 'region': parts[3], 'account_id': ...
07b4931788302da710d368b1dc39ae27e92f1313
620,480
def copy_grid(grid): """Copy grid.""" return [row[:] for row in grid]
ec7479d8706b22745ac2cebbc5af7043db08fe8b
620,481
def flatten(l): """Flatten a singly nested list. Examples -------- >>> flatten([[0,1,2], [4,5]]) [0, 1, 2, 4, 5] """ return [item for sublist in l for item in sublist]
907e13a628009b128853d3a9be163a0d1377cf04
620,484
def _includes(opt): """ Return the #include directives for the user-defined list of include files. """ includes = [] if opt.include_files is not None and len(opt.include_files) > 0: for include_file in opt.include_files: if include_file[0] == '"' or include_file[0] == '<': ...
69eb081f543f9758d25a4de9c52e9f6b91751cfe
620,486
def _var2numpy(var): """ Make Variable to numpy array. No transposition will be made. :param var: Variable instance on whatever device :type var: Variable :return: the corresponding numpy array :rtype: np.ndarray """ return var.data.cpu().numpy()
66ad4d1a6b87757a883b5f515ae6107af8ac9ca5
620,487
def make_help_cmd(cmd, docstring): """ Dynamically define a twill shell help function for the given command/docstring. """ def help_cmd(message=docstring, cmd=cmd): print('=' * 15) print('\nHelp for command %s:\n' % cmd) print(message.strip()) print() print('=...
6b1047dd5c692b7632a07a7ea2ea374e81bb0c46
620,488
def is_connectable(bnode, cnode): """ >>> bnode = {'entry': {'pos': 'N'}} >>> cnode = {'entry': {'pos': 'J-K'}} >>> is_connectable(bnode, cnode) True >>> bnode = {'entry': {'pos': 'V-Y'}} >>> cnode = {'entry': {'pos': 'V-S'}} >>> is_connectable(bnode, cnode) False """ ctable ...
685d0add73fd53071b39d03cecb925386b8e712d
620,489
from typing import List def _add_docstring_to_top_level_func(line: str, docstring: str) -> str: """ Add docstring to the top-level function line string. Parameters ---------- line : str Target function line string. e.g., `def sample_func(a: int) -> None:` docstring : str ...
e4fcee2a5ac3bae9508174315884aea128dabf93
620,490
def bool_to_str(bool_val): """convert boolean to strings for YAML configuration""" if not isinstance(bool_val, bool): raise TypeError("The bool_val is required to be boolean type") return "true" if bool_val else "false"
7ba44d0bb3d47b8fd572b1dddf96b5f8c45135a3
620,492
import slugify def create_slug(s: str) -> str: """Convert a plain string into a slug. A slug is suitable for use as a URL. For instance, passing ``A new world`` to this function will return ``a-new-world``. """ return slugify.slugify(s)
2b405bd342ae8a18970ee8037f28ceb8f4b75caa
620,493
def get_boundaries(bucket_names): """ Get boundaries of pandas-quantized features. >>> bucket_names = ["whatever_(100.0, 1000.0)", "whatever_(-100.0, 100.0)"] >>> get_boundaries(bucket_names) [(100.0, 1000.0), (-100.0, 100.0)] """ boundaries = [] for bucket_name in bucket_names: ...
ccd7c668dec4d22fa6da94091a6848ba4cade74f
620,498
def _normalize_vendor(vendor): """Return a canonical name for a type of database.""" if not vendor: return "db" # should this ever happen? if "sqlite" in vendor: return "sqlite" if "postgres" in vendor or vendor == "psycopg2": return "postgresql" return vendor
908e1be991b6fa068744c756690511623bdd1e37
620,501
def days_in_minutes(days): """ Returns int minutes for float DAYS. """ return days * 60 * 24
37f464879e45ea7f183a50ce5a394564b636753e
620,503
def splice_data(data: str, width: int, height: int) -> list[str]: """Splice a data chunk into a number of layers :param data: Image pixels :param width: Image width in pixels :param height: Image height in pixels :return: List of layer of pixels """ layer_length = width * height assert ...
a00848b23a99566aa9076e58c9d60de29641b56a
620,505
def split_by_indel_size(df): """ Sort 1-nt and >1-nt indels Args: df (pandas.DataFrame) Returns: df_mono (pandas.DataFrame): df for 1-nt indels df_non_mono (pandas.DataFrame): df for >1-nt indels """ df_mono = df[df["indel_size"] == 1] df_non_mono = df[df["indel_size"] > ...
cdd5c79815e1d13d31eb43a7c628b71875098c24
620,508
import torch def jacobian(f, x, out_dim): """Computes Jacobian of a vector-valued function. Given f: batch_size x input_dim -> batch_size x output_dim Computes Jacobian Matrix J: batch_size x output_dim x input_dim By passing a gradient matrix to the backward call of the output tensor NOTE: ...
9aaae0b3672b83493677c860996aeba4ad632c76
620,511
def check_op(op): """ :param op: op to be checked :return: op if acceptable, raise error if not """ acceptable_op = ["=", ">=", "<=", "CONTAINS", "!!=", ">", "<", "<>", "IS NULL", "IS NOT NULL"] if op not in acceptable_op: raise KeyError("'op' sent ('%s') not acceptable. Please check yo...
44ebd45b45d87e4bcc2482732103e1dcf1ca6be9
620,513
def get_model_image(model_name, image_name: str = ""): """ Auxiliary function to get the image of the model :param model_name: model name :param image_name: image name :return: image path :rtype: str """ path_name = ( f"images/{model_name}/{model_name}.png" if not image_n...
ac196a4e9a13acd72e1b12875e019244034c4279
620,514
def build_group_dict(groups:list) -> dict: """Build a dict of groups, code -> group.""" group_dict = {} for group in groups: group_dict[group.code] = group return group_dict
919cafa81953e762727442ed0eefca32a5d11c48
620,515
def seconds_to_hms(seconds: int) -> str: """ Returns string like "23:01:59" or "297:59:03" from seconds. """ m, s = divmod(seconds, 60) h, m = divmod(m, 60) return f"{h:02d}:{m:02d}:{s:02d}"
fceeb62891600fac12818651a2fa6ecb8c1b4b06
620,518
def to_latlon_for_days(dataframe): """For each day get list of typles with lat lon that is needed for api call params: dataframe: dataframe with colums lat, lon, time returns: dict(key:date, value: list of tuples with latlon) """ result = dict() ...
e6673b467ff3fe60764c3b26a9dcbf38b34e9893
620,519
def bin_title(bin): """The title of a Bin instance in text representations""" return 'Sample @ ' + bin.iso8601time
08b7cfd64e26381d85483924bf2e7601db98d0f4
620,525
def _get_relationships(notation): """ Return the list of orthology relationships to keep. ENSEMBL homology relationships are defined in: https://www.ensembl.org/info/genome/compara/homology_types.html Posible values to this function are '1:1', '1:n' and 'm:n'. >>> _get_relationships('1:1') ...
b2c60ed7812be8c2a7739938ce3c7b477838e85e
620,527
import math def gaussian(x, mean, sdev): """ Computes a gaussian """ first, second = 0, 0 if sdev > 0: first = 1 / (math.sqrt(2 * math.pi) * sdev) second = math.e ** (-((x - mean) ** 2) / (2 * (sdev ** 2))) return first * second
8c9d06b5f33dd732e8519c7d57bb5975bdc2a173
620,532
from typing import Any from typing import Union def parse_int(v: Any) -> Union[int, None]: """Tries to parse to int :param v: Value to parse to int :param type: Any :return: Parsed int or None if error occured :rtype: Union[int, NoneType] """ try: return int(v) except ValueEr...
650be7910be9b8bd6d78bc891d87faf5b5275605
620,535
import re def grep(pattern, string=None, filename=None): """ simulate linux grep command return lines matching a pattern in a string or a file. Parameters: pattern: regular expression string Usage examples: result = grep('keyword', filename='a.txt' ) for i in result: ...
37cd81dcb409ca88ba0fd6b39d46ac4526702694
620,541
def api_route(api_path, method="GET"): """Decorate a function as API route/command.""" def decorate(func): func.api_path = api_path func.api_method = method return func return decorate
b58c6db09a65ef9e35093bfe001ed563829a08d8
620,542
from typing import Dict from typing import Any def platform() -> Dict[str, Any]: """ Returns: The schema for the `platform` block """ data = { "type": "list", "schema": { "type": "dict", "schema": { "name": {"type": "string", "required": ...
b5725dc731dda25fb176ad83fa4b51323fa7eb01
620,543
from typing import Any from functools import reduce def dgetattr(obj: Any, attr: str, default: Any) -> Any: """ getattr with dot seperated attribute list """ try: return reduce(getattr, attr.split("."), obj) except AttributeError: return default
12361f12ef40c7c34fac182c47e0e0a8f784f18e
620,545
def pretty_html(html: str) -> str: """ Add padding at the beginning of code and span elements to format the HTML output Args: html (str): the HTML output string """ format_html = html format_html = format_html.replace("<code", "\n{}<code".format(" " * 12)) format_html = format_h...
117f0d18b0c1c5a95ed2375f00cbd92a4400b213
620,546
def my_circle(my_radius): """Calculates the area of a circle given its radius. Keyword arguments: my_radius (float) -- Radius of the circle. Returns: Float -- Area of the circle. """ return (3.14 * my_radius * my_radius)
4e129c1758e68b57852ad9e1e43fd9a19157c10e
620,547
def minmax_scale(img, scale_range=(0, 1), orig_range=(0, 255)): """Rescale data values from original range to specified range :param img: (numpy array) Image to be scaled :param scale_range: Desired range of transformed data. :param orig_range: Original range of input data. :return: (numpy array) S...
a3adb16bfce041cc3505cda624f9b998780cf7ab
620,555
def vec2str(a, fmt='{}', delims='()', sep=', '): """ Convert a 3-sequence (e.g. a numpy array) to a string, optionally with some formatting options. The argument `a` is also allowed to have the value `None`, in which case the string 'None' is returned. The argument `delims` can be used to specify d...
9ff70fa411ce68300d27c8d4a7d6032905f5adea
620,556
def check_textgrid_duration(textgrid,duration): """ Check whether the duration of a textgrid file equals to 'duration'. If not, replace duration of the textgrid file. Parameters ---------- textgrid : .TextGrid object A .TextGrid object. duration : float A given length of ti...
1494e1b98bc0c9df9f9e543550fbdb834c490871
620,557
import hashlib def checksum_sha256(file_path, block_size=65536): """Get sha256 checksum for a file""" h = hashlib.sha256() with open(file_path, "rb") as f: for chunk in iter(lambda: f.read(block_size), b""): h.update(chunk) return h.hexdigest()
13bd7aeaec0486fcbd8baf81ceefcc021a96ea44
620,562
def subset_BEA_Use(df, attr): """ Function to modify loaded BEA table based on data in the FBA method yaml :param df: df, flowbyactivity format :param attr: dictionary, attribute data from method yaml for activity set :return: modified BEA dataframe """ commodity = attr['clean_parameter'] ...
c3fbb7fc07e0bac81501f57c4f557b360601e3fb
620,564
def is_top_level(comment): """ returns if the comment is top level (directly replied to the post) """ return comment.parent_id == comment.link_id
6561c15f95e4308bfbf90d293b05ae3b6493f05f
620,566
def togrid(fen): """ Takes FEN (without extra information at end) and returns a grid args: fen[0] "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR" returns: grid[0] [['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], ['', '', '', '', '', '', '', ''], ['', ...
a53a4a160f6df8e6c403e0f42fe4471a5e919fb7
620,570
def formatNumber(number): """Ensures that number is at least length 4 by adding extra 0s to the front. """ temp = str(number) while len(temp) < 4: temp = '0' + temp return temp
33caf6a3304f8c0e39f937fc11f2daee463a6286
620,573
def praw_to_user(user): """ Converts a PRAW user to a dict user. Args: user: :class:`praw.models.Redditor` Note 1: accessing redditor attributes lazily calls reddit API Note 2: if user.is_suspended is True, other attributes will not exist Note 3: subreddit refers to a user profile (stored as a subredd...
fdeed0340e0acee15bb494507c9aedaa5c168829
620,574
def df_drop_nan_rows(df, verbose=False): """Remove entries in dataframe where all rows (besides 'time') have nan values. """ N_init = df.shape[0] colnames = [c for c in df.columns if c not in ['time', 'turbid', 'index']] df = df.dropna(axis=0, subset=colnames, how='all') if verbose: ...
8490d79f0296b4415ce1485706087accefe562e5
620,577
def ansible_facts(ansible_module): """Return ansible_facts dictionary.""" return ansible_module.setup()
5948379ccc80cf8012c5da717985a940cfc35b4d
620,581
def ApplyParsedXPathQuery(trees, xpath_query): """ Apply a parsed XPath Query to a list (sequence) of `trees`.""" filtered_nodes = iter(trees[:]) for q in xpath_query: filtered_nodes = q.Filter(filtered_nodes) return filtered_nodes
520c5c1a9500dbbae5b448b622c0f6c5c4487f12
620,583
def ci_lookup(the_key, the_dict, default=None): """Case-insensitive lookup Note that this will not work if keys are not unique in lower case - it will match the last of the matching keys >>> the_dict1 = {'Me': 'Andrew', 'You': 'Boris', 'Her': 'Natasha'} >>> ci_lookup('heR', the_dict1) ...
6027304b9465c71bc3b5de89dcd8c66347fdd510
620,584
def _lookup_by_value(themap, value): """ Do a reverse lookup on a map (assumes 1-to-1) """ for k in themap: if value == themap[k]: return k return None
0059681d6bb1c676d94970548e72037d53e98d73
620,586
def rotated_array_search(nums, target): """ Find the index by searching in a rotated sorted array Args: nums(array), target(int): Input array to search and the target Returns: int: Index or -1 """ # Binary search, O(n log n) in time and O(1) in space lo, hi = 0, len(nums)-1 ...
17a8e3f7aeb08bd699bfc8260ee9fa8a881e234a
620,591
from pathlib import Path import json def deserialize_wikifier_config(uid: str, pid: str, region_filename: str) -> dict: """ This function reads and deserialize the wikifier config file :param uid: :param pid: :param region_filename: :return: """ file_path = str(Path.cwd() / "config" / ...
c5d50a695bd0730ef5ada5679ed9eabdffd10a17
620,592
def getHeadersFromSWIG (filename): """getHeadersFromSWIG (filename) -> (filename1, filename2, .., filenameN) Reads the list of %include directives from the given SWIG (.i). The list of C/C++ headers (.h) included is returned. """ stream = open(filename) lines = stream.readlines() stream.close() line...
9b0c3c000083f08665bcbf26e6e4966d5dbd9f91
620,595
def _build_var_list_str(var_names): """ Builds the string that contains the list of variables in the parameterized variable format for SQL statements. Args: var_names ([str]): The list of var names, likely the keys in the dict returned by `_prep_sanitized_vars()`. Returns: (str...
d1626fcf5727ccaf91652e61fbd4d2399358fa07
620,597
def is_palindrome(string: str) -> bool: """Checks is given string is palindrome. Examples: >>> assert is_palindrome("abccba") >>> >>> assert is_palindrome("123321") >>> >>> assert not is_palindrome("abccbX") """ if not isinstance(string, str): raise TypeE...
0354b8f6a3058e823c4591266918fe234dce82dd
620,599
def _package_variables(variables, check_type): """ Removes token and customer id and adds check type to dict data Removes the token from the dictionary that will be sent to NodePing in JSON format as well as the customer id since these aren't a part of the check data. Also adds the check type. :ty...
4296b501992d5e6070078d4a71eab3d4dc4f08c6
620,601
def has_doc(f): """Check if function has doc string.""" return f.__doc__ is not None
7208b4b0f4491ca959a380bc1782b0655138f21f
620,602
def key_in_kwargs(key, **kwargs): """ Tests if a key is found in function kwargs | str, kwargs --> bool """ kwarg_dict = {**kwargs} if key in kwarg_dict: return True return False
89a37ef281e89048f89bdee10563877361375fdd
620,604
def embedding_dimension(vertices): """ Get the dimension of the space a simplex is embedded in. :param vertices: Vertices of the simplex ((n + 1) x m matrix where row i contains the i:th vertex of the simplex). :return: Dimension m of the space the simplex is embedded in. :rtype: int """ re...
8795af279d68c1234750a45224757385e42b362d
620,611
def _nbcols(data): """ retrieve the number of columns of an object Example ------- >>> df = pd.DataFrame({"a":np.arange(10),"b":["aa","bb","cc"]*3+["dd"]}) >>> assert _nbcols(df) == 2 >>> assert _nbcols(df.values) == 2 >>> assert _nbcols(df["a"]) == 1 >>> assert _nbcols(df["a"].valu...
7d7dc2557cf0ad31cc964d5cba32a940db9ac375
620,613
from datetime import datetime def valid_after_from_network_statuses(network_statuses): """Obtain the consensus Valid-After datetime from the ``document`` attribute of a ``stem.descriptor.RouterStatusEntryV3``. :param list network_statuses: returns datetime: """ for ns in network_statuses: ...
ecd62ee0046279c4ebe72335c932da61fa404391
620,615
import inspect def _check_simulator(simulator): """Checks that the simulator is callable and takes just two parameters For the simulator to be functional within the IMNN it must have a specific form where it takes a random number and a set of parameter values and returns a simulation generated at tho...
96ac74dca4e19f6ab6035b48f7e09975ea2195a8
620,619
from click.testing import CliRunner def runner(request): """Get a click.CliRunner instance.""" return CliRunner()
0c05e9b5ea42944c1f9e05e26c4d35cce2a6106f
620,621
def _is_sld(model_info, id): """ Return True if parameter is a magnetic magnitude or SLD parameter. """ if id.startswith('M0:'): return True if '_pd' in id or '.' in id: return False for p in model_info.parameters.call_parameters: if p.id == id: return p.type ...
05c3d62ea95f5bc849809944d00b522b488900f0
620,622
import six def s(*l): """Join all members of list to a byte string. Integer members are converted to bytes""" r = b'' for e in l: e = six.int2byte(e) r = r + e return r
746566ce400340d4d6e4bba38e4ac672c5817a90
620,623
def build_single(sequence, state_size, state): """ A small temporary model for lower order Markov Chains called during prediction when previously unseen state is encountered. :param sequence: Sequence to learn :param state_size: Order of the Markov Chain :param state: Current state :return: Lower order Markov Ch...
7e0d30a13aedc6df36193d3106d8491e41ce1300
620,625
def to_vis_json_metagraph(metanodes, cross_edges): """Produce Vis.js formatted network data (for children metagraphs). Args: metanodes (dict): Metanodes of the metagraph. cross_edges (dict): Edges running between metanodes. Returns: Vis.js formatted network data. """ nodes...
bc9d687299ac10c68ec0c4cb74fb1a879b94f13b
620,630
def B1(tree): """ Returns the B1 statistic: the reciprocal of the sum of the maximum number of nodes between each interior node and tip over all internal nodes excluding root. """ b1 = 0.0 nd_mi = {} for nd in tree.postorder_node_iter(): if nd._parent_node is None: co...
c253fd3abddae09c855973cd2f9512cc56e21e6e
620,632
def _norm2x(xp, xrange, xcenter): """ Convert normalized x in (-1, 1) back to data x unit Arguments xp: float | np1darray in (-1, 1) xrange: float MHz xcenter: float MHz Returns x: float | np1darray """ return xp / 2 * xrange + xcen...
1d199d0952112181eeeeff4c804f8d30c0af72ca
620,634
def get_confusion_matrix(classes: list, dataclasses: list): """ creates a confusion matrix :param classes: is a one-dimensional list containing the class names :param dataclasses: a 1-dimensional list containg the orignal and predicted class of each instance in data :return: a 2-dimensional list wi...
e5017c3be76ea5edeca8bdfead84881aaeef99a0
620,638
def rf_fit(rf, x_train, y_train): """ rf_fit will create the Random Forrest with the defined parameters and fit the model to the training data. Parameters ---------- rf: sklearn.ensemble._forest.RandomForestClassifier RandomForest which will be trained x_train: numpy.ndarray arr...
b4d3fd1680f57df85f86739b55ff01bd01c254ab
620,639
def build_paths(base_path, partial_paths): """Build a list of full paths by concatenating each partial path with the base path""" paths = [base_path + partial_path for partial_path in partial_paths] return paths
5b246f0c4594df140b6c221e11493d9233310bc5
620,641
def set_value_where_condition(df, value, col_val, value_cond1, col_cond1): """Set a value in a column where multiple conditions are fit Args: df (pd.DataFrame): Dataframe. value (int, float, str): Value to set. col_val (str): Column name for the set value value_cond1 (int, f...
cb65aeff934b7c4672ac66287698e3bda64defe4
620,643
def return_(value = None): """Create a return statement.""" if value is not None: return [['return', value]] else: return [['return']]
5dd7ff3b9905c2c35000d12f2a2cead8ee7cfe10
620,645
def hessian_vector_product_lr(label,ypred,x,v,C=0.03,has_l2=True,scale_factor=1.0): """Get implicit hessian-vector-products without explicitly building the hessian. H*v = v + C *X^T*(D*(X*v)) """ xv = x.dot(v) D = ypred * (1 - ypred) dxv = xv * D if has_l2: hvp = C * x.T.dot(dxv) + ...
30b3cc7c2c223349564d1d935556c28b53c2440d
620,647
def sort_dict_by_vals(dictionary, reverse=True): """ Sort dictionary by values :param dictiory: Dictionary object :reverse(boolean): Set to True to sort the values in descending order """ return {key: value for key, value in sorted(dictionary.items(), key=lambda item: item[1]...
7c0eebb15419b2ab5c28f4b39b64639f05d80793
620,648
import socket def validate_ipv6(ip): """ Validate an ipv6 address :param ip: The string with the ip :return: True ip if it's valid for ipv6, False otherwise """ ip = str(ip) try: socket.inet_pton(socket.AF_INET6, ip) except socket.error: return False return True
020570f461e17e2003b9385fb7219434fba283fa
620,652
async def assert_reply_contains(self, contents, substring): """ Send a message and wait for a response. If the response does not contain the given substring, fail the test. :param str contents: The content of the trigger message. (A command) :param str substring: The string to test against. :return...
b2f3088280535d224b18f7c638a0c4711f6e2204
620,653
def match_predictions(y_predicted, y_target_names, pred_node_predicted, pred_node_target_names): """Add final level node prediction results to final level-wide prediction result This method matches the node prediction result, which is only a small fraction of the whole level prediction, with the level-wide predict...
039616b6882682764bcf9b456af4398c87e2e8a5
620,656
def mround(x, base=5): """Round value x to nearest multiple of base.""" return int(base * round(float(x) / base))
6c4e45e563fe30259bd9ed7f5c4b19091e8070b6
620,657
def two_places_at_once(sequence): """ Demonstrates iterating (looping) through a sequence, but examining TWO places in the sequence on the SAME ITERATION. This particular example returns the number of items in the sequence that are bigger than the previous item in the sequence. For example, if ...
800b8ee60751dd916fdc9cf7ff4fbe9a3896f81e
620,663
def binarySearch(alist, item, start, end): """ Recursive Binary Search. O(log(n)) time complexity. :type alist of ordered values. :type item to find :type starting index :type ending index """ if start > end: return False mid = (start + end) // 2 if alist[mid] == item: return True elif ...
2ecba6482e80bcba46a6b8158c1251518c9c37e0
620,664
def feature_path(node): """Returns the feature path of a node.""" if node.is_group(): return [node.name()] type = node.type() if not type: type = '?' return feature_path(node.parent()) + [type]
cef9bb4cddf07e7d7abeb1c590810f275a81b922
620,667
def emitter_injection_efficiency(i_en=0,i_e=1): """ The emitter injection efficiency measures the fraction of the emitter current carried by the desired electrons or holes in a NPN or PNP device. The default is for a NPN device. Parameters ---------- i_en : float, required Elect...
819bf79e3df1fcfa11ec49702af36aadb95b9f20
620,670
def count_number_of_this_labels(data_set_list:list,image_path_string:str): """ Assumption: that data_set_list has dictionary elements with a 'ImagePath' element """ return len([v for v in data_set_list if v["ImagePath"] == image_path_string])
21bc5ce085cd251750f6f92f7f864bf1e052f1d6
620,671
import itertools def FindClusters(xs, flags, active_flag_val): """Find repeated ranges of a certain value in a list. Args: xs: x coordinate of each value. flags: values corresponding to each x-coordinate. active_flag_val: the flag value we're searching for. Example: FindClusters([0, 1, 2, 3, 4...
40b0c894aac771a921c507974338aaf91a76ac53
620,674
def is_complete(board: list[list[int]]) -> bool: """ Check if the board (matrix) has been completely filled with non-zero values. >>> is_complete([[1]]) True >>> is_complete([[1, 2], [3, 0]]) False """ return all(elem != 0 for row in board for elem in row)
6e54f56c5e2a68fe15d61d526d0b4d968c57f357
620,676
def solution(array): # O(N) """ Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which togeth...
6199cd05bc414b677f37f556cc631d9cb4aed1f4
620,683
def power(value: float) -> float: """Compute power.""" return value ** 2
136d16080f48c799f07806af9aa9ec95338749bd
620,685
def bbox_for_point(point, size): """Calcs square bounding box for provided center and bounding box size. :type point: list :param point: bounding box center :type size: float :param size: size of square bounding box :rtype: list :return: new bounding box """ x0 = point[0] - size / 2.0 y0 = point[...
114d424a009f2ab908cc34a17a472822469f86fe
620,686
def isInactive(edge): """Return 1 if edge is active, else return 0.""" if edge[2] >= len(edge[4]): return 1 return 0
d4a8170de24018df12798d8fa40df3b2fac45349
620,689
def object_kind(object_path): """ Parse the kind of object from an UDisks2 object path. Example: /org/freedesktop/UDisks2/block_devices/sdb1 => device """ try: return { 'block_devices': 'device', 'drives': 'drive', 'jobs': 'job', }.get(object_path...
de4055755ff741aa7ea38b257df75ee96b114ece
620,692
def lstringstrip(s_orig, s_strip): """ Left-strip a whole string, not 'any of these characters' like str.lstrip does """ if s_orig.startswith(s_strip): return s_orig[len(s_strip):] else: return s_orig
0b954c0e44511f920dd0e4c214cea3eb082ec7b6
620,694
import threading def background(f): """Threading decorator. Use @background above the function you want to thread (run in the background).""" def bg_f(*a, **kw): thread = threading.Thread(name=f.__name__, target=f, args=a, kwargs=kw) thread.start() return thread return...
7e8d2b1c8ab42cbe318914acb9dc3c8367b45323
620,696
import string import random def random_id(size=16, chars=string.ascii_lowercase): """Return a random id string, default 16 characters long.""" return ''.join(random.choice(chars) for _ in range(size))
d3e69834de41f11dab86eb0714360bfa36c3c6ef
620,697
def apim_nv_delete(client, resource_group_name, service_name, named_value_id): """Deletes an existing Named Value. """ return client.named_value.delete(resource_group_name, service_name, named_value_id, if_match='*')
c73a3ff2d96da9cc5b503eb5c841eb0bc7d3aef3
620,698
def rectangle_points(pos, width, height): """Return the points of a rectangle starting at pos.""" x1, y1 = pos x2, y2 = width + x1, height + y1 return [(x1, y1), (x1, y2), (x2, y2), (x2, y1)]
238cd9b961895b560579e30d213607dca6218a5a
620,703
def imcrop(image, crop_range): """ Crop an image to a crop range """ return image[crop_range[0][0]:crop_range[0][1], crop_range[1][0]:crop_range[1][1], ...]
f727a48296a9af8eb18aa1bd66eea8d133ac9cf3
620,704
from typing import OrderedDict def _add_mlst(mlsts: dict) -> dict: """ Read through MLST results and create column each schema. Args: mlsts (dict): The MLST results associated with a sample Returns: dict: Per schema MLST hits """ results = OrderedDict() for key, vals in m...
04c031902a2496c0ef9cd468f8b17f0727a13548
620,705
def get_single_band(fnames,band_numbers,band_num): """ Function to return the file path for a single band, given a band number and list of input file paths. Parameters ---------- fnames : LIST List of band file locations, as generated by get_filenames(). band_numbers : LIST ...
12f51ae740fe50a0deb0ceb959329a6e98e49ff8
620,707
def create_verifier_for_dsa(signature, hash_method, public_key, image_properties): """Create verifier to use when the key type is DSA :param signature: the decoded signature to use :param hash_method: the hash method to use, as a cryptography object :param public_key: the pu...
c94630ca7e4126b48d4e37059cdca14636a60f4e
620,714
def all_edges(G, nbunch=None, data=False): """ Get a list of all (both incoming and outgoing) edges of (Multi)DiGraph G :param G: (Multi)DiGraph :param nbunch: list of nodes whose adjacent edges we want to find :param data: boolean: return list with or without nodes data :return: corresponding l...
88e7203bcada08aac671b2d7f5c8f41a90afba03
620,715
def chance_of_missing(num_of_keys: int, num_of_draws: int, total_choices: int): """Given total number of choices, the number of keys among the choices, and total number of draws, what are the chances of not being to draw a single key in all the draws. """ r = 1 for _ in range(num_of_draws): ...
29884be8d275fd8690a9224ddf819338b02821e2
620,718
def calculate_delta_x(a: float, b: float, n: int) -> float: """ Calculate delta_x = (b - a) / n n = data points samples a = min x value of integral b = max x value of intergal """ return (b - a) / n
2aed6bfdc8c67d97f4ee432308e681b77b21be44
620,719
def precond_grad_kron(Ql, Qr, Grad): """ return preconditioned gradient using Kronecker product preconditioner Ql: (left side) Cholesky factor of preconditioner Qr: (right side) Cholesky factor of preconditioner Grad: (matrix) gradient """ if Grad.shape[0] > Grad.shape[1]: return Ql....
35dc9ad0c78a96f4e39abbc1d94636a2f1508cd7
620,721