content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def _prefix_keys(results: dict, prefix: str) -> dict: """ Add a prefix to existing keys Args: results (dict): The dictionary of results prefix (str): A string to prefix each key with Returns: dict: The result dictionary with prefixed keys. """ prefixed = {} for key,...
fab96f54b2df8b8aea566049448c05951839c0d5
583,829
import torch def calculate_correct_fan(tensor, mode): """Calculate fan of tensor. Args: tensor (torch.Tensor): Tensor to calculate fan of. mode (str): Which type of fan to compute. Must be one of `"fan_in"`, `"fan_out"`, and `"fan_avg"`. Returns: Fan of the tensor base...
e3329336bd307be48e767d1487a0662c9181ec31
583,835
def PyDict_Size(space, w_obj): """ Return the number of items in the dictionary. This is equivalent to len(p) on a dictionary.""" return space.len_w(w_obj)
a2181edcc341560f7d14fb259c85fabbb5aba573
583,840
def save_name(column): """Remove characters from a string to make it good for saving. Paramters --------- column : string Returns ------- string The column name with special characters removed. """ remove_these = [' (%)', ' (kpc)', ' '] replace_with_these = ['', '', '-'...
f855bcc23b4bc32f0b0bdebd137a1fd45a40b6eb
583,848
import torch def get_translation_matrix(translation_vector): """Convert a translation vector into a 4x4 transformation matrix""" T = torch.zeros(translation_vector.shape[0], 4, 4).to(device=translation_vector.device) t = translation_vector.contiguous().view(-1, 3, 1) T[:, 0, 0] = 1 T[:, 1, 1] = 1 ...
04e225a3132ee02727b82c64f8cb9552e3896693
583,849
def rm_prefix(string, prefix): """ Removes prefix from a string until the new string no longer starts with the prefix. """ while string.startswith(prefix): string = string[len(prefix):] return string
d614b15bea06685c61a37fea4a5da79f008a106b
583,851
def snakecase_to_camelcase(name): """ Convert snake_case to CamelCase """ return "".join([w[0].upper() + w[1:] for w in name.split("_")])
616b849f819d85780e1d18f505914b46154021a7
583,854
def subset_series(df, weights, n: int = 1000, random_state: int = 2020): """Return a sample of time series. Args: df (pd.DataFrame): wide df with series as columns and DT index n (int): number of unique time series to keep, or None random_state (int): random seed """ if n is Non...
215ade1ccbf68eaa1253806c8369f7f4ed6f5ed7
583,858
def closest(a:int, b:int) ->int: """ Return an integer which is closes to b and divisible by a """ b = round(b/a) * a return b
8061467c4fdbd34f612eaa4dd979b5f93b565a8b
583,863
def find_first(collection, predicate): """ Find first element in collection that match predicate. :param collection: Collection to find :param predicate: check predicate :return: First matched element, or None if not found """ for item in collection: if predicate(item): ...
fcadf85684e407048c6f599d78b73dd6800c4ce0
583,865
def get_missing_time_points(dfs): """ Find missing time points for each vegetation dataframe in `dfs`, and return a dict, with the same key as in `dfs`, but with values corresponding to missing dates. Parameters ---------- dfs : dict of DataFrame Time series data for multiple sub-im...
f9611df7b777107e1dc8c10ce5ca59c39286539f
583,871
def get_counts_in_time(counts, seconds=60): """ Split up a list of times (each representing a single count) to get a list containing the number of counts in each interval of the parameter 'seconds'. """ start = counts[0] # The start value of each interval. # Tuple containing lis...
9c714c039364f60d89f260a32d691bb5b3d2858b
583,874
from typing import List import random def generate_random_class_weights(size: int) -> List[float]: """ Generate a list of random class weights of length size. """ class_weights = [random.random() for i in range(size)] total = sum(class_weights) scaled_class_weights = [w / total for w in class_...
33aab067e656287add3121dbab94ad5dbd7d9491
583,875
def is_eval_epoch(cfg, cur_epoch): """Determines if the model should be evaluated at the current epoch.""" return (cur_epoch + 1) % cfg.TRAIN.EVAL_PERIOD == 0 or ( cur_epoch + 1 ) == cfg.OPTIM.MAX_EPOCH
6d799ce2d556db991d726a73e5f36f8d44a4bd0e
583,878
def _SedPairsToString(pairs): """Convert a list of sed pairs to a string for the sed command. Args: pairs: a list of pairs, indicating the replacement requests Returns: a string to supply to the sed command """ sed_str = '; '.join(['s/%s/%s/g' % pair for pair in pairs]) if pairs: sed_str += ';...
1670288782a87ab4de3f78e1e00865fc46d07a8c
583,880
def _job_status(job): """Utility function that returns the status of a job :param job: job json :type job: json :rtype: str """ if 'activeRuns' in job: return "Running" # short circuit will prevent failure elif 'schedules' not in job or not job['schedules']: return "Un...
59c9775391b36315b37653eac1d71176839a7d34
583,883
import torch def cartesian_prod_2d(tensors): """ Returns a tensor of tensors CP, where CP_i,j is the j-th element of the i-th tuple in the cartesian product of given tensors. This differs from torch.cartensian_prod in the case 'tensors' is a single tensor, because in that case torch.cartes...
c94a23deaeb0504c54a4bd513dc039bcf3ac7a82
583,884
import random def _choose_bases(n): """Choose appropriate bases for the Miller-Rabin primality test. If n is small enough, returns a tuple of bases which are provably deterministic for that n. If n is too large, return a mostly random selection of bases such that the chances of an error is less than ...
4d1b8c447667538dda618f667af859856174c054
583,885
def _len(n: int): """Digit length.""" return len(str(n))
4aed2fc65c02b1037d5c049428ec7551c1236a4e
583,892
import functools def authenticated(method): """Decorate with this method to restrict to authenticated user.""" @functools.wraps(method) def wrapper(self, *args, **kwargs): if not self.current_user: self.redirect(self.settings["login_url"]) return else: r...
fad01a4005fdba30b68fa7d2b1256aeb6272cae1
583,896
def convert_csv(csv_white, csv_comma=""): """Convert white-space-delimited CSV to comma-delimited CSV. Args: csv_white: Original CSV file with white space as the delimiter. csv_comma: New CSV file with comma as the delimiter. Default use the same prefix as the original CSV. """ ...
85b77e81b06653f45c58c868a384f5d328fa97de
583,897
def get_test_submission_variant(case_obj): """Returns a test clinvar variant submission object""" variant_subm_obj = { '_id' : "{}_a99ab86f2cb3bc18b993d740303ba27f".format(case_obj['_id']), 'csv_type' : "variant", 'case_id' : case_obj['_id'], 'category' : "snv", 'local_i...
b26d77c223e7a86711118f4ab2e77cb7e4fd96b7
583,898
def bind_twos_complement(val): """ does over/underflows for 32 bit two's complement numbers :param val: :return: """ if val < -2147483648: return val + 4294967296 elif val > 2147483647: return val - 4294967296 return val
ec2225fe396c74bac215c791765409cb1c51cbce
583,899
from typing import Sequence from typing import Iterable import itertools def sliced(seq: Sequence, n: int) -> Iterable[Sequence]: """Yield slices of length *n* from the sequence *seq*. >>> list(sliced((1, 2, 3, 4, 5, 6), 3)) [(1, 2, 3), (4, 5, 6)] If the length of the sequence is not divisib...
c495f17c0954489fe7cedf32c2572497a28261b9
583,900
import mpmath def cdf(x, a, b): """ Cumulative distribution function of the beta distribution. """ if a <= 0 or b <= 0: raise ValueError('The shape parameters a and b must be greater ' 'than 0.') if x < 0: return mpmath.mp.zero if x > 1: return ...
4dd5b0999f7fdb5a4d6face96b5a64e296cf20f1
583,901
import json def index_by_page_id(s): """Pair a dict with a page_id key, pair the page_id with the dict. Args: s: a dict as a JSON document. Returns: a tuple of page_id, and parsed Python dict. """ d = json.loads(s) return (d['page_id'], d)
a960a645d56864edec7c040795e2ae5f71a26bf0
583,902
def get_code_coverage_threshold(cli_arguments, config): """Get the code coverage threshold that can be specified in the config file or via CLI.""" return cli_arguments.code_coverage_threshold or config.get_overall_code_coverage_threshold()
33ae4844a9ad4c56f6c5e2dd08509a6321345a10
583,907
def get_properties_storage(instance: object) -> dict: """ Returns the dictionary into which the managed properties are recorded. If the object has an instance or class attribute named 'properties_storage', the value of this attribute is used as the storage for managed properties, provided that it is a ...
7664de8e8a8d3ef27e2856c80c1e068085b614d5
583,910
def make_age_sex_map(b01001): """Make a map from age and sex to columns in Census table b01001 Generally, you'll want to use the compiled version in age_sex.py """ t = b01001.stacked(add_dimensions=True) t = t[['column', 'sex', 'min_age', 'max_age']].drop_duplicates() as_map = {} for id...
5a5c01532ca3ef8f5f19af4b9d46f6c063f0a0bc
583,914
def chr2num(chrom): """Make chr# #.""" return chrom[3:] if chrom.startswith('chr') else chrom
ed7d880e73c103a74e650b9e2b7307545ba6a6eb
583,916
import math import functools def lcm(*x): """ Returns the least common multiple of its arguments. At least two arguments must be supplied """ if not x or len(x) < 2: raise ValueError("at least two arguments must be supplied to lcm") lcm_of_2 = lambda x, y: (x * y) // math.gcd(x, y) ...
4e0756d8a7af52bd8a87dfa5fc24a27e7217cd80
583,919
import csv def get_csv_data(file_name: str) -> list: """_summary_ Get user data from csv file and return a list of dictionaries. Args: file_name (str): _description_ Returns: list: _description_ List of dictionaries contain the user data. The list is empty if the file is ...
3aac50799f1f4b3e8f5025e363187856aa97e0ab
583,923
def true_color(a, factor=2.5): """ Apply "true color" transformation to ndarray """ return factor*a
c32989d8978238eb29a836677e14affa8f408664
583,925
from typing import Any def select_all(dummy: Any) -> bool: """ Returns True """ return True
86fa134791603024a3fb01ebe20ed5730c5edd65
583,926
import operator as op from functools import reduce def comb(n, r): """n choose r combination function""" r = min(r, n-r) numer = reduce(op.mul, range(n, n-r, -1), 1) denom = reduce(op.mul, range(1, r+1), 1) return numer // denom
24a1b4b2e3a5d2aafea6a8bfe19bb802750495e7
583,928
def list_slit(lst, size=None): """ Function to split range into n sub-ranges, or into m sub-ranges of the size <= size :param lst: range to split :param size: size of a sub-range """ if not size: size = len(lst) return [lst[i:i + size] for i in range(0, len(lst), size)]
abd53d61015ba6458a6dc11b3dfa96e3fb2608a7
583,932
import torch def maybe_cuda(t): """Calls `cuda()` on `t` if cuda is available.""" if torch.cuda.is_available(): return t.cuda() return t
be09e47d2d94522e5a165eff679ca530b668e0d7
583,936
def is_cli_mode(argv): """Use CLI mode if found command line options.""" return len(argv) > 1
2d2e406cdb55171ae6b5296d3a1447e57d1e5dd0
583,937
def recs_to_dict(keyfldname, recs): """Given an iterable of recs and a keyfldname, build and return a dictionary of records""" d = dict() for rec in recs: d[rec[keyfldname]] = rec return d
bf941cfa3abd3cd92128c2fbd6993ea8646d61c5
583,939
def try_import(package, message=None): """Try import specified package, with custom message support. Parameters ---------- package : str The name of the targeting package. message : str, default is None If not None, this function will raise customized error message when import error ...
3ac0e758cba3f31ce80bb6493a04140a4d6a41ac
583,941
import typing def get_table(lines: typing.List, table_name: str) -> typing.List: """ Gets the given Table from OLSR data. :param lines: :param table_name: :return: """ lines = lines[lines.index("Table: " + table_name) + 2:] lines = lines[:lines.index("")] return [line.split("\t") ...
8ca5e54bc6d828d4d48090c4f46a98ff2f9651f5
583,943
import pickle def load_model_str(data_str): """ Loads existing model from data_str Parameters ---------- data_str - pickled representation data of the model Returns ---------- loaded model """ return pickle.loads(data_str)
881079c523757c820d541e2420856a2776b61d74
583,944
def getInvA(A, Anorm): """ Given list A containing renormalized tensor with norm 1 and a list of its norm, return the invariant version of Ainv Parameters ---------- A : list renormalized tensors with norm 1. Anorm : list norm of the tensors Returns ------- Ainv :...
2f31499884e5313429949ab0bd45c7a93c4b6a58
583,946
def _pylong_join(count, digits_ptr='digits', join_type='unsigned long'): """ Generate an or-ed series of shifts for the first 'count' digits. Assumes that they fit into 'join_type'. (d[2] << 2*n) | (d[1] << 1*n) | d[0] """ def shift(n): # avoid compiler warnings for overly large shifts ...
e2dd4c5190ccc1eb96b4052a1ab7772db4c77ffd
583,947
def get_client_ip(environ): """ Naively yank the first IP address in an X-Forwarded-For header and assume this is correct. Note: Don't use this in security sensitive situations since this value may be forged from a client. """ try: return environ["HTTP_X_FORWARDED_FOR"].split(",")[0...
92b6e45b37b2dd52e326a9e85589211745fd5c2d
583,951
def squared_root_normalization_output_shape(input_shape): """ Return the output shape for squared root normalization layer for any given input size of the convolution filter :param input_shape: shape of the input :return: output shape """ return (input_shape[0], input_shape[-1])
3bae379d75fea5c3b521f7ac14fd5f8fa6a2ef8e
583,952
def X_blobs(Xl_blobs): """ X dataset from `Xl_blobs`. """ return Xl_blobs[0]
9e79fb31baed96fa0396497e9299e99f2a7131d2
583,961
def get_procedure_windows(procs, procs_per_window, step_size ): """ Parameters: procedures : an iterable of Syngo objects procs_per_window : an int Returns: a list of lists of Syngo objects, each representing a window and having len of procs_per_window. each list is sorte...
36c6372ba877499b2b319180c15c7cb84c4a3eaa
583,963
def to_camel_case(snake_case_str): """ Returns `snake_case_str` (e.g. `some_str`) in CamelCase (e.g. `SomeStr`). :param snake_case_str: A string in `snake_case` :return: The string in `CamelCase` """ els = [ s[:1].upper() + s[1:] for s in snake_case_str.split("_") ] retu...
8f565919361ceed7cee127e46850688d8093eeb2
583,979
import math def geodetic2cartesian(lat_degrees, lon_degrees, ele_m): """ Compute geodetic coordinates (latitude, longitude, elevation) to Cartesian coordinates. :param lat_degrees: Latitude in degrees (float) :param lon_degrees: Longitude in degrees (float) :param ele_m: Elevation in meters ...
875474ad7aed382a62da1039b05be7029470ef4e
583,981
def _is_essentially_unique(cube, layer, unique_cubes): """Returns `True` if the cube is, so far, essentially unique. In general, a cube is essentially unique in comparison with a collection of cubes if it is not isomorphic to any of the cubes in the collection. A naïve implementation of this function ...
7d0375fae2bfe9bfa0e0cbf02922e79cdecfdb59
583,982
def _formulate_as_vc(G): """Formulate a Vertex Cover ILP given a graph G. Parameters ---------- G : Networkx Graph Graph to formulate the VC ILP from. Returns ------- string ILP in CPLEX LP format. """ # Problem lines lines = [] # Set objective lines.a...
604093e56688d2137069f47ac13edd39a5824a31
583,985
def transcribe(seq): """Transcribes a DNA sequence to RNA. Input: string of A's, T's, G's, and C's Output: string of RNA basd on input DNA. Converts using the following rules: A->U, T->A, G->C, C->G """ rna = '' for letter in seq: if letter == 'A': rna = rna + 'U' ...
087e7bc4f5115b52e71660241516ee3c63d9eec0
583,986
def make_definition(resources, include_sqs): """ Makes a definition for the demo based on resources created by the AWS CloudFormation stack. :param resources: Resources to inject into the definition. :param include_sqs: When True, include a state that sends messages to an Amazon ...
9f577d425aee95a914cc8514b51b637ed965dae0
583,987
def find_image_by_name(images, img_name): """Search the list of registered images for one whose image name is 'img_name'. Return the image if found, otherwise None. """ for img in images: if img['imagename'] == img_name: return img return None
c437afd30ea996b84345b538922864181201baea
583,989
def coms_matrix_to_list(communities_matrix): """Convert an [N, C] communities matrix to a communities list of len [C]. Parameters ---------- communities_matrix : np.ndarray or sp.spmatrix, shape [num_nodes, num_coms] Binary matrix of community assignments. Returns ------- communiti...
c38ceca15836b2f02200dae79e7ac5f4afbeb1c2
583,991
def replace_lines(regexer, handler, lines): """Uses replacement handler to perform replacements on lines of text First we strip off all whitespace We run the replacement on a clean 'content' string Finally we replace the original content with the replaced version This ensures that we retain the cor...
cb5c1ceb135da6677b3cca43e173def34c7cf412
583,993
def normalize_string(string: str) -> str: """ removes trailing or leading whitespace, then converts it to lowercase """ return string.strip().casefold()
9ea80ad5e2ce46aa5beae31baef43e312d3ff785
584,000
def linear(z): """Does not apply any non linearity to output.""" return z
a0fa770ff8e3e9c1df0f544efcb8ed6753589ebd
584,001
from operator import contains from operator import ge from operator import gt from operator import le from operator import lt from operator import eq from operator import ne def arg_comparitor(name): """ :param arg name :return: pair containing name, comparitor given an argument name, munge it and r...
49e316c43d0d2b971dd2ea8cf354c979513ef45f
584,002
def to_unicode(text, encoding='utf-8', errors='strict'): """Force text to unicode""" if isinstance(text, bytes): return text.decode(encoding, errors=errors) return text
dc9968212b33d57fa00587d5f8607222303106ae
584,003
def update_sample_name(sample_name: str): """ Update sample name to remove file name if directory name present e.g. 'dir_name | filename' becomes 'dirname'. """ if "|" in sample_name: return "|".join(sample_name.split("|")[:-1]) return sample_name
fa9052fe8748b0cbce0b46be8983094a1bd08093
584,005
def add_two_numbers(first_number, second_number): """ Params: first_number(int/float): The first number to add second_number(int/float): The second number to add Returns: result(int/float): The added result of two numbers """ result = first_number + second_number return ...
686c6bbd681c668324aea3413ab08300917bb53b
584,006
def remove_punctuation(words): """Remove all punctuations and words that contain punctuations. Parameters ---------- words : string Original word-token list Returns ------- new_words : list of strings List with all remaining word-tokens """ new_words = [] punctuation = ['.', ',', '?', '!', ';', "'...
340eb799ebd2082bede20d2625d88f94d49ae41f
584,009
import six def merge_dict(dict1, dict2): """Merges :obj:`dict2` into :obj:`dict1`. Args: dict1: The base dictionary. dict2: The dictionary to merge. Returns: The merged dictionary :obj:`dict1`. """ for key, value in six.iteritems(dict2): if isinstance(value, dict): dict1[key] = merge...
f587e3690f557967460cd8cf8fc1fa06a0159479
584,010
def mock_parser_none(args): """Return None, mocking get_parsed_context.""" return None
204607a0bf566de3619f42fe90b5015277b4aea3
584,014
def SortCrescent(li, index): """ Argument: - li a list of lists. - index an integer Return: - A sorted list of lists in a crescent order by the elements located at the index position of each list contained in li. """ #ex :[ """""" return(sorted(li, key = lambda x: x[index]))
7b840892b4342de57ae11012a445ca07c781156f
584,015
def visible(filename): """Exclude hidden files""" return not filename.startswith('.')
987c209ba189247241dca3b6b70888283f5eaf9e
584,017
def divide(gdf, left, right): """ Division of 'left' by 'right' Parameters ---------- gdf : GeoDataFrame Input GeoDataFrame left : str, numeric Left column or value in expression right : TYPE Right column or value in expression Returns ------- result : S...
f8cef1e473aa4e178b25b27c7819abfa73c93d5c
584,018
import hashlib def password_to_key(password: str) -> bytes: """Generate a AES Key from password.""" key: bytes = password.encode() for _ in range(100): key = hashlib.sha256(key).digest() return key[:16]
c5931efe2e3830468d1c949ad00ccbf3effbd4ed
584,020
import inspect def function_has_named_argument(f, attr): """ return True if a given function accept a given attribute """ return attr in inspect.getfullargspec(f).args
fe2fc7e6be91750bd6cb92dda22b7291660b1d35
584,026
def allowable_stress_unity_check(sigma, allowable, df=0.72): """Calculate the allowable stress unity check value. Refs: https://en.wikipedia.org/wiki/Permissible_stress_design https://en.wikipedia.org/wiki/Factor_of_safety :param sigma: applied stress level to be checked. :type sigma: float :p...
eb4a7a6e4cef7f2fc6ab9b7dfa610860b533a571
584,031
def beam_efficiency(antenna_solid_angle, beam_solid_angle): """ Fraction of flux in the main beam that registers at the receiver. Kraus, Radio Astronomy, eq. 6-23. This is generally larger than the aperture efficiency by a factor of 1.2 - 1.4. """ return beam_solid_angle/antenna_solid_angle
17de11f9305971e779b4dcc8a4d34eae53bf544b
584,032
from datetime import datetime def calculate_tz_offset(local_time_str, server_datetime_str): """Given a local_time without date and a server_datetime in UTC, calculate the user's timezone offset in minutes. This is not accurate for all cases, but should be approximately correct for the most common ones. ...
79b098ffd6427fc2d5263569e7647d7f4bae6d8b
584,036
import time def curr_datetime() -> str: """ Get current time as formatted string. >>> curr_datetime() '16022021' """ localtime = time.localtime() return time.strftime("%d%m%Y", localtime)
ea0619ac670d7f3317a9a2471710d266382b2277
584,037
import requests import json def cts_brenda_to_kegg(brenda_name, max_requests=3): """ Returns the KEGG id of a compound, from the name on BRENDA. """ cts_response = requests.get('http://cts.fiehnlab.ucdavis.edu/' 'service/convert/Chemical%20Name/' ...
a5190172f445debafe2a2e32ae08865d7f00db3a
584,040
import six def py2_str(c): """Wraps around a class, adding python2 support to __str__ If running under Python 2 then __str__ will discard non-ascii characters and __unicode__ will be added. """ if six.PY2: old_str = c.__str__ def py2_str_wrap(self): return old_str(self...
9b506e3806c83f9e4414abfe19bdc8f8ba3f5464
584,042
def get_results_from_payload(payload): """ SG sometimes returns Lists or one keyed Dicts """ if isinstance(payload, dict): return next(iter(payload.values())) else: return payload
35e6eb1f89cff45744b7edf49238572f1150a428
584,048
import re def get_valid_file_ending(s): """ Modified after: https://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename def get_valid_filename(s): s = str(s).strip().replace(' ', '_') return re.sub(r'(?u)[^-\w.]', '', s) In addition, start and end of file endin...
76cd98ddff301b9fd42374a706527eae9a0666d8
584,049
def last_blocks_that_logged( event_sig='0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' ): """Query that returns blocks, that had `event_sig` log events. You can limit the number of responses by tweaking the `size` parameter of `es.search(...)`. Usage: es.search('ethereum', ...
ed45cf2235f91124a2ad6f5c0f8e49269d385238
584,055
def format_ocean_proximity(raw_df): """ Changes the feature `ocean_proximity` to be lowercase and change the value `<1H OCEAN` to `within_one_hour_ocean` Args: raw_df: pandas data frame object with the raw data from the csv Returns: formatted_df: pandas df object with the `ocean_proximit...
f895b991c2443d3533cde0d9fcb9831d68d211d1
584,057
def get_offset_array_start_and_end(array_length, array_offset, arry_2_lngth=None): """ Usage: array_start, array_end = get_offset_array_start_and_end(array_length, array_offset, arry_2_lngth) single axis boundry in context of offset Args: array_length: image dimension (positi...
1286f1aaeffddeaef6748e39f29e5f45a5eac2e0
584,059
def __create_gh_repo_url(account: str, repo: str) -> str: """ Given an account name and a repo name, returns a cloneable gh repo url. """ return 'https://github.com/' + account + '/' + repo + '.git'
276019ad4951b5ac883206c8ada49a7456580fa7
584,061
import pathlib import gzip def _get_opener(filename: str): """Helper to get the opener type based upon the filename.""" path = pathlib.Path(filename) if not path.is_file(): raise OSError(f'Filename "{filename}" does not exist.') extension = path.suffix if extension == '.gz': opener...
51f51df0a08fd94d26f3aa92cfccd0a62132064e
584,063
def div(a, b): """ Divides two values. Params: a (float) - First value to divide b (float) - Second value to divide Returns: Value a divided by b (float) """ return float(a)/float(b)
f1a6f2a9eae8462995bffdc6b2621a72dabbe4df
584,065
def window(tokens, size: int = 3): """ Generate samples for a window size. Example: ```python >>> window(['a', 'b', 'c', 'd'], size=2) [(['a', 'b'], 'c'), (['b', 'c'], 'd')] ``` Args: tokens: List of tokens size: Window size Returns: List of windowed sample...
82a14ae0f216d3ecb7c4bb56bdd51e9d78899426
584,067
def dict_is_all_none(dict_item: dict) -> bool: """ Test if all dictionary items are None. :param dict_item: A dictionary object to be testes. :return bool: True if all keys have None as value, False otherwise """ for _key, _value in dict_item.items(): if _value is not None: ...
145c055b7a63d6b3c4945dbde5c6a2499b49161c
584,070
def ENDS_WITH(rule_value, tran_value): """Return True if tran_value ends with rule_value Parameters: rule_value: Value from the rule file to check for. tran_value: Value from transaction. Return: bool: Will return true if `tran_value` ends with `rule_value`. """ rule_value ...
06a4439ceb2d8ad268a503de3be172bba4e33bc0
584,071
def class_decode(b): """Decode the data type from a byte. Parameters: b (byte): Byte with the encoded type Returns: str: Name of the decoded data type """ if b == b'\x00': cls = 'float64' elif b == b'\x01': cls = 'float32' elif b == b'\x02': cls = 'bool' ...
4bd7ccf2bf7d4f0892ae3504e02a01cc542b23df
584,074
def is_valid_bbox(rect): """Left/top must be >= 0, W/H must be > 0""" return rect[0] >= 0 and rect[1] >= 0 and rect[2] > 0 and rect[3] > 0
8e0661482172e6ca4fc71ae5596903ece69ff570
584,081
def get_a_cluster(base, cluster_id, expected_status=None, wait_timeout=None): """Utility function that gets a Senlin cluster.""" if expected_status is None: res = base.client.get_obj('clusters', cluster_id) else: base.client.wait_for_status('clusters', cluster_id, expected_status, ...
6176db5da0991c1a5973f3ec155943d8c17edbba
584,082
def create_role_for_computer_reports(api, configuration, api_version, api_exception): """ Creates a role with rights that are appropriate for reading computer properties and assigning policies to computers. :param api: The Deep Security API modules. :param configuration: Configuration object to pass to the...
8e6d9fec0fafb23287d080ef31ee76404d08dcef
584,086
def raw_ops(tasklist): """Convert returned operations to raw operations.""" return [t.raw_task_data() for t in tasklist]
1bc1612b903952200e624aad7171d639d622d560
584,089
def _calculate_simple_heat_index(temp: float, rh: float) -> float: """ Simplified heat index regression, applicable when HI is under 80 """ return 0.5 * (temp + 61.0 + ((temp - 68.0) * 1.2) + (rh * 0.094))
079462e842c5b849ad10bea39fe507ef05863cdf
584,092
import math def similarity(di, dj): """Cos similarity. usage: >>> a = {0:2, 1:1, 2:1} >>> b = {0:1, 2:1} >>> print round(similarity(a, b), 5) 0.86603 """ inds = set(di.keys()) & set(dj.keys()) s = len(set(di.keys()) & set(dj.keys())) if s == 0: return 0.0 up ...
f1347b55a47150ba177b50e1668557b77f78a8e8
584,094
from pathlib import Path def _lines_to_set(path): """ Converts lines from the file in the specified path to set of strings which are lines in the file. Returns empty set when file doesn't exist. """ out = set() if Path(path).is_file(): with open(path) as f: out = set(f.read...
2f2827bf3ff5c5aff044aacbc5ea1e466403ab94
584,100
def _GetPercentageChange(value1, value2): """Returns the percentage change between the specified values.""" difference = value2 - value1 return 0 if value1 == 0 else difference/value1 * 100
987d2cd20456ad5fad72145adecdda96256b9162
584,109
def has_params(data, *args): """ Validates required parameters against an object. :param data: :param args: required parameters :return: """ if not data: return False for a in args: if not a in data: return False v = data[a] if not v or v.issp...
aeff14dcec72dec81945dcff4798ff981ff45ccf
584,110
def call_if(tf, callable, *args, **kwargs): """Call the given callable with the given arguments iff tf is True.""" if tf: return callable(*args, **kwargs)
99ebc5977ca0f864401243f10ab4215b993f338b
584,111
def is_int32(t): """ Return True if value is an instance of an int32 type. """ return t.typecode == "i"
075c87757c0942042a267f3a2acf280209894400
584,112