content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def is_skipped_node(node_entry): """Whether a node is not counted. Parameters ---------- node_entry : dict Node entry. Returns ------- out : bool whether node is skipped. """ # Operators not counted in graph tuner. _SKIPPED_OP = ["Tuple"] return node_entry[...
22c4e49a2bc65711d105c3adfd8bd8c22205ed19
165,426
def sanitize_kvstore_list(kvstore_list): """ Creates a new dictionay only with allowed keys. """ new_kvstore_list = [] allowed_keys = [ 'id', 'key', 'value', 'kv_type', 'kv_format', 'kv_inherited', ] for item in kvstore_list: sanitized...
6466560e417ab483dcfbac28fc495dab92f0a3cd
146,918
def slow_roll_diffusion(potential, potential_dif, planck_mass=1): """Returns the slow-roll diffusion as a function. Parameters ---------- potential : function The potential of the slow-roll inflation simulated. potential_dif : function The first derivative of the potential of the sl...
8f203c5d788da733cd2371819843e742d0aded91
219,657
def disproportionation(oh, ai, aii, aiii): """disproportionation rate law from Fratzke, 1986""" return (ai * oh + aii * oh * oh) / (1 + aiii * oh)
7d3e1bda1700e4b154d88d70f7c069f9a0a7cd11
189,748
def create_response(bot_reply, end_of_session=False): """Base reply for Alexa""" response = { "version": "1.0", "response": { "outputSpeech": { "type": "PlainText", "text": bot_reply, }, "reprompt": { "outputSpeech": { "type": "PlainText", "te...
8401929422884db01868f3fd8d69342778d0e9c0
269,492
def count_lines(path) -> int: """Return the line count of a given path.""" with open(path) as file: return sum(1 for _ in file)
354bb98147d29dbab7d2c2b28cf40968feb8fb53
91,404
def _sort_esystem(evals, evec_collection): """Utility function that sorts a collection of eigenvetors in desceding order, and then sorts the eigenvectors accordingly. Parameters ---------- evals : numpy array The unsorted eigenvalues. evec_collection : list of arrays List where ...
b4f2380cf337296e57460e07c3c074fda6c63f64
572,009
from typing import Optional from typing import Union def convert_string_to_bool(param: str) -> Optional[Union[bool, str]]: """Converts a request param of type string into expected bool type. Args: param: str. The params which needs normalization. Returns: bool. Converts the string param ...
701310ee196edf6b7937a60513da011c80d18da1
391,507
import pathlib def get_file(file: pathlib.Path) -> str: """Extract all lines from a file.""" with open(file, "r") as f: return f.read()
86f7a57b5b5394e82082a11f69a37514f39e0e71
600,925
def pick_files(profile_dir, **kwargs): """ Return paths to the files from the profile that should be backed up. There are 17 files that can be backed up. They have been organized into 11 categories for your convenience: - autocomplete - bookmarks - certificates - cookies ...
623e97335747a23f9aee8433d1e3934e29edfd4d
691,948
def SuiteLikelihood(suite, data): """Computes the weighted average of likelihoods for sub-hypotheses. suite: Suite that maps sub-hypotheses to probability data: some representation of the data returns: float likelihood """ total = 0 for hypo, prob in suite.Items(): like = suite....
a04fd8a2946371092438845813cb051acf2b2304
610,960
def split_nth(seq, separator, n): """ Split sequence at the n-th occurence of separator Args: seq(str) : sequence to split separator(str): separator to split on n(int) : split at the n-th occurence """ pos = 0 for i in range(n): pos = seq.index(separator, pos + 1...
7eac612c842639c8bc8b85d16142e4137360da84
123,905
from typing import Any from typing import Iterable def gen_repr(obj: Any, attrs: Iterable, **kwargs) -> str: """Generates a __repr__ string. Used to create consistent `__repr__` methods throughout ZeroBot's codebase and modules. Parameters ---------- obj : Any object A reference to a...
1e70351500554e9dfca145f7bdff0af0be0e18ee
342,958
def iso7064mod37_hybrid_36(source: str) -> str: """ iso7064mod37_HYBRID_36校验算法 :param source: 需要添加校验的字符串 :return: 校验位 """ alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*" m1 = 36 m2 = 37 p = m1 n = len(source) + 1 i = n while i >= 2: s = p + alphabet.index(...
bdd80186848d75aa35b4f3bcd187a6cabce477b1
330,775
def subsample(df, freq=2): """ Subsample the original data for reduced size :param df: df, dat :param freq: int, every freq item will be taken :return: df, subsampled df """ df = df.iloc[::freq, :] return df
5ffde37406d73ed02a99bcedf098fe3781dcdb37
576,277
def make_conf() -> dict: """Create standard ladim configuration to be used for testing""" return dict( version=2, time=dict(dt=[30, "s"], start="2000-01-02T03", stop="2000-01-02T03:02",), grid=dict(module="ladim2.ROMS",), forcing=dict(module="ladim2.ROMS",), release=dict...
94c5450d680a4e3da1894859ba6c98fd884f4619
188,867
import re def clean_extra_newlines(textbody): """Removes excess newlines""" multi_returns_re = re.compile(r"\n\n+") textbody = multi_returns_re.sub(r"\n\n", textbody) return textbody
3d21bb84a97cced98679784bb3d256547c9c6961
305,548
def simulate(dynamics,x0,ufunc,T=1,dt=1e-3): """Returns a simulation trace of dynamics using Euler integration over duration T and time step dt. Args: dynamics (Dynamics): the system. x0 (np.ndarray): the initial state. ufunc (callable): a policy u(t,x) returning a control vect...
89931fa50fcee831e90b71c601573bb4758e6cd3
618,460
import csv def parse_fastqc_result(path_to_qc_summary): """ Args: path_to_qc_summary (str): Path to the fastqc report summary file. Returns: dict: Parsed fastqc R1 report. All values except are either "PASS", "WARN", or "FAIL". For example: { "basic_statistic...
133de8f205a601d39d361502d3fb64edd7745433
621,329
import json def load_json(filename): """ Loads a file as json """ with open(filename) as f: page = f.read() return json.loads(page)
5be1d70c2cb53d8c9148344e6f26fed2df5f6027
470,064
def unstack_m(state,b1): """Generate a pickup subtask.""" if state.is_true("clear", [b1]): for atom in state.atoms: if atom.predicate.name == "on" and atom.args[0].name == b1: return [('unstack',b1,atom.args[1].name)] return False
0d524c5180c45846e04395807a4c8fb60290d417
556,633
def is_callID_active(callID): """Check if reactor.callLater() from callID is active.""" if callID is None: return False elif ((callID.called == 0) and (callID.cancelled == 0)): return True else: return False
f54a05fde58db53319bc34cca79629011e2f2ffd
656,094
def read_follower_file(fname, min_followers=0, max_followers=1e10, blacklist=set()): """ Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids. """ result = {} with open(fname, 'rt') as f: for line in f: parts = line.split() ...
f9ed294a9783b562b17885f0c696e25f288d05dd
92,231
def extractFlags( item, report=1 ): """Extract the flags from an item as a tuple""" return ( item.negative, item.optional, item.repeating, item.errorOnFail, item.lookahead, item.report and report, )
e34207daca168051e77f725c41ddc17942559ba2
302,973
from typing import Mapping from typing import List def _mapping_to_mlflow_hyper_params(mp: Mapping) -> List[str]: """ Transform mapping to param-list arguments for `mlflow run ...` command Used to pass hyper-parameters to mlflow entry point (See MLFlow reference for more information) All mapping value...
c0d1fe9083ddf6fce29b98bd88de209a06a47f02
667,264
def font_parse_string(font): """ Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bold" or ('Arial', 10, 'Bold) :return: style string that can be combined with other style strings """ if font is None: return '' if type(font) is str: _font ...
81d987728c89f9b652a8cb0255bd27cfa59a4074
444,694
def word_contains(word: str, necessary: str) -> bool: """Check if a word contains all of the given characters :param word: the word to check :param necessary: a string containing all necessary characters ("" for none) :return: True if the word contains all characters """ characters = set(necess...
067f103dc20506bdc194eece4aa72b5bf9c84113
333,714
def add_line_numbers(lines, start=0, fn=None): """Prefix lines with numbers. Parameters ---------- lines : list or list-like of str Lines to be prefixed with a number. start : int, optional The index at which line numbers start (default is 0). fn : str, optional File nam...
13b9b1fb93e9c0a501d2e6e6ced0c34a662b94b1
504,460
from typing import Callable def callable_name(func: Callable) -> str: """Return the qualified name (e.g. package.module.func) for the given callable.""" if func.__module__ == 'builtins': return func.__name__ else: return '{}.{}'.format(func.__module__, func.__qualname__)
6eeeb86d333ee1090957d656c2545a4a609ff918
56,081
def shuffle(x, order=None): """Reorganizes the given string according the order - list of character indices. """ if order == None: return x res = "" for o in order: res += x[o] return res
daa1c33160f82917be40b082e6a0df70fdfd49c8
79,243
def axial_to_cubic(col, slant): """ Convert axial coordinate to its cubic equivalent. """ x = col z = slant y = -x - z return x, y, z
f1f5a4e5794d08897abc7f41c5a0e5d69a659d19
450,394
def isPalindrome(n): """returns if a number is palindromic""" s = str(n) if s == s[::-1]: return True return False
2261cdae02a2c3b8665bfc09c991be524110fbb2
220,166
import configparser def read_config(config_file): """Read the config file. Args: config_file (file) : Plugin config file Returns: object: config object """ config = configparser.ConfigParser() config.read(config_file) return config
20d67952dfd6c619f5693996162e2cca984af483
72,834
def get_identifier_name(cursor): """ Retrieves the identifier name from the given clang cursor. :param cursor: A clang cursor from the AST. :return: The identifier as string. """ return cursor.displayname
771b5a2f40530f0f5729f4d5c42b6d2a6666b2bc
398,005
def _GetHost(cpu, target_os): """Returns the host triple for the given OS and CPU.""" if cpu == 'x64': cpu = 'x86_64' elif cpu == 'arm64': cpu = 'aarch64' if target_os == 'linux': return cpu + '-unknown-linux' elif target_os == 'mac': return cpu + '-apple-darwin' elif target_os == 'ios': ...
1431239a7352a3cee23bcc0aec8d1961dcb7296f
110,191
def eof(f, strict=False): """ Standard EOF function. Return ``True`` if the the marker is at the end of the file. If ``strict==True``, only return ``True`` if the marker is exactly at the end of file; otherwise, return ``True`` if it's at the end of further. """ p=f.tell() f.seek(0,2) ...
e75436b149af4eb48aa3da4d7f6f2f0d76487ac2
426,218
def is_label_in(node, label): """ Searches the immediate children of a node for a certain label, returning True when such a label exists, and False when it doesn't """ return any([child.label() == label for child in node])
b91cb1c3a5823b741cb74d9ff5cd94945cb39bf7
391,435
import pkg_resources def check_package_installed(package_name): """ Uses pkg_resources.require to certify that a package is installed :param package_name: name of package :type package_name: str :return: boolean value whether or not package is installed in current python env :rtype: bool ...
521124512d8cb7177876ce8b96a756108df33866
288,129
import itertools def flatten(its, n): """Take the n-dimensional nested iterable its and flatten it. Parameters ---------- its : nested iterable n : number of dimensions Returns ------- flattened iterable of all items """ if n > 1: return itertools.chain(*(...
9702327c36ad004ed3108a81747f5b7bcb7bd3f8
254,998
def get_padding(dimension_size, sectors): """ Get the padding at each side of the one dimensions of the image so the new image dimensions are divided evenly in the number of *sectors* specified. Parameters ---------- dimension_size : int Actual dimension size. sectors : int ...
4bf0e3f4483586f1a41d5b65a3a6cb5e1dbbd6dc
106,533
def digitize(n): """Convert integer to reversed list of digits.""" stringy = str(n) return [int(s) for s in stringy[::-1]]
8e3e763cffa1718b9d494b868d1dd551a8f5f59e
392,126
def obv(df, price, volume, obv): """ The On Balance Volume (OBV) is a cumulative total of the up and down volume. When the close is higher than the previous close, the volume is added to the running total, and when the close is lower than the previous close, the volume is subtracted from the running...
19f4c456ed501523d2b349e2766d482bd1fef13b
6,727
from pathlib import Path def resolve_paths_to_new_working_dir(paths: list, new_work_dir: str) -> list[Path]: """Resolve a list of file paths relative to the new working directory. Args: paths: User-provided paths. new_work_dir: The new working directory. Returns: List of new path...
da4553d93b0013191eb18399c2ac16749a006980
432,540
from typing import List from typing import Any def get_max_column_lengths(rows: List[List[Any]]) -> dict: """ :param rows: 2D list containing objects that have a single-line representation (via `str`). :return: A dict of the maximum string length in each column """ number_of_columns = len(rows[0...
26e8e177d47022b43b37f986d8e3e18bbdbbf679
490,135
def get_billing_data(order): """Extracts order's billing address into payment-friendly billing data.""" data = {} if order.billing_address: data = { 'billing_first_name': order.billing_address.first_name, 'billing_last_name': order.billing_address.last_name, 'bill...
3f020b13905f33c215d32ec1a3b2e4f4af369e15
73,363
def is_string(s): """Check if the argument is a string.""" return isinstance(s, str)
050be89ec88be7a6067464d4ad846acbf560d119
660,923
def suggest_patience(epochs: int) -> int: """Current implementation: 10% of total epochs, but can't be less than 5.""" assert isinstance(epochs, int) return max(5, round(.1 * epochs))
e1631576d63dc3b62df636fb555739158035a25a
28,882
def make_inverted(m, n): """ Given two integers m and n, write a function that returns a reversed list of integers between m and n. If the difference between m and n is even, include m and n, otherwise don't include. If m == n, return empty list If m < n, swap between m and n and continue. Example 1: Input: ...
83692c924162bb595d01c9b7e1cb8c818497faf1
651,998
def renders(col_name): """ Use this decorator to map your custom Model properties to actual Model db properties. As an example:: class MyModel(Model): id = Column(Integer, primary_key=True) name = Column(String(50), unique = True, nullable=False) ...
7128e0dac6d2c0b1519729e708fe7cb1b14c3596
620,247
def run_sklearn_metric_fn(metrics_fn, labels, probs): """Wrapper around sklearn metrics functions to allow code to proceed even if missing a class in evaluation Args: metrics_fn: a function that takes labels and probs labels: 1D label vector probs: 1D probabilities vector Returns: ...
5398bfa38db405e212c9aa6e4688aa6d47c26f2d
189,053
def color_component_int_to_float(rgb_component: int) -> float: """ Converts a color component from integer to float :param rgb_component: a color component given in int range [0, 255] :return: a color component in float range of [0,1] """ return rgb_component / 255.0
edd1390e2c3a2462d906091b3ac58c1d74a2891f
348,016
def _first(iterable, what, test='equality'): """return the index of the first occurance of ``what`` in ``iterable`` """ if test=='equality': for index, item in enumerate(iterable): if item == what: break else: index = None else: raise N...
0421ac9aa5c6c2f0e2f55a913fa49d9bf79edb63
643,397
def get_tlp(results): """Fetches a target log prob from a results structure""" if isinstance(results, list): return get_tlp(results[-1]) else: return results.accepted_results.target_log_prob
98c4046b1691533b311b87aa8d52c6cbe71da221
399,171
def split_df(df, columns_split): """Split a dataframe into two by column. Args: df (pandas dataframe): input dataframe to split. columns_split (int): Column at which to split the dataframes. Returns: df1, df2 (pandas dataframes): Split df into two dataframe based on column. The first has the fir...
37aee5783680f6827891c737c9a4ffb9bba89b27
653,196
def classpath_entry_xml(kind, path): """Generates an eclipse xml classpath entry. Args: kind: Kind of classpath entry. Example values are 'lib', 'src', and 'con' path: Absolute or relative path to the referenced resource. Paths that are not absolute are relative to the p...
5b350d2e2dc75f96348ba83fed739a83ac144053
572,302
def get_active_sessions_orchestrator( self, ) -> list: """Get all current active sessions on Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - activeSessions - GET - /session/activeSessions :return:...
3dd38d66816e2bdace27ab24b6609ec44ee02057
634,734
import textwrap def wrap_line(line: str, width=29): """Wraps a long string into multiple lines with a default width of 29 :param width: maximum length of 1 row :param line: str :return: str """ return '\n'.join(textwrap.wrap(line, width=width))
92dfeb830fdf27d7fa1f97c9501808a83073e465
215,068
import re def _do_subst(node, subs): """ Fetch the node contents and replace all instances of the keys with their values. For example, if subs is {'%VERSION%': '1.2345', '%BASE%': 'MyProg', '%prefix%': '/bin'}, then all instances of %VERSION% in the file will be replaced with 1.2345 and s...
c62e542f15ffd38cc2cb38bf088552340d132d59
135,850
def extract_image_class(filename: str) -> str: """ Extract the class label for a given filename. Args: filename: the filename to extract a class label for Returns: a class label based on the image's filename """ # extract the filename itself without the absolute path filen...
b500f1ae215ab60db6f3f98d5d58467f4f821e72
311,592
def lower_rep(text): """Lower the text and return it after removing all underscores Args: text (str): text to treat Returns: updated text (with removed underscores and lower-cased) """ return text.replace("_", "").lower()
a9e6c507146ba1b0c9bcd924867b330edc8e6d0f
81,805
def normalize_to_midnight(dt_obj): """Take a datetime and round it to midnight""" return dt_obj.replace(hour=0, minute=0, second=0, microsecond=0)
f00fe4425972840a5a6d81a0ac8cf8315f2e53be
430,002
import re def is_sha(text): """ To be considered a SHA, it must have at least one digit. >>> is_sha('f75a283') True >>> is_sha('decade') False >>> is_sha('facade') False >>> is_sha('deedeed') False >>> is_sha('d670460b4b4aece5915caf5c68d12f560a9fe3e4') True >>> is_...
cb2f4dca633a81921d9489bc5d20b895448675b5
552,542
def get_surrounding_text(text, sub_start, sub_end=None, distance=25): """ Looks for the substrings, 'sub_start' and 'sub_end' variables in 'text' and return a new substring with a number equal to 'distance' characters in the left of 'sub_start' position and in the right of 'sub_end' position if they exi...
c5ad4a80940260ca591b7974ef9a37441140be78
628,018
import random def get_best_move(board, scores): """ Find all empty squares with max score, then randomly returns one of them as (row, col) tuple """ empty_list = board.get_empty_squares() best_score = float('-inf') best_move = [] # check for max value in scores for item in empty_list: ...
0cf0f1ccb45abbdb2032df329271b65c9ee6bc26
364,228
import struct def readInt(byteArray, start): """Read the byte array, starting from *start* position, as an 32-bit unsigned integer""" return struct.unpack("!L", byteArray[start:][0:4])[0]
9a4c2dc107fd395e9bdb7f127c152aa95c071ac7
507,774
def is_uniq(values): """ Check if input items are unique Parameters ---------- values : set set of all values Returns ------- True/False, MULTI/unique value """ if len(values) == 0: return True, '' elif len(values) == 1: return True, list(values)[0] ...
00fd70ab7b6cc20f5c32948b0bfffbb924e0da9e
414,381
def grid_edge_is_closed_from_dict(boundary_conditions): """Get a list of closed-boundary status at grid edges. Get a list that indicates grid edges that are closed boundaries. The returned list provides a boolean that gives the boundary condition status for edges order as [*bottom*, *left*, *top*, *rig...
2f285ef9c5065741759c83ae83021277b42aae9e
291,483
from typing import Tuple def _normalize_line(raw_line: str) -> Tuple[str, str]: """Normalizes import related statements in the provided line. Returns (normalized_line: str, raw_line: str) """ line = raw_line.replace("from.import ", "from . import ") line = line.replace("from.cimport ", "from . ci...
c35b7f7e79ff824427c055b66a1858d2483cf8ba
549,641
def clean(df, GPS = False, elevation = False, TEC = False, VTEC = False, locktime = False): """Clean Removes erroneous values of VTEC Args: df (dataframe): Master dataframe containing TEC measurements GPS (bool): (default: False) If True, only GPS satellite data is included and vice-versa elevation (bool):...
d00e3b7857c06e84d360e94c87f40e29a0ee7b71
74,516
def comp_radius(self): """Compute the radius of the min and max circle that contains the slot Parameters ---------- self : HoleM50 A HoleM50 object Returns ------- (Rmin,Rmax): tuple Radius of the circle that contains the slot [m] """ Rmax = self.get_Rext() - self....
d498ca0a82c868caa2f78828a1a6777f36be7d05
372,446
import math def angular_momentum(m, v, r, theta): """ Calculates the angular momentum of an object of mass 'm' whose linear velocity is 'v' and radius of the path traced by the object is 'r', angle between velocity and radius is 'theta' Parameters ---------- ...
a37ec10b1375e4b14c8a27e938c7e63839518509
111,160
def join_strings(strings, join_char="_"): """Join list of strings with an underscore. The strings must contain string.printable characters only, otherwise an exception is raised. If one of the strings has already an underscore, it will be replace by a null character. Args: strings: iterable of...
291055e33f73762e62345eadf2b63f2af529ab40
386,369
def no_hidden(files): """Removes files that start with periods. """ return([x for x in files if not x.startswith('.')])
e03a88ed3387b707484d767f746edc18da012f46
219,871
def preload(pytac_lat): """Load the elements onto an 'elems' object's attributes by family so that groups of elements of the same family can be more easily accessed, e.g. 'elems.bpm' will return a list of all the BPMs in the lattice. As a special case 'elems.all' will return all the elements in the latt...
b65c6950442bf3afd55f1b3cc5c67529170c3b69
628,260
def parse_file(filename): """ Parses a file and counts the occurrences of the word "pride" Args: filename: The file to be parsed Returns: The number of occurrences """ count = 0 # this is a super cool way to open a file, so it # will automatically be closed / cleaned up ...
5bc4336e06ac4cf0d90be8e97462f11de2bebacd
574,023
def cannot_add(left, right): """ Addition error. """ return "Cannot add {} and {}.".format(left, right)
624d6e40801ec0af563705a6eb2ef1a7dc26c49f
352,525
def _get_interpretation_normality(test_name: str, pvalue: float, sig_level: float): """Displays p-value of the specific normality test, along with test result interpretation Args: test_name (str): Name of statistical test p...
c6abfd63319f515ad4467bb261a40eacbe0a3e09
397,979
def deserialize_tuple(d): """ Deserializes a JSONified tuple. Args: d (:obj:`dict`): A dictionary representation of the tuple. Returns: A tuple. """ return tuple(d['items'])
aa502d4e16e824b354b00e0055d782cd10fe6b48
674,556
def bubble_sort(t_input): """ Bubble Sort Algorithm Simple and slow algorithm http://en.wikipedia.org/wiki/Bubble_sort Best case performance: O(n^2) Worst case performance: O(n^2) Worst Case Auxiliary Space Complexity: O(1) :param t_input: [list] of numbers :return: [list] - sorted lis...
3e0d19bb66c1e3569d8a2cc9aefb742867f6ae53
232,834
import re def cleanFilename(fname): """Turn runs of bad characters to have in a filename into a single underscore, remove any trailing underscore""" return re.sub("_$", "", re.sub("[ _\n\t/()*,&:;@.]+", "_", fname))
9dce26172d9b4cc6db3c9cdd13e4855c224a1a0c
68,914
def rect2pathd(rect): """Converts an SVG-rect element to a Path d-string. The rectangle will start at the (x,y) coordinate specified by the rectangle object and proceed counter-clockwise.""" x0, y0 = float(rect.get('x', 0)), float(rect.get('y', 0)) w, h = float(rect.get('width', 0)), float(rec...
910e0c45783d47f9533fa096e464ebce30705428
251,475
from typing import Pattern import re def r(regex: str) -> Pattern: """Compiles a regular expression.""" return re.compile(regex, flags=re.MULTILINE)
53af59d7a5c5149ee31c2ab42df2cf3a68327d39
147,386
def check_rule_name_ending(rule_name, starlark_rule_types=('binary', 'library')): """ Return True if `rule_name` ends with a rule type from `starlark_rule_types` Return False otherwise """ for rule_type in starlark_rule_types: if rule_name.endswith(rule_type): return True ret...
f31bbeb71f8cdefecab5c86f183a1972dc836a85
152,491
def find_missing_number(nums): """Returns the missing number from a sequence of unique integers in range [0..n] in O(n) time and space. The difference between consecutive integers cannot be more than 1. If the sequence is already complete, the next integer in the sequence will be returned. >>> find...
4e5074db26924971c1d2ff65a28367256ded10b0
141,389
def dummy_import(monkeypatch): # (MonkeyPatch) -> Callable """ This fixture monkeypatches the import mechanism to fail. After raising an `ImportError`, the monkeypatch is immediately removed. """ def dummy_import(*args, **kwargs): try: raise ImportError("this is a monkeypatch"...
341bd038135e1d689af50677d1fc1fbdc96c730a
642,559
def _is_typing_type(field_type: type) -> bool: """Determine whether a type is a typing class.""" return hasattr(field_type, '_subs_tree')
f0259babf9c5c4025306197e93193d6ab2d66de7
178,333
def smart_bool(value): """Convert given value to bool, using a bit more interpretation for strings.""" if isinstance(value, str) and value.lower() in ["0", "no", "off", "false"]: return False else: return bool(value)
90b5c33d38f8ed00a5bf97ddc314ea4901c172af
132,069
def get_walkID(filename): """Create walkID from filename. Args: filename (str): contains 3 substrings 'trial_[trial_num]' 'walklr_[walk_side]' 'visit_[visit_num'] Returns: walkID (str): formatted as [trial_num]-[walk_side]-[visit_num] """ trial =...
c70bdf7202546f98d3f9ccea13c677c313d45536
363,440
def fmt_quil_str(raw_str): """Format a raw Quil program string Args: raw_str (str): Quil program typed in by user. Returns: str: The Quil program with leading/trailing whitespace trimmed. """ raw_quil_str = str(raw_str) raw_quil_str_arr = raw_quil_str.split('\n') trimmed_qu...
e95c26f3de32702d6e44dc09ebbd707da702d964
707,167
import re def convert_to_padded_path(path, padding): """ Return correct padding in sequence string Args: path (str): path url or simple file name padding (int): number of padding Returns: type: string with reformated path Example: convert_to_padded_path("plate.%d...
67a7d029dd7139302f60a275512e5ff30700c48a
360,102
def index() -> str: """Rest endpoint to test whether the server is correctly working Returns: str: The default message string """ return 'DeChainy server greets you :D'
ce0caeb9994924f8d6ea10462db2be48bbc126d0
706,565
import torch def angle_axis_to_rotation_matrix(angle_axis): """Convert batch of 3D angle-axis vectors into a batch of 3D rotation matrices Arguments: angle_axis: (b, 3) Torch tensor, batch of 3D angle-axis vectors Return Values: rotation_matrix: (b, 3, 3) Torch tensor, ...
bd3300f2b341ec42c40af14763731a14e224cef5
216,782
from pathlib import Path import yaml def loadConfigDict(configNames: tuple): # pathLib syntax for windows, max, linux compatibility, see https://realpython.com/python-pathlib/ for an intro """ Generic function to load and open yaml config files :param configNames: Tuple containing names of config fil...
1bbee88e3ff5df7f26f1502eb34d72a33d01b348
655,434
def get_location_by_offset(filename, offset): """ This function returns the line and column number in the given file which is located at the given offset (i.e. number of characters including new line characters). """ with open(filename, encoding='utf-8', errors='ignore') as f: for row, l...
434b60a80fffd8068ea6d90ead92d914127f3b3e
21,236
def __ensure_suffix(t, suffix): """ Ensure that the target t has the given suffix. """ tpath = str(t) if not tpath.endswith(suffix): return tpath+suffix return t
392bf04404e2d739c676ede578410db34d232789
670,424
from typing import Dict from typing import Set def lettres_freq_inf(freqs : Dict[str,int], fseuil : int) -> Set[str]: """Précondition : fseuil > 0 Retourne les lettres de fréquence inférieure à fseuil dans freqs. """ # Lettres de fréquence inférieure au seuil finf : Set[str] = set() ...
2f67e809c355a590fb99ed7639cd90bebbadfe33
553,599
def mean(X): """ Compute the mean for a dataset of size (D,N) where D is the dimension and N is the number of data points """ # given a dataset of size (D, N), the mean should be an array of size (D,1) # you can use np.mean, but pay close attention to the # shape of the mean vector you are r...
ee887eed8f6ac70d09f40762df2ece52dea74a2c
484,222
import pkg_resources def bank_validation_str(iban: str, bank_code: str) -> list: """ Retrieves a string with the bank information :param iban: An iban string :type iban: str :param bank_code: the bank code :type bank_code: str :return: A list with the bank information :rtype: str ...
6c3ab1ee8ac79eeb79f59cadd349936a4809070d
379,468
def update_toestand(A, x, resistent=[]): """ Voor een gegeven verbindingsmatrix A en een binaire toestandsvector x (0: vatbaar/resitent, 1: geinfecteerd) op tijdstip t, bereken de toestandsvector op tijdstip t+1. Optioneel kan je een lijst met indices van resistente individuen geven. """ # u...
20ce9e50f6ebf0ca5d26c9e0ca3c789e81a94dee
582,003
def safe_unicode(obj): """Safe conversion to the Unicode string version of the object.""" try: return str(obj) except UnicodeDecodeError: return obj.decode("utf-8")
f6a592f7ea0de5179f1b8a91e0bd75c9a5d522df
73,547