content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import torch from typing import Tuple def find_matching_pairs( y: torch.Tensor, a_pair_info: torch.Tensor, b_pair_info: torch.Tensor) -> Tuple[torch.Tensor,torch.Tensor]: """ Given a batch of ground truth label maps, and sampled pixel pair locations (pairs are across label maps), identify whic...
35310dc7614d6c3f80302b83ca83c87644828150
553,483
def _js_repr(val): """Return a javascript-safe string representation of val""" if val is True: return 'true' elif val is False: return 'false' elif val is None: return 'null' else: return repr(val)
b5462a172a4aa68cc78e8bf9f9752991d4e7903d
142,862
import copy def unravel(l): """ Unravel Union node to get all permutations of types for each action Parameters ---------- list : list of Qiime2.types Returns ------- list of lists - list of permuations of types for each action """ result = [l] for i, x in enumerate(l): ...
0c676ff8477b8964cdf0a2885e709e8b27ed066c
139,961
def actions2trajectory(position, actions): """ helper function to map a set of actions to a trajectory. action convention: 1 - upper left, 2 - up, 3 - upper right 4 - left, 0 - stop, 5 - right 6 - lower left, 7 - down, 8 -lower right Inputs: - position: numpy array representing...
27d27e134cb71f930b82d6f8561c71e9f2eccbc8
509,187
import string import re def consonant_sounds(word: str): """Return a set with all the consonant sounds in word. Ex: chatting -> {'ch', 't', 'ng'}. Note that 'tt' becomes 't'.""" consonants = ''.join([c for c in string.ascii_lowercase if c not in 'aeiou']) pattern = f'[aeiou]*([{consonants}]+)' ...
bf7b8706c1c27634b8cd925ff9099d02b788499a
234,201
def tibetan_leap_month(date): """Return 'leap month' element of a Tibetan date, date.""" return date[2]
1e4fa5c15ec0556703ff32f162954f2722b1f26a
537,588
def mean(xs): """Returns the mean of the given list of numbers""" return sum(xs) / len(xs)
05404301294bf2ff7c632857d31d33c78741bcfd
611,614
def process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (dictionary) raw structured data to process Returns: List of dictionaries. Structured data with the following schema: [ { "chain": string, ...
d4f8b290cbf04de75c148d13331ef46b11405338
161,239
def acs(concept, paragraph, model, min_length, stop_words=[]): """ :param concept: str, the concept word for the concept :param paragraph: list, a list of the tokens in the paragraph :param model: gensim.models.Word2Vec, model containing word vectors :return: float, the distance between the concept ...
4af462fb970fed1b7e8f42576e5cceac6b912ad6
669,444
import re def camelize(string): """ Convert string to CamelCase notation (leave first character upper). >>> camelize('Color_space') 'ColorSpace' >>> camelize('ColorSpace') 'ColorSpace' """ return re.sub(r'_([a-zA-Z])', lambda x: x.group(1).upper(), string)
98a6fcfb89d13bc7ea7e065a2e8401eaa43a20ad
337,404
def convert_float(s): """Converts values, handling bad strings.""" try: return float(s) except (ValueError, TypeError): return None
f521645d818ab45ba111b538c5169b9817030ee9
346,115
def rol(x, i): """Rotate the bottom 32 bits of x left by i bits.""" return ((x << i) | ((x & 0xffffffff) >> (32 - i))) & 0xffffffff
33ecbe3ed9f0806e14c6abbfb75889e916dfc78b
658,453
import re def _parse_txt_channel(header: str) -> str: """Extract channel and label from text headers and return channels as formatted by MCDViewer. e.g. 80ArAr(ArAr80Di) -> ArAr(80)_80ArAr Args: headers: channel text header Returns: Channel header renamed to be consistent with MCD View...
d286b80b237f03de52d252e4e7f823de2a469a4f
374,854
def unpackLine(string, separator="|"): """ Unpacks a string that was packed by packLine. """ result = [] token = None escaped = False for char in string: if token is None: token = "" if escaped and char in ('\\', separator): token += char escaped =...
f6fff254be36ab9d43184ffdc973c79be323bc51
204,588
def braced(input): """Put braces around a word""" return '{%s}' % input
0c0e3f3518580587c83eac95ba901541291fddc7
146,921
def override(original, results): """ If a receiver to a signal returns a value, we override the original value with the last returned value. :param original: The original value :param results: The results from the signal """ overrides = [v for fn, v in results if v is not None] if len(o...
3594a74f569b0d0ea0f2114b35243569b4325a31
497,767
def parsimony_informative_or_constant(numOccurences): """ Determines if a site is parsimony informative or constant. A site is parsimony-informative if it contains at least two types of nucleotides (or amino acids), and at least two of them occur with a minimum frequency of two. https://www.megasof...
3b547cc72b5cda912c0693df7fd8735c888fee42
181,535
from typing import Dict from typing import Tuple def get_colormap() -> Dict[str, Tuple[int, int, int]]: """ Get the defined colormap. :return: A mapping from the class names to the respective RGB values. """ classname_to_color = { # RGB. "noise": (0, 0, 0), # Black. "animal": (7...
069a7c4aff434d72a0d67bc4b59db732589541a7
97,675
def to_chr(x): """chr(x) if 0 < x < 128 ; unicode(x) if x > 127.""" return 0 < x < 128 and chr(x) or eval("u'\\u%d'" % x)
1f2eebb014f328e3ff6184a56663db814ebfa34b
106,549
from typing import Union def convert_seconds_to_hms(sec: Union[float, int]) -> str: """Function that converts time period in seconds into %h:%m:%s expression. Args: sec (float): time period in seconds Returns: output (string): formatted time period """ sec = int(sec) h = sec //...
f7b81898e82a13b95a82a22c42470f2df158b0c8
459,708
def get_cincinnati_channels(major, minor): """ :param major: Major for release :param minor: Minor version for release. :return: Returns the Cincinnati graph channels associated with a release in promotion order (e.g. candidate -> stable) """ major = int(major) minor = int(minor...
e57ad8d26ea0a397e8c3f9edc99174f78b506564
701,580
def age_bin(age, labels, bins): """ Return a label for a given age and bin. Argument notes: age -- int labels -- list of strings bins -- list of tuples, with the first tuple value being the inclusive lower limit, and the higher tuple value being the exclusive upper lim...
9caccc667b55f66824bcf8802161384590cc2a08
697,886
def read_text(file_location, not_exists_ok=False): """Read text from a file Args: file_location (str): Location of file not_exists_ok (bool, optional): If True and file does not exist, will return "" instead of throw an exception. Defaults to False. Returns: str: The text in the fi...
8fe16392a8d8dbdb10c62a9575ee7f7815d4544f
370,729
def has_alpha(img): """Checks if the image has an alpha channel. Args: img: an image Returns: True/False """ return img.ndim == 4
15e673deb3024e3a321571b1a1a27d5c310089a1
79,752
def insert_into_every(dods, key, value): """Insert key:values into every subdictionary of dods. Args: dods: dictionary of dictionaries key: key to hold values in subdictionaires value: value to associate with key Returns: dict: dictionary of dictionaries with key:values ins...
d472702e9ba0f255e07e2e728ed6e52da5d51517
339,517
def get_errno(e): """Get the error code out of socket.error objects """ return e.args[0]
af8427bf4bfbed62b2641cb1e135505a8c7ddbc9
181,724
def get_built_config_distribution(built_config, minimal_diffs): """ Args: built_config: Configuration built so far minimal_diffs: List of all the minimal diffs in built config space Returns: A probability distribution over blocks in the built config -- probabilities of next removal ...
e956afaa885bfbecc79e002bd3dc25f7ce2e8e12
227,839
def determine(hand): """Returns a list of values, a set of values, a list of suits, and a list of cards within a hand.""" values, vset, suits, all_cards = [], set(), [], [] for x in range(len(hand)): values.append(int(hand[x])) vset.add(int(hand[x])) suits.append(hand[x].suit) ...
60318bf9c9259f0741caaadb0246d2d8d66ca4f5
39,155
def state_schema(cfg): """Given config data, return the Cerberus schema for the state. """ return { cfg['time_key']: { 'type': cfg['time_type'], 'required': True, 'nullable': True}, 'status': { 'allowed': cfg['status_values'], 'requ...
f6ec291aee761aac1aabc0ecc47240d68b05ac90
557,074
import re def split_into_chunks(code): """ Split code into chunks, each chunk being a function definition """ # Create an empty list to store chunks chunks = [] # Create a string to store the current chunk chunk = '' # For each line in the code for line in code.splitlines(): ...
bc1d44060c14237893c522c04b3a04445dd5ea60
603,558
import json import copy def get_args(request, required_args): """ Helper function to get arguments for an HTTP request Currently takes args from the top level keys of a json object or www-form-urlencoded for backwards compatability. Returns a tuple (error, args) where if error is non-null, the...
b44e058590945211ca410005a5be2405b4756ca4
703,466
import re def is_jira_issue(string): """Returns True if input string is a valid JIRA issue key, else False""" jira_regex = r"^[A-Z]{1,10}-[0-9]+$" return bool(re.match(jira_regex, string))
854355bfb5ebf02cec68a35220133588a135a2ea
264,979
def validate_geography(lon: float, lat: float): """ Verifies that latitude and longitude values are valid :param lon: longitude value in degrees :param lat: latitude value in degrees :return valid: boolean for whether the lon/lat values are valid """ lon_valid = lon >= -180 and lon <= 180 ...
00ba1bab9a8fcdfa764da6b23c5be93c087d572d
170,785
def _rectify_identifier(station, textprod): """Rectify the station identifer to IEM Nomenclature.""" station = station.strip() if len(station) == 4 and station.startswith("K"): return station[1:] if len(station) == 3 and not textprod.source.startswith("K"): return textprod.source[0] + st...
a4abd3ef40cc2dac718deceabf6d9caa2d8384df
556,357
def strategy(history, memory): """ Defect every few turns, based on the fibonacci sequence. i.e., defect turn 2 (1), turn 3 (1), turn 5 (2), turn 8 (3), turn 13 (5) """ if memory is None: last_defection_turn = 0 prev_fibonacci = 1 current_fibonacci = 1 else: last_...
009710f3fb9eb4c5802b3beb0239afe2de6acdfb
44,909
def mcfadden_r2(ll_est, ll_null): """ McFadden's Pseudo R-squared when the saturated model is not available. Parameters ---------- ll_est : numpy array Estimated Log likelihood. ll_null : numpy array Null-model log-likelihood. Returns ------- m_r2 : float Mc...
4a08299368d695f4b760fb118071bbd7a78a86a2
335,143
import json def load_labels(label_fpath): """ Load stored labels Params: label_fpath (str): file-path to stored labels Returns: the dict containing the report (stored) labels """ with open(label_fpath, 'r') as f: labels = json.load(f) return labels
1f3b9988e2862f2e7a34c423c64488fe10e6956e
206,240
import time def is_expired(epoch_time): """True if current time has passed the provided epoch_time""" return time.time() > epoch_time
b264fd1d73fe7f9c97592e6bffc27c81574d6bde
700,738
def zero_penalty(self, real_data, fake_data): """ No penalty """ return 0
9f1c19a5784eb1cee672fbba8fc665aef125570e
412,380
def dict_append_to_value_lists(dict_appendee, dict_new): """ Appends values from dict_new to list of values with same key in dict_appendee Args: dict_appendee: dict with value lists (as created by dict_values_to_lists function dict_new: dict with new values that need to be appended to dict_a...
3f39a6bca91c3429a04f0047673f6231d29336eb
694,168
import torch def ume_ustat_h1_mean_variance(feature_matrix, return_variance=True, use_unbiased=True): """ Compute the mean and variance of the asymptotic normal distribution under H1 of the test statistic. The mean converges to a constant as n->\infty. feature_matr...
ea9d90d96bd8de490c3a9b4533a81a1bd87ef93d
344,045
def dict_pathsearch(dict, path): """ Finds a value inside a dictionary of dictionaries given a path-like string of keys separated by periods. Raises KeyError if the requested path doesn't exist. Example ------- Given a dictionary like the following: { foo : "foo" ...
d1265627ca0e8e349151c6668dc740e224c84a0f
561,118
def mz_validator(number: str, nr_format: str = "international") -> list: """ Verify if the given number is valid Args: number (str): The phone number to be validated nr_format (str, optional): The number has international identification code. Defaults to international. Returns: lis...
4e89bcadb805b644d852e3a45190a0685f85f2ad
207,785
def _extract_array(array, shape, position): """Helper function to extract parts of a larger array. Simple implementation of an array extract function , because `~astropy.ndata.utils.extract_array` introduces too much overhead.` Parameters ---------- array : `~numpy.ndarray` The array f...
669d011b861098ee8246758dcc73bba8d1b94ca5
540,178
from typing import List def _wraptext(text: str, length: int = 78) -> List[str]: """ Wrap long text into several lines of text is smart enough to wrap words that are too long to a new line :param text: str, the long text to wrap :param length: int, the number of characters to wrap at :return...
cfbc70d061912878f62cde61fbea3df9d0d1649d
224,732
def _path_to_release(path): """Compatibility function, allows us to use release identifiers like "3.0" and "3.1" in the public API, and map these internally into storage path segments.""" if path == "v3": return "3.0" elif path.startswith("v3."): return path[1:] else: raise R...
84ea8a22e3a1d82df249161fd76b12c370f70742
695,654
def sumar_valores_pares(numeros: list) -> int: """ Sumar valores pares Parámetros: numeros (list): Una lista de números enteros. Retorno: int: La suma de los números de la lista que sean pares. """ suma_par = 0 for numero in numeros: if numero % 2 == 0: suma_par +...
f7c9a2838b60e77f04ae83ded46f64e61919691f
526,752
def float_validator(minimum=None, maximum=None, allow_exponent=False): """ Creates a callable which will validate text input against the provided float range. Parameters ---------- minimum : None or float The lower bound of allowable values, inlcusive. None indicates no lower bound....
3b3defcbd3593dd879daa3283258cb5cee149992
415,162
def _as_list(obj): """A utility function that treat the argument as a list. Parameters ---------- obj : object Returns ------- If `obj` is a list, return it. Otherwise, return `[obj]` as a single-element list. """ if isinstance(obj, list): return obj else: retur...
7b4ad031afc5f208ad0d58a93a7456ff15586b5b
534,261
def _any(itr): """Similar to Python's any, but returns the first value that matches.""" for val in itr: if val: return val return False
a71eb2643af93d76031290d8083a6595b3560084
120,701
import random def random_color(s): """ The function returns a random RGB color; It helps to get random colors since the number of variables is not known """ number_of_colors = s color = ["#" + ''.join([random.choice('0123456789ABCDEF') for j in range(6)]) ...
e4150e15ddb1ea1843f811929b1de20735e983b4
231,084
def filename_for(resource): """Generate a unique base file name for the given resource. :param resource: A k8s resource definition dict, expected to have at least a kind and metadata.name. :return: A base file name (no directory) that should be unique for the given resource (assuming the re...
2feb6589b1b0c7b3dc9d60f5d2b629e221923290
433,916
def truncate(predictions, targets, allowed_len_diff=3): """Ensure that predictions and targets are the same length. Arguments --------- predictions : torch.Tensor First tensor for checking length. targets : torch.Tensor Second tensor for checking length. allowed_len_diff : int ...
183dbe4c3400fbccea8a76850afc29cdf06a84dc
85,877
from typing import List from typing import Dict from typing import Any import copy def expected_gui_urls(gui_urls: List[Dict[str, Any]], haproxy: bool, yarl: bool) -> List[Dict[str, Any]]: """Get the expected value of a gui-url list for a single product. The implementation transforms th...
95cb2a2029463887fe7dc44f3c113ce1f8e58b26
518,685
def splitOut(aa): """Splits out into x,y,z, Used to simplify code Args: aa - dictionary spit out by Returns: outkx, outky, outkz (numpy arrays) - arrays of the x, y, and values of the points """ outkx = aa['x'][::3] outky = aa['x'][1::3] outkz = aa['x'][2::3] return out...
3be9e1938374a823a78aa6f8478c8cd02e4e9c50
690,829
def get_stimuli(task_type, sequence): """There is some variation in how tasks record session information. Returns the list of stimuli for the given trial/sequence""" if task_type == 'Copy Phrase': return sequence['stimuli'][0] return sequence['stimuli']
1c6cb3aa8433b6494a4035862df642da05d80269
345,443
import re def is_re(s): """Return True if s is a valid regular expression else return False.""" try: re.compile(s) except: return False else: return True
c41e682218bab17f8209b6c93c74b9d868ff9be4
346,739
def merge_stage1(p1, p2): """Merge partial statistics.""" p1 = p1.add(p2, fill_value=0) return p1
3dd3e026d58aadc00192ca90dc77e9d98c8689ef
524,566
import yaml def get_filenames(filenames_file): """Extract the list of file that are required for test, from the input file. Args: filenames_file (str): the path of filenames file Returns: filenames (list): the filenames extracted from the input file. """ with open(filenames_file,...
88ce0ab51e423c032569cc143ed18bfc5688070b
309,170
def set_ceid(country="US", language="en"): """Set the base country and language for the RSS Feed Args: country (str, optional): Country abbreviation. Defaults to "US". language (str, optional): Country Language abbreviation. Defaults to "en". Returns: ceid (str): acceptable RSS fe...
ad0a008942eee99da95770031e44479e6eb83b6f
522,499
def graph_return(resp, keys): """Based on concepts of GraphQL, return specified subset of response. Args: resp: dictionary with values from function keys: list of keynames from the resp dictionary Returns: the `resp` dictionary with only the keys specified in the `keys` list R...
72cc27e97a53c2533b02f99a4bba8db8a57dc430
217,931
def state_value(state, address, init=0, end=15): """ init and end are included on the desired slice """ if state is None: return 0 binary = format(state[address], '016b') r_init = len(binary)-1-init r_end = len(binary)-1-end kBitSubStr = binary[r_end: r_init+1] return int(kBi...
c0c1ff7a77ed8b0eac48fbad3fd0e7d3cac16132
280,352
def hash_copy(space, w_res): """ Copy hashing context""" return w_res.deepcopy()
7f06334029d2ec3df4d5cdbd682e372f9adaed1d
372,815
def prettify_date(date_string): """ This function receives a string representing a date, for example 2018-07-28T10:47:55.000Z. It returns the same date in a readable format - for example, 2018-07-28 10:47:55. """ date_string = date_string[:-5] # remove the .000z at the end date_prettified = dat...
43dcbfbc73e7efbbf607e57c7f08a2322d8c7958
545,063
def format_num(num) -> str: """ Examples: format_num(10000) -> 10,000 format_num(123456789) -> 123,456,789 :param num: :return: """ num = str(num) ans = '' for i in range(len(num)-3, -4, -3): if i < 0: ans = num[0:i+3] + ans ...
a6e4059f81edd0cc1afa55eacd7440f4876513e0
52,607
def getChildElementsListWithSpecificXpath(parent, xpath): """ This method takes a parent element as input and finds all the children containing specified xpath Returns a list of child elements. Arguments: parent = parent element xpath = a valid xml path value as supported by python, refer ...
8576d7236d2328962766bd60946a38897a68471b
183,364
import math def distance(point_a, point_b): """ Returns the distance between two points given as tuples """ x0, y0 = point_a x1, y1 = point_b return math.hypot(x0 - x1, y0 - y1)
d41cec3978ea62b3b93e1e64b1f1103bce88d231
670,544
def frange(start, final, increment): """Return equally spaced float numbers between two given values.""" numbers = [] while start < final: numbers.append(start) start += increment return numbers
df6a34ca11e77b61a697887d46ba10f5813acd58
248,209
def diffmean(xl, yl): """Return the difference between the means of 2 lists.""" return abs(sum(xl) / len(xl) - sum(yl) / len(yl))
36a449f68311f6ec8b23698c9c9797501eb73240
660,150
def degrees_to_miles_ish(dist:float): """ Convert degrees lat/lon to miles, approximately """ deg_lat = 69.1 # dist_lat_lon(42, 74, 43, 74) deg_lon = 51.3 # dist_lat_lon(42, 73, 42, 74) return dist * 60.2
f4485060dcba6821f479138f905afe6a008532d4
351,056
def barycentric_to_cartesian(bary, vertices): """ Compute the Cartesian coordinates of a point with given barycentric coordinates. :param bary: The barycentric coordinates. :param vertices: The triangle vertices (3 by n matrix with the vertices as rows (where n is the dimension of the space)). ...
3576f93d190ef52669a0ba80483dea88c75696ac
32,740
def time_shift(x, shift): """Shift a series by a specified amount""" xshift = x.copy() if shift > 0: xshift[shift:] = x[0:-shift] elif shift < 0: xshift[0:shift] = x[-shift:] elif shift == 0: pass return xshift
37487ec4557231f2d72f523b1bdbdc0824bea40d
202,630
def skeleton_df_to_swc(df, export_path=None): """ Create an SWC file from a skeleton DataFrame. Args: df: DataFrame, as returned by :py:meth:`.Client.fetch_skeleton()` export_path: Optional. Write the SWC file to disk a the given location. Returns: ``st...
586476baedfe827be84939aa56e95e2afdb695b2
195,508
def htmlentities(text): """Escape chars in the text for HTML presentation Args: text (str): subject to replace Returns: str : result of replacement """ for lookfor, replacewith in [ ("&", "&amp;"), (">", "&gt;"), ("<", "&lt;"), ("'", "&#39;"), ('...
7931032e152f1f971a80efddba0239507df101bc
190,594
def integer(i): """ Parses an integer string into an int :param i: integer string :return: int """ try: return int(i) except (TypeError, ValueError): return i
702f2179eaf82bf1c004eeb7dbc72a0d44dfad5f
507,106
def is_in_ring(a): """ Whether the atom is in a ring """ return a.IsInRing()
0f0ea015aa4d91ea94d25affd4a937037a0f4ed0
579,364
def GetPDFMultiByteInt(s, i, fieldlen): """Get a multibyte int from a string of bytes Args: s: string of bytes i: int, offset in s to start getting the result fieldlen: int, how many bytes to get Returns: int: accumulated multibyte value (high order byte first in s) """ ans...
2f8021a4a4ff276409a1cfbf37b73d664fb338f5
323,564
def tlbr2ltwhcs(boxes, scores): """ Top-Left-Bottom-Right to Left-Top-Width-Height-Class-Score """ new_boxes = [] for box, score in zip(boxes, scores): new_boxes.append([box[1], box[0], box[3] - box[1], box[2] - box[0], 0, score]) return new_boxes
d74c2c99f84bdfa3f1bffbbbf2b5a6c7bf607c56
442,717
import csv def load_data(path, delimeter=','): """ Reads the data from a CSV file Skips lines starting with # Arguments: path - path of the file to read (optional) delimeter - delimeter between columns Returns: Data in form of a 2D array """ data = [] with open(path, newl...
2fd0f0a2e6f4d3ef0c83fd818bd900d76455ae4e
135,294
import pickle def choices_from_pickle(paths): """ Get conformer choices as RDKit mols from pickle paths. Args: paths (list[str]): conformer path for each of the two molecules being compared. Returns: fp_choices (list[list[rdkit.Chem.rdchem.Mol]]): RDKit mol choi...
5004e7968aeb64c0e37afd2bf595a504387c0a28
227,357
def empty(piece): """To check if given piece is empty Necessary because an empty position can be both ' ' or '* ' """ if piece == ' ' or piece == '* ': return True return False
e2dbd54f64e169bba77f13921a53e711f36c4643
463,356
def config_database_option(config, key, dbname=None, getbool=False): """ Get database-level config option """ if config is None: return None if dbname is None: return None section = 'database "{}"'.format(dbname) if not section in config: return None return config[section...
fd9f42c06ada9fd1a7f846da6e43ddac71e271fd
572,091
def get_float_formatter_func(precision=None, thousands_sep=False, zero_string='0'): """ Returns a function that gives ``zero_string`` if the float is 0, else a string with the given digits of precision. """ def float_formatter(f): if isinstance(f, str): ...
3e0ff275c1c658710c6363c1dc32e111fdc65483
97,174
def msg_to_bytes(msg, standard="utf-8"): """Encode text to bytes.""" return bytes(msg.encode(standard))
634b1482c61773601a899bdd42c055960c03fc3b
395,779
def get_symmetric_quantization_range_and_scale(activation_is_signed: bool, activation_n_bits: int, activation_threshold: float): """ Calculates lower and upper bounds on the quantization range, along with quantization ...
d3a42550d01b51c5e685f9cf8271e48ceb4b8b80
270,208
import torch def softplus_inv(x, eps=1e-6, threshold=20.): """Compute the softplus inverse.""" y = torch.zeros_like(x) idx = x < threshold # We deliberately ignore eps to avoid -inf y[idx] = torch.log(torch.exp(x[idx]) - 1) y[~idx] = x[~idx] return y
a03a0eae38e4b23c32dd6264257cba3d9ba8dbc4
154,098
import string import random def generate_password(length=12, ascii_lower=True, ascii_upper=True, punctuation=True, digits=True, strip_ambiguous=False, strip_dangerous=True): """ This function will return a password consisting of a mixture of lower and upper case letters, numbers, an...
05195875abedab2f2c8998c675bc08dd4123ef53
339,386
import re def get_categories_from_text(edit): """Return the categories contained in a given wikitext.""" cat_pattern = r"\[\[Category:(?P<cat>.+?)(\|.*?)?\]\]" return [x[0] for x in re.findall(cat_pattern, edit)]
81237b0e5c9c3ac7f7db3f3ea84e673576859950
182,292
import json def load_input_blocks(path): """ Load stored blocks from disk e.g., load_input_blocks('./testdata/btc_blocks_json_samples/300000--300007') """ with open(path) as json_file: blks = json.load(json_file) return blks
8b6c75411e4dc7e2d429ee57471f06fc3af6fdb0
597,758
def heading(text, level): """ Return a ReST heading at a given level. Follows the style in the Python documentation guide, see <https://devguide.python.org/documenting/#sections>. """ assert 1 <= level <= 6 chars = ("#", "*", "=", "-", "^", '"') line = chars[level] * len(text) re...
43ef5bc1fdfb6c34279e9aa74ac420c1b1110e3a
657,939
import math def custom_percent(value): """Display a number with a percent after it, or a dash if not valid""" if math.isnan(value): return "-" return str(value) + "%"
4f170cf1d4b4d74dfaa993ca996bb8ed0cc51259
342,097
import itertools def construct_game_queries(base_profile, num_checkpts): """Constructs a list of checkpoint selection tuples to query value function. Each query tuple (key, query) where key = (pi, pj) and query is (p1's selected checkpt, ..., p7's selected checkpt) fixes the players in the game of diplomacy ...
1ffa16ebfd04f468cbde6db264ba33373c1b1d05
640,089
def SignalSegmentation(X,YSimulated,Cut): """ Function to split the X and the YEstimated in two slices according to the Cut point. Parameters ---------- X: Array of int32 Array containing the abscissa's values that are going to be segmented YEstimatedy: List List contai...
85ede2094edfacf8fec6dcfbbf816fc980107283
184,059
from typing import Iterable def intersection(sets: Iterable[set]): """Intersection of sets""" try: s = next(sets := iter(sets)) except StopIteration: return set() else: s = set(s) for x in sets: s.intersection_update(x) return s
c2fc164516296b87788ae065d787932b914bd489
570,576
def strip_strings(value): """ Strip excess whitespace, on strings, and simple lists using recursion """ if (value == None): return None elif (type(value) == list): # List, so recursively strip elements for i in range(0, len(value)): value[i] = strip_strings(value[i]) return value else: try: value...
c861855c2db989fe01bcf1f9ec2badd9d2c91b55
409,989
def get_module_id_from_event(event): """ Helper function to get the module_id from an EventHub message """ if "iothub-connection-module_id" in event.message.annotations: return event.message.annotations["iothub-connection-module-id".encode()].decode() else: return None
e183824fff183e3f95ef35c623b13245eb68a8b7
2,828
import random def random_int(min, max): """ Get random integer :param min: Minimum value (included) :param max: Maximum value (included) :return: Random integer """ return random.randint(min, max)
dd0b70b0a7a3957a2bcc4200eb03a28306886dc7
94,619
def urljoin(*args): """Join a set of strs for URL creation This method is commonly used by appending a URL to the `ENDPOINT` Parameters ---------- str URL names to join Returns ------- str The joined URL """ return '/'.join(map(lambda a: a.strip('/'), args))
67f7bc2f6512253e977b54bbf53cad375a543ded
447,709
def create_user_lookup(users_json): """Create a dictionary containing user profiles keyed to Canvas user ID.log_status. We'll need this lookup user names for submission commenters. users_json -- JSON collection of user profiles, as returned by load_users_json(). Returns dictionary. """ lookup_d...
69882d1491a44cad3cbd7d11e1b4e0c021b28f59
383,821
def textfile_contains(filename, marker): """ Return True if a textfile contains a string. """ try: with open(filename, 'r', encoding='utf8') as file: text = file.read(); if marker in text: return True except Exception as e: print(e) return False
c3cc966441fb65c9b5fbc0efdf56ba0f842f0565
111,642