content
stringlengths
42
6.51k
def pysiphash(uint64): """Convert SipHash24 output to Py_hash_t """ assert 0 <= uint64 < 1 << 64 if uint64 > (1 << 63) - 1: int64 = uint64 - (1 << 64) else: int64 = uint64 uint32 = (uint64 ^ uint64 >> 32) & 4294967295 if uint32 > (1 << 31) - 1: int32 = uint32 - (1 << ...
def is_public_function(function_name): """ Determine whether the Vim script function with the given name is a public function which should be included in the generated documentation (for example script-local functions are not included in the generated documentation). """ is_global_function =...
def gaussian_sum(number: int) -> int: """ Gets the sum of all numbers up to the provided number. E.g. gaussian_sum(5) == sum([1, 2, 3, 4, 5]) :param number: :return: """ return number * (1 + number) // 2
def _flatten_results_with_err(results_with_err): """flatten results with error Args: results_with_err ([(Error, result)]): results with error Returns: (Error, [result]): error, results """ err_msg_list = [] results = [] for idx, (each_err, each_result) in enumerate(results_...
def timestr_to_int(time_str): """ Parse the test time set in the yaml configuration file and convert it to int type """ # time_int = 0 if isinstance(time_str, int) or time_str.isdigit(): time_int = int(time_str) elif time_str.endswith("s"): time_int = int(time_str.split("s")[0]) elif...
def ContentTypeTranslation(content_type): """Translate content type from gcloud format to API format. Args: content_type: the gcloud format of content_type Returns: cloudasset API format of content_type. """ if content_type == 'resource': return 'RESOURCE' if content_type == 'iam-policy': ...
def list_account(account_id): """For a specific account list the subfolders that are available.""" return ['transactions', 'balance']
def str2num(s): """User input is always received as string, str2num will try to cast it to the right type (int or float)""" try: return int(s) except ValueError: pass try: return float(s) except ValueError: # Fallback to the original type return s
def count_digits_recursion(number: int) -> int: """ >>> count_digits_recursion(-123) 3 >>> count_digits_recursion(-1) 1 >>> count_digits_recursion(0) 1 >>> count_digits_recursion(123) 3 >>> count_digits_recursion(123456) 6 """ number = abs(number) return 1 if numb...
def factorial(n: int): """ >>> factorial(5) 120 >>> factorial(4) 24 """ resultado = 1 for i in range(1, n + 1): resultado = resultado * i return resultado
def __parse_request_range(range_header_text): """ Return a tuple describing the byte range requested in a GET request If the range is open ended on the left or right side, then a value of None will be set. RFC7233: http://svn.tools.ietf.org/svn/wg/httpbis/specs/rfc7233.html#header.range Examples: ...
def _calc_resolelement(w, fcol, r, A): """Calculate the resolution element using dw=r*w/A/fcol returns resolution element in mm """ return r * w / A / fcol
def resolve_uri(uri): """ Resolves uri if it's not absolute :param uri: str uri :return: str url """ if not(uri.startswith('http://') or uri.startswith('https://')): return '127.0.0.1%s' % uri else: return uri
def contains_only_char(s, char): """ Check whether a str contains only one kind of chars :param s: str, the string for checking :param char: str, the char for checking :return: """ for c in s: if c != char: return False return True
def scale_relative_risks_for_equivalence(proportions, relative_risks): """ :param proportions: dictionary :param relative_risks: dictionary :return: dictionary """ new_reference_deno = 0.0 for stratum in proportions.keys(): new_reference_deno += proportions[stratum] * relative_risks[...
def lookup_tlv_type(type_id): """Convert TLV type to human readable strings by best guess""" result = 'unknown' if type_id == 0x01: result = 'MAC address' elif type_id == 0x02: result = 'address' elif type_id == 0x03: result = 'software' elif type_id == 0x06: re...
def _to_lowercase(ftype, fname, *_): """Transforms a feature to it's lowercase representation.""" return ftype, fname if fname is ... else fname.lower()
def encode_problem_index(function_idx, dimension_idx, instance_idx): """ Compute the problem index for the bbob suite with 15 instances and 24 functions. """ return instance_idx + (function_idx * 15) + (dimension_idx * 15 * 24)
def mergesort(unsorted_list): """Sort a list.""" if len(unsorted_list) > 1: mid = len(unsorted_list) // 2 left_half = unsorted_list[:mid] right_half = unsorted_list[mid:] mergesort(left_half) mergesort(right_half) i = 0 j = 0 k = 0 while...
def greatest_common_divisor(value1: int, value2: int): """Calcula o maior divisor comum de dois valores""" value1 = abs(value1) value2 = abs(value2) if value1 < value2: value1, value2 = value2, value1 remainder = value1 % value2 if remainder == 0: return value...
def batches(batch_size, features, labels): """ Create batches of features and labels :param batch_size: The batch size :param features: List of features :param labels: List of labels :return: Batches of (Features, Labels) """ assert len(features) == len(labels) output_batches = [] ...
def calc_acc(fn: float, fp: float, tp: float, tn: float) -> float: """ :param fn: false negative miss :param fp: false positive or false alarm :param tp: true positive or hit :param tn: true negative or correct rejection :return: accuracy """ return (tp + tn) / (tp + tn + fn + ...
def get_next_player(players, currentplayer): """Returns the next player in an ordered list. Cycles around to the beginning of the list if reaching the end. Args: players -- List currentplayer -- Element in the list """ i = players.index(currentplayer) + 1 return players[i % len(...
def preprocessing(list_of_tokens, head_indexes_2d): """ Get head indexes only for word-pieces tokenization """ batch_size = len(list_of_tokens) xx = [[]] * batch_size for i in range(batch_size): xx[i] = [0] * len(list_of_tokens[i]) for idx, item in enumerate(h...
def average_dominant_color(colors, mitigate=175, max_margin=140): """This function is used to calculate the dominant colors when given a list of colors There are 5 steps : 1) Select dominant colors (highest count), isolate its values and remove it from the current color set. 2) Set m...
def clean_zip_city(word): """Remove leading comma and line break from zip_city""" return word.lstrip(',').strip()
def get_pandas_df(): """ Gets pandas DataFrame if we can import it """ try: import pandas as pd df = pd.DataFrame except (ModuleNotFoundError, ImportError): df = None return df
def fahrenheit_to_celsius(fahrenheit): """ Convert temperature from Fahrenheit to Celsius PARAMETERS ---------- fahrenheit: float A temperature value in units of Fahrenheit RETURNS ------- celsius: float A temperature value in units of Celsius """ #convert tempe...
def transform_data(scores): """Convert list of dicts to a list of lists""" transformed_data = [list(col) for col in zip(*[d.values() for d in scores])] return transformed_data[0], transformed_data[1]
def get_parent_language(lang): """If the passed language is a variant, return its parent Eg: 1. zh-TW -> zh 2. sr-BA -> sr """ is_language_variant = "-" in lang if is_language_variant: return lang[:lang.index("-")]
def get_vidhost(url): """ Trim the url to get the video hoster :return vidhost """ parts = url.split('/')[2].split('.') vidhost = '%s.%s'%(parts[len(parts)-2],parts[len(parts)-1]) return vidhost
def _c(s,modifier=0,intensity=3,color=0): """ mod ::= 0(reset)|1(bold)|2(faint)|3(italic)|4(underline) int ::= 9(intense fg) | 3(normal bg) clr ::= 0(blk)|1(red)|2(grn)|3(ylw)|4(blu)|5(mag)|6(cyn)|7(wht) """ escape = "\x1b[" reset_modifier = 0 ns = f"{escape}{modifier};{intensity}{color}m...
def bkp_log_all(args_array, server): """Function: bkp_log_all Description: bkp_log_all function. Arguments: (input) args_array (input) server """ status = True if args_array and server: status = True return status
def nextDay(year, month, day): """ Returns the year, month, day of the next day. Simple version: assume every month has 30 days. """ years = year months = month days = day + 1 if days > 30: days = 1 months = month + 1 if months > 12: months = 1 ...
def getTemperature(U_code,y_helium,ElectronAbundance): """U_codes = res['u'] y_heliums = res['z'][:,1] ElectronAbundance=res['ne']""" U_cgs = U_code*1e10 gamma=5/3. kB=1.38e-16 #erg /K m_proton=1.67e-24 # g mu = (1.0 + 4*y_helium) / (1+y_helium+ElectronAbundance) mean_molecu...
def get_data_from_response(response: dict, capture_headers: bool = True) -> dict: """ Capture response data from lambda return """ result = {} if "statusCode" in response: try: result["status_code"] = int(response["statusCode"]) except ValueError: # statusCod...
def get_share_for_user(shares, user): """Gets the share for a specific user. :param shares: iterable of share objects :param user: the user the share is for """ if not shares: return None for share in shares: if share.for_user_id == user.id: return share return...
def niceformat(ret): """ Converts to percentage and format to 1 decimal place """ return round(ret*100,1)
def remove_vibrots(vibrot, modes): """ Removes specified modes from anharmonic constant matrix INPUTS: xmat - anharmonic constant matrix modes - the modes to delete from the matrix (with 1 being the first mode) OUTPUTS: xmat - anharmonic constant matrix with columns and rows deleted for sp...
def int2str(integer): """Representation of an integer as character""" if integer < 26: return chr(integer + ord('a')) elif integer < 52: return chr(integer - 26 + ord('A')) elif integer < 62: return chr(integer - 52 + ord('0')) else: raise ValueError("Invalid integer,...
def contains_non_letters(word): """Helper for :meth:`analyze`""" for char in word: if not char.isalpha(): if not char in ["'", "-"]: return True return False
def pairs(sequence): """Returns the list of pairs that you can create from the sequence. The results are ordered and no duplicates will be included, also, if <a,b> is in the result then <b,a> won't be.""" sequence = sorted(list(set(sequence))) indices = list(range(len(sequence))) return [(sequen...
def DetermineLocaleType(locale_str): """Determines the locale 'type' for a given locale name. Returns: (string) Always one of the following strings, 'world' If the locale name refers to the world. 'country' If the locale name looks like a country ID. 'region' If the locale name ...
def sum_cubes(n): """Sum the first N cubes of natural numbers. >>> sum_cubes(5) 225 """ total, k = 0, 1 while k <= n: total, k = total + pow(k, 3), k + 1 return total
def calc_upsampling_size(input_size: int, dilation: int = 1, tconv_kernel_size: int = 3, tconv_stride: int = 2, tconv_padding: int = 1, output_padding: int = 1) -> int: """ Helper functio...
def _is_interactive(module): """ Decide whether this is running in a REPL or IPython notebook """ return not hasattr(module, '__file__')
def fixName(name): """PMML tag name substitutions to avoid conflicts with Python syntax.""" out = name.replace("-", "_") if out == "True": out = "AlwaysTrue" elif out == "False": out = "AlwaysFalse" elif out == "from": out = "isfrom" return out
def parabolic(f, x): """Quadratic interpolation for estimating the true position of an inter-sample maximum when nearby samples are known. f is a vector and x is an index for that vector. Returns (vx, vy), the coordinates of the vertex of a parabola that goes through point x and its two neig...
def del_fake_nums(intList, step): #8 """ Delete fake numbers added by the fake_nums function (only used in decryption) """ placeToDelNum = [] for index in range(0, len(intList), step+1): placeToDelNum.append(index) newIntList = [item for item in intList] for index in reversed(placeTo...
def log2lin(dlogyl,dlogyu,logy): """ From a given uncertainty in log-space (dex) and the value of y, calculates the error in linear space. Returns a sequence with the lower and upper arrays with errors. """ # Upper error bar dyu=10**logy*(10.**dlogyu-1.) # Lower error bar dyl=-10**logy*(10.**-dlogyl-1.) retur...
def ask_for_continuation(iteration: int) -> bool: """ Ask the user if we can proceed to execute the sandbox. :param iteration: the iteration number. :return: True if the user decided to continue the execution, False otherwise. """ try: answer = input( "Would you like to proc...
def sign(x): """ Returns 1 or -1 depending on the sign of x """ if x >= 0: return 1 else: return -1
def _isleap(year): """Return True for leap years and False otherwise. """ return year % 4 == 0 and (year % 100 !=0 or year % 400 == 0)
def get_first(values: list): """ Function that takes in a list and returns the first value (and the .text attribute if it exists), otherwise returns nothing @param values: list that contains 0-many results @returns: the first item of the list or None """ out=None if len(values) > 0: ...
def format_bytes(size): """ Convert bytes to KB/MB/GB/TB/s """ # 2**10 = 1024 power = 2 ** 10 n = 0 power_labels = {0: 'B/s', 1: 'KB/s', 2: 'MB/s', 3: 'GB/s', 4: 'TB/s'} while size > power: size /= power n += 1 return " ".join((str(round(size, 2)), power_labels[n]))
def pad_key(padname, prefix='pad'): """Redis Pad key generator. Key contains Pad name and prefix. :param padname: redis pad name. :param prefix: redis key prefix. """ return '%s:%s' % (prefix, padname)
def db_to_ascii(field): """ converts an db style atom name to ascii """ field = field.replace('_','-') return field
def get_capped_integer(number, min_value=1, max_value=100): """ A helper function to limit an integer between an upper and lower bound :param number: Number to keep limited :type number: int or str :param min_value: Lowest possible value assigned when number is lower than this :type min_value: ...
def twice_x(x): """Callback to fill the marketing example value.""" return float(x) * 2
def tilted_L1(u, quantile=0.5): """ tilted_L1(u; quant) = quant * [u]_+ + (1 - quant) * [u]_ """ return 0.5 * abs(u) + (quantile - 0.5) * u
def lowercase_term_id(term_key: str) -> str: """Lowercase the term value (not the namespace prefix) Args: term_id (str): term identifier with namespace prefix, e.g. MESH:Atherosclerosis Returns: str: lowercased, e.g. MESH:atherosclerosis """ (ns, val) = term_key.split(":", 1) ...
def get_p2p_scatter_2praw(model): """ Get ratio of variability (sum of squared differences of consecutive values) of folded and unfolded models. """ return model['scatter_2praw']
def is_symbol_included_for_completeness(symbol: str) -> bool: """ Determine whether a symbol is listed for sake of type completeness. """ return symbol.endswith(':completeness')
def test_regions(regions,x,y): """ Determines whether point (x,y) falls within any of regions """ for region in regions: if x > region[0] and x < region[2] and y > region[1] and y < region[3]: return True return False
def get_smallest_divisible_number_brute_force(max_factor): """ Get the smallest divisible number by all [1..max_factor] numbers by brute force. """ number_i = max_factor while True: divisible = True for factor_i in range(1, max_factor+1): if number_i % factor_i > 0: ...
def calculate_fcc_nc(listA, listB): """ Calculates the fraction of common elements between two lists not taking into account chain IDs. Much Slower. """ largest,smallest = sorted([listA, listB], key=len) ncommon = len([ele for ele in largest if ele in smallest]) return (ncommon, ncommon...
def _extra_langs(): """Define extra languages. Returns: dict: A dictionnary of extra languages manually defined. Variations of the ones generated in `_main_langs`, observed to provide different dialects or accents or just simply accepted by the Google Translate Text...
def unquote_wordtree(wtree): """Fold the word tree while removing quotes everywhere. Other expansion sequences are joined as such. """ def unquote(wtree): unquoted = [] if wtree[0] in ('', "'", '"', '\\'): wtree = wtree[1:-1] for part in wtree: ...
def recursive_convert_to_unicode(replace_to_utf): """Converts object into UTF-8 characters ignores errors Args: replace_to_utf (object): any object Returns: object converted to UTF-8 """ try: if isinstance(replace_to_utf, dict): return {recursive_convert_to_u...
def _get_min_and_index(lst): """ Private function for obtaining min and max indicies. """ minval, minidx = lst[0], 0 for i, v in enumerate(lst[1:]): if v < minval: minval, minidx = v, i + 1 return minval, minidx
def rgb_to_hex(r, g, b): """ Convert RGB color to an Hexadecimal representation """ return "%02x%02x%02x" % (r, g, b)
def is_hex(s): """ Test if a string is a hexadecimal in string representation. :param s: The string to test. :return: True if hexadecimal, False if not. """ try: int(s, 16) return True except ValueError: return False
def uniq(iterable, key=lambda x: x): """ Remove duplicates from an iterable. Preserves order. :type iterable: Iterable[Ord => A] :param iterable: an iterable of objects of any orderable type :type key: Callable[A] -> (Ord => B) :param key: optional argument; by default an item (A) is discarded ...
def get_create_indexes_queries(graph_name, backend): """Format all SQlite CREATE INDEXES statements with the name of the RDF graph to insert.""" if backend == "sqlite" or backend == "sqlite-catalog": return [ f"CREATE UNIQUE INDEX IF NOT EXISTS {graph_name}_spo_index ON {graph_name} (subject...
def median(iterable, sort=True): """ Returns the value that separates the lower half from the higher half of values in the list. """ s = sorted(iterable) if sort is True else list(iterable) n = len(s) if n == 0: raise ValueError("median() arg is an empty sequence") if n % 2 == 0: ...
def base40_to_interval_name(base40): """Base40 number to interval name conversion :param base40: Base40 interval number :type base40: int :returns: Interval name :rtype: str **Examples** >>> base40_to_interval_name(46) '+M9' """ direction = '-' if base40 < 0 else '+' octa...
def write(path, data): """Write data to a text file. Args: path (str): Full path to file data (str): File text Returns: int: Number of characters written """ with open(path, 'w') as handle: return handle.write(data)
def translate_country(country_name): """Tries to account for the fact that there's different ways to write the name of the same country, and the slugification alone doesn't not standardise it. Also, it'll be of help to some spanish users. """ translation_dict = { "us": "usa", "unite...
def mask_dotted_from_bits(bits): """Creates a subnet mask string in dotted notation from number of bits.""" assert bits > 0 assert bits <= 32 mask = '0' * 32 mask = mask.replace('0', '1', bits) dot_mask = '%s.%s.%s.%s' % ( int(mask[:8], 2), int(mask[8:16], 2), i...
def collision(state, n): """returns true if boulder collides with alien""" for i in range(n): p=False if state[0:n][i]==state[-n:][i] and state[0:n][i]=='1': return True return False
def example_to_features_predict(input_ids, attention_masks, token_type_ids): """ Convert the test examples into Bert compatible format. """ return {"input_ids": input_ids, "attention_mask": attention_masks, "token_type_ids": token_type_ids}
def get_e_young_nu_poisson(mu, lambda_): """ Get the young's module and the poisson ratio from 2D plane stress Lame coefficients lambda and mu (Note: used formulas in get_lambda_mu and solved for e_young and nu_poisson) Parameters ---------- mu : float, np.float Lame coefficients mu. ...
def split_path(path): """ Splits the text and build a nice import statement from it. Note: only well defined import paths are supported. Not something invalid like '..foo.bar..'. >>> split_path('foo.bar.Batz') ('foo.bar', 'Batz') >>> split_path('..lel') ('..', 'lel') >>> split_path('...
def restructure(transactions): """ Restructure transactions, so that each month every possible positin gets listed, even if its value is zero. transactions: ordered dict of transactions """ all_months = [tr.items() for month,tr in transactions.items()] all_groups_listed = [[x[0] for x in g]...
def pick_attributes(old_dict, attributes, skip_non_existing=True): """ Pick requested key value pairs from a dictionary and return a new dictionary """ new_dict = {} for attribute in attributes: if attribute in old_dict: new_dict[attribute] = old_dict[attribute] elif not ...
def find_possible(key, possible): """ Given a key and a list, find possible matches Right now it just checks for case """ if key in possible: return key possible = [x for x in possible if x.lower() == key] if possible == []: return None return possible[0]
def solution(x, y): """Returns ID that is only present in one of the two lists passed as args Args: x: list of prisoner IDs y: list of prisoner IDs Returns: int value of the additional prisoner ID """ try: a = set(x) b = set(y) except TypeError: ...
def dr_evil(amount): """ >>> dr_evil(10) '10 dollars' >>> dr_evil(1000000) '1000000 dollars (pinky)' >>> dr_evil(2000000) '2000000 dollars (pinky)' """ if amount >= 1000000: return f"{amount} dollars (pinky)" else: return f"{amount} dollars"
def compose(im, y, fns): """ apply a collection of transformation functions fns to images """ for fn in fns: #pdb.set_trace() im, y =fn(im, y) return im if y is None else (im, y)
def _make_particle_visible_svg(text,particles,plidx): """ Takes svg file and makes particle visible at specified file location. """ for particle in particles: lidx = text.find("label=\"%s\""%str(particle+1),plidx) text = text[:lidx]+text[lidx:].replace("display:none","display:...
def hashable(obj): """Convert `obj` into a hashable object.""" if isinstance(obj, list): # Convert a list to a tuple (hashable) return tuple(obj) elif isinstance(obj, dict): # Convert a dict to a frozenset of items (hashable) return frozenset(obj.items()) return obj
def find_secondary_lithology(tokens_and_primary, lithologies_adjective_dict, lithologies_dict): """Find a secondary lithology in a tokenised sentence. Args: tokens_and_primary (tuple ([str],str): tokens and the primary lithology lithologies_adjective_dict (dict): dictionary, where keys are exac...
def args_validity_check(*unknown_args): """ Raise an Error if any args are unrecognized by all the parsers unknown_args: unknown_args1, unknown_args2, ... """ if len(unknown_args) == 1 and len(unknown_args[0]) > 0: return False base_unknown_args = unknown_args[0] for arg in base_unkno...
def new_sleep_summary(timezone, model, startdate, enddate, date, modified, data): """Create simple dict to simulate api data.""" return { "timezone": timezone, "model": model, "startdate": startdate, "enddate": enddate, "date": date, "modified": modified, ...
def popcnt(b): """ Return number of "1" bits set in 'b' """ return len([x for x in bin(b) if x == "1"])
def bessel_fw3d(x, **kwargs): """ Fullwave3D's approximation of the modified zero-order Bessel's function of the first kind. Parameters ---------- x : float Argument of the function. Returns ------- s : float Value of the function. Named identical to fullwave3D. Notes ----- From...
def selection_sort(arr): """ Selection sort repeatedly finds the minimum and moves it to the front """ l = len(arr) if l == 0: return arr for i in range(l): min_i = i for j in range(i+1, l): if arr[j] < arr[min_i]: min_i = j temp =...
def calc_distance(v_i, v_f, a): """ Computes the distance given an initial and final speed, with a constant acceleration. :param: v_i: initial speed (m/s) v_f: final speed (m/s) a: acceleration (m/s^2) :return d: the final distance (m) """ d = (v_...
def _is_ipv6_addr_link_local(ip_addr): """Indicates if a given IPv6 address is link-local""" return ip_addr.lower().startswith('fe80::')
def fibonacci(n: int) -> int: """ Returns n-th Fibonacci number n must be more than 0, otherwise it raise a ValueError. >>> fibonacci(0) 0 >>> fibonacci(1) 1 >>> fibonacci(2) 1 >>> fibonacci(10) 55 >>> fibonacci(-2) Traceback (most recent call last): ... V...