content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
from typing import Tuple def _get_start_size(d: dict) -> Tuple[int, int]: """Returns a tuple of ints that represent the true start byte and size based on the provided dict. This is a convenience function such that if you have these values in a dictionary with a *StartByte* and *Bytes* keys. Sinc...
a4c5b87000bccca282e31dba2f30da81cedaf150
111,354
def power(base: float, exponent: float) -> float: """ Returns the value of the first argument raised to the power of the second argument. :param base: the base :param exponent: the exponent :return: the value a :sup:b """ return base ** exponent
f80ee99054fb36098e1ac63ae0240eace78a4fc8
111,355
def _match_instname_wo_host(instance_name1, instance_name2): """ Test 2 instance names for equality ignoring the host name. Creates copy to avoid changing input instance names. """ in1 = instance_name1.copy() in2 = instance_name2.copy() in1.host = None in2.host = None return in1 == i...
21d755524ff78d3be023a7aa888d5252a6c9258f
111,364
from pathlib import Path def _represent_path(self, data: Path): """ Serialize a `Path` object to a string. .. warning:: Path("./aaa") serializes to "aaa" :param data: [description] :type data: pathlib.Path """ return self.represent_scalar("tag:yaml.org,2002:str", str(data))
5b9da2c3b849d756a9a895ee85ea4c1f80ac3630
111,367
import time def FORMATTED_TIME(format="[%Y-%m-%d_%H.%M.%S]"): """Return the formatted current time. Args: format (str): The time format. Returns: str: The formatted current time. """ return time.strftime(format,time.localtime(time.time()))
81a7dda3d1e041f647bb61f10e492ad78330aee5
111,368
def tee(*funcs, name=None, doc=None): """Create a function which broadcasts all arguments it receives to a list of "sub-functions". The return value of the tee function is a generator expression containing the return values of the individual sub-functions. T = func.tee(f, g, h) T(x) # equi...
b3c3b7e85844fe9c31255ac2b265c3c2048ffa80
111,370
import json def pretty_json(obj): """Format an object into json nicely""" return json.dumps(obj, separators=(',', ':'), sort_keys=True, indent=2)
028b1de8ddd66c4c9cc4937371d87c62db8fb9d2
111,374
def change_one(pair, index, new_value): """Return new tuple with one element modified.""" new_pair = list(pair) new_pair[index] = new_value return tuple(new_pair)
82f3f29639044bdfdf861cc0c7917cf521ac74aa
111,375
import logging def calculateDelay(fSampling, receptionDelay): """ Calculates delay until signal acquisition starts. :param fSampling: Sampling frequency of DAQ :param receptionDelay: Delay until reception of signals :return: Active delay until acquisition """ logging.info(' Function ...
94023ea66908a41e5d267e6d355535274be3067c
111,377
def __replace_symbols(transcript): """ Replaces Chinese symbols with English symbols. """ transcript = transcript.replace("。", ".") transcript = transcript.replace(",", ",") transcript = transcript.replace("!", "!") transcript = transcript.replace("?", "?") return transcript
e14726736be275321bb4f7112587a5623b7b90ac
111,378
from pathlib import Path def ensure_exists(p: Path) -> Path: """ Helper to ensure a directory exists. """ p = Path(p) p.mkdir(parents=True, exist_ok=True) return p
b64968cd6f4e29a0d44d78da1b27003415731f86
111,379
def calc_data_rate(bands_spectral, bits, cameras, frame_rate, pixels_total): """ Calculate the data rate generated by an imager that may comprise multiple cameras. Returns ------- double : bits per second """ r...
92903108091520f63da26b18d982b151ca44b3be
111,380
def parseprevload(prevload): """ Parses prevload list into readable HTML option objects :param prevload: Array of txt filenames :return: HTML String of <option> objects """ resultstring = '' for f in prevload: resultstring += '<option value="' + f + '">' + f + '</option>' retu...
7bc38596742eee69e89b4cf2bdc0a4f80b6f7c91
111,381
import requests def is_responsive_404(url): """ Hit a non existing url, expect a 404. Used to check the service is up as a fixture. :param url: :return: """ try: response = requests.get(url) if response.status_code == 404: return True except ConnectionError: ...
46a5f869d4e86accaa07dc186e1fe758a49ab312
111,384
def __get_type_CMA(code): """ Get the intensity category according to "Chinese National Standard for Grade of Tropical Cyclones", which was put in practice since 15 June 2006. Reference: http://tcdata.typhoon.org.cn/zjljsjj_sm.html 0 - weaker than TD or unknown 1 - tropical depression...
4b310e3ddb9fc71d16b6026bb2240ca78141503e
111,386
import pathlib def get_directory_contents(path: pathlib.Path): """Iterates through a directory and returns a set of its contents.""" contents = set() for filename in path.glob('**/*'): # Remove the original parent directories to get just the relative path. contents.add(filename.relative_to...
a6e5e8bb2a4894de4b0ef54a1f2f727ec68c86a5
111,393
def gby_count(df, col, col_full_name=False): """ Perform groupby count aggregation, rename column to count, and keep flat structure of DataFrame. Wrapper on pd.DataFrame.groupby """ if col_full_name: col_name = "count_" + col else: col_name = "count" return df.groupby(col...
413dc3b6b74d631c40d2f7e7ade3c8188893efea
111,395
from pathlib import Path def get_file_stem(file: str) -> str: """ Returns file stem :param file: Filename with or without path :return: just the filename without extension """ return Path(file).stem
886525fbfbeb2c93d61a6d25d03b8411f13de9f0
111,399
def canonicalise_message_line(line): """ Given a line known to start with the '%' character (i.e. a line introducing a message), canonicalise it by ensuring that the result is of the form '%<single-space>MESSAGE_IDENTIFIER<single-space>text'. Parameters: line - input line. Known to start with ...
07afdd59035bb68582e0d51e8695231beeaf8169
111,400
def _filter_col8(interval, keys=None): """ Filter the content of last column in interval. Parameters ---------- interval : pybedtools.Interval Interval. keys : list List of keys that should be kept in result. Returns ------- string Filtered content of last c...
80fc16469c17d1165d9162a19188b210ea76204e
111,404
from pathlib import Path from typing import List def search_all_files(directory: Path) -> List[Path]: """ Search all compressed files in a directory Args: directory (Path): Directory to search. Returns: List[Path]: List of files ending in .gz in search directory. """ dirpath ...
a9abb5150da9c5492f3acfd5b61609da889d49f6
111,410
def is_legal_name(val): """ Function to check if a string is a valid column name, attribute name or condition name. These are the characters that have been found to be problematic with these names and the responsible for these anomalies: - " Provokes a db error when handling the templates due ...
9f00393fca0fcd7043a364f692bbbd1a86f3f3a5
111,411
from typing import Counter def most_common(sequence): """Return most common item in sequence.""" return Counter(sequence).most_common(1)[0][0]
f471b3b0197a6d7b85bf7554c2fb733990bcb210
111,412
def get_subdirs(path): """ Returns all the sub-directories under `path`. """ return (item for item in path.iterdir() if item.is_dir())
d7632c27118d53682fab631b3a365a346da793ad
111,419
def remove_toffoli_from_line(local_qasm_line, qubit_1, qubit_2, target_qubit): """ Remove a specific Toffoli gate from a line of qasm. Args: local_qasm_line: The line of qasm qubit_1: The first control qubit of the Toffoli gate qubit_2: The second control qubit target_qubit:...
3bd95d5514af966dddb1f203b43749b51def1646
111,423
def bytes_from_int(x: int): """ Convert integer to bytes """ return x.to_bytes((x.bit_length() + 7) // 8, byteorder='big')
95542506f87cffe21e05032ef5449017dd13732f
111,424
def put_pixel(color: list, pixels: list, w: int, cord: tuple) -> list: """[Put pixel at coordinate] Args: color (list): [color of the pixel] pixels (list): [list of pixels] w (int): [width of the image] cord (list): [tuple of x,y] Returns: list: [list of pi...
a2d8b0a0b52e289f0bbc1fb22f67c1e0483f10de
111,431
def all_identical(seq): """ Return true if all items in seq are identical. """ return len(seq) == 0 or seq.count(seq[0]) == len(seq)
a053564ceef48815ac0910dea768a48e2c824d65
111,433
import click def _validate_ambiguous_command(kwargs): """Validate for conflicting options and suggest a fix.""" msg = ( 'Ambiguous command! You have requested both to delete all' ' {resource}s _and_ to delete {resource}s by layer ID. Please choose' ' only one.' ) if kwargs['del...
3af30b7d819236fa10b2577a2e431659cfa87cd2
111,439
def HMS(secs): """Return tuple of hours, minutes, and seconds given value in seconds.""" minutes, seconds = divmod(secs, 60.0) hours, minutes = divmod(minutes, 60.0) return hours, minutes, seconds
9f0a099392d554a789c5d13483a266ac414807bf
111,447
def number_of_divisors(n): """ Number of divisors of n. >>> number_of_divisors(28) 6 """ cnt = 1 if n > 1: cnt += 1 half = n//2 for i in range(2, half+1): if n % i == 0: cnt += 1 return cnt
dc0c758b480d30335ddf89fcba5d09e40b2683e6
111,451
import requests def get_reg_D_page() -> str: """ pulls the list of recent reg D fillings from the SEC """ list_of_results = "https://www.sec.gov/cgi-bin/current?q1=0&q2=4&q3=D" list_html = requests.get(list_of_results) assert list_html.status_code == 200, "Problem pulling list of reg D filling...
d7db2f99a79a855a1c8c59e67de000e3684081db
111,456
def _fix_links(md): """Change links in markdown to make them work in HTML.""" md = md.replace('(doc/', '(') md = md.replace('.md)', '.html)') return md
ed6f215a7525f8a62b7323417ab8843a142680aa
111,459
def to_wld(mapnik_map, x_rotation=0.0, y_rotation=0.0): """ Generate a World File string from a mapnik::Map.""" extent = mapnik_map.envelope() pixel_x_size = (extent.maxx - extent.minx)/mapnik_map.width pixel_y_size = (extent.maxy - extent.miny)/mapnik_map.height upper_left_x_center = extent.minx + ...
b193fedfdb05fd8b6f46e5b8a603e8a13152d60f
111,460
def make_testitem(nodeid, keywords, location): """Return JSON-serializable test item.""" item = { 'nodeid': nodeid, 'lineno': location[1], # The outcome will be overridden in case of failure 'outcome': 'passed', } if keywords: item['keywords'] = keywords retur...
cfcf0a4233f8ef73cce889cf4b674c47936deb09
111,461
def get_total_num_policies(data): """Returns a dictionary of US state id and the total number of state-level policies as key-value pairs. Parameters: data (list): a list of dictionaries where each dictionary is formed from the data. Returns: state_id_2_policy_counts (dict): a dictionary of...
b36e45e3799cba37e443ec18bddac21e5459b71b
111,464
def truncate_chars_end_word(value: str, max_length: int): """ Truncates a string after a specified character length but does not cut off mid-word. """ if len(value) > max_length: truncd_val = value[:max_length] if value[max_length] != " ": truncd_val = truncd_val[:truncd_...
4348293177e88b5f1bc453431f676c3734217553
111,465
import re def words(text, reg=re.compile('[a-z0-9]+')): """Return a list of the words in text, ignoring punctuation and converting everything to lowercase (to canonicalize). >>> words("``EGAD!'' Edgar cried.") ['egad', 'edgar', 'cried'] """ return reg.findall(text.lower())
ff2ba22c24b6edab6d2beb49ba18e182cc7cd440
111,467
def get_name_for_obj(obj): """Return a 'name' field for an object. Most objects have a field called `name`, so we try this first. If this fails, we try `reference` (for Datafiles) and `synonym` (for Synonyms), otherwise we just return 'Unknown'. """ if "name" in obj.__dict__: return obj.name...
afa09f74d30809c826b39ce4a0973453154f451c
111,471
def number_in_set(c,s): """Function that takes a counter and a set and returns the sum of counts for all items in that set""" return sum(v for k,v in c.items() if k in s)
3f9387e0caf98762a053e6c8ab1dc253203da825
111,473
from typing import Callable import functools from typing import Any import torch def torch_no_grad(func: Callable) -> Callable: """Decorator that runs the decorated function in a context with disabled PyTorch gradient calculations. Disabling gradient calculations is useful for inference time, when you ar...
b2819c3289b34c9704c992b1b9733e7009d1ed06
111,475
def read_excluded(exc_arg): """Read the list of excluded genes.""" if exc_arg is None: return set() f = open(exc_arg, "r") ret = set(x.rstrip() for x in f) f.close() return ret
feaa1d19bc2c5adf3dae108391302825b11f586e
111,477
import base64 def make_pubsub_event(data: str) -> dict: """Make pubsub event dictionary with base64-encoded data.""" b64data = base64.encodebytes(bytes(data, "utf-8")) return {"data": b64data}
a541c6647671efd528c24194449ec72d38e89592
111,478
def partisan_gini(election_results): """ Computes the partisan Gini score for the given ElectionResults. The partisan Gini score is defined as the area between the seats-votes curve and its reflection about (.5, .5). """ # For two parties, the Gini score is symmetric--it does not vary by party. ...
31fbca907e30e55dfe87cab4b524e5e1cff984ab
111,488
import math def l2_distance(data1, data2): """ l2_distance function Find the L2 distance between two data points. Args ---- data1 : np.array pixel array data2 : np.array pixel array Returns ------- Number """ sum = 0 for i in range(len(data1)): ...
e2c88d67783e7812656d1577d04529eb523df368
111,491
def name(obj): """return the object name Using in template: '{{ obj|name }}' """ return obj.__class__.__name__
e35f26f13b04ead1c77444883c80ba55147a3937
111,494
def extract_first_authors_name(author_list): """ Extract first name from a string including list of authors in form Author1; Author2; ...; AuthorN """ return author_list.split(';')[0].split(' ')[0]
95828febeb44357e86e291a912c7ed730aa05769
111,501
def _resolve_yes_no(value): """ Fix for default values other than True or False for click_prompt_yes_no(). :param value: Return value of click.prompt(..., ..., type=click.BOOL) :returns: Returns True/False. """ return True if value in [True, 'True', 1, '1', 'yes', 'y'] else False
4315841791798df5cac7dbda995f27858f948fb4
111,503
def produce_inter_times(timestamps, max_filter=None): """ Produces a list of the ordered timespans in seconds between epoch timestamps. Args: timestamps: list of positive numbers representing epoch time stamps in seconds. Returns: inter_times: list of time i...
e7b91435dd4bfe24cd02f81c759872e9bd4ed359
111,507
def calculate_percentages(counts): """ Given a list of (token, count) tuples, create a new list (token, count, percentage) where percentage is the percentage number of occurrences of this token compared to the total number of tokens. Arguments: counts (list of (str or unicode, int)): tuples...
7f474ac0635da47dda9409e209481c8078e2881f
111,511
def _get_target_service_attr_obj(service_instance, target_attr_name): """ get attribute object, includes validation for 2nd gen shell namespace :param ServiceInstance service_instance: :param str target_attr_name: the name of target attribute. Do not include the prefixed-namespace :return ServiceAtt...
eefc3df77992dbb1a8df4b125dbb367517a0f088
111,515
def _static_vars_(**kwargs): """ Adds static variables to a decorated function Code taken from https://stackoverflow.com/questions/279561/ what-is-the-python-equivalent-of-static-variables-inside-a-function :param kwargs: :return: """ def decorate(func): for k in kwargs: ...
2d426a50678aeb7c6ebb667bd172b11ccfe6e244
111,517
def jumpTable(prefix, *args): """ Return a string consisting of a series of <a href='#prefix-xxx'>xxx</a>. Include <font size='1'></font> around all of it. """ header = "<font size='1'>" sep = "" for table in args: header = header + sep + "<a href='#" + prefix + "-" + table + "'>" + ...
3ed0bed76243b5f0c805ddf331e8d3e67fc162a1
111,519
def factorielle(n): """Fonction récursive qui renvoie la valeur n! = 1 x 2 x 3 x ... x n """ if n == 0: return 1 return n * factorielle(n - 1)
e12a87f9799bd56ee4c18b2f392c32c51a91dbe4
111,521
import pickle def binary_encode(data): """ default binary encoder """ return pickle.dumps(data, 0)
56489ad67e601387e9671cc88dbcb4957140b2e5
111,522
import re def parse_rst_params(doc): """ Parse a reStructuredText docstring and return a dictionary with parameter names and descriptions. >>> doc = ''' ... :param foo: foo parameter ... foo parameter ... ... :param bar: bar parameter ... :param baz: baz parameter ...
be35bdff9ea9aca182b44d3423c4987696e8c2c4
111,523
def _get_alpha(i, n, start=0.4, end=1.0): """ Compute alpha value at position i out of n """ return start + (1 + i)*(end - start)/n
464a5d0388262d77a29593062d55ffc3da220262
111,525
def against_wall(data, pos): """ Get a list of the directions of walls that the snake is adjacent to. """ width = data['board']['width'] height = data['board']['height'] adjacent = [] if pos['x'] == 0: adjacent.append("left") if pos['x'] == width - 1: adjacent.append("right") ...
2a51d433e42d2cb9f13bda1d165027fd33429735
111,528
def dec_to_bin(number): """ Returns the string representation of a binary number. :param number: int, base 10 :return: str, string representation base 2 >>> assert(dec_to_bin(10) == '1010') """ return '{0:b}'.format(number)
421986f99f8777555098287a02add89335ba5619
111,534
def remove_punctuation(text, keep_cash=True): """ Remove punctuation from text. Input ----- text : str Text to remove punctuation from. keep_cash : bool (default True) Whether to remove the dollar sign '$' or not. """ # Define which punctuation to remov...
d882292635c628d7f7c7a00626c5901a7acdf6a3
111,537
def fmt(docstr): """Format a docstring for use as documentation in sample config.""" # Replace newlines with spaces, as docstring contain literal newlines that # should not be rendered into the sample configuration file (instead, line # wrappings should be applied automatically). docstr = docstr.rep...
c6932066135d576b583be497a0075f203ccbdb99
111,539
def getResidInfo(resid, nodes, resExcludes=[]): """ Get the node information for specified protein residue index. Parameters ---------- resid : int protein residue number nodes : pandas dataframe Dataframe in which to translate protein index to node index (indices). resExclu...
74d217896923c3e6ee2a73607df1e01e24502df1
111,540
import math def pixel_coords_zoom_to_lat_lon(PixelX, PixelY, zoom): """Convert pixel coordinates and zoom from Bing maps to lan, lot Parameters ---------- PixelX : int horizontal distance from upper left corner in pixels PixelY : int vertical distance from upper left corner in pix...
b7e338e756ae606c95078d8c6a684e8fa81614be
111,541
def text_compare(one, two): """Compares the contents of two XML text attributes.""" if not one and not two: return True return (one or "").strip() == (two or "").strip()
442db43f4fdeb4d563f38b384a2ffa00cf0233ec
111,544
def uniquifier(seq, key=None): """ Make a unique list from a sequence. Optional key argument is a callable that transforms an item to its key. Borrowed in part from http://www.peterbe.com/plog/uniqifiers-benchmark """ if key is None: key = lambda x: x def finder(seq): seen =...
ab834043538b4207a4b124977c97ba89fa9adcb7
111,547
def get_objects_zsize(L): """Retrieve objects size (2/3D). Args: L (np.array): labelled thresholded image. Returns: list: Z size of every object in the labelled image. """ return [(L == i).astype("int").sum(0).max() for i in range(1, L.max())]
73e8ae27c6338a8659fcd4662d3791ca16d38dc4
111,551
def parse_is_forfeit(d): """ Used to parse whether or not one of the teams forfeited the match. """ return bool("FOR" in d.get("uitslag", ""))
eb5f96e6003df4d656314040c144ccdbd1168f27
111,555
def frozenset_repr(iterable): """ Return a repr() of frozenset compatible with Python 2.6. Python 2.6 doesn't have set literals, and newer versions of Python use set literals in the ``frozenset()`` ``__repr__()``. """ return "frozenset(({0}))".format( ", ".join(map(repr, iterable)) ...
a5074a59f58898cbb42db6fcb827c47034e32acb
111,556
def bytes_from_int(v, pad_to): """Creates little-endian bytes from integer.""" assert v >= 0 return int.to_bytes(v, pad_to, byteorder="little")
04bf58f6e71494e690788bd870fdfc361abe2513
111,559
from typing import List def generate_class(class_type: str, name: str, types: List[str]) -> str: """Generate thrift struct from types >>> print(generate_class("struct", "Foo", ["i64", "optional string", "set<i32> (cpp.ref = 'true')"])) struct Foo { 1: i64 field_1; 2: optional string field_2; ...
6c51f7fcccefaba675a30707dcd1d65b46e85319
111,563
def percent2float(percent): """ Converts a string with a percentage to a float. """ percent = percent.replace(" ", "") percent = percent.strip("%") return float(percent) / 100
059bd0accdf6c3ac249604bb342f523c1825a173
111,569
from typing import Dict from typing import Any def constant() -> Dict[str, Any]: """ Returns: Schema for validating the `constant` block """ data = { "type": "list", "schema": { "type": "dict", "schema": { "name": {"type": "string", "requ...
c82a50e181786ae8e5cad30e4fe131063469077d
111,573
def match_state(exp_state, states): """ Matches state values. - exp_state: A dictionary of expected state values, where the key is the state name, the value the expected state. - states: The state content of the state change event. Returns either True or F...
4cfceb2bbc03c433aefda0e6b2da7c182da57d9e
111,574
import six def str_map(param): """Ensure that a dictionary contains only string values.""" if not param: return {} for k, v in six.iteritems(param): if v is not None and (not isinstance(k, six.string_types) or not isinstance(v, six.string_types)): ...
8f57a0fb3c23796c4f2b2bee7022581bb9435e42
111,576
def compute_empirical_p_value(value, random_values, direction): """ Compute empirical p-value. Arguments: value (float): random_values (array): direction (str): 'less' | 'great' Returns: float: p-value """ if direction == 'less': significant_random_values...
530d3c9f8d6674cdf10680c401657a63ce44f3fa
111,579
def checkValence( k,newgraphs,nodesValence ): """ Returns True if graph k's valence is different from any other new graph's valence, False otherwise. """ for i in newgraphs: # check if valences are equal if nodesValence[k] == nodesValence[i]: return False return True
3877d512e0f305485f4d5606ab048bbb054a33cb
111,580
import math def implied_vol_quadratic_approx( underlying, strike, rate, maturity, option_value): """implied_vol_quadratic_approx calculates implied volatility by Corrado-Miller approximation formula. See Corrado, C. J., & Miller, T. W. (1996). A note on a simple, accurate formula to comput...
6d5d649399878deb7c3018f81ef4528fd462eb4a
111,582
def choose(n, r): """Return number of ways of choosing r items from an array with n items. Parameters ---------- n : int number of items to choose from r : int number of items to choose Returns ------- combinations : int The number if ways of making the choice ...
7eea6484f92c87560ea7f74c43cc688a1f76b9c3
111,585
def get_public_email(user): """ Helper function to return public user email to send emails """ if len(user.get_all_user_emails()) > 0: return next((email for email in user.get_all_user_emails() if "noreply.github.com" not in email), None)
2681833db958bc985017b4446576703c3a91a6e5
111,588
def makeRootRelativePath( env, path ): """ Takes a path relative to the current working directory and converts it to a root-relative path (e.g., a path beginning with a hash symbol). """ return "#%s" % env.Dir( path ).path
2f3d1c2d6f013f685dedef991b1e2df722fabb2c
111,589
def part1(depths): """Count no. of times depth increases""" increase_count = 0 for i in range(1, len(depths)): if depths[i] > depths[i - 1]: increase_count += 1 return increase_count
526a111c1b17da715699d78ebaeb1460223a9129
111,590
def get_nested_attr(obj, attr_name): """Same as getattr(obj, attr_name), but allows attr_name to be nested e.g. get_nested_attr(obj, "foo.bar") is equivalent to obj.foo.bar""" for name_part in attr_name.split('.'): if hasattr(obj, name_part): obj = getattr(obj, name_part) else: ...
32a563ea084ad25dc3017772d3b7eeac0906fc29
111,592
import re def _version_info(module): """Helper function returns a tuple containing the version number components for a given module. """ try: version = module.__version__ except AttributeError: version = str(module) def cast_as_int(value): try: return int(v...
eb82c7d173c1edd31745c65f206ef2b4682ac253
111,603
def accuracy(output, labels): """ Calculate accuracy. Args: output: output of a model. labels: ground truth labels. Returns: float: accuracy score. """ if any([s > 1 for s in labels.shape]): s = output.round() + labels numerator = (s == 2).sum()....
6391fdfd5c585aacd543a64c948424b7d0b07c3f
111,611
import random def get_train_test(percent_train): """Randomly choose test or train label Parameters ---------- percent_train: float the fraction of the training set with respect to the full (training + test) set Returns ------- sample: string 'test' or 'train' set """ ...
9730753decac292076033521fffe62006b10fed2
111,614
def clamp(minimum, value, maximum): """ Clamp the passed `value` to be between `minimum` and `maximum`, including. """ return max(minimum, min(maximum, value))
dd99e9c7b211bcc17c9888afdddc88a9b59cb3df
111,615
def prefix_with(constant, pieces): """ From a sequence create another sequence where every second element is from the original sequence and the odd elements are the prefix. eg.: prefix_with(0, [1,2,3]) creates [0, 1, 0, 2, 0, 3] """ return [elem for piece in pieces for elem in [constant, piece]]
27a1bf59759175cdfbaa647f3788adece2f3f636
111,629
def i2osp(x: int, xlen: int) -> bytes: """ Convert a nonnegative integer `x` to an octet string of a specified length `xlen`. https://tools.ietf.org/html/rfc8017#section-4.1 """ return x.to_bytes(xlen, byteorder='big', signed=False)
e7710a8334631ee6abc402f37e00835b1b0fa50e
111,630
import re def cleanText(t): """ Clean input text :param: t: text string :return: cleaned text """ encoded_string = t.encode("ascii", "ignore") t = encoded_string.decode() t = re.sub(r'(www).*[\s]*', '', t) t = re.sub(r"[^A-Za-z0-9,!?*.;’´'\/]", " ", t) t = re.sub(r"...
efe74e2033db80271344320f91364c5aaa0f1170
111,631
import curses def ensure_terminal_size() -> bool: """Helper method to ensure correct terminal size""" if curses.LINES >= 24 and curses.COLS >= 80: return True return False
4f3b68441d2b8bb7a5d02f8994fea7dc5f26e8ac
111,632
import torch def get_left_right_top_bottom(box, height, width): """ - box: Tensor of size [4] - height: scalar, image hight - width: scalar, image width return: left, right, top, bottom in image coordinates """ left = (box[0] * width).type(torch.int32) right = (box[2] * width).type(tor...
9ecb3fb06203f6b2fe50e83b12da2992473fdc02
111,635
def prepare_numbers(numbers): """Prepares the numbers for the chatbot to interpret. Parameters ---------- numbers : list Numbers that the user has input into the chatbot Returns ------- numb : list List of integers that the chatbot can use to put into the calcul...
3f60538c993e2f544e25ca3b6a988856585284fb
111,636
def incrementalAverageUpdate(avg, sample, sample_number): """ :param avg: the old average :param sample: the new sample to update the average with :param sample_number: the current sample number (#samples observed so far+1) Updates an average incrementally. """ return avg + (sample - avg) ...
09145fcbce6343d341613b813af999bbfd5ee619
111,637
def package_name_from_repo(repository): """ Owner and project from repository. >>> package_name_from_repo('https://github.com/NoRedInk/noredink.git') ('NoRedInk', 'noredink') """ repo_without_domain = repository.split('https://github.com/')[1].split('.git')[0] (owner, project) = repo_witho...
4eef01deb7ee77bfcfef8461eba1ba6402c171fe
111,638
def next_batch(X, y, counter, batch_size): """ Returns the next batch from the preprocessed data Args: X: EEG input data of size [batch_size, window_length, electrodes] y: lables, size [batch_size] counter (int): the batch number Returns: batch of data and corresponding lables """ ...
825693bd088bfec117536461b22b1231bc97fea4
111,639
def textfile_contains(filename, marker): """ Return True if a textfile contains a string. """ try: with open(filename, 'r', encoding='utf8') as file: text = file.read(); if marker in text: return True except Exception as e: print(e) return False
c3cc966441fb65c9b5fbc0efdf56ba0f842f0565
111,642
def check_transaction_threw(client, transaction_hash): """Check if the transaction threw/reverted or if it executed properly Returns None in case of success and the transaction receipt if the transaction's status indicator is 0x0. """ receipt = client.web3.eth.getTransactionReceipt(transaction...
0f6fa3ea236a58a948c634b1dc35f25402ab74e2
111,643
def human_readable_int(x): """ Transforms the integer `x` into a string containing thousands separators. """ assert isinstance(x, int) in_str = str(x) digit_count = len(in_str) out_str = "" for (n_digit, digit) in enumerate(in_str): if (n_digit > 0) and (((digit_count - n_digit) ...
49bd3fbd9be2cebf85c27b178f9683fa19f021d1
111,649
def find_val_in_col(value, column): """ Returns the Row value in which the "value" was found """ for n, cell in enumerate(column): if cell.value == value: return n + 1 return 0
f5f7a1d5276b8b8c765edd069adab346673c0302
111,651
import re def convert_string_to_snake_case(name): """ Converts a string to Snake Case :param name: A string :return: A string in snake case Example use case: - Events from might have custom properties in camelCase like userId, and userEmail - Use this to rename keys to user_id and user_email...
177530486b1e011f625731837773b029a31b14da
111,653