content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import collections def comp_initial(tags, treebank): """Compute initial probability for the given set of tags and training corpus Args: tags (list): list of unique tags from the corpus treebank (object): File object with train corpora loaded. nltk.corpus.reader.tagged.TaggedCorpusReader ...
51dc836e33d301524064897eee89a77bba1e2797
81,587
def get_num_fft(sample_rate, window_len): """ Function get_num_fft calculates optimal number of FFT points based on frame length. Less number of FFT points than length of frame will lose precision by droppping many of the samples. Therefore, we want num_fft as a power of 2, greater than frame length...
bbab1ec96fb78b2facba181cf9eba3b6bc1e9129
81,595
def label(field): """Return a label for a data field suitable for use on a graph axis. This returns the attribute 'long_name' if it exists, or the field name, followed by the units attribute if it exists. Parameters ---------- field : NXfield NeXus field used to construct the label. ...
c087a57a597ea4feef1d293d371fb6175042644c
81,597
def filter_features(features, key, include=None, exclude=None): """Filter an iterable of GeoJSON-like features based on one of their attributes. Parameters ---------- features : iterable of dict Source GeoJSON-like features. key : str Property key. include : tuple of str, op...
b2bfea17bae33ece7f37bb35d08569fa8fd061b0
81,602
def bucket_from_url(url): """ Extracts a bucket name from an S3 URL. url: an S3 URL, or what should be one Return value: bucket name from S3 URL """ if url[:6] == 's3n://': start_index = 6 elif url[:5] == 's3://': start_index = 5 elif url[0] == '/': start_in...
82c98e613948d8369c3a74a7d87b9a374c54928d
81,608
def calculate_management_strategy(fef, mtbfa, mtbfgp): """ Function to calculate the minimum required management strategy for the entire program or a test phase. :param float fef: the average fix effectiveness factor over the period to calculate the management strategy. :param...
2d72a733af36f6e3f724f52699c377cf04e4e8c7
81,609
import re def getAlignmentLength(cigar): """ Computes the alignment length given a cigar string. Needed for Start + End calculation. @type cigar: string @param cigar: Cigar string (SAM) @rtype: int @return: alignmentlength """ # I - insertions do not extend the alignment # S ...
6a8e99cb6250d26ed1c9771ada9694a316ee917c
81,610
def val_and_std(token): """check the validity of a token; standard it if needed Args: token (string): a token Returns: string: an standardized token if the token is valid otherwise return None """ token = token.strip("\"\'-") tran_t = token.replace("-", "").replace("'", "...
754f6f520fd12ebf688bc7bd801d39fae16a68fc
81,617
def market_clock ( self ): """Receive information about the state of the exchange """ url_suffix = 'market/clock.json' results = self.call_api ( method = 'GET', url_suffix = url_suffix, use_auth = False ) x = { k:v for k,v in results.items() if k in ( 'message','status') } return x
c290f527e5151dfcf47fe29b5e739903623180bd
81,620
import re def _parse_bonds_from_svg(bond_elements, mol): """Extract bonding information from SVG elements Args: bond_elements (list[xml.etree.ElementTree.Element]): List of SVG path elements. mol (rdkit.Chem.rdchem.Mol): RDKit mol object] Returns: list[dict]: JSON-sty...
f78462ac81f29ca7300c0d269f963df0a1b72feb
81,630
def ask(question: str) -> str: """Ask the user to provide a value for something.""" print(question) response = input() return response
de420095822a16aacee571fc114de65cb7380d3e
81,632
from pathlib import Path def generate_csv( symmetric_corr_table, rna_info, data_load_sources, stringency, out_dir ): """ Given a correlation table of RBPs binding to an RNA molecule of interest, generates and saves a CSV file containing the correlation values. :param symmetric_corr_table: A nested...
b6d2a7e668371af0b601e88243ea2308d32196bc
81,633
def get_auto_name(name: str, rnn_layers: int, rnn_size: int, rnn_bidirectional=False, rnn_type='lstm') -> str: """Generate unique name from parameters""" model_name = f"{name}_{rnn_layers}l{rnn_size}" if rnn_bidirectional: model_name += 'bi' if rnn_type == 'gru': model_name += '_gru' ...
841e801319fee1a4dce56cf760ea6c2081e48177
81,635
def get_column_unit(column_name): """Return the unit name of a .mpt column, i.e the part of the name after the '/'""" if "/" in column_name: unit_name = column_name.split("/")[-1] else: unit_name = None return unit_name
b7cbc268aebadf3dfed541b5e246ad46295826c8
81,637
def resolve_dependencies(func_name, dependencies): """Given a function name and a mapping of function dependencies, returns a list of *all* the dependencies for this function.""" def _resolve_deps(func_name, func_deps): """ Append dependencies recursively to func_deps (accumulator) """ if f...
af8d4eec403ea40f52514d8af53bf1020941b5fb
81,638
def getJunitTestRunnerClass(version): """ Get the correct junit test running class for the given junit version Parameters ---------- version : int The major version for junit Returns ------- str or None Returns str if `version` is either 3 or 4 Returns None otherwis...
2020c1b9b128595048521bcee7bbd4ccf04c36bc
81,643
def quaternion_to_xaxis_yaxis(q): """Return the (xaxis, yaxis) unit vectors representing the orientation specified by a quaternion in x,y,z,w format.""" x = q[0] y = q[1] z = q[2] w = q[3] xaxis = [ w*w + x*x - y*y - z*z, 2*(x*y + w*z), 2*(x*z - w*y) ] yaxis = [ 2*(x*y - ...
b98f5a59b7fb5f741d388b2eab22726acf6e2ac5
81,644
def getHeaderResponse(station, type='FixedStation'): """ Get header response :param station: station name id :param type: station type (FixedStation or MobileStation) :return: header response """ response = {'id': station} response['station_name'] = station response['scientificName'] = 'CanAirIO Air qua...
ed16dca9ed3187f038fb70828dc2c9632eb045a7
81,650
def _nonetypeclass(*args, **kwargs): """Initializer function that returns Nonetype no matter what.""" return None
438fb33596a02d474edafde375a661508514c6cd
81,651
def _get_username(acs_info): """ Gets the admin user name from the Linux profile of the ContainerService object. :param acs_info: ContainerService object from Azure REST API :type acs_info: ContainerService """ if acs_info.linux_profile is not None: return acs_info.linux_profile.admin_u...
02258432845599c7e198f4069f25123e2be14535
81,654
def list_len(x): """Implement `list_len`.""" return len(x)
81b49aa40c74d14ded61d26de8d3fb71b6c8a3e1
81,655
def verify_input(json_data): """ Verifies the validity of an API request content :param json_data: Parsed JSON accepted from API call :type json_data: dict :return: Data for the the process function """ # callback_uri is needed to sent the responses to if 'callback_uri' not in json_dat...
ad84c15d89fc060575f2dc84acf96dd10f7721e9
81,656
def normalize_greek_accents(text): """Sanitize text for analysis. Includes making turning grave accents into acutes, making the whole text lowercase and removing punctuation (.,·) """ # Switch graves to acutes text = text.replace(u'ὰ', u'ά') text = text.replace(u'ὲ', u'έ') text = text.r...
b60cd80b54fabff73ef460e6ba51685a7ae7367e
81,661
def _to_num(src_string): """Convert string to int or float if possible. Original value is returned if conversion failed. """ if not isinstance(src_string, str): return src_string src_string = src_string.strip() try: return int(src_string) except ValueError: try: ...
2904b44a12073bfe466869e965473e932c79d164
81,662
def reformatStripList(stripList): """\brief Converts a list of channels into a string for being included in the .xml file. The string contains all the strip numbers, separated by a space. """ String = '' for channel in stripList: String = String + str(channel) + ' ' # Remove the last space. String = ...
d8d33bfc6e69d9b94a63ac1ff310d989cf5f8b16
81,666
def is_nearest_multiple(m, a, b): """ Replacement for m % b == 0 operator when variable is incremented by value other than one at each iteration. m is assumed to be increased by a at each iteration. If not exactly divisible, this function returns True the first iteration returns True the first iteration...
78ecf301ad0b6d9d0daca08ea17ef204d511f10b
81,669
def is_y_or_n(string): """Return true if the string is either 'Y' or 'N'.""" return string in ['Y', 'N']
47bf100bc1b687211513b58e8330ca6904c80bb8
81,677
from typing import Tuple def _calculate_fold_number(length: int, max_length: int, folding: bool) -> Tuple[int, int]: """Calculate the number of the folded and unfolded items. Arguments: length: The object length. max_length: The configured max length. folding: Whether fold the "repr" ...
5cf1f9173b826c78b87e50cf7b360c71732962cb
81,680
def clean_data(data): """ This function takes in data and returns a mutated version that converts string versions of numbers to their integer or float form depending on the type of value. Parameters: data (list): A list of dictionaries. Returns: (list): A list of dictionaries with ...
756ce5805022b0779a575d7f6c83e7740fed135b
81,693
def mask2list(bitmask, number=1): """ Convert an integer bitmask into a list of integers. >>> mask2list((1 << 14) | (1 << 0)) [1, 15] """ if not bitmask: return [] this = [] if bitmask & 1: this = [number] return this + mask2list(bitmask >> 1, number + 1)
da5f4076f9bec3353c365f4da939dfb92bd14f96
81,694
def removeDuplicateObservations( linkages, linkage_members, min_obs=5, linkage_id_col="orbit_id", filter_cols=["num_obs", "arc_length"], ascending=[False, False] ): """ Removes duplicate observations using the filter columns. The filter columns are used to sor...
e878416adbb380a84f9e4a4941228f065486c570
81,695
def human_format(num: int) -> str: """Returns num in human-redabale format from https://stackoverflow.com/a/579376 Args: num (int): number. Returns: str: Human-readable number. """ # f if num < 10000: return str(num) magnitude = 0 while abs(num) >= 1000: ...
6331d7c8d57ca3b93be80af882ccfdf6047a16ab
81,696
import json def load_output(results): """Load json result from broker. """ if results['Code'] == '0': try: var = json.loads(results['Stdout']) except Exception as e: raise Exception('JSON load failed: {}'.format(e)) else: raise Exception('Operation fail...
94959ed37ab58384b21ade5f0e188beff669358e
81,697
from typing import List from typing import Tuple def boundingbox_intersection( box1: List[int], box2: List[int] ) -> Tuple[int, List[int]]: """ Compute the intersection of two bounding boxes. The bounding boxes have the notation [xmin, ymin, XMAX, YMAX]. Args ---- box1: the first...
a42b30ef8fcb32500867fa7c6e92cea2d601c1dd
81,698
from typing import List def find_the_runner_up_score(arr: List[int]) -> int: """ >>> find_the_runner_up_score([2, 3, 6, 6, 5]) 5 """ return sorted(set(arr))[-2]
b1004d86a9e07d5dd55cb683676790fed0957503
81,700
def preconvert_preinstanced_type(value, name, type_): """ Converts the given `value` to an acceptable value by the wrapper. Parameters ---------- value : `Any` The value to convert. name : `str` The name of the value. type_ : ``PreinstancedBase`` instance The pre...
257948a0ebed93dcb8772d74c8378b9f5a42af36
81,701
import logging def run_flushdb(redis_con): """ Purpose: Run Redis FlushDB Command. Will clear all keys and values from the Redis Database (good for clearing cache when redis is used as a caching solution) Args: redis_con (Redis StrictRedi...
7e65b420a827a2204d0f40cb8534ce35c1427ce0
81,704
def storage_method(meth): """ Decorator to mark the decorated method as being a storage method, to be copied to the storage instance. """ meth.storage_method = True return meth
7cb277fd0dca7aa2348e0ca6d173c2e97d1cb589
81,710
def openhand(config,hand,amount): """Opens the hand of the given Hubo configuration config by the given amount. hand is either 'l','r', 'left', or 'right' and amount is in the range [0,1] ranging from closed to open. """ if hand!='left' and hand!='right' and hand!='l' and hand != 'r': raise ...
8b5f1fc930ff37d8626fcceb3a63d73d3fe966c5
81,711
import uuid def generate_molecule_object_dict(source, format, values): """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Opti...
4a917521a2fd5d4f5f5180aa7d5da60aec2cd00a
81,712
def get_all_rpi_info(self): """ Returns dictionary with all available RPI information """ return { 'ip': self.get_rpi_ip(), 'hostname': self.get_rpi_hostname(), 'cpu_temp': self.get_rpi_cpu_temp(), 'usb_devices': self.get_rpi_usb_devices(), 'version': self.get_rpi...
cbfbdbcfe66bcd64222c5853968a35aed71292af
81,714
def num_leading_spaces(text: str, space_char: str = " ") -> int: """Count number of leading spaces in a string Args: text: String to count. space_char: Which characters count as spaces. Returns: Number of leading spaces. """ return len(text) - len(text.lstrip(space_...
1483b8a7fe3905fef354bb71ea25bf741bcc8a5f
81,715
def coerce_enum(value, cls): """Attempt to coerce a given string or int value into an Enum instance.""" if isinstance(value, int): value = cls(value) elif isinstance(value, str): value = cls[value] return value
4eaf7f7a2624d940002c2946cb36d8f92d968ed9
81,727
def drop_columns_by_regex(df, column_regex): """Returns dataframe with columns matching the regex dropped.""" return df[df.columns.drop(list(df.filter(regex=column_regex)))]
ac0fd5f21176fedf6c1c15226173541ba43e0f28
81,732
def attr_val_bool(elem, attr_name): """Returns the boolean value of attribute *attr_name* on element *elem* or None if no such attribute does not exists.""" attr = elem.find_attribute(attr_name) return attr.normalized_value.strip() in ('1', 'true') if attr else None
ce32a9c35939167f52c821dbf752cc285bc468c5
81,735
def clean_accessions(records): """Extract accession keys from SeqRecords. The id of the given records is processed to remove domain location info added by HMMer. Most other records won't have a '/' character in the FASTA header key. """ return (rec.id.rsplit('/', 1)[0] for rec in records)
117c9bbad8278e8aa9ab978439da908648a9c2d2
81,742
import pathlib def get_relative_path_view(file_path: pathlib.Path) -> str: """ make relative path from current path to `file_path` :param file_path: absolute file path :type file_path: pathlib.Path :return: string that represents relative path to `file_path` :rtype: str """ current_pat...
76119de54839ebd3d28910bdf1f74bf0609c2572
81,743
import importlib def _load(name: str): """Load a python object from string. Args: name: of the form `path.to.module:object` """ mod_name, attr_name = name.split(":") mod = importlib.import_module(mod_name) fn = getattr(mod, attr_name) return fn
7a9f615961726b75fe33049881029727b1994dc4
81,746
def select(lstbox, multiple): """Returns the user's selection a Listbox Keyword arguments: lstbox -- Tkinter Listbox Widget multiple -- indicates whether to return a string or a list""" reslist = list() selection = lstbox.curselection() for i in selection: entrada = lstbox.get(i) ...
8bec60a43138785b7cb4d6795d264723ed9ffde0
81,747
def split_into_lines(text,char_limit,delimiters=' \t\n', sympathetic=False): """Split a string into multiple lines with maximum length Splits a string into multiple lines on one or more delimiters (defaults to the whitespace characters i.e. ' ',tab and newline), such that each line...
29d48d0c836528643ac5a3e10f277a0231c2916f
81,749
def is_in(obj, iterable): """ Determine if an obj instance is in a list. Needed to prevent Python from using __eq__ method which throws errors for ndarrays. """ for element in iterable: if element is obj: return True return False
5cd11086ff6e40fb15a6392f4ef5ee6b4822cb2e
81,751
import collections import itertools def part2(lines): """ Analyzing all the possible numbers we get: a b c d e f g ----------------------------------- 0: x x x x x x 1: x x 2: x x x x x 3: x x x...
7eb8a5f67558ebf9514bb9909be67ead5b63f5a5
81,757
from typing import Dict import requests def read_number_from_es(es_host) -> Dict[str, int]: """ Get numbers of records :param es_host: the address where the elastic search is hosted :return: numbers of records in all indices found at the given address """ counts = {} url = f"{es_host}/_cat...
7b1c0259403c398cad527497e988d4f737856eba
81,758
import copy def clean(data): """ This function takes a list of lists as an argument, makes a deep copy of the list, and, within the deep copy, strips strings of trailing whitespece converted and converts numbers to integers. Parameters: data (list): A list of lists, each representing a party'...
cd9cae4400097195adb1f618ebb4739c2496e970
81,761
import re def headers_to_strings(headers, titled_key=False): """Convert HTTP headers to multi-line string.""" return "\n".join( [ "{0}: {1}".format( key.title() if titled_key else key, re.sub( r"Credential=([^/]+)", "C...
8dd64c582c4c6abcb13525406455caf5c4e38547
81,769
def loop_zip(strA, strB): """(str, str) => zip() Return a zip object containing each letters of strA, paired with letters of strB. If strA is longer than strB, then its letters will be paired recursively. Example: >>> list(loop_zip('ABCDEF', '123')) [('A', '1'), ('B', '2'), ('C', '3'), (...
748fb794778d99a2beae644b93e2ee96d2a169a7
81,771
def get_enabled_bodies(env): """ Returns a C{set} with the names of the bodies enabled in the given environment @type env: orpy.Environment @param env: The OpenRAVE environment @rtype: set @return: The names of the enabled bodies """ enabled_bodies = [] with env: for body in env.GetBodies(): ...
ea5a86538edefaacf5b47ea22b9abc3ee87bba81
81,774
def has_loops(path): """Returns True if this path has a loop in it, i.e. if it visits a node more than once. Returns False otherwise.""" for node in path: count = 0 for n in path: if node == n: count +=1 if count > 1: return True return Fal...
2cce551bbc8ffc2de0ac08359ae110a707cb62d3
81,775
from typing import List def lines_to_list_int(lines: str) -> List[int]: """ Transform multi-line integer input to a list. """ return list(map(int, lines.splitlines(keepends=False)))
2436ade0416e89915795abde56462aa58ff1620c
81,776
import csv def parse_mlst_result(path_to_mlst_result): """ Args: path_to_mlst_result (str): Path to the mlst report file. Returns: list of dict: Parsed mlst report. For example: [ { 'contig_file': 'SAMPLE-ID.fa', 'scheme_id': 'ec...
ca7f3972c00da4da4d09494baa3e189742e420ef
81,780
def test_suites(*suite_names): """Decorator that adds the test to the set of suites. Note that the decorator takes in Test instances, so this decorator should be used *above* the @checkers.test decorator (so that the @checkers.test decorator will have already been applied and returned a Test instance.) Args...
56748f5c0f2b9eb1e16ed3ca53036d293d67c733
81,782
def any_non_int_numbers(collection): """Returns true if any numbers in the collection are not integers""" return any(map(lambda n: not isinstance(n, int), collection))
a263dbfb0c7bea528ca3ef2c271e10495bc1acda
81,785
def sort_ipv4_addresses_without_mask(ip_address_iterable): """ Sort IPv4 addresses only | :param iter ip_address_iterable: An iterable container of IPv4 addresses | :return list : A sorted list of IPv4 addresses """ return sorted( ip_address_iterable, key=lambda ...
5aac315ee06e0da0eb0e17704ee623a8ca9f199e
81,786
def remove_from(index, element): """ A wrapper around del element[index]. params: index: the index at which we should delete element: an element that implements __delitem__ """ del element[index] return element
00f7a12867489682129af8ef71236f09957e44cc
81,789
def get_empty_cells(grid): """Return a list of coordinate pairs corresponding to empty cells.""" empty = [] for j,row in enumerate(grid): for i,val in enumerate(row): if not val: empty.append((j,i)) return empty
b853f7f2f8017db0c1d37426b21785b4fa958350
81,793
from pathlib import Path def check_and_create(directory: Path) -> Path: """Create directory if it doesn't exist and return it.""" if not directory.is_dir(): directory.mkdir(parents=True, exist_ok=True) return directory
3fc5dc5476387a2ce37ec6021668d993b9bd667a
81,798
def get_value_of_scoring_none_condition(sc, ml_task): """Updates sc value, if sc is None. Args: sc: str or None. Scoring. The selection criteria for the best model. ml_task: str. Machine learning task. Returns: sc: str. Scoring. The selection criteria for the best model. """ ...
e55d557056f6c078af9ea7d99d502360469d4272
81,802
def _length_of_axis_dimension(root, axis_name): """Get the size of an axis by axis name. Parameters ---------- root : netcdf_file A NetCDF object. axis_name : str Name of the axis in the NetCDF file. Returns ------- int Size of the dimension. """ try: ...
11e0af90d6cd1c9603b14b03fb7df81f10bf25d7
81,804
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
from typing import OrderedDict import json def dump_json(obj, separators=(', ', ': '), sort_keys=False): """Dump object into a JSON string.""" if sort_keys is None: sort_keys = not isinstance(obj, OrderedDict) # Let it sort itself. return json.dumps(obj, separators=separators, sort_keys=sort_keys...
9c800ceee12cbe5b3cf4eda9530b018ecdf22dc8
81,806
import re def fetchthumb(item): """ Get the thumbnail image for an item if possible """ text = item.summary if 'content' in item: text = item.content[0].value # regex to get an image if available thumb_search = re.search('(https?:\/\/[\S]+\.(jpg|png|jpeg))', text, re.IGNORECASE) if thumb_search: retur...
d2bbb9793500b49238e40b583df54816587c1884
81,811
import torch def convert_half_precision(model): """ Converts a torch model to half precision. Keeps the batch normalization layers at single precision source: https://github.com/onnx/onnx-tensorrt/issues/235#issuecomment-523948414 """ def bn_to_float(module): """ BatchNorm...
c899bc0e7f97deb8983794e4ea81ceac2551ec22
81,814
def _isIPv6Addr(strIPv6Addr): """Confirm whether the specified address is an IPv6 address. :param str strIPv6Addr: IPv6 address string that adopted the full represented. :return: True when the specified address is an IPv6 address. :rtype: bool Example:: strIPv6Addr ...
45b330bbd74cc22be467f50f1c8a78c2fb7bdec5
81,815
def get_teams(email_subject): """ Returns the visiting, home teams from email subject line. :param str email_subject: subject line from iScore email :returns: visiting_team, home_team :rtype: str, str """ subject_parts = email_subject.split() return subject_parts[6], subject_parts[8]
c2132841259a154194b9c29e0b11546fb37cf61a
81,819
def _name_to_desc(name): """Convert a name (e.g.: 'NoteOn') to a description (e.g.: 'Note On').""" if len(name) < 1: return '' desc = list() desc.append(name[0]) for index in range(1, len(name)): if name[index].isupper(): desc.append(' ') desc.append(name[index]) ...
af673982a4d790cfa0007da3012ec772b4800806
81,827
import re def re_lines(pat, text, match=True): """Return a list of lines selected by `pat` in the string `text`. If `match` is false, the selection is inverted: only the non-matching lines are included. Returns a list, the selected lines, without line endings. """ assert len(pat) < 200, "It...
aa04cfdbf5dfa2c3aed6d22e3f3671f69ab4481f
81,829
def _trimmed(array, border_size): """Return a view on the array in the border removed""" return array[border_size:-border_size, border_size:-border_size]
63d38e0af7112abe15b5e76b3526b37ee3055c39
81,830
def login(client, username, password): """Simulate a log-in from a user. After the log-in request, the client will be redirect to the expected page. Parameters ---------- client : :class:`flask.testing.FlaskClient` The testing client used for unit testing. username : str The us...
6a595c1d31b0cc331b40bd25d6c6c827ea10fa66
81,838
import random import string def random_hex(length): """ Generate random string from HEX digits """ return ''.join(random.choice(string.hexdigits) for i in range(length))
080145444b30f02578c3b1dbab671aff5141def0
81,839
def is_upside_down_text_angle(angle: float, tol: float = 3.) -> bool: """Returns ``True`` if the given text `angle` in degrees causes an upside down text in the :ref:`WCS`. The strict flip range is 90° < `angle` < 270°, the tolerance angle `tol` extends this range to: 90+tol < `angle` < 270-tol. The ang...
9a964dbfed0fe341b9ccb99a783e8262c0af6ca3
81,849
import ipaddress def get_all_hosts(ipnet): """ Generate the list of all possible hosts within a network Arguments: ipnet -- an IP network address in the form <ip>/subnet such as 192.168.1.0/24 or 69f6:a34:2efb:19ca:d40::/74 Returns: all hosts -- a gener...
c4d78463ed8c3094663d1b4df412fe89a794eee1
81,851
import re def FuzzyFilter(collection, searchInput): """ Fuzzy Filters a defined collection :collection: The collection to filter :searchInput: The input string to fuzzy match :returns: A list of suggestions """ suggestions = [] pattern = '.*?'.join(searchInput) # Converts 'djm' to ...
48f280bf175f45fc9b1c853f8341c431241786ab
81,857
from pathlib import Path def find_package_top(file: Path): """Find package top directory.""" while True: if len(file.parts) == 1: raise ValueError('Package top was not found!') if not file.with_name('__init__.py').exists(): break file = file.parent return fi...
1a065d6b7c68acb93188b187dd91fc6f9a57eeaf
81,859
from datetime import datetime def parse_generalized_datetime(ts): """Parse an ASN.1 generalized datetime string. Currently, only fractionless strings are supported. The result is returned as a datetime object. """ result = None if ts[-1] == "Z": result = datetime.strptime(ts, "%Y%m%d%H...
917b4a67de18f9080bee038b94de6f393d2c84cc
81,864
import unicodedata def normalize_unicodedata(text: str) -> str: """ Applies unicodedata normalization of the form 'NFC'. """ return unicodedata.normalize('NFC', text)
e7f69616d9f5dee067acfb22077cdfdf9e0860d0
81,867
def labeled_point_to_row_col_period(labeled_point): """Helper function to reconstruct period, row, and column of labeled point Used in .map call for predictions Args: labeled_point (LabeledPoint): cell with label and features Returns: tuple (int, int, str): row, col, period """ fe...
e18bd88a8d4a341bec000e0fa250fd7ade69b32b
81,872
def to_slice(idxs): """Convert an index array to a slice if possible. Otherwise, return the index array. Indices are assumed to be sorted in ascending order. """ if len(idxs) == 1: return slice(idxs[0], idxs[0]+1) elif len(idxs) == 0: return idxs stride = idxs[1]-idxs[0] ...
408cd4d0e21abdfb32ef21360cf30af7d973c166
81,878
def GetDescription(key_list, key_count): """Generates a description from readings. We simply add 1) the most general reading and 2) the most specific reading. 1) and 2) are simply approximated by checking the frequency of the readings. Args: key_list: a list of key strings. key_count: a dictionary of ...
c91da52d7b76169ca37df23f3ccda409f4453dad
81,879
def hr_time(seconds): """Formats a given time interval for human readability.""" s = '' if seconds >= 86400: d = seconds // 86400 seconds -= d * 86400 s += f'{int(d)}d' if seconds >= 3600: h = seconds // 3600 seconds -= h * 3600 s += f'{int(h)}h' if se...
5e852331df6db8b9aaa43fa49d709d2f93b68907
81,880
def round_down(dt, timeframe): """Round a datetime object down based on the given timeframe.""" day = 1 if timeframe == "year" else dt.day hour = 0 if timeframe in ["year", "month", "week"] else dt.hour return dt.replace(day=day, hour=hour, minute=0, second=0, microsecond=0)
06f5310a8150a16c6d6b0dbf61190ee31ee4272b
81,881
def warshall(graph): """ Warshall's Algorithm for Shortest Path Complexity: O(V^3) It produces the shortest paths between all the vertices. """ for k in range(len(graph)): for i in range(len(graph)): for j in range(len(graph)): graph[i][j] = min(graph[i][j], ...
c3bff1fa525ee677b9a2c184215832843d4d9ad0
81,885
def sgn(x): """ Return the sign of *x*. """ return 1 if x.real > 0 else -1 if x.real < 0 else 0
d0b937d417d5edcbade7b7e64555d944fcd6c631
81,887
def is_factor_term(obj): """ Is obj a FactorTerm? """ return hasattr(obj, "_factor_term_flag")
7148f0536a4ed0bd5ed724bf18c1228405f0ac3a
81,888
def required_child_amount_rule(model, cr, ca): """ In order for a child resource to select a child activity, a certain amount of child budget is required. A child activity is selected if and only if the provided amount is sufficient. :param ConcreteModel model: :param int cr: child resource :pa...
0a582e4d76cc3a1768de2ba9990c8410ae2ed514
81,890
def _str_len_check(text, min_len, max_len): """ Validate string type, max and min length. """ if not isinstance(text, str): raise ValueError("expected string type") if not (min_len <= len(text) <= max_len): raise ValueError(f"length should be between {min_len} and {max_len} character...
691f3f0083e892fdb3ee8fbe614cc5d8edafa4be
81,891
def convert_voxels_padding(voxels, pad_width): """ Convert the voxels gained before padding to the voxels after padding. (i.e. position at small image -> position at large image). """ dim = voxels.shape[1] new_voxels = voxels.copy() if type(pad_width) == int: pad_width = tuple([p...
182724d7967009de9f7d9a6e6c0c4790d0f73fdb
81,892
def get_drop_path_keep_prob(keep_prob_for_last_stage, schedule, current_stage, num_stages): """Gets drop path keep probability for current stage. Args: keep_prob_for_last_stage: A float, the drop path keep probability for last stage. This flag is used in conjunction with the f...
293a827f6657b86d8099b68c8b26b4a08a7a31dc
81,893
from typing import Dict from typing import Any def validate_result(result: Dict[str, Any]) -> bool: """Validates the result.json file generated by prosecoPlanner.cpp Parameters ---------- results: Dict[str, Any] Loaded result.json file. Returns ------- bool Validity of th...
98cc89046e2bb567705705aef3e713cb50dbac2d
81,894
def _collapse_conformers(molecules): """ Collapse conformers of isomorphic molecules into single Molecule objects. This is useful when reading in multi-conformer SDF files because the SDF reader does not automatically collapse conformers. This function should not modify lists of Molecule objects wh...
d9340cca58a9688c4c68d2d36342c1fc4561e8dc
81,900
def _FormatLogContent(name, content): """Helper function for printing out complete log content.""" return '\n'.join(( '----------- Start of %s log -----------\n' % name, content, '----------- End of %s log -----------\n' % name, ))
23b0f7808f2af63d6aebaa2055fc009d36ff100d
81,901