content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def upload_media(request, form_cls, up_file_callback, instance=None, **kwargs): """ Uploads media files and returns a list with information about each media: name, url, thumbnail_url, width, height. Args: * request object * form class, used to instantiate and validate form for upload * call...
3e8fa5429cfd9f19b69525a4d7d97d414fb02820
662,369
def Split_Dataset_B_Res(sub, feature, label, channels): """ Split one subject's data to evaluate the results of LOSO-CV on Dataset B. Args: sub: leave one subject out. feature: input fNIRS signals. label: input fNIRS labels. channels: fNIRS channels. Returns: X_...
7639521f82c48205e05ab6d1c039f6556e45b29b
662,371
import re def get_parent_compseg_or_ted_uid(tixi3, xpath): """ Finds the uid of the nearest parent which is a component segment or trailing edge device :param tixi3: TiXI 3 handle :param xpath: XPath of the element to start the search """ end = [it.end() for it in re.finditer('(componentSegmen...
3bca3829baa465bbbd48a29602c09a3a147f1fc9
662,374
def _float(value: str) -> float: """Convert string to float value Convert a string to a floating point number (including, e.g. -0.5960D-01). Whitespace or empty value is set to 0.0. Args: value: string value Returns: Float value """ if value.isspace() or not value: r...
501e73417178744a6f620438773e34708908c0de
662,375
def task_wrapper(task): """Task wrapper for multithread_func Args: task[0]: function to be wrapped. task[1]: function args. Returns: Return value of wrapped function call. """ func = task[0] params = task[1] return func(*params)
7ea69ef64dbc9fbed43083169beb0e6cee7fe4d5
662,377
def escape_for_sql_like(string): """Function that escapes % or _ symbols provided by user SQL LIKE syntax summary: - ``%`` -> match any number of characters - ``_`` -> match exactly one character """ return string.replace('%', '\\%').replace('_', '\\_')
69a4a1c3c263508ff15c8c8836fa0b35bb4f7649
662,380
import json import re def dict_to_jsonl(dict_input): """ takes a dict object and turns it into a jsonl doc """ jsonl_contents = json.dumps(dict_input) jsonl_contents = re.sub(f"\n","",jsonl_contents) return jsonl_contents
20dca5ae5be83aa6156720ce92040793e6f1f0aa
662,385
def parse_desc(tokens): """ >>> parse_desc(Tokenizer("0 01BWA Helix Collective 000000Payroll31Mar310315 ")) {'FinancialInstitutionName': 'BWA', 'ProcessDate': '310315', 'ApcaNumber': 0, 'GeneratedBy': 'Helix Collective', 'EntriesD...
9687498db13a90d6ab9e0c0246bb35ca14a007c6
662,389
def addListsElementWise(a, b): """Add corresponding elements of two lists. The two lists do not have to have the same length. Nonexisting elements are assumed to have a value of 0. A new list is constructed and returned. """ if len(b) > len(a): a, b = b, a # Now len(a) >= len(b) r =...
d11d36d14869001f0a14a5201d63ed575e67eeeb
662,391
def merge_two_dicts(dict1, dict2): """ Merges two dictionaries into one :param dict1: First dictionary to merge :param dict2: Second dictionary to merge :return: Merged dictionary """ merged_dict = dict1.copy() merged_dict.update(dict2) return merged_dict
40dbb033e63c71c16f2b6cfe012a07ab7b2f41b9
662,392
def pretty_tree(x, kids, show): """Return a pseudo-graphic tree representation of the object `x` similar to the `tree` command in Unix. Type: `(T, Callable[[T], List[T]], Callable[[T], str]) -> str` It applies the parameter `show` (which is a function of type `(T) -> str`) to get a textual represe...
7a92a0048fa8efedf86eff2ba7deeb5b4fa40f66
662,394
import torch def is_f_contig(tensor: torch.Tensor, strict: bool = False) -> bool: """Check if a pytorch Tensor is column-contiguous (Fortran order) Column-contiguity means that the stride of the first dimension (of a 2D tensor) must be equal to 1. In case of 1D tensors we just check contiguity P...
b3fe41475430e1c7780215f376d1a0d9eb6c15da
662,396
def _find_machine(oneandone_conn, instance): """ Validates that the machine exists whether by ID or name. Returns the machine if one was found. """ for _machine in oneandone_conn.list_servers(per_page=1000): if instance in (_machine['id'], _machine['name']): return _machine
4a0d83c696891b032cb88817c52c8265bef68a97
662,397
def extract_user(event): """ :param event: (required) the event from the request :return: The username of the user who made the request """ return event["requestContext"]["authorizer"]["claims"]["cognito:username"]
9404bcc7468230a354c2cd41d1c3949e237660d7
662,398
def _bool(xml_boolean): """Converts strings "true" and "false" from XML files to Python bool""" assert xml_boolean in ["true", "false"], \ "The boolean string must be \"true\" or \"false\"" return {"true": True, "false": False}[xml_boolean]
27803aace78f1ee1ecaa5c271955218dfcd0458a
662,399
def binary_search(value, array, start_idx=None, end_idx=None): """ Выболняет бинарный поиск значения в отсортированном по возрастанию массиве. :param value: Значение, которое необходимо найти. :param array: Массив поиска. :param start_idx: Начальный индекс поиска (для рекурсивного вызова) :para...
efb1396d00d44cc669c1c8d344d3334894181ae7
662,401
def make_s3_key_path(job_config, course = None, filename = None, session = None, mode = None, job_id = None): """ Create a key path following MORF's subdirectory organization and any non-null parameters provided. :param job_config: MorfJobConfig object. :param course: course slug (string). :param fi...
2aca0240a25baa0abbbac0502236f6898805b509
662,404
def get_rare_elements_number(d, n): """ Count the number of rare elements :param d: dictionary to use :param n: the threshold for rarity :return: the number of rare elements as a string """ i = 0 for k, v in d.items(): if v < n: i += 1 return str(i)
367aab5fdf4efb945cccfb9dffd95573cbd72a3c
662,405
def no_by_per(totalhp, percentage): """ rtype: num of `percentage` from total eg: 1000, 10 -> 10% of 1000 (100) """ return totalhp * percentage / 100
7884f94634863d434afb358a1612c5b57cb56744
662,407
def relative_error(U, V, product=None): """Compute error between U and V relative to norm of U.""" return (U - V).norm(product) / U.norm(product)
d6babc4cdca0c2095e36c63ed08a1f87e774a8a0
662,412
def ifg_dates_dc_to_cum(ifg_dates): """Given the names of the daisy chain of interfergorams, find the names of the cumulative ones relative to the first acquisition. Inputs: ifg_dates | list | names of daisy chain ifgs, in form YYYYMMDD_YYYYMMDD Returns: ifg_dates_cum | list | names of cum...
756e8277887baeeb95d63dacd719878b1836c09c
662,414
def is_none_p(value): """Return True if value is None""" print("is_none_p", value) return value is None
2b0ab594fab76c856058884fd43252a591f86e78
662,418
def trend(series, n): """Return the running average, minimum and maximum of a series for an n- element moving window.""" meanvals = [] minvals = [] maxvals = [] running = [] for val in series: running.append(val) if len(running) > n: running.pop(0) meanval...
3e40c734548d8773401e255fb844a6683ef1c871
662,420
def isWild(card, wild_numbers): """returns true if a card is a wild""" if card.number in wild_numbers: return True else: return False
b9a10089d8befa8c5f3c8656e8e4834763caa8fd
662,422
def check_string(string: str, chars: list) -> bool: """ Returns True if one element of chars is in the string. :param string: String to check. :param chars: list of strings to check if one of it is in the string. :return: bool """ return any((char in string) for char in chars)
10cbfdc573914c738b5c0dc2ea7dd4fa606703eb
662,430
def percentage(value, refer_to): """Return the percentage of the reference value, or the value unchanged. ``refer_to`` is the length for 100%. If ``refer_to`` is not a number, it just replaces percentages. """ if value is None or value == 'auto': return value elif value.unit == 'px': ...
81738835f31e5651f29bc49aac06d6ee0142439d
662,436
def validate_slug(slug, digits=8): """ Return true if a slug is a string and has the correct number of digits. """ return isinstance(slug, str) and len(slug) == digits
d8d3d30b20649bb1e3a1b2758b8e85de0fe27b39
662,439
def flat_eq(x, y): """ Emulate MATLAB's assignment of the form x(:) = y """ z = x.reshape(1, -1) z = y return z.reshape(x.shape)
e39deae6e7df1afcb6e903348ab8480daa31b936
662,441
def is_select(status): """Returns true if the first word in status is 'select'.""" if not status: return False return status.split(None, 1)[0].lower() == "select"
95323a52e4d4b2911053c628b67b8da89deeec3d
662,442
def assoc_in(d, keys, value, factory = dict): """ Update value in a (potentially) nested dictionary This function was inspired by toolz.update_in and adopted for bazel. Source: https://github.com/pytoolz/toolz/blob/master/toolz/dicttoolz.py Args: d: dictionary on which to operate ...
4d58539e11a16355f4d5414a23af8a7a7cfed820
662,445
def add_group(groups_collection, group_name): """Adds a new group to the groups collection if it doesn't already exit :param groups_collection: Mongo collection that maintains groups :param group_name: Name of group to be added :return: ObjectID of new group :return: None if group already exists ...
8dd424d573f55d56382ad0bf498a6b02db36a2ab
662,446
def file_get_contents(filename): """ Returns file contents as a string. """ with open(filename) as file: return file.read()
2572068496a9a3cd185d4cd2f469bbe2f9669c6b
662,448
def is_contained(a, b): # Multiset: a < b """ bool: True if list a is fully contained in list b. """ b = b[:] try: [b.remove(s) for s in a] except ValueError as err: return False return True
ad828d4a8efb44d56f061eec745da125a3218f7d
662,449
def index_dependent_values(self, chromosome): """Test of the GA's ability to improve fitness when the value is index-dependent. If a gene is equal to its index in the chromosome + 1, fitness is incremented. """ # Overall fitness value fitness = 0 for i, gene in enumerate(chromosome): ...
20df3cc47ef566f34fbdba4eca84a85795a02408
662,450
def manhattan_dist(c1, c2): """ Compute Manhattan distance between two coordinates """ return abs(c1[0] - c2[0]) + abs(c1[1] - c2[1]) + abs(c1[2] - c2[2])
1c91e684dee200a4695e02e4a5cd4185cb995951
662,452
import importlib import pkgutil def _walk_modules(path): """ Loads a module and all its submodules from the given module path and returns them. If *any* module throws an exception while importing, that exception is thrown back. """ # Support for namespace packages is added. See PEP 420. #...
73abe5071044157d2caddf4bfc0db676dd7010b3
662,459
def child_fun(current_person): """This function checks whether the person has a child or not and works accordingly. Parameters: current_person: The current Person object. Returns: The picked child number and the children list as a tuple. """ ch_lst = current_person.get_chil...
6af533cd0c447e015eac0a69789e298368e408cd
662,462
from typing import Pattern def _match_root(root, name): """ Args: root (str or re.Pattern): Root. name (str): File URL or path. Returns: bool: True if match. """ return (isinstance(root, Pattern) and root.match(name)) or ( not isinstance(root, Pattern) and name.st...
a51d8ef6c4dba4ad1405116f12a868999336b4e9
662,468
def fate_lr_decay(initial_lr, lr_decay, epochs): """ FATE's learning rate decay equation Args: initial_lr (float): Initial learning rate specified lr_decay (float): Scaling factor for Learning rate epochs (int): No. of epochs that have passed Returns: Scaled...
e8435afc466c0ca2b7156b2b95370bcd38fef0d5
662,469
def bin2state(bin, num_bins, limits): """ :param bin: index in the discretization :param num_bins: the total number of bins in the discretization :param limits: 2 x d ndarray, where row[0] is a row vector of the lower limit of each discrete dimension, and row[1] are corresponding upper l...
04c5107946f72bddc1900dbaa5906203c597837a
662,473
def board_full(board): """ Utility function that returns True if the given board is full and False otherwise Arg board: board - the board you want to check """ for row in board: for piece in row: if piece == '*': return False; return True;
a4c5b71cd9aa95f848acb96c62f850afbbf4805e
662,475
def always_reversible(iterable): """An extension of :func:`reversed` that supports all iterables, not just those which implement the ``Reversible`` or ``Sequence`` protocols. >>> print(*always_reversible(x for x in range(3))) 2 1 0 If the iterable is already reversible, this function retur...
76442c9c7c020a10e168ce0a8d787afc6d15facc
662,477
def assert_single_element(iterable): """Get the single element of `iterable`, or raise an error. :raise: :class:`StopIteration` if there is no element. :raise: :class:`ValueError` if there is more than one element. """ it = iter(iterable) first_item = next(it) try: next(it) except StopIteration: ...
16cec15d07b47bc9ae75dddee5eace13eec22e15
662,480
def fasta_split(fasta_str): """ Splits a fasta file like: >sp|P10636|TAU_HUMAN Microtubule-associated protein tau OS=Homo sapiens OX=9606 GN=MAPT PE=1 SV=5 MAEPRQEFEVMEDHAGTYG SPRHLSNVSST >ANOTHER_TAU_HUMAN Microtubule-associated protein tau OS=Homo sapiens OX=9606 GN=MAPT PE=1 S...
84e02801132673a89a9d084630865b94c0abae04
662,484
import string import random def random_string(length=255, extra_chars=''): """ Generate a random string of characters. :param length: Length of generated string. :param extra_chars: Additional characters to include in generated string. """ chars = string.ascii_letters + extra_chars re...
fa434400b65343709d604d418c4d2f9f596e90cb
662,485
import time def timer(input_func): """ returns the execution time of a function wrapped by this decorator""" def timed(*args, **kwargs): start_time = time.time() result = input_func(*args, **kwargs) end_time = time.time() print("{0} took {1:0.5f} secs".format(input_func.__name_...
da477a47d5db6f1c2b449914ad6e1dd383754a5b
662,486
def scan_file(classifier, location): """ Run a license and copyright scan on file at `location`, using golicense-classifier. Parameters ---------- classifier : LicenseClassifier() `LicenseClassifier` instance for scanning files location : str Location of the file """ ...
f09ec02b6d00115f0bf067846418c6652eed4205
662,487
def get_line(sample): """Build a list of relevant data to be printed. Args: sample (dict): an object from project samples Returns: list(str): list of relevant data to be printed """ return "\t".join( [ sample.last_status.created.isoformat(), str(samp...
2849cd6e87b681199d9cb12b9e58c8a793f20e12
662,489
import re def parse_host_list(list_of_hosts): """Parse the comma separated list of hosts.""" p = set( m.group(1) for m in re.finditer("\s*([^,\s]+)\s*,?\s*", list_of_hosts)) return p
51c49f0ec1ada98ca08c7e30b169fffc858cf8dc
662,491
def inv_ensure_4d(x, n_dims): """Remove excess dims, inverse of ensure_4d() function.""" if n_dims == 2: return x[:, 0, 0, :] if n_dims == 3: return x[:, :, 0, :] else: return x
86e3b9fad06b6f85f8c883d0ae7ce88017a6a62d
662,494
def posix_invocations(trace_graph): """Return number of total POSIX API invokations""" return sum(map(lambda x: x[1], trace_graph.full_paths_dict.items()))
dd2fdde445ff7738ee06002dd9b9cc6cd1ebad2f
662,500
async def mistyversion_header(request, handler): """Add Misty-Command-Version header """ response = await handler(request) response.headers['Misty-Command-Version'] = 'Current' return response
7339714e33fc2a73868e9a0ba8113991d5774340
662,503
def labels_to_generate(epitope_files, ppi_files): """ Takes 2 lists of files and extracts the chains for which to generate labels. """ all_files = epitope_files + ppi_files chains = [] for f in all_files: chain = f.split('.')[0].split('_')[-1] if not chain in chains: ...
a752d95572ee76e9cc6ce8af3fb86e6133d2c2c2
662,505
def elliptic_range(num_pages, current): """ Produce a list of numbers from 1 to num_pages and including current. Long runs of successive numbers will be replaced by "...". """ def gap(start, stop): if stop - start < 3: return range(start, stop) return ["..."] ret = []...
f27fd176abce07fc084ce8d7ae6ed04324cdd809
662,506
def dd_valley_value_map_nb(record, ts): """`map_func_nb` that returns valley value of a drawdown.""" return ts[record['valley_idx'], record['col']]
c2f08fb8fb81be4d8e57dac949d8048d83c7dcec
662,510
from typing import List def part_2(expenses: List[int]) -> int: """Find the three entries in expenses that sum to 2020 and return their product. Args: expenses: List of integer expense values. Returns: Integer product of three entries that sum to 2020. """ return { a * b ...
5bc40d2d14f120eca021520c5063b4864dcf1bf7
662,512
def _quote(data): """Prepare a string for quoting for DIGEST-MD5 challenge or response. Don't add the quotes, only escape '"' and "\\" with backslashes. :Parameters: - `data`: a raw string. :Types: - `data`: `bytes` :return: `data` with '"' and "\\" escaped using "\\". :return...
e9f05dff72ddc8b66d61c2a4ba5f7140c45e4665
662,517
import math def velocities(course, vel): """ Converts target velocities from course and modulus to vector components Vx and Vy :param course: target course :param vel: modulus of target velocity :return: Vector components Vx and Vy """ return round(vel * math.cos(math.radians(course)),...
474f340cd3a505e33a19753844b5b636561d5089
662,520
def error_compatibility_score(h1_output_labels, h2_output_labels, expected_labels): """ The fraction of instances labeled incorrectly by h1 and h2 out of the total number of instances labeled incorrectly by h1. Args: h1_output_labels: A list of the labels outputted by the model h1. h2_o...
3ab007b4608d43830576ce905687a74777ba8de6
662,522
def is_json_metadata(text): """Is this a JSON metadata?""" first_curly_bracket = text.find("{") if first_curly_bracket < 0: return False first_equal_sign = text.find("=") if first_equal_sign < 0: return True return first_curly_bracket < first_equal_sign
5d67e5d6f79cd81e30f1726c9184300e59ad9ff2
662,524
def external_edges(graph, nbunch): """ Get the edges external to a set of nodes """ return (edge for edge in graph.edges(nbunch) if any(node not in nbunch for node in edge))
501c724cf4ec6268bd6706515f3be52fdc5057b8
662,525
def convert_sqlite_version(version): """ Return a version converted from the sqlite human version format to the download version format. For instance: >>> convert_sqlite_version('3.36.0') '3360000' >>> convert_sqlite_version('3.36.0.2') '3360002' See also: https://www.sqlite.org/ve...
afa72cf1fcdce2330b70163b827292e4aac360d7
662,529
def new_grid_size(grid, kernel_size, stride=1, padding=0): """ Calculate new images size after convoling. Function calculated the size of the grid after convoling an image or feature map. Used formula from: https://adeshpande3.github.io/A-Beginner%27s-Guide-To-Understanding-Convolutional-Neural-Networks-Pa...
cb6607a7fa0927ae90aceb170f0c69acfcbb1b76
662,532
def convert_timetable(start, end): """ Function to convert rows to time :param start: Starting row number :param end: Ending row number :return: Tuple with all correct starting and ending times """ timetable = { 1: ("8:30", "9:20"), 2: ("9:20", "10:10"), 3: ("10:30",...
69790dd28b69dc62ebba613d4b55a7627e43cafc
662,533
def convert_tuples_to_bitstrings(tuples): """Given a set of measurement tuples, convert each to a little endian string. Args: tuples (list of tuples): the measurement tuples Returns: A list of bitstrings """ # Convert from tuples to bitstrings bitstrings = [] for tuple_i...
a2da6c8191032f1530ceb490ad33510a6d7152cb
662,535
def chunk(data, index): """ Split a string into two parts at the input index. """ return data[:index], data[index:]
04026ec0e09c831ddc478117f75a6e77fd06393b
662,538
import re def is_complete_url(url): """ 验证 url 是否完整 :param url: :return: """ re_result = re.match("http.*", url) if re_result is None: return False return True
3215b3cd56857fe85f77473267d6e44894809461
662,542
import random def random_selection(population, fitness, eq): """ Selection of the best two candidates given fitness function :param population: list of numpy array :param fitness: function to fit :param eq: params to fitness function :return: tuple of two more promising individuals (numpy vect...
208f6d958bfdaf339233abd69c4918cf6a75cf5b
662,549
def object_to_dict(xmp): """ Extracts all XMP data from a given XMPMeta instance organizing it into a standard Python dictionary. """ dxmp = dict() if not xmp: return {} for item in xmp: if item[-1]['IS_SCHEMA']: dxmp[item[0]] = [] else: dxmp...
e0cf7f56b8a9e4819485f60d853c0175b2123e67
662,554
def round_gls(gls, precision=None): """Returns genotype likelihoods rounded to the desired precision level. Args: gls: A list of floats. The input genotype likelihoods at any precision. precision: Positive int. The number of places past the decimal point to round to. If None, no rounding is performed...
12a04d646830a2c32da3d8c377d57e3c1aeddb8a
662,557
import pathlib def peer_save_path(current_path: pathlib.Path, append: str) -> pathlib.Path: """ get save path of concatenated result. this path is peer to current prediction file and append string: <prd.name>_<append>.<suffix> :param current_path: pathlib.Path: current prediction file Path object ...
8c4b2b02743c86ebf3db102ab0c67c0d7c41c74d
662,560
def mult(m, n): """ return the smallest multiple of m that is >= n """ return m * ((n+m-1) // m)
e59d82accd5bc5422806d45728521f6a9d420d96
662,561
import re def _tls_trailer_length( data_length: int, protocol: str, cipher_suite: str, ) -> int: """Gets the length of the TLS trailer. WinRM wrapping needs to split the trailer/header with the data but the length of the trailer is dependent on the cipher suite that was negotiated. On Win...
98ccf856254ca2d151c551a6e7f6cbaaa693f392
662,563
def fix_alpha(with_alpha, without_alpha): """ Given two of the same image, one with an alpha channel and one without, add the alpha channel back into the image without, and return it. :param with_alpha: :param without_alpha: :return: """ alpha_added = with_alpha.copy() alpha_added[:...
abd2c81d5569983ce8a30233112e1d5b5bf48b89
662,566
def number_day_to_name_day(number): """ Receives a number where 0 is sunday and returns the name of the day :param number: :return: """ weekDay = {0: 'Domingo', 1: 'Segunda', 2: 'Terça', 3: 'Quarta', 4: 'Quinta', 5: 'Sexta', 6: 'Sábado', 7: 'Domingo'} return weekDay[number]
62aed7b9d944650ecc79c167d7b71b0f0c505ca8
662,571
def get_color_commands(indices, colors): """Returns postscript coloring string given indices and colors. - indices: base 1 index of color. NOT BASE 0. - colors: color name corresponding to color name used to generate color_map. - indices and colors must be lists of the same...
3b111463146cf3e2d7025074dbd86e4c576a9013
662,572
def is_subset(subset, set): """ Determines if 'subset' is a subset of 'set' :param subset: The subset :param set: The set :return: True if 'subset' is a subset of 'set, False otherwise """ cpos = 0 for c in set: if c == subset[cpos]: cpos += 1 # Found the char if cpos == le...
6a81019a8ee8cbf192182d89c9deb71e6d55d49e
662,573
from typing import Dict def deep_update_dict(first: Dict, other: Dict) -> Dict: """ Perform in place deep update of the first dictionary with the values of second :param first: The dictionary to be updated :param other: The dictionary to read the updated values :return: A reference to first dictio...
b32308f8f921fcb949c820a688bf01566ea4f351
662,578
def get_lastkey(path, delimiter="/"): """ Return name of the rightmost fragment in path """ return path.split(delimiter)[-1]
0e2287c95974466fae70b15c75aca11d5ed02795
662,580
def getColor(isInside): """ Returns color of points depending on if they're close to rect """ if isInside: return 'green' else: return 'red'
0eef7cb71c9be495969e90871bf4dfdb6c484de1
662,581
def _xml_escape(data): """Escape &, <, >, ", ', etc. in a string of data.""" # ampersand must be replaced first from_symbols = '&><"\'' to_symbols = ('&' + s + ';' for s in "amp gt lt quot apos".split()) for from_, to_ in zip(from_symbols, to_symbols): data = data.replace(from_, to_) re...
b6b2db648a8dd7321498ac2e7df77b8823b7593b
662,582
import re def _make_pretty_usage(infos): """ Makes the usage description pretty and returns a formatted string. Expected input: func(*) - ... func(expr[, expr...]) - ... Expected output: <table class="table"> <thead> <tr> <th style="width:25%">Function</...
afe9717fedfec86905aa40ca6e8aeab03b8a293d
662,583
def compute_II_fr(stretch,muscActivation,species): """ Compute the firing rates of the II afferent fibers. Uses the experimetnally derived model devloped by Prochazka (1999 (2)). Keyword arguments: stretch -- muscle stretch in mm. muscActivation -- normalized muscle activation [0 , 1]. """ bias = 80 xCoef = 1...
1411109acc3cda06606ff4741b602613fcf7be4a
662,587
def get_ep_next(ep_latest, ep_num): """ for provided episode name and number return which should be the next episode Parameters ---------- ep_latest: string the full name of the episode ep_num: the current episode number Returns ------- : string the name of the nex...
8c8ee9c4becce9d6bfc8401f086053a026d40439
662,588
def effective_prior(p_tar, c_miss, c_fa): """This function adjusts a given prior probability of target p_targ, to incorporate the effects of a cost of miss, cmiss, and a cost of false-alarm, cfa. Args: p_tar: target prior c_miss: cost of miss c_fa: cost of false alarm Returns: ...
a9fd665d626dd5384824b43ce2aca6a41ee2d7e8
662,590
import collections def _get_odim_root_attributes(nch, grps): """Retrieve root attributes according CfRadial2 standard. Parameters ---------- grps : dict Dictionary of root hdf5 groups ('how', 'what', 'where') Returns ------- attrs : dict Dictionary of root attributes ...
5c99a54cf97d2cc2592e5442f6671c374af5655d
662,594
def version_tuple(v): """Get an integer version tuple from a string.""" return tuple(map(int, (str(v).split("."))))
2a89af9bff389d143afe554bec9287ae6cc3d98c
662,595
def norm(X, n=2): """Return the n-norm of vector X""" return sum([x**n for x in X])**(1/n)
101941824728e5eb28ce40d9ddae7a0f5c6acc5d
662,599
def _in_chunks(seq, size): """ Return sequence in 'chunks' of size defined by size """ return (seq[pos:pos + size] for pos in range(0, len(seq), size))
c5e1f2c95e2cac7543ca312d60e346b1cc3c3141
662,602
def coalesce(*fields, **kwargs): """ Return a function which accepts a row and returns the first non-missing value from the specified fields. Intended for use with :func:`petl.transform.basics.addfield`. """ missing = kwargs.get('missing', None) default = kwargs.get('default', None) de...
eef78039912fc28cf4d7d20a361b583fcb9bf755
662,608
import json def parse_desc(rec): """ Parses annotations from a sequence description """ ann = {} desc = rec.description # Nothing to parse. if rec.id == desc: return ann, '' # Attempts to split the description for parsing into JSON payload = rec.description.split(" ", ma...
9e0922939dd693ab4d0374d7473610d73c9ac2f3
662,609
def node(l, v, r, b): """Make an AVL tree node, consisting of a left tree, a value, a right tree, and the "balance factor": the difference in lengths between the right and left sides, respectively.""" return (l, v, r, b)
87a934ab9f4d49c772b4e8900916d75a7868c323
662,610
def get_best_technical_set(df): """Identify set with greatest AUROC in dataframe. Args: df (pd Dataframe): must contain 'auroc_mean' and 'full_label'. Returns: best_set (str): label of best technical set. """ df = df.sort_values(by=['auroc_mean'], ascending=False, ...
a332fe45a674526aae65d23c0fa643bf6c478cd7
662,612
def uM_to_mgml(species_mws, species_concs, scale=1000000): """ Args: species_mws: (dict) For example {'enzyme_1' : 33000, 'substrate_1' : 150} species_concs: (dict) For example {'enzyme_1' : 10, 'substrate_1' : 10000} scale: (int) The scale we are working on. 1=M, 1000=mM, 1000,000=uM....
fa9121d354978bc0d1e5d5cc7033d37b4f0b6df2
662,616
def load(f): """ read a file into a string """ fh = open(f) text = fh.read() fh.close() return text
6f8efa32c48309c8768e71b7fa0a46791c83746b
662,621
import inspect def get_params(f): """ Returns parameters and default values to class constructor Example: get_params(_classifier['RandomForestClassifier']) >> {'n_estimators': 100, 'criterion': 'gini', ... 'ccp_alpha': 0.0, ...
c489d1b5296fc116fd83d492eb656b1d1cb524d2
662,623
def get_nonce_bytes(n): """BOLT 8 requires the nonce to be 12 bytes, 4 bytes leading zeroes and 8 bytes little endian encoded 64 bit integer. """ return b"\x00"*4 + n.to_bytes(8, 'little')
3c35dd968d2b92a38937a14a1cecf73a40bd16d2
662,632
def humanize_bytes(num_bytes): """ Convert a number of bytes to human version :param num_bytes: int: bytes to be converted to :return: str """ val = num_bytes suffix = "B" factor = 1000 if val >= factor: val = val / factor suffix = "KB" if val >= factor: v...
a78b16ab91ba639bc7e6e98ca66c72c2d2b4cbea
662,633
def categorical_fillna(data, col, value="N"): """ Fills a categorical features Nan Values with the provided value, returns a new column. The pandas function sometimes does not work """ def helper(x): if isinstance(x, float): return value return x return data[col].app...
5ebfb76e5090e3d149ab6f6e28ebc6987479b483
662,635
def _is_max_limit_reached(current: int, maximum: int = -1) -> bool: """Check if the limit has been reached (if enabled). Args: current: the current value maximum: the maximum value (or -1 to disable limit) Returns: bool: whether the limit has been reached """ return maximum...
ddf459277651837f6f0b2787dd23896dd6a38cda
662,640