content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def seconds_to_str(value: int) -> str: """Convert seconds to a simple simple string describing the amount of time.""" mins, secs = divmod(value, 60) hours, mins = divmod(mins, 60) if value < 60: return f"{secs} second{'s' if secs != 1 else ''}" elif value < 3600: return f"{mins} min...
64fb7d97ee1a914aa47edce5d478c3c763b11756
387,145
def count_None(seq): """Returns the number of `None` in a list or tuple Parameters ---------- seq : list or tuple input sequence Returns ------- num : integer number of `None` in the sequence """ return sum(i is None for i in seq)
f3d6621175ad60de4a6c9a007d241cad95367064
433,455
def filter_code_block(inp: str) -> str: """Returns the content inside the given Markdown code block or inline code.""" if inp.startswith("```") and inp.endswith("```"): inp = inp[3:][:-3] elif inp.startswith("`") and inp.endswith("`"): inp = inp[1:][:-1] return inp
2ed3eb692d251b526b21f858d4d8e72634f63758
174,146
def payloadDictionary(payload, lst): """creates payload dictionary. Args: payload: String SQL query lst: List of Strings keywords for payload dictionary Returns: dikt: dictionary dictionary using elements of lst as keys and payload a...
2b674dde0cbb8e898d821c28c92f54cab891dbf1
433,898
from datetime import datetime def parse_timestamp(timestamp): """ :param timestamp: float (common timestamp) :return: datetime--object that is computed using the passed timestamp """ dt_object = datetime.fromtimestamp(timestamp) return dt_object
fcf770711cf0c747ae1dfd6004e6b5388707def0
80,414
def calculate_maximum_speedup(n: int, f: float) -> float: """ Utilizes Amdahl's Law to calculate the maximum possible speedup. Parameters ---------- n: int The number of processors on the specific machine. f: float The fraction of the program/code/calculation that must be execut...
6cf320aa95320a9f3e9633c1a93fb0fc5f4b3224
500,414
def parse_time(timestring): """ Given a string of the format YYYY-MM-DDTHH:MM:SS.SS-HH:MM (and optionally a DST flag), convert to and return a numeric value for elapsed seconds since midnight (date, UTC offset and/or decimal fractions of second are ignored). """ date_time = timestrin...
7b4adbe36fbd5fd8f484b1e0b346c9673183e555
613,562
def python_3000_has_key(logical_line): """ The {}.has_key() method will be removed in the future version of Python. Use the 'in' operation instead, like: d = {"a": 1, "b": 2} if "b" in d: print d["b"] """ pos = logical_line.find('.has_key(') if pos > -1: return pos, "W601...
1be1f91c6f52960b138ae05297b0b7f9b5123dc0
645,301
def is_file_format(file_name, file_extensions): """ Checks whether the extension of the given file is in a list of file extensions. :param file_name: Filename to check :param file_extensions: File extensions as a list :returns: True if the list contains the extension of the given file_name """ ...
5d8afd55cb618662e5db9e619252d50cd88a4d81
562,217
def is_leap_year(year): """Returns whether a given year was a leap year""" # "There is a leap year every year whose number is perfectly divisible by four - # except for years which are both divisible by 100 and not divisible by 400." # quoted from Western Washington University # https://www.wwu...
658106b2151bbdd4c126517472ee9c8147a3e8a8
236,598
def variance(rv, *args, **kwargs): """ Returns the variance `rv`. In general computed using `mean` but may be overridden. :param rv: RandomVariable """ return rv.variance(*args, **kwargs)
479175f7c101612ea14cef7caf3c5876c2714987
42,828
def argparse_bool(s): """ parse the string s to boolean for argparse :param s: :return: bool or None by default example usage: parser.add_argument("--train", help="train (finetune) the model or not", type=mzutils.argparse_bool, default=True) """ if not isinstance(s, str): return s ...
3c2c0a45d58fe5aa693647b3023644b8ca1047ad
349,593
def norm_filters(weights, p=1): """Compute the p-norm of convolution filters. Args: weights - a 4D convolution weights tensor. Has shape = (#filters, #channels, k_w, k_h) p - the exponent value in the norm formulation """ assert weights.dim() == 4 return weights.vi...
036c9af69aa2bf930911cdc1775fd0aafd980a93
117,190
import io def is_file_obj(o): """Test if an object is a file object""" return isinstance(o, (io.TextIOBase, io.BufferedIOBase, io.RawIOBase, io.IOBase))
94437b1bd758ae0fcc8a274a7366f01c93c8ee85
80,568
def update_max_depth(depth_node_dict): """ Maximum tree depth update. Input: - depth_node_dict: A map from node depth to node ids as a python dictionary. Output: - max_depth: The maximum depth of the tree. """ max_depth = max(depth_node_dict.keys()) return max_depth
0ab7fd3bfca6f3ea70c374e113adcc3d65b541e0
550,363
def merge_dict_tree(a, b): """Merge two dictionaries recursively. The following rules applied: - Dictionaries at each level are merged, with `b` updating `a`. - Lists at the same level are combined, with that in `b` appended to `a`. - For all other cases, scalars, mixed types etc, `b` replac...
b3822fb59706bad679bd6e9370ad68cbc66039b1
374,045
def _dms2dd(degrees, minutes, seconds): """Helper method for converting degrees, minutes, seconds to decimal. Args: degrees (int): Lat/Lon degrees. minutes (int): Lat/Lon minutes. seconds (int): Lat/Lon seconds. Returns: float: Lat/Lon in...
88a576b47184b274e5ee820238675ce0190a8248
190,621
from dateutil import tz def dt_as_utc(dt): """Convenience wrapper, converting the datetime object dt to UTC.""" if dt is None: return None return dt.astimezone(tz.tzutc())
c148d2dc3d8164324661ff6f4f070c49b6406ac7
57,721
def _label_suffix(label: str, suffix: str) -> str: """Returns (label + suffix) or a truncated version if it's too long. Parameters ---------- label : str Label name suffix : str Label suffix """ if len(label) > 50: nhead = 25 return "".join([label[:nhead], ".....
de2ea748c97af55b96cb81eca47c94ab1f712125
375,965
def wrap_commands_in_shell(ostype, commands): """Wrap commands in a shell :param list commands: list of commands to wrap :param str ostype: OS type, linux or windows :rtype: str :return: a shell wrapping commands """ if ostype.lower() == 'linux': return '/bin/bash -c \'set -e; set -...
abc8a72494e1ed24aefd46f0a7ed7ae79bc97d40
525,359
def concat_name(first_name: str, last_name: str) -> str: """Return new string 'last_name, first_name'.""" return f"{last_name}, {first_name}"
981ab94041f53a5eacda6f0386d30c751fc2c5b4
348,956
def sse_pack(event_id: int, event: str, data: int, retry: str = "2000") -> str: """Pack data in Server-Sent Events (SSE) format.""" return f"retry: {retry}\nid: {event_id}\nevent: {event}\ndata: {data}\n\n"
075d7f58248b72a5835c6b9b65332fbcb799f2a8
689,427
import re def processed_string_data(sentence): """replace " with ' Args: sentence (str): string of characters Returns: str: original string put in "" with all internal " replaced with ' """ return '"{}"'.format(re.sub("\"", "'", sentence))
5e7b3301413b42ab3dbf38d568d5d19736617596
243,670
from bs4 import BeautifulSoup def find_forms(soup: BeautifulSoup): """ Returns a list of forms found on a particular webpage """ return soup.findAll('form')
2e6922b57f33a42d8cbe98c33a8507b26bf4026b
289,240
def impute_loan_term(data): """ Imputes loan term value with the mean loan term. """ data['Loan_Amount_Term'] = data['Loan_Amount_Term'].fillna(data['Loan_Amount_Term'].mean()) data['Loan_Amount_Term'] = data['Loan_Amount_Term']/12 return data
6810360dfb88a54dba1af37287c32c5e3a618a8b
280,345
from typing import List def flatten_list(my_list: List[List]) -> List: """ Flatten a list of list :param l: list of list :return: list """ return [item for sublist in my_list for item in sublist]
0c33e3ca968d3038e13a4949f70e2de5b0f2521a
469,947
def is_reply(tweet: dict): """Return True if the passed tweet is a reply. :param tweet: JSON dict for tweet """ if tweet["tweet"]["in_reply_to_screen_name"]: return True return False
b486eac4c38af91e9972af3799f7c6984082bc41
338,917
def get_vm_resource_id(subscription_id=None, resource_group=None, vm_name=None): """ Return full resource ID given a VM's name. """ return "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Compute/virtualMachines/{}".format(subscription_id, resource_g...
ab6ae0b9142c4ae6ffc228e7adc3fc63acdf44d7
377,310
def recursive_binomial_coefficient(n, k): """Calculates the binomial coefficient, C(n,k), with n>=k using recursion Time complexity is O(k), so can calculate fairly quickly for large values of k. >>> recursive_binomial_coefficient(5,0) 1 >>> recursive_binomial_coefficient(8,2) 28 >>> recu...
07af2d622d91228eb370d6074c43702c10fdede6
665,572
def map_url_to_job_config(url, config_mapping): """Return job name and config of the longest matching URL in the config mapping.""" job_name, job_config = (None, None) match_length = 0 for candidate_url, match in config_mapping.items(): if url.startswith(candidate_url) and len(candidate_url) > m...
3922157307debf5401160aa00dfa42e36d562775
536,397
from networkx import get_edge_attributes def uninformative_prediction(G, required_links): """ Function to predict links in an uninformative manner, i.e., the majority parity. So, if there are more positive links that negative links, then a positive link is predicted and vice-versa Args: G...
6f89b6703f8df7c42c3b03c85efea6b2d4318d81
666,617
def _operation_to_pooling_shape(operation): """Takes in the operation string and returns the pooling kernel shape.""" splitted_operation = operation.split('_') shape = splitted_operation[-1] assert 'x' in shape filter_height, filter_width = shape.split('x') assert filter_height == filter_width return int(...
997dad0b4613c3ca9a3bf21cd54c8b6344758235
382,773
import json import codecs def encode_blob(data): """ Encode a dictionary to a base64-encoded compressed binary blob. :param data: data to encode into a blob :type data: dict :returns: The data as a compressed base64-encoded binary blob """ blob_data = json.dumps(data).encode('utf...
266f0b6440adfae165a9d8d6877a111736e22488
678,060
def _nan_div(numerator, denominator): """Performs division, returning NaN if the denominator is zero.""" return numerator / denominator if denominator != 0 else float('NaN')
e3537b8f1721cddfd6e38e3628f0e19d94d966c9
337,616
def metalicity_jk_v_band(period, phi31_v): """ Returns the JK96 caclulated metalicity of the given RRab RR Lyrae. (Jurcsik and Kovacs, 1996) (3) (Szczygiel et al., 2009) (6) (Skowron et al., 2016) (1) Parameters ---------- period : float64 The period of the star. phi31_v : ...
fddd8e895372a68f1aaf96b4879155adb2cf0a8e
568,909
from operator import truediv def toratio(s): """Converts a pandas series of string to numeric ratios. Parameters -------------- s: pandas.Series of string Returns ---------- panda.Series of float """ return s.apply(lambda x: truediv(*[int(y) for y in x.split('/')]))
14594ea84478d0b2cbd8eab28f6810c628b02464
193,059
def optimal_noverlap(win_name,win_len): """ This function is intended to support scipy.signal.stft calls with noverlap parameter. :param win_name: (str) name of the window (has to follow scipy.signal.windows naming) :param win_len: (int) lenght of the FFT window :return : (int) optimal overlap in po...
d98db08a9e08b6639a38a324799d1141e65b1eb4
19,554
import random def get_random_variant(variants): """ selects a random element from the 'variants' list """ return random.sample(variants,1)[0] # string #return get_1st_variant(variants)
505c098761fda5c0fb66c531dc5ccda4ebeea2e0
325,968
import functools def RequireAuth(handler): """Decorator for webapp2 request handler methods. Only use on webapp2.RequestHandler methods (e.g. get, post, put), and only after using a 'Check____Auth' decorator. Expects the handler's self.request.authenticated to be not False-ish. If it doesn't exist or eval...
edb8f223318d0b22511d6307ed6c35bc83a4ae4a
19,259
from typing import Tuple def __check_for_newline(line: str, pos: int) -> Tuple[bool, int]: """Check if line is newline. Args: line: line. pos: current position. Returns: bool and current position. """ saw_newline = False while pos < len(line) and line[pos].isspace(): if line[pos] == '\n'...
461adcf7d37be95a41df073e474544c1891ae8b3
597,263
import ast def string_to_dictionary(string): """ Converts a dictionary string representation into a dictionary :param string: str :return: dict """ return ast.literal_eval(string)
3024a15ebcb615500bff7f5cc2728e1d71adae04
188,205
import re def stripXML(text): """ Remove XML annotation from a string. """ text = re.sub(r'<[^>]*>', '', text) text = re.sub(r'\s+', ' ', text) text = text.strip() return text
41204d697bd986a51c9b1bf28ac0fae1813b0a33
606,556
def ext_valid_update_path(cursor, ext, current_version, version): """ Check to see if the installed extension version has a valid update path to the given version. A version of 'latest' is always a valid path. Return True if a valid path exists. Otherwise return False. Args: cursor (cursor) ...
68cab905811904d6f8a8421fc409efe7f7e8703f
396,779
def runtime_enabled_function(name): """Returns a function call of a runtime enabled feature.""" return 'RuntimeEnabledFeatures::%sEnabled()' % name
7269952d9a5b2f343e985b6c571a3a8cb896cb15
278,939
def remove_managed_variant(store, managed_variant_id): """Remove a managed variant.""" removed_variant = store.delete_managed_variant(managed_variant_id) return removed_variant
b6e4af712b276d30d7b27ba0210316132fcf8ba4
114,409
from typing import Any import torch def move_to(obj: Any, device: torch.device): """Credit: https://discuss.pytorch.org/t/pytorch-tensor-to-device-for-a-list-of-dict/66283 Arguments: obj {dict, list} -- Object to be moved to device device {torch.device} -- Device that object will be moved to ...
9ed0ee66d2976aa0b17c0c0c060d6f29cf19f03f
110,254
import requests def request_issues(url): """Request issues from the given GitHub project URL. Parameters ---------- url : str URL of GitHub project. Returns ------- response : Response Response data. """ response = requests.get(url) return response
9f33675d687941873d9b401ddd381894b8cdb3e2
668,527
import math def ang_threep(a,b,c): """ Measures the angle formed by three points. The angle goes from 0 to 360. Point 'a' it's the anchord, and the measured angle it's the one that goes from 'b' to 'c' clockwise. """ ang = math.degrees(math.atan2(b[1]-a[1], b[0]-a[0]) - math.atan2(c[1]-a[1], c[0]...
79b449509b83c484f1192c3947563844f1e51a5c
370,594
import math def approx_atmospheric_refraction(solar_elevation_angle): """Returns Approximate Atmospheric Refraction in degrees with Solar Elevation Angle, solar_elevation_angle.""" if solar_elevation_angle > 85: approx_atmospheric_refraction = 0 elif solar_elevation_angle > 5: approx_...
7c447bee72d385113c3e9d749c74e9e5788429e6
162,683
def NeededPaddingForAlignment(value, alignment=8): """Returns the padding necessary to align value with the given alignment.""" if value % alignment: return alignment - (value % alignment) return 0
e7e9cb58fc43b4c249758acf54a49a344c3d8034
600,523
def inner_p_s(u, v): """ Calculate the inner product space of the 2 vectors. """ s = 0 if len(u) != len(v): s = -1 else: for i in range(len(u)): s += u[i]*v[i] return s
cee6fa97ea8604d911985eba67570b6887a42b7e
330,256
def _first_paragraph(doc: str) -> str: """Get the first paragraph from a docstring.""" paragraph, _, _ = doc.partition("\n\n") return paragraph
4d20e54eba1068e76e59d30316aada9d1c600e6d
196,474
def scale_to_range(min_max_old, element, min_max_new=[0, 10]): """Scale element from min_max_new to the new range, min_max_old. Args: min_max_old: Original range of the data, [min, max]. element: Integer that will be scaled to the new range, must be within the old_range. min...
263f08a7247af4feea9f498bd2ac2a129f949556
670,526
def chocolate_feast(n, c, m): """Hackerrank Problem: https://www.hackerrank.com/challenges/chocolate-feast/problem Function that calculates how many chocolates Bobby can purchase and eat. Problem stated below: Little Bobby loves chocolate. He frequently goes to his favorite 5&10 store, Penny Auntie, to b...
be400b13b15fbed6d21a95a7cbc35fd474ed7fb7
60,708
def first_not_none(*args): """Return first item from given arguments that is not None.""" for item in args: if item is not None: return item raise ValueError("No not-None values given.")
009619994339b3e7593cb8343e8d3e2eae959f0b
206,097
def _write_swift_version(repository_ctx, swiftc_path): """Write a file containing the current Swift version info This is used to encode the current version of Swift as an input for caching Args: repository_ctx: The repository context. swiftc_path: The `path` to the `swiftc` executable. ...
55eae8cc8e5aa52ed35d0f3a564372292c2cc664
89,449
def X1X2_to_Xs(X1, X2): """Convert dimensionless spins X1, X2 to symmetric spin Xs""" return (X1+X2)/2.
9938f188d766d7895986b8796bb8eeeafe3b5b7d
29,174
import math def _toexponent(number): """ Formats exponent to PENELOPE format (E22.15) Args: number (Float): Number to format Returns: str: number to PENELOPE format (E22.15) """ if number == 0.0: exponent = 0 else: exponent = int(math.log10(abs(number))) ...
4f17f6c467ad309e372a506d5917cd9ed44c9e0e
540,174
def rotate_point(point: tuple, rotation: int, axis: int) -> tuple: """Rotate the point around the given axis, from the origin. Args: point (tuple): Coordinate tuple in the form (x,y,z) rotation (int): rotation ID. Indicating counter-clockwise rotation. 0 = no rotation, 1...
7d4c259049bd2b797c3e41fe8b84f5300f0c4817
233,812
from typing import Union from typing import Optional from pathlib import Path def check_for_project(path: Union[str, "Path"] = ".") -> Optional["Path"]: """Checks for a Brownie project.""" path = Path(path).resolve() for folder in [path] + list(path.parents): if folder.joinpath("brownie-config.jso...
026ccf715c7dbf9f1e7f3add2d84f7e661996928
674,590
import base64 def _decode(elem): """ Modifies transaction data with decoded version """ elem["tx_result"]["log"] = eval(elem["tx_result"]["log"]) events = elem["tx_result"]["events"] for event in events: for kv in event["attributes"]: k, v = kv["key"], kv["value"] kv[...
06ae1243a0554509fa85742ecc9e388383071055
224,666
def delta_days(t0, t1): """Returns: time from `t0` to `t1' in days where t0 and t1 are Timestamps Returned value is signed (+ve if t1 later than t0) and fractional """ return (t1 - t0).total_seconds() / 3600 / 24
6a4c8a69fe1931454e77d2d684002600ca0525ed
425,273
def cget(mat, *i): """ Returns the column(s) '*i' of a 2D list 'mat' mat: matrix or 2D list *i: columns to extract from matrix NOTE: If one column is given, the column is returned as a list. If multiple columns are given, a list of columns (also lists) is returned """ if len(i) == 1: ...
596e4ae985c55fe3046b84627138668e266e6707
544,857
import random def _random_tiebreak(winners, n=1): """ Given an iterable of possibly tied `winners`, select one at random. """ if len(winners) == 1: return winners else: return random.sample(winners, n)
0d24678a0eea7df9a880dfbdd0fba2d809f78894
226,374
def safe_get(mapping: dict, key, default=None): """ :param mapping: dictionary of key values :param key: key being searched for :param default: default value in case key was not present in the dict :return: default value if the key is not present in the mapping dictionary, else the value in the dict...
e337f82958a0d384b963874298d870ec8e4cb5be
570,563
def get_int(db,key): """ Get integer value from redis database """ value_str = str(db.get(key)) return int(value_str)
b64bb2d74a3e4cc56b467989ee14f9beed47238d
143,404
def harmonic(n): """ Compute the n-th Harmonic number Compute Hn where Hn = 1 + 1/2 + 1/3 + ... + 1/n Parameters ---------- n : int n-th number Returns ------- hn harmonic number """ hn = 0 for i in range(1, n): hn += 1 / i return hn
cd4d870b66b5fc037c3b3c11b3c735e91c476c6b
51,077
import torch def toHWC(bchw : torch.Tensor): """ Converts a tensor in BxCxHxW to BxHxWxC """ return bchw.movedim((0,2,3,1), (0,1,2,3))
2f5c8a915dbef752392edd3d5f7e0e0fd512b813
246,655
import copy def even_spliter(total, inRange=[250, 500]): """ Splits the total into chunks where they are the size inRange ------ total: The value that needs to be split ------ inRange: List(min, max) min: The minimum value the split size needs to be max: The maximum split size befo...
6a0b94de1a1fb25766c09cab51801d8c8c173e42
471,940
def parse_range(entry, valid, default): """ parsing entries entry - value to check default - value if entry is invalid valid - valid range return - entry or default if entry is out of range """ if valid[0] <= entry <= valid[1]: result = entry else: result = default ...
0ddf60748c5b7c53e3861560e0262f6b763e5f7f
546,519
import inspect def get_unbound_fn(method_or_fn): """Return an unbound function from a bound method.""" if inspect.ismethod(method_or_fn): return method_or_fn.__func__ elif callable(method_or_fn): return method_or_fn else: raise ValueError('Expect a function or method.')
b82c279ac419df4278d4da4ec9c4ad903bd92e0b
124,966
def get_time(value): """Get a generic time in second and stored on a float value, with the 2 integer values Arguments: value -- Time to convert: [time sec, time microsecond] Return: float time in second """ return float(value[0]) + float(value[1])*0.000001
003ade1cb06a2f617541474d5e0d60546c786492
534,069
def get_class_def(class_name): """ Returns the definition for the given class name. """ parts = class_name.split('.') module = ".".join(parts[:-1]) mdl = __import__(module, globals=globals()) for comp in parts[1:]: mdl = getattr(mdl, comp) return mdl
e2e7c5bbf808815a5357a40f6d879f5043997cff
335,367
import torch def initial_inducing_points( train_data_loader, feature_extractor, args ): """ Initialises inducing points Shape: num_tasks X num_inducing_points X hidden_size """ inducing_points = [] for batch in train_data_loader: if len(inducing_points) ...
fa0e74cc394d6ea05a89a3dc9906e7d65e79728c
519,820
from typing import Tuple def size2shape(size: int) -> Tuple[int, int]: """convert a plate size (number of wells) to shape (y, x)""" assert size in [384, 1536] return (16, 24) if size == 384 else (32, 48)
81795acc3992ff0d1b8b39997e8d60b19ea43db0
665,401
def get_accuracy(predictions, targets): """ Calculates the accuracy for a set of prediction and targets. predictions Softmax'ed output values of the network. targets One hot target vectors """ accuracy = (predictions.argmax(1).cpu().numpy() == targets.cpu().numpy...
ea53cd79913b08cd10d4f1263890f82c662d1c60
198,020
from typing import Optional from typing import Mapping from typing import Any def _set_dut(tb_params: Optional[Mapping[str, Any]], dut_lib: str, dut_cell: str ) -> Optional[Mapping[str, Any]]: """Returns a copy of the testbench parameters dictionary with DUT instantiated. This method updates the...
763c8e6836bd1bdd9db19648b4c6cbeaf33a7fd4
204,324
def format_value(val): """ A helper function to format fields for table output. Converts nested dicts into multilist strings. """ if isinstance(val, dict): return "\n".join([ f"{k}: {val[k]}" for k in val.keys()]) return val
c42dea3a5687c0ca32e27ddb4ddc2cf86a666d1c
499,580
def case(bin_spec: str, default: str = "nf") -> str: """ Return the case specified in the bin_spec string """ c = default if "NF" in bin_spec: c = "nf" elif "ÞF" in bin_spec: c = "þf" elif "ÞGF" in bin_spec: c = "þgf" elif "EF" in bin_spec: c = "ef" return c
b2fdab5d1a48e1d20c3a561707033970cac55356
16,097
import smtplib def get_email_server(host): """Return an SMTP server using the specified host. Abandon attempts to connect after 8 seconds. """ return smtplib.SMTP(host, timeout=8)
eccc3a2e4bf2ca8a3ea7ca2899876da9a8d464c6
331,885
def oxygen_cost_v(v): """Effectively defines Daniels' pace-power relationship. AKA speed-to-vdot. Assumed to be the same for all runners. Args: v (float): velocity in m/min. Returns: float: oxygen cost to cover distance in mL/kg/min. """ a1 = 0.182258 a2 = 0.000104 c = -4.60 return a1 ...
685ba9c4fdef898f312f2cfbd0aacb374b541ea1
86,720
import json def getProcessedCloudtrailRecords(cloudtrailRecords=None): """ This function accepts the 'Records' portion of a cloudtrail monitoring report as a json object and extracts records to build a valid json string that can be stored in s3 and read by snowflake. The json string will be an...
2b25717d5e63dd1f63bb9fa772d310763c71eb49
198,278
def pixel_color_checker(data, row_index, pixel_index, R, G, B): """ :param data: image data as array :param row_index: index of image row to be checked :param pixel_index: index of pixel to be checked :param R: value (in range [0, 255]) at the R (red) value of the RGB notation :param G: value (i...
c188eca743b67dcf27456b3d7375507f6007f816
51,826
import pathlib def derive_filepath(filepath, append_string='', suffix=None, path=None): """Generate a file path based on the name and potentially path of the input file path. Parameters ---------- filepath: str of pathlib.Path Path to file. append_string: str String to app...
174c439a5285441fcca7902bfd1c542348f6fb3d
681,942
def is_in_list(obj, obj_list): """ Check if obj is in obj_list explicitly by id Using (obj in obj_list) has false positives if the object overrides its __eq__ operator """ for o in obj_list: if(id(o) == id(obj)): return(True) else: return(False)
93676c25d4bb5fd77e1402467c69218c36db554b
141,179
def get_matrix_as_list(matrix): """ Retu9rns the given mamtrix as list of components :param matrix: OpenMaya.MMatrix :return: list(float) """ return [ matrix(0, 0), matrix(0, 1), matrix(0, 2), matrix(0, 3), matrix(1, 0), matrix(1, 1), matrix(1, 2), matrix(1, 3), matrix(2...
d17b81e764c53189037dd4bcd5e59abb03257d77
247,863
def update_max_for_sim(m, init_max, max_allowed): """ updates the current maximal number allowed by a factor :param m: multiplication factor :param init_max: initial maximum chromosome number allowed :param max_allowed: previous maximum chromosome number allowed :return: the current updated maxi...
cf7f662d4bc817328e04ad28b2dfcf853bad9079
148,716
import random def random_from_alphabet(size, alphabet): """ Takes *size* random elements from provided alphabet :param size: :param alphabet: """ return list(random.choice(alphabet) for _ in range(size))
aeb8e4f1609ab799dd2dd6d66b8bf266fcb34f20
673,883
import math def PKCS1(message : int, size_block : int) -> int: """ PKCS1 padding function the format of this padding is : 0x02 | 0x00 | [0xFF...0xFF] | 0x00 | [message] """ # compute the length in bytes of the message length = math.ceil(math.ceil(math.log2(message-1)) / 8) template = "0200" # generate a...
33b65d1a0304f3d205d0fd2e4c52d4675d5b6ca0
100,578
def resample_factor_str(sig_sample_rate_hz: float, wav_sample_rate_hz: float) -> str: """ Compute file string for oversample and downsample options :param sig_sample_rate_hz: input signal sample rate :param wav_sample_rate_hz: wav sample rate; supports permitted_wav_fs_values ...
1f6f1e9b87d45112f47bdb6570b76ee03248cc8a
367,218
import re def _uses_settings(file): """Check if file imports AppSettings class. Returns: bool: True if it does, False otherwise. """ with open(file) as src_file: return bool(re.search('AppSettings', src_file.read()))
f77013b36974e00d75e0a99b0b761a942de6f94b
168,680
def smart_split(line): """ split string like: "C C 0.0033 0.0016 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'" in the list like: ['C', 'C', '0.0033', '0.0016', 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'] """ flag_in = False l_val, val = [], [] for hh in line.s...
7249b6598f93c93ba17f668e5d0554ebae31a100
632,857
from pathlib import Path import hashlib def md5_hash_file(path: Path) -> str: """ Get md5 hash of a file. Args: path (Path): Absolute path or relative to current directory of the file. Returns: str: The md5 hash of the file. """ m = hashlib.md5() with path.open("rb") as ...
de398edd1476bf03cd78a3ddfd3e3c4ce8e14e1e
72,728
import struct def path_pack(data, pack = struct.pack, len = len): """ Given a sequence of point data, pack it into a path's serialized form. [px1, py1, px2, py2, ...] Must be an even number of numbers. """ return pack("!l%dd" %(len(data),), len(data), *data)
b1482633220f7649512d51165789011f1092fb40
516,922
def __m_rs(soup): """ Gets the most read news from the Rolling Stone page :param soup: the BeautifulSoup object :return: a list with the most read news from the Rolling Stone page """ news = [] anchors = soup.find('ol', class_='c-trending__list').find_all('a') for a in anchors: tit...
5142ce2a441a7512f641008cc8755a3a45444d0c
608,152
def perform_PCA_inverse(pca, dataset_pca): """ Transform n-D array to back to original feature space Args: pca (object): Scikit-learn PCA object (n-D array) : n-D NumPy array of transformed dataset Returns: (n-D array) : n-D NumPy array of dataset inversely transformed back to origi...
c3286178e055a869fd98b71fb7a25fcc1c7187a9
199,080
import yaml def get_options(option_fname): """Load options from YAML file""" with open(option_fname) as opt_file: options = yaml.full_load(opt_file) return options
4cdf099b8802e385bb82cc36ad0f404df50e0980
423,293
def parse_arguments(parser): """Read user arguments""" parser.add_argument( "--arxiv_id", type=str, required=True, help="arxiv paper ID to use to produce a new paper", ) args = parser.parse_args() return args
d3c80bf88bdb9e647d890d63f7050555e1940d0f
224,398
import torch import math def pose_error(R0: torch.Tensor, t0: torch.Tensor, R1: torch.Tensor, t1: torch.Tensor): """Compute the rotation and translation error. Adapted from PixLoc (author: Paul-Edouard Sarlin) https://psarlin.com/pixloc/ Args: * R0: The [3 x 3] first rotation matrix. * t0:...
b1079781a3426ded29496bcff02097fb7f0a08ab
686,964
def length(iterable): """ Return number of items in the iterable. Attention: this function consumes the whole iterable and can never return if iterable has infinite number of items. :Example: >>> length(iter([0, 1])) 2 >>> length([0, 1, 2]) 3 """ try: return len(itera...
1c2963290d22b9076d3f8f51dd84e586de711b11
680,171