content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import collections def _merge_compiler_kwds(list_of_kwds): """ Merges a list of keyword dictionaries. Values in these dictionaries are lists of values, the merged dictionaries will contain the concatenations of lists specified for the same key. Parameters ---------- list_of_kwds : list of...
0538be77849a061d04a2678f15c77fff9b07c5dd
468,710
def largest_odd_times(L): """ Assumes L is a non-empty list of ints Returns the largest element of L that occurs an odd number of times in L. If no such element exists, returns None """ l = L.copy() l.sort() l.reverse() for x in l: if l.count(x) % 2: return x ...
280d071bebeec911efbcbbae2eb28090e2e7870e
45,960
def cut_out(s, phrase): """ Returns the input string <s> but with all occurrences of <phrase> deleted <phrase> should be one or more words, separated by whitespace. Effort is made to preserve one space between words, which makes it better than s.replace(phrase, '') >>> s = 'the quick brown fox...
4f7cc45f6a384087665120e821ca569059273150
435,869
def read_converged(content): """Check if calculation terminated correctly""" if "Normal termination of Gaussian" in content.strip().split("\n")[-1]: return True return False
f6e02a8be9f774636b5c5f211a967afa3541e6ac
397,925
import re def is_valid_hostname(hostname): """ Takes a hostname and tries to determine if it is valid or not Args: hostname: String of the hostname to check Returns: Boolean if it is valid or not """ # Borrowed from https://stackoverflow.com/questions/2532053/validate-a-hostn...
fd56f664cbd41483b006f832c83f4e0d15e35098
593,796
def propagate_options(options): """Propagate child option values depending on selected parent options being specified""" if options.all: options.implemented = True options.missing = True if options.implemented: options.implemented_ovals = True options.implemented_fix...
e7170c6fe385f264535ac57274d47a1eca9859a2
364,856
import logging def greenlet_exception_logger(logger, level=logging.CRITICAL): """ Return a function that can be used as argument to Greenlet.link_exception() that will log the unhandled exception to the given logger. """ def exception_handler(greenlet): logger.log(level, "Unhandled except...
98f413f5f8432214d051f306490014e6927562f2
16,577
import pickle def extract_features_from_file(file): """Extracts features from a file using `pickle.load`.""" return pickle.load(file)
7fd0befa2551f8c282f76435ae08d2cea68a50e7
274,049
import math def quantile(x, q): """ Compute quantile/percentile of the data Parameters ---------- x : list of float Data set q : float Quantile to compute, 0 <= q <= 1 """ if not 0 <= q <= 1: raise ValueError("Invalid quantile") y = sorted(x) n = len(...
a19a6cfa97e5e55fc095c032cf86d51d1f2e2098
399,764
from typing import Tuple def _get_func_expr(s: str) -> Tuple[str, str]: """ Get the function name and then the expression inside """ start = s.index("(") end = s.rindex(")") return s[0:start], s[start + 1:end]
8ac212727859fc2df01cc12164118d9cfcf66d9f
654,209
def A070939(i: int = 0) -> int: """Length of binary representation of n.""" return len(f"{i:b}")
31b12e493645c3bdf7e636a48ceccff5d9ecc492
1,350
def _read_file(path, mode='r'): """Return the contents of a file as a string. Returns '' if anything goes wrong, instead of throwing an IOError. """ contents = '' try: with open(path, mode) as f: contents = f.read() except IOError: pass return contents
050760a1c583cd8a07ded4437fc53ad461b22f98
254,830
from typing import List from typing import Optional def peek(tokens: List[str]) -> Optional[str]: """Return the next token without consuming it, if tokens is non-empty.""" if tokens: return tokens[-1] return None
89163cfb252977a52bb6ad0a1ba5cc6153bfcd08
505,596
def getManagedObjectTypeName(mo): """ Returns the short type name of the passed managed object e.g. VirtualMachine Args: mo (vim.ManagedEntity) """ return mo.__class__.__name__.rpartition(".")[2]
85d846402d2ce6baf6af2f4c6b006a1926c41b8d
562,850
def telescopes_unicity(tel_list): """ Check if all the telescopes in a list are unique Parameters ---------- tel_list: list of telescopes classes Returns ------- Boolean: True if all telescopes in the list are unique """ are_unique = True for tel1 in tel_list: for te...
5f8be803ca23541595d1e341957594d77ecfbd65
184,149
import math def get_camera_side_radius(angle: float, camera_distance: float) -> float: """Gets the length of the sides of the triangle FOV when rendering the triangle vertices :param angle: The angle of the camera in radians in our own coordinate space, where 0 is East and PI / 2 is North :param camera_d...
abc954573bcc3200d36f9e1ee952116e31598f75
522,041
def _SNR(coef): """ Return the signal-to-noise ratio for each constituent. """ if "Lsmaj" in coef: SNR = (coef["Lsmaj"] ** 2 + coef["Lsmin"] ** 2) / ( (coef["Lsmaj_ci"] / 1.96) ** 2 + (coef["Lsmin_ci"] / 1.96) ** 2 ) else: SNR = (coef["A"] ** 2) / (coef["A_ci"] / ...
ac3bdd752d062a72ffc64fb9171e3f636d0e26e8
687,444
def config_parser_to_dict(config): """ Translates the items in the config parser object to dict. :param config: RawConfigParser :return: Dictionary with the contents :rtype: dict """ contents = {} for section in config.sections(): contents.update({section: {item[0]: item[1] for...
b093af16a4b775b1b0eb8e7d8f2ff603f2257827
606,514
from pathlib import Path def seed_root_fixture() -> Path: """ This fixture returns a path to the seed data defined for tests. :return: the path to the seed data root directory """ return Path(__file__).resolve().parent / 'data' / 'seed'
0876cbce1bea77c8a9f0c435391556238197ca49
140,670
def abr_step(N,E,Q): """Run the expectation (abr) step of the EM algorithm. This variant assumes that the true-positive and false-postive rates are global, namely not node-specific. Parameters ---------- N : numpy.array The number of times that each edge has been measured (i.e....
5793c8be4f0d4b1cb345c73e57b60d2f71d46bc1
366,222
def CheckStructuralModelsValid(rootGroup, xyzGridSize=None, verbose=False): """ **CheckStricturalModelsValid** - Checks for valid structural model group data given a netCDF root node Parameters ---------- rootGroup: netCDF4.Group The root group node of a Loop Project File xyzGri...
d11ce42b041b8be7516f827883a37b40f6f98477
708,475
def quick_loc_df(loc_list, target_df, attribute=None): """ faster replacement for target_df.loc[loc_list] or target_df.loc[loc_list][attribute] pandas DataFrame.loc[] indexing doesn't scale for large arrays (e.g. > 1,000,000 elements) Parameters ---------- loc_list : list-like (numpy.ndarray, ...
a4991757e58982d5fa256d6a1ac3a6b96e17ac00
418,494
def cleanBin(s, fixspacing=False): """ Cleans binary data to make it safe to display. If fixspacing is True, tabs, newlines and so forth will be maintained, if not, they will be replaced with a placeholder. """ parts = [] for i in s: o = ord(i) if (o > 31 and o < ...
92f53bb1fa966bf18c107f37be5f9158c00f52f5
471,943
import ast def _get_long_name(node): """ Return a name (possibly dotted) corresponding to the give node or None. If the node is a Name node or an Attribute node that is composed only of other Attribute or Name nodes, then return the full dotted name for this node. Otherwise, i.e., if this node co...
24e3b6e33e63e7a71a046f33b47243a69982e1f6
238,247
import torch def get_all_pairs_indices(labels): """ Given a tensor of labels, this will return 4 tensors. The first 2 tensors are the indices which form all positive pairs The second 2 tensors are the indices which form all negative pairs """ labels1 = labels.unsqueeze(1) labels2 = labels....
b388c79990267bf52519fd583b822ade988abe97
255,544
def intt(tup): """Returns a tuple components as ints""" return (int(tup[0]),int(tup[1]))
4a596a707d175a7ef1caeca5b1bf8d48ed760b75
285,505
def step_name_str(yaml_stem: str, i: int, step_key: str) -> str: """Returns a string which uniquely and hierarchically identifies a step in a workflow Args: yaml_stem (str): The name of the workflow (filepath stem) i (int): The (zero-based) step number step_key (str): The name of the st...
2b4a3abd0334f4834c18b9e99bce070983667e0a
203,736
def check_special_non_rotor_cases(mol, top1, top2): """ Check whether one of the tops correspond to a special case which could not be rotated `mol` is the RMG Molecule to diagnose `top1` and `top2` are indices of atoms on each side of the pivots, the first index corresponds to one of the pivots Spe...
8b2dc235f6b75591e532ee579b977b3899decce5
579,809
from datetime import datetime def itl_to_datetime(itltime): """ convert EPS ITL time format to python datetime object Args: itltime (string): EPS ITL time string formt Returns: datetime: python datetime """ return datetime.strptime(itltime, '%d-%b-%Y_%H:%M:%S')
693c9bea0743c62f017e8a086c862b2dfbf34ede
498,553
import re def tokenize(library): """ Function that takes a string of text a tokenizes it. The text is returned tokenized. """ # Make sure all words are written with lower cases library = library.lower() # Remove non-alphabetic characters tokenizer = re.compile(r"\W+") # tokenize ...
b638cda4945aee3ed377614968998314121735cf
31,605
import re def extract_answer_text(options_text: str, answer_tag: str): """Extracts correct answer's text from all options. Args: options_text: all options as text in various format. answer_tag: correct answers tag a, b, c, ... Returns: parsed option text corresponding to the correct answer. """ ...
63c2027087d405c99831b2e6ea922d1989f51c20
41,415
def find_argument_target(xmrs, nodeid, rargname): """ Return the target of an argument (rather than just the variable). Args: xmrs: The [Xmrs] object to use. nodeid: The nodeid of the argument. rargname: The role-argument name of the argument. Returns: The object that is...
741fd56df510cb16f1e34baa0545a6307554b1cd
482,214
from typing import Mapping def is_dict(x): """Checks if argument is a dictionary.""" return isinstance(x, Mapping)
25a675a868083d787f35e17a60cff02fee72cbc8
95,466
def test_sequence(N): """ Compute the infinite sum of 2^{-n} starting from n = 0, truncating at n = N, returning the value of 2^{-n} and the truncated sum. Parameters ---------- N : int Positive integer, giving the number of terms in the sum Returns ------- limit : float ...
ccd026374e353a55e23cbb9866c5c7a4c31a6f71
607,522
from datetime import datetime def today_yyyymmdd() -> str: """ Get the current date in YYYYMMDD format. Args: None. Returns: (str): Today's date in YYYYMMDD format. """ return datetime.now().strftime("%Y%m%d")
ce3db969773606aa0c2fee1aa99b08826e3db6cb
358,160
from typing import Union from typing import Dict from typing import Any from typing import List from typing import Tuple import math def computeWaveDataMaxTime(data: Union[Dict[str, Any], List[Dict[str, Any]]], dt: float) -> Tuple[float, int]: """ Compute the pulse duration time of all the wave data input. ...
be65c6c6199847a0f2cca9ceedb74152675c506e
443,355
def range_to_level_window(min_value, max_value): """Convert min/max value range to level/window parameters.""" window = max_value - min_value level = min_value + .5 * window return (level, window)
0a388ff48a29f0daff20a7cdfd200f8330a32a15
701,209
def obj_frequencies(df): """Total number of occurrences of individual objects.""" return df.OId.value_counts()
96f2805e8f35fd549527751413fb8f84d93fbf6f
463,718
from typing import Union def gb_to_gib(gb: Union[int, float]) -> float: """ Gigabyte (Gb) to Gibibyte (GiB) :param gb: Gigabytes (Gb) :return: Gibibyte (GiB) """ return gb * 1.07374
9a5060e9e40d9fb462a9f720d377a0fa18e3d7f1
170,090
def no_parenthesis_usage(decorator_function, decorated): """ called with no arg NOR parenthesis: @foo_decorator we have to directly apply the decorator :param decorated: :param decorator_function: :return: """ return decorator_function()(decorated)
b18f5bcf7036584c3f9f64ddec377a37c0ed096b
549,547
def neuter_name(name): """ Makes a string suitable to be file name + id (no equality signs) Args: name: string to process Returns: A string without special characters """ reserved_chars = '\\/:*?"<>|=' for char in reserved_chars: name = name.replace(char, '') return ...
cb0351b09656c3d9475408362f9acfd42905ccfc
476,654
def wraps_class(orig, suffix): """ Rename the decorated class to match the ``orig`` with a suffix added. :see: `functools.wraps` """ def decorator(cls): cls.__name__ = orig.__name__ + suffix cls.__qualname__ = orig.__qualname__ + suffix cls.__module__ = orig.__module__ ...
3293c90db7cf066b43a841a0139ef146ed326697
588,912
import random def guess_number(start: int, end: int) -> int: """Return a number in specified range.""" result = random.choice(range(start, end + 1)) return result
f1545fe7264c3a14484450884b47b256756957b5
660,779
def get_kafka_topics(consumer): """Return a set with the name of topics found in kafka backend Args: consumer (obj): Kafka consumer object Returns: set(str): A set of strings (topic names) """ return consumer.topics()
9a55a2241c78f46a3577513a92c0b1f0965b669d
385,546
import re def get_edu_text(text_subtree): """return the text of the given EDU subtree, with '_!'-delimiters removed.""" assert text_subtree.label() == 'text', "text_subtree: {}".format(text_subtree) edu_str = ' '.join(word for word in text_subtree.leaves()) return re.sub('_!(.*?)_!', '\g<1>', edu_str)
4add5d6697f5bede2636fb7d2704c5b72827ed97
650,526
def groom_model(model): """Reset the feature indicators.""" model.commits, model.ticket = 0, None return model
257ff18f50e320179018be8b886bc9f17df2c76e
169,963
def parse_grid(grid): """ converts a grid like K F A L G B M H C N I D O J E to ABCDEFGHIJKLMNO """ rows = [row.strip().split(" ") for row in grid] return "".join(rows[row][col] for col in range(2, -1, -1) for row in range(0, 5))
f1cb825e3d20edd2db92fee4104204e9bcb1f54a
11,018
from typing import Dict def _get_credentials(credentials_name: str, credentials: Dict) -> Dict: """Return a set of credentials from the provided credentials dict. Args: credentials_name: Credentials name. credentials: A dictionary with all credentials. Returns: The set of request...
ef5dfe295022a549a040af264993cbf742e69db0
517,237
import re def multi_replace(txt, find, repl, ignore_case=False, whole_word_only=False): """ caastools.utils.multi_replace(text, repl, ignore_case=False, whole_word_only=False) -> str Performs simultaneous multi-replacement of substrings within a string :param txt: string in which replacements are to b...
cdeb5d7668b03d11e0c5a1c1a3759cdcc245bfa1
208,714
def idle_time(boutlist, idle_threshold=15): """Takes list of times of bouts in seconds, returns idle time in seconds, i.e. time spent without bout for longer than idle_threshold in seconds. """ idle_time = 0 for i in range(0, len(boutlist) - 2): inter_bout_time = boutlist[i + 1] - boutlist[...
8d13872860433752b5171032d60299f380fd2557
355,077
def read_file(filename): """ Read input file and save the locations into a list. :param filename: input file :return: list of locations """ locations = [] with open(filename, 'r', encoding='UTF-8') as file: for line in file: locations.append([[int(location), False, False]...
29134cf716c599fe94dde6b656143c0ab845e29e
292,788
import torch def gce(logits, target, q = 0.8): """ Generalized cross entropy. Reference: https://arxiv.org/abs/1805.07836 """ probs = torch.nn.functional.softmax(logits, dim=1) probs_with_correct_idx = probs.index_select(-1, target).diag() loss = (1. - probs_with_correct_idx**q) / q r...
baa9f8c4984328a2c9702fdfa9f338afd57b7ce4
364,964
import re def is_string_valid_tarball_unpack_directory_name(dirname: str, package_name: str, version_number: str) -> bool: """ Check if the folder obtained by unpacking the source tarball is compliant with debian packaging :param dirname: directory to check :param package_name: name of the source...
df86b85bb47edbd0eebf5e96fab2b329983289f1
80,470
def parse_int(string): """ Like int(), but just returns None if it doesn't parse properly """ try: return int(string) except ValueError: pass
3438121f722c3d9541a20735b38c758cfce2a1c6
400,484
def en_wiki_url(name): """ Create an english wikipedia page url from a persons name """ name = name.replace(' ', '_') return 'https://en.wikipedia.org/wiki/'+name
8bcae19352fc0795647fafe6fee8c41050f93f26
328,183
def basicFitness(individual, env): """ The trivial case, where fitness is just the result of passing through the environment. """ return individual.result
7d108bac92ce390699b66e1ead5b08080856c5be
10,344
from typing import Optional from typing import Dict from typing import Any def define_by_run_func(trial) -> Optional[Dict[str, Any]]: """Define-by-run function to create the search space. Ensure no actual computation takes place here. That should go into the trainable passed to ``tune.run`` (in this exam...
f8237b135e3a6467bdefd397f1da0ebaec0f4380
29,608
def sum_non_reds(s): """ Sum all numbers except for those contained in a dict where a value is "red". Parameters ---------- s : int, list, or dict An item to extract numbers from. Returns ------- int The total of all valid numbers. """ if isinstance(s, int): ...
8d5ffb05b3575d9d3b34d3836b5ef7e728471ddd
652,536
import torch def inverse_transformation(trans_12): """ Function that inverts a 4x4 homogeneous transformation """ if not trans_12.dim() in (2, 3) and trans_12.shape[-2:] == (4, 4): raise ValueError("Input size must be a Nx4x4 or 4x4. Got {}" .format(trans_12.shape...
324f8f387197df0bf30963297b28aa7af727e305
417,064
import inspect def getargspec(function): """ Extends inspect.getfullargspec to allow us to decorate functions with a signature. :Parameters: ---------------- function : callable function for which we want to know argspec. :Returns: ------- inspect.FullArgSpec """ ...
9b5633d4fa3c7d9fdc9e41ad7e77f147d3bec9de
213,925
def divisors(n): """ Count the number of divisors of a positive integer n. :param n: an integer input. :return: the number of divisors of an integer.count_sheeps """ return sum(1 for x in range(1, n + 1) if n % x == 0)
b0367d30f21f8184a73170a6e768ae2954e72afd
303,960
import textwrap def wrap_paragraphs(text, width=72): """Wrap all paragraphs in a text string to the specified width. ``width`` may be an int or a ``textwrap.TextWrapper`` instance. The latter allows you to set other options besides the width, and is more efficient when wrapping many texts. ""...
a1c3fb77530e9247ad2e3568eb0d3ea917520e71
150,833
import re def find_line(line: str, pattern: str, i_case: bool, is_regexp=False) -> bool: """ Check if line contains matches for pattern, with case and regexp flags. Returns True if pattern is found in line. """ found = False if i_case: line = line.lower() pattern = pattern.low...
7c1e1f98ec618f37479fe36e48304850ca1741c2
581,609
def scenario_base(data, vertex, edge): """Base scenario: change nothing-""" return data, vertex, edge
46ba07863d793294c47f240b0840c4023516ed49
453,961
import torch def l1_loss(pre, gt): """ L1 loss """ return torch.nn.functional.l1_loss(pre, gt)
c552224b3a48f9cde201db9d0b2ee08cd6335861
6,358
def set_tags(template: str, analysisname: str, era: str, sample_group: str) -> str: """ Function used to set the tags in the template. Args: template: The template to be modified. analysisname: The name of the analysis. era: The era of the analysis. sample_group: The sample ...
2d3e5ee0f321e5c7a5d6e8446936519c65f12bda
483,178
def get_useful_tags(xlsform): """Return the ODK tags from 'survey' to retrieve the value for. This function compares each ODK 'name' to a pre-approved list and keeps that name if there is a match. Args: xlsform (pmix.Xlsform): An xlsform (workbook) object Returns: A list of ODK ta...
b1aea6e27ef07e69d0c58d13a12ae9e6bf565751
433,736
def flatten(iterable, tr_func=None, results=None): """Flatten a list of list with any level. If tr_func is not None, it should be a one argument function that'll be called on each final element. :rtype: list >>> flatten([1, [2, 3]]) [1, 2, 3] """ if results is None: results = ...
a2c54e77632ecba09cc57fbd5c3b059f28ce8eb3
397,374
def generator_to_list(generator, max_count=None): """ Convert generator to list :param max_count|int: the maximum element count to be joined. """ datas = [] count = 0 for r in generator: count += 1 datas.append(r) if max_count is not None and count >= max_coun...
30c26d4787279a8e3f77c6c20997ba89e26b64dc
285,890
def pagination_page_numbers(current_page): """ Return a list of page numbers which should be shown for page navigation. Example: When there are seven pages in total, the progression of page numbers which should be shown (where the current page is highlighted) are as follows: [1] 2 3 4 7 ...
d3867609111d4766af3969355eefc093321e3b94
531,484
from typing import Tuple import math def reduce_to_coprime(number1: int, number2: int) -> Tuple[int, int]: """Divides given numbers by their greatest common divisor, thus making them coprime.""" gcd = math.gcd(number1, number2) return number1 // gcd, number2 // gcd
3ba0296ed9f62fda33a7d8dfd735692fb76e6317
604,959
def to_tensor_item(value): """ Transform from None to -1 or retain the initial value. :param value: a value to be changed to an element/item in a tensor :return: a number representing the value, tensor with value -1 represents the None input """ if value is None: value = -1.0 re...
55eccdd964cb7dda9449f69080f36f1f6f9cddf4
363,727
def format_line_obj(line_obj, ordered_attributes, delimiter): """Formats an object into delimited string If attribute not found, a ':(' will be inserted instead """ return str(delimiter).join((str(line_obj.__dict__.get(attr, ':(')) for attr in ordered_attributes))
be7da1fa6bd080047bdd235d332b72e770dcfa48
13,073
def cities_in_EU(cities_data, countries_data): """Returns a dictionary whose key:value pair is "name of city":"EU membership", e.g., "Graz":"yes" or 'Aalborg':'no'; the size of the dictionary must equal the number of cities represented in cities_data """ # Hint: # Use nested for in loops to gene...
57d0b5f58dd2218fb06d358c7262edf7af9724bd
168,702
def filter_out_nonred(list_of_pixels): """ Takes a 1-d list of pixels and filters out the pixels that aren't "red-colored". Returns the list of red pixels. """ return [pixel for pixel in list_of_pixels if pixel[0] > 160./255. and max(pixel[1], pixel[2]) < 60./255.]
8e4bd91fbf1ffbb4896abc2ce6726e52fbcbced3
526,015
def train_test_split(df, frac): """Create a Train/Test split function for a dataframe and returns both the Training and Testing sets. Frac referes to the precent of data you would like to set aside for training""" train_split = df[: (int(len(df) * frac))] test_split = df[(int(len(df) * frac)):] ...
3f92e3c0da5d58238e87eb2d39b33473fdc8682f
208,597
def get_region_for_chip(x, y, level=3): """Get the region word for the given chip co-ordinates. Parameters ---------- x : int x co-ordinate y : int y co-ordinate level : int Level of region to build. 0 is the most coarse and 3 is the finest. When 3 is used the sp...
3b018413e57fc7baa3d36e816b47b545c9d8c1e5
673,321
import math def get_radian_angle_btwn_vecs(vec1_x, vec1_y, vec2_x, vec2_y): """Compute the angle between two vectors (vec1, vec2) in radians. :param vec1_x: the x-coordinate of vec1 :param vec1_y: the y-coordinate of vec1 :param vec2_x: the x-coordinate of vec2 :param vec2_y: the y-coordinate of ...
f8365b19a4a38eefd3e750556322a1c6522a9e2a
596,803
def g(x, y): """ A multivariate function for testing on. """ return -x**2 + y
a134054e8731bd81c2f91980e71ede051dfc305f
637,728
def nodesets2affiliations(communities): """ Transform community format to "snapshot_affiliations" Representation expected in input: dictionary, key= community ID, value= node set Representation in output: dictionary, key=node, value=set of snapshot_affiliations ID :param communities: dictionary, k...
028ed5573e079f964452249fe4abc17e2654c546
592,094
def correct_thresholds(p): """ Checks that the thresholds are ordered th_lo < th < th_hi """ return ( (p['th_lo'] < p['th']) or p['th'] == -1 ) and \ ( (p['th'] < p['th_hi']) or p['th_hi'] == -1 )
e2e840f14cab1b46bb2ce5b6ad9fb45bfa0510bf
124,904
def most_prolific(dict): """ Takes a dict formatted like "book->published year" {"Please Please Me": 1963, "With the Beatles": 1963, "A Hard Day's Night": 1964, "Beatles for Sale": 1964, "Twist and Shout": 1964, "Help": 1965, "Rubber Soul": 1965, "Revolver": 1966, ...
3cad35f0b06dad0f68a674857be80db30e142e83
77,063
import json def dethemify(topicmsg): """ Inverse of themify() """ json0 = topicmsg.find('{') topic = topicmsg[0:json0].strip() msg = json.loads(topicmsg[json0:]) return topic, msg
527cd8c3bb5a9ae75600b19050ca388b9321c630
678,389
def str2float(str_val, err_val=None): """ Convert a string to a float value, returning an error value if an error occurs. If no error value is provided then an exception is thrown. :param str_val: string variable containing float value. :param err_val: value to be returned if error occurs. If N...
e4eeda0335b47fd1eeda9e3c49349975a8e1744b
658,681
from typing import List def valid_path(n: int, edges: List[List[int]], start: int, end: int) -> bool: """ Finds a valid path in a graph from start to end and returns true if a valid path can be found, else returns false. Will use a BFS as we can be able to traverse the vertices 1 level at a time until we...
5ad6dd72fc735b34ae442cc2d651b4ef0b129e50
497,328
def object_type(r_name): """ Derives an object type (i.e. ``user``) from a resource name (i.e. ``users``) :param r_name: Resource name, i.e. would be ``users`` for the resource index URL ``https://api.pagerduty.com/users`` :returns: The object type name; usually the ``type`` property of...
b74e373691edf8a8b78c2a3ff5d7b9666504330a
707,183
def parseFraction(f): """Parse a fraction (a string of the form N/D) returning a float. Returns None if f is not in the form N/D, or if D is 0.""" p = f.find("/") if p < 1: return None s1 = f[:p] s2 = f[p+1:] try: v1 = int(s1) v2 = int(s2) except ValueError: r...
12002963d09e2096453d0b3a316934004ff7074a
290,146
def linear(x, a, b): """Linear function Parameters ---------- x, a, b: float linear function f = ax + b Returns ------- f: float linear function f = ax + b """ return a * x + b
4c4db0e7020db2ef24b70133be99a0b444d7d096
252,218
def body_method(name): """ Wrapper to expose a method on a Block object's compressed_body """ def wrapper(self, *args, **kwargs): if not hasattr(self, '_compressed_body'): self._compress_body() wrapped_method = getattr(self._compressed_body, name) return wrapped_metho...
c0c833635b85b2f34cc735bc4a46831b48b73fb9
387,508
def check_distance_to_permuted_principal_subrows_lb(r_distribution, s_distribution, d): """ For vectors r of size m and s, a row of some n×n distance matrix D, check if l∞-distance from r to the set P, comprised of permutations of those subvectors of s that are a row of some m×m principal submatrix ...
2ebc23c06cd630fa4baae4763719a9b5fa07fe73
332,904
import unicodedata def remove_accented_chars(text): """ Removes accented characters from the test """ new_text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore') return new_text
b3a4e5b2bed54b17ed1d406f37009cacfe029217
76,277
import json import requests def create_destination_connection_profile(project, location, destination_config, token): """ This function will create the destination connection profile in Google Cloud DataStream :param project: Google Cloud project id mentioned in variables.py :param location: Google Clo...
8c66947e0e2164fc73be11525ac66d929292e6dd
409,254
import torch def count_params(model: torch.nn.Module) -> int: """ Count the number of parameters in a model. Args: model (torch.nn.Module): PyTorch model. Returns: int: Number of learnable parameters. """ return sum(p.numel() for p in model.parameters() if p.requires_grad)
1479868bf255ff89a4e9e43ba2783ae53f845d7b
183,401
def highlight(msg): """ Highlight in yellow provided message :param msg: Message to highlight :return: Highlighted message """ return "\033[1;33m{}\033[0m".format(msg)
415fa5ca6ed91b15fba847bf771d6b15c529b51b
551,158
def ROS_ANY_TO_BB_STRING(anyTypeValue): """ Converts a ROS value to a BB string type. Receives: anyTypeValue: the ROS value to convert Returns: the converted BB String value """ return str(anyTypeValue)
e58d9f0a9523fb0d5fc52ca6376df612f52ea4f4
563,765
def rosen_suzuki(x): """ Evaluate polynomial from CONMIN manual. """ return x[0]**2 - 5.*x[0] + x[1]**2 - 5.*x[1] + \ 2.*x[2]**2 - 21.*x[2] + x[3]**2 + 7.*x[3] + 50
873ffb4ed0945ea1101f738349e93276741205bb
132,865
from typing import Iterator from typing import List import unicodedata import re def preprocess(strings: Iterator[str]) -> List[str]: """Preprocess a collection of strings. The following preprocessing steps are taken: Convert to lowercase, normalize unicode, and remove special characters (non-alphanumeri...
6c2f7388ff078f1c2eef6a549d5270c3c03bdecf
323,511
def get_coordinates_from_token(token, mod): """ A function which takes a mod and a token, finds the token in the mod, and then returns the coordinate (tuple) at which the token is found. If it is not found, it returns None. """ for coordinates, token_in_mod in mod.items(): # No possibility of du...
429e42a6439972d23bc54ac5108f196aa0ca93b7
45,780
import warnings def resample_nanmean(data, dim='time', resample='M', nmin=15, **kwargs): """ Resample Dataset and apply a minimum for resampling mean Args: data (DataArray, Dataset): Input fields dim (str): datetime dimension resample (str): upsampling frequency nmin (int): mi...
c6ace88d87664af4d5b313c866a4b25334e489fc
593,071
def bin_widths(edges): """Return the widths of a set of bins given the edges""" return edges[1:] - edges[:-1]
7563fe31731a54d7fd6e85f63ce70797f3781a24
250,011