content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def hash_string(s, is_short_hash=False): """Fowler–Noll–Vo hash function""" if not is_short_hash: h = 14695981039346656037 for c in s: h = ((h ^ ord(c)) * 1099511628211) & 0xFFFFFFFFFFFFFFFF if h == 0: h = 1 # Special case for our application (0 is reserved inter...
c6718943c4a2791e3b336a543099ef4cd5a68335
684,522
import numpy def hexgrid_circle_convert(d, incircle=False): """ Convert between the circumscribe circle and the incircle of a hexagon. Args: d (:obj:`float`): The reference hexagonal diameter. By default this is the circumscribed circle (see ``incircle``). inc...
59fff28b88868b2fb0cbecc3e264cf53ab10c0a7
684,523
import csv def create_mapping(path, src, dest, key_type=None) -> dict: """ Create a dictionary between two attributes. """ if key_type is None: key_type = int with open(path, 'r') as f: reader = csv.DictReader(f) raw_data = [r for r in reader] mapping = {key_type(row[src])...
41c7c9230ffdced8ff8d27d4cf9ea0968febea3d
684,524
import sys def init(vertices, start_vertex): """ Initialization : setting all distances to +infinity except for the starter vertex. """ distances = dict() for vertex in vertices: distances[vertex] = sys.float_info.max distances[start_vertex] = 0. return distances
6e6a2113c803514e09bfba31ee8d754cf99eb0e2
684,525
def set_axis(mode_pl): """Sets Active Axes for View Orientation. Note: Sets indices for axes from taper vectors Axis order: Rotate Axis, Move Axis, Height Axis Args: mode_pl: Taper Axis Selector variable as input Returns: 3 Integer Indicies. """ order = { ...
9f3cd41bc48eb191d1bdb214ddc868fc5698f30b
684,526
import ssl import aiohttp def get_aiohttp(config): """Return a configured AioHttp client. NOTE: this is a convenience function only to reduce boiler plate. Inputs: config: k8s.configuration.Config instance Typically you pass it whatever `k8s.utils.load_config()` returns. Returns...
d5edad16eefaace65bb7d3faec962cbe3c4dc613
684,527
import functools def wrap_boto3_dynamodb_table(table): """Wraps a boto3 dynamodb table to provide some utils table = wrap_boto3_dynamodb_table(boto3.resource("dynamodb").Table("my-table")) """ def ignore_empty_pagination_key_wrapper(fn): @functools.wraps(fn) def wrapper(*args, **kwar...
c390ba65e6240d50fa2b852ac8cc9f11b1172606
684,528
import pickle def load_pickle(pickle_path): """Utility function for loading .pkl pickle files. Arguments --------- pickle_path : str Path to pickle file. Returns ------- out : object Python object loaded from pickle. """ with open(pickle_path, "rb") as f: ...
436496808be87c92fb6e46bcd4e110984ed64c85
684,530
import torch def l2LossMask(pred, gt, mask): """MSE with a mask""" return torch.sum(torch.pow(pred - gt, 2) * mask) / torch.clamp(mask.sum(), min=1)
d9e1e0d595c417095e1ac215f320332e53ba41c7
684,531
def update_params(params, **kwargs): """ Updates a dictionary with the given keyword arguments Parameters ---------- params : dict Parameter dictionary **kwargs : kwargs New arguments to add/update in the parameter dictionary Returns ------- params : dict Up...
2b2b8ccd68885b4f8f26267e13447a07feceffc3
684,532
def init_data(d, form_data): """Init data_input.""" form_data.update(d) form_data['get_snmp_var'] = [x['var'] for x in d['oid']['get']] form_data['walk_snmp_var'] = [x['var'] for x in d['oid']['walk']] form_data['list_option'] = [x['dest'] if type(x) == dict else x fo...
e258e30ad3798a9fccbc59baa09cb7cfc06e0f09
684,533
def model_to_ranges(model: int, channel: int): """Returns current, voltage and resistance (for voltage and current) ranges""" current_ranges = [] voltage_ranges = [] resistor_v_ranges = [] resistor_i_ranges = [] if model == 4110: current_ranges = [1] if channel == 0: ...
c088e9e47770b985418a7782ec3bb20a3011327d
684,534
def odd_coins(coins): """ Filter the coin denominations and retrieve only odd-numbered ones. :param coins list - Possible coin denominations to use. :return list - The odd coin denominations. """ odd_ones = [] for denomination in coins: if denomination % 2 == 1: odd_ones...
e1309257555f560504da5a567a2cc2cb97d3c2f5
684,535
def docker_push_age(filename): """Check when the Docker image was last pushed to Docker Hub.""" try: with open(filename, "r") as handle: return float(handle.read().strip()) except FileNotFoundError: return 0
68432194c3623d9586b7df2f671ff9e722a23e7a
684,536
def split_regions(samples, window, stepsize): """ :param samples: :param window: :param stepsize: :return: """ subsamples = [] # this is just to avoid running over the end # if "gapped" windows are required at some point, # need to check subsamples assert window >= stepsize, ...
9f307e3651dcad5d3aff43e506b246d66555343d
684,537
def naive_derivative(xs, ys): """ naive forward or backward derivative """ return (ys[1]-ys[0])/(xs[1]-xs[0])
1caf45d0a7c9c8a307bb949bf4a73eee63fcd5e5
684,538
def is_triangle(triangle: int): """any tn in triangle sequence is t = ½n(n+1): Solving with quadratic formula reveals n is only an integer if (1+8t) ** 0.5 is an integer and odd""" if int((1+8*triangle)**0.5) == (1+8*triangle)**0.5 and ((1+8*triangle)**0.5)%2 == 1: return True return False
df568b8610b0e2cd99b06e91b0a73e3724e487a9
684,539
def reverse_list(full_list_text): """Returns a numerically ordered list if the list was in reverse order in the article.""" full_list = full_list_text.split('\n') full_list.reverse() full_list = list(filter(None, full_list)) # Filters out empty list elements. return '\n'.join(full_list) + '\n'
dd4d5a5cd97f15136a5b6d1c6fcc0de854a3f61a
684,540
import re def make_write_file_block(content:str, outname:str, directory:str='/usr/local/etc/ehos/'): """ makes a yaml write_file content block Args: content: what to enter as content into the block outname: the filename the yaml points to directory: the directory the yaml points to ...
e1c48cf17f2f1483a2f79d0fe9382215aa8d39b1
684,541
def flatten_dict(a_dict, parent_keys=None, current_parent_key=None): """Given a dict as input, return a version of the dict where the keys are no longer nested, and instead flattened. EG: >>> flatten_dict({"a": {"b": 1}}) {"a.b": 1} NB: The kwargs are only for internal use of the functi...
cdd69b1d5119d83c36266c13c5bec772ae138cb5
684,542
def filter(record): """ Filter for testing. """ return record if record["str"] != "abcdef" else None
cbdbbf519043417308d903c4af2afa7b06d8557b
684,544
def _is_cache_function(func): """Determines if a function is cached or not""" return hasattr(func, "cache_info")
4ac92fba413667f3a91936475eb1a39abc814871
684,545
import os def _source_from_filename(filepath: str) -> str: """Get the source string from a scan filename. Source represents the .tar.gz container which held this file. Args: filepath: 'gs://firehook-scans/echo/CP_Quack-echo-2020-08-23-06-01-02/results.json' Returns: Just the 'CP_Quack-echo-2020...
992a3492a314e9ebf0557ecd2fb7e7c62002e993
684,547
def _validate_timeout(timeout, where): """Helper for get_params()""" if timeout is None: return None try: return int(timeout) except ValueError: raise ValueError('Invalid timeout %s from %s' % (timeout, where))
02d1239e16109cce3ed6a97d637ae46625e7c8fa
684,548
def sns_subscribe(*args): """ Mock requests to the SNS SubscribeURL """ return ''
6664e812ce36be51f718d6e9c8bd7d6bb8ffc6d6
684,549
def sort(source_list, ignore_case=False, reverse=False): """ :param list source_list: The list to sort :param bool ignore_case: Optional. Specify true to ignore case (Default False) :param bool reverse: Optional. Specify True to sort the list in descending order (Default False) :return: The sorted ...
7ece5826c9b99b21fcd5d764a01b0e738fb1ae6c
684,550
import argparse def options(): """Parse program arguments.""" parser = argparse.ArgumentParser() parser.add_argument("-i", "--inputs", default="tcp://127.0.0.1:5558", help="Input enpoints - comma separated list") parser.add_argument("-d", "--directory", default="/tmp/", help="Default directory to writ...
2ec05d03f8f5c712be3ddafe465b7748aad27961
684,552
def get_scene(videoname): """ActEV scene extractor from videoname.""" s = videoname.split("_S_")[-1] s = s.split("_")[0] return s[:4]
150aa651fa799b66c03fd1bc96d18745ffcb8007
684,553
def VtuFieldComponents(vtu, fieldName): """ Return the number of components in a field """ return vtu.ugrid.GetPointData().GetArray(fieldName).GetNumberOfComponents()
9c2c997cf4ec3e417d1b7d2568fa7a2e9aee4e8d
684,554
def get_note_title(note): """get the note title""" if 'title' in note: return note['title'] return ''
55c18473daf98b4a1fc2023a8ffd258b1e9df8bd
684,556
def merge(source, target): """Merge a source dictionary into a target dictionary :param source: source dictionary :param target: target dictionary :return: source merged into target """ for key, value in source.items(): if isinstance(value, dict): # get node or create one ...
813b83fdc749bf3017e2e6cedece7ceb96651d4e
684,557
def get_type_and_tile(erow): """ Trivial function to return the OBSTYPE and the TILEID from an exposure table row Args: erow, Table.Row or dict. Must contain 'OBSTYPE' and 'TILEID' as keywords. Returns: tuple (str, str), corresponding to the OBSTYPE and TILEID values of the input erow....
e2bf59c4b352865a55ce5a8bcaa2499811a92aaa
684,558
import tempfile import subprocess import json import os def extractHeadersJSON(vcfname): """ Extract the VCF header and turn into JSON :param vcfname: VCF file name :return: VCF header in JSON format """ tf = tempfile.NamedTemporaryFile(delete=False) tf.close() vfh = {} try: s...
7f5782bc9958a01e69c26c59d7e7cbad77f95171
684,559
def format_license(license: str) -> str: """ Format license using a short name """ MAX = 21 if len(license) > MAX: license = license[:MAX-3] + '...' return license
4705d80d840edd745ccb21dae02a4e442a9d6333
684,560
def parse_cookies(cookies_list): """Parse response cookies into individual key-value pairs.""" return dict(map(lambda x: x.split('='), cookies_list.split('; ')))
da2280ef4b2b67b9262ccd3b59293ed3faf8add9
684,563
def inject(variables=None, elements=None): """ Used with elements that accept function callbacks. :param variables: Variables that will be injected to the function arguments by name. :param elements: Elements that will be injected to the function arguments by name. """ def wrapper(fn): ...
9b7ad2679acb4e1a3e01b0191d0af96fb88cc2de
684,564
def plur_diff(cardinality: int, singular: str, plural: str): """Pluralises words that change spelling when pluralised.""" return f"{cardinality} {plural if cardinality - 1 else singular}"
8043eac937bb3f5d8dd02f7b0b4f989fb41cf8b3
684,565
def increment(number): """Increases a give number by 1.""" return number + 1
030bbc9452e7c4d56fc29fcc53aadcf4a2ae6835
684,566
from typing import List from typing import Tuple def three_variables_large_mean_differences() -> List[Tuple[Tuple[float, float, float], float]]: """Each entry represents three random variables. The format is: ( (mean1, mean2, mean3), covariance_scale ) and covariance scale controls how...
047f544dd15196bcb0494098451fc4f9c9edfc87
684,567
def variable_names(): """ :return: """ agonise = 1 labour = 2 cypher = 3 return agonise + labour + cypher
65e7e5fc251385a18f0a6cbff0543fa7ad1c0855
684,568
import os def read_program(filename: str) -> str: """Read program from file""" filepath = os.path.dirname(__file__) with open(os.path.join(filepath, "..", "programs", filename), "r") as f: return f.read()
817a71fc5b5e0dcd6346f1079859cca5bbce6b76
684,569
def getColor(val, minval, maxval): """ Convert val in range minval..maxval to the range 0..120 degrees which correspond to the colors Red and Green in the HSV colorspace. """ h = (float(val-minval) / (maxval-minval)) * 120 return str(h/360)+' 1.000 1.000' # r, g, b = hsv_to_rgb(h/360, 1.,...
ef6aa09d8379d076a3526485fcc84786efc0de4b
684,570
def pivot_genres(df): """Create a one-hot encoded matrix for genres. Arguments: df -- a dataFrame containing at least the columns 'movieId' and 'genre' Output: a matrix containing '0' or '1' in each cell. 1: the movie has the genre 0: the movie does not have the genre """ r...
ecf2754b0d1504cb207be04798d1bf3cd315c9d6
684,571
def check_error(http): """ Checks for http errors (400 series) and returns True if an error exists. Parameters ---------- http : addinfourl whose fp is a socket._fileobject Returns ------- has_error : bool """ err = http.code if 400<= err < 500: print("HTTP error {}...
20ba1426758e68b196708ec3260ff1f3a86c2820
684,573
def bproj(M, P): """Project batched marices using P^T M P Args: M (torch.tensor): batched matrices size (..., N, M) P (torch.tensor): Porjectors size (..., N, M) Returns: torch.tensor: Projected matrices """ return P.transpose(1, 2) @ M @ P
5334ed8c045ade690aad954663edd2ef0dbc561c
684,574
def is_sequence(nums): """Return True if a set of numbers is sequential i.e. 8, 11, 14, 17.""" nums = sorted(list(nums)) if len(nums) < 3: return False while nums: first_difference = nums[1] - nums[0] second_difference = nums[2] - nums[1] if first_difference != second_di...
a824f7f890040178c6df1ba8c1c67b26069258ca
684,575
import os def stamp_contents_match(stamp_file, stamp_contents): """Return True is stamp_file exists and contains the given contents.""" if not os.path.exists(stamp_file): return False with open(stamp_file) as f: return f.read() == stamp_contents
e2312aee04aecb90712fd5083d00ba87d6366fba
684,577
import hmac from hashlib import sha1 def verify(git_hash: str, local_key: str) -> bool: """verifies that git string is the same as the local string""" local_hash: str = "sha1=" + hmac.new(str.encode(local_key), digestmod=sha1).hexdigest() return hmac.compare_digest(git_hash, local_hash)
a5fae6a9901cf7e649805e7cac2df47aaa1a6b41
684,578
def PickUpTextBetween(text,startstr,endstr): """ Pick up lines between lines having "stratstr" and "endstr" strings :param str text: text data :param str startstr: start string :param str endstr: end string :return: text list :rtype: lst """ rtext=""; start=False for ss in text:...
c92cec3f445110a011dc1b885e1161ceb71d2342
684,579
def partition(s): """Returns: a list splitting s in two parts The 1st element of the list consists of all characters in even positions (starting at 0), while the 2nd element is the odd positions. Examples: partition('abcde') is ['ace','bd'] partition('aabb') is ['ab', 'ab'] Pa...
fa144a6a36d2673a38bc2d857759d50e9aec58cd
684,580
import shutil def get_disk_space(destination: str): """Obtain size of free disk space. :param destination: folder to check """ _, _, free = shutil.disk_usage(destination) return free
f3f43a1063c4962999a0af35ab015d633bd674cf
684,582
from typing import Set from pathlib import Path import yaml def _ci_patterns() -> Set[str]: """ Return the CI patterns given in the CI config file. """ repository_root = Path(__file__).parent.parent ci_file = repository_root / '.github' / 'workflows' / 'ci.yml' github_workflow_config = yaml.sa...
e91289fb6e365f4d185e9c5bf650992cba7c74dd
684,583
import os def _infra_enabled(): """ This function returns whether to send info to New Relic Infrastructure. Enabled by default. """ return os.getenv("INFRA_ENABLED", "true").lower() == "true"
b6723ce5f923d211242fba361983bc4e86096d8a
684,584
def get_center(bounds): """ Returns given element center coords:: from magneto.utils import get_center element = self.magneto(text='Foo') (x, y) = get_center(element.info['bounds']) :param dict bounds: Element position coordinates (top, right, bottom, left) :return: x and y co...
050734d661b5cee6efcbd81407d08405123cdbad
684,585
def josephus_bitwiseVer3_1(n): """ n = 2^m + l f(1) = α f((bm bm-1 bm-2 ... b2 b1 b0)2) = (α βbm-1 βbm-2 ... βb1 βb0)2 α=1, β=-1, γ=1 verified based on Ver3 using shift operation to get βbi, i=0,1,2,...,m aming at more general expression and readable """ result = 0 if n != 0: ...
297853295a8ccf54364cfe3c8cedb2911688076e
684,586
def check_kwargs(input_kwargs, allowed_kwargs, raise_error=True): """Tests if the input `**kwargs` are allowed. Parameters ---------- input_kwargs : `dict`, `list` Dictionary or list with the input values. allowed_kwargs : `list` List with the allowed keys. raise_error : `bool...
6d65e6f4b3f64e8ee1903b32907adb99e3bcf7df
684,587
import os def pkg_path(filename): """Returns a path for given rpm in fixture""" return os.path.join(os.path.dirname(__file__), '..', 'fixtures', filename)
f43b2f2adc3ba9b9e0280655e132ddcc9e04293d
684,588
def _get_new_training_session_class(): """ Returns a session manager class for nested autologging runs. Examples -------- >>> class Parent: pass >>> class Child: pass >>> class Grandchild: pass >>> >>> _TrainingSession = _get_new_training_session_class() >>> with _TrainingSessio...
1247d76bb5c23089ae2e1c8f0a7d8e55ca6422e9
684,589
def _optimize_ir(ctx, src): """Optimizes an IR file. The macro creates an action in the context that optimizes an IR file. Args: ctx: The current rule's context object. src: The source file. Returns: A File referencing the optimized IR file. """ entry = ctx.attr.entry ar...
3d236c538afa3584b85de8574873eb34dbda4aa5
684,590
import re def split_keystring_into_keycodes(keystring): """ Breaks str into individual keycodes. Returns a list of keycode strings. """ # prepare to break keystring into keycodes cmdedit = keystring # separate tokens with | chars... cmdedit = re.sub(r'\+\{Enter\}', '|@|', cmdedit) ...
d62447bb06b1bb2c5f9eb94b5a81528fb363696f
684,592
from typing import List from typing import Tuple def merge_sort(arr: List[int]) -> Tuple[List[int], int]: """Return ``arr`` sorted and the amount of inversions in ``arr``.""" if len(arr) <= 1: return arr, 0 mid = len(arr) // 2 left, ls = merge_sort(arr[:mid]) right, rs = merge_sort(arr[mid...
ae9727bce390dda12154b1a97dea7f57ba1a8eed
684,593
def AUlight(exclude=()): """Return AU standard colors (light). Available colors: 'blue', 'purple', 'cyan', 'turquoise', 'green', 'yellow', 'orange', 'red', 'magenta', and 'gray'. Keyword arguments: exclude -- tuple of strings (default empty) """ AU_colors = {'blue' :( 0, 61,115), ...
557ac5bc7d38ea059d0939e51c8b6063c9231782
684,594
import os import pickle def load_pickle_object(file_path): """Load a pickled Python object from local directory Parameters ---------- file_path : string The path (absolute or relative) to the target directory where the pickle file is stored Returns ------- pickle_obj : Python obj...
da2982c0242a9f0e47106ce287eac9c9ce52da54
684,595
def startswith(s1, s2): """ Proxy to the startswith method. """ return s1.startswith(s2)
a85356364c660ee1df3dbbe11f0424ac6b42a108
684,596
def r1(a, k): """ the stupiest way T(n): O(nk) """ a = a[:] n = len(a) # repeat k times: for i in range(k): t = a[-1] for j in range(n-1, 0, -1): a[j] = a[j-1] a[0] = t return a
f7b7ebe6beb97e7097bcdb1eed2032b7a62779af
684,597
def closest_power_2(x): """ Returns the closest power of 2 that is less than x >>> closest_power_2(6) 4 >>> closest_power_2(32) 16 >>> closest_power_2(87) 64 >>> closest_power_2(4095) 2048 >>> closest_power_2(524290) 524288 """ n=1 while 2**n <x: n = n+1 ...
ce5531c1bd264cd4496aca74498f7105c24eaaad
684,598
def filterStrategies(sl): """Filters the set of available strategies.""" return sl
cf66e081009be7d347732c0acc7de7b6178a156a
684,599
def ellipsize(msg, max_size=80): """This function will ellipsize the string. :param msg: Text to ellipsize. :param max_size: The maximum size before ellipsizing, default is 80. :return: The ellipsized string if len > max_size, otherwise the origi...
d894228f64f3f1b1b061dd81eacac96ad5d9cd8b
684,600
def stateful_flags(rep_restart_wait=None, quorum_loss_wait=None, standby_replica_keep=None): """Calculate an integer representation of flag arguments for stateful services""" flag_sum = 0 if rep_restart_wait is not None: flag_sum += 1 if quorum_loss_wait is not None: ...
b5ed2e1558dcc40e56700d7c32dcd7c07ee6c589
684,602
import random def random_bool(probability=0.5): """Returns True with given probability Args: probability: probability to return True """ assert (0 <= probability <= 1), "probability needs to be >= 0 and <= 1" return random.random() < probability
45b3ec3f15218df3da7b962301dc5174dbfa11c7
684,604
def seperate_messsage_person(message_with_person): """ Seperates the person from the message and returns both """ # Split by the first colon split_colon = message_with_person.split(":") # Get the person out of it and avoid the first whitespace person = split_colon.pop(0)[1:] # Stitch the...
b5a9549caec7a0083de7d3c980fca8b2a10560bb
684,605
def user_item_answered(data, condition): """Only the items with the total number of answers according to the :fun:`condition`. """ assert callable(condition), "The condition is not a function." items = data['user_id'].map(str) + ',' + data['place_id'].map(str) item_values = items.value_counts()...
f10f0003c86b8148b92b95285a857eeb64a760b6
684,606
from datetime import datetime from dateutil import tz def _epoch_to_datetime(epoch_seconds): """ Converts a UTC UNIX epoch timestamp to a Python DateTime object Args: epoch_seconds: A UNIX epoch value Returns: DateTime: A Python DateTime representation of the epoch value """ ...
a4bab04e6e80698631e2200a9824a2befec29502
684,608
def list_arg(raw_value): """argparse type for a list of strings""" return str(raw_value).split(",")
38e411618a0508c3639802fe67615aa29df8fcb2
684,609
def get_vcf(config, var_caller, sample): """ input: BALSAMIC config file output: retrieve list of vcf files """ vcf = [] for v in var_caller: for s in sample: vcf.append(config["vcf"][v]["type"] + "." + config["vcf"][v]["mutation"] + "." + s + "." + v)...
d0d8df42a8248374f81a6b09dc1a4d4867bad483
684,611
def json_paths_to_json_patch_paths(paths): """ Change JSONPath to JSON patch paths. Note: The JSONPatch class uses JSONPath under the hood anyway so this is pointless. You can just make a list of paths direct and wrap it. """ patch_paths = [] for path in paths: p = str.replace...
2cd70973e2996872083a3a3eb7d0d35ca78b8703
684,612
def form_hex(dense_hash): """Hexadecimal encoding from dense hash.""" return ''.join([format(number, '02x') for number in dense_hash])
2eab80f6011b0fa179a619b0d7e5823fdd77a387
684,613
def _get_nodes_without_in_edges(graph): """Get all nodes in directed graph *graph* that don't have incoming edges. The graph is represented by a dict mapping nodes to incoming edges. Example: >>> graph = {'a': [], 'b': ['a'], 'c': ['a'], 'd': ['b']} >>> _get_nodes_without_in_edges(graph) ({'a...
367a7c136e795f768a96bb6b013a09f0fb6ed967
684,614
import re def sentences(s): """Convert a string of text to a list of cleaned sentences.""" result = [] for sentence in s.split('.'): sentence = re.sub(r"[^A-Za-z0-9 ']", " ", sentence) sentence = re.sub(r"[ ]+", " ", sentence).strip() result.append(sentence) return result
7139c9d1595d12fc18e17a45c1cadafcb8f838f7
684,615
from typing import OrderedDict def _build_dict_prob_cnv(): """ construct the dictionary used to build the function that will take a cnv score and spits out a proba of being true cnv """ # Values come from Guillaumes H. prob_cnv_vrai_str = \ "15 20 80 25\n" + \...
bd36052220ba1c3c4a968a43748830e2349f1a55
684,616
import argparse def add_text_generate_args(parser: argparse.ArgumentParser): """Text generate arguments.""" group = parser.add_argument_group("Text generation", "configurations") group.add_argument("--temperature", type=float, default=0.9, help="The temperature of sampling.") ...
dee91ae6d890f59ae46475bea2610f759e064852
684,617
def generate_pents(limit): """Generates pentagonal numbers up to limit""" n = 1 pents = [] while n*(3*n - 1)/2 < limit: pents.append((n*(3*n - 1)//2)) n += 1 return pents
587cb390e8cc9f23d186e1a924453165520516a6
684,618
def is_string(val): """ To check if a variable is a string in the HTML templates. """ return isinstance(val, str)
8254dbb8395436cd3ec24174ebb4980c4af57cda
684,619
def spilock(func): """ Delegate function, to lock and unlocki SPI""" def wrapper(*args): spi = args[0].spi_eve while not spi.try_lock(): pass ret = func(*args) spi.unlock() return ret return wrapper
c61b5790d7cb9a06a0626df9b4f1ae2e2c6b4372
684,620
def remove_preprocessed_filename_definition(filename:str) -> str: """Remove the three first letters to hyandle preprocessed names Args: filename(str): Returns: Raises: """ return filename[2:]
5d20392218bcba8c33d4d91a0d0b9df154f5f1f1
684,621
def _is_plain_value(dict_): """Return True if dict is plain JSON-LD value, False otherwise.""" return len(dict_) == 1 and '@value' in dict_
07a3d6167195ae7486a7e7a985f9b415829f7a42
684,622
def weighted_precision(moving, fixed, weights=None, dim=None): """Estimate the (weighted) error precision (= inverse variance) Parameters ---------- moving : ([*batch], *spatial) tensor fixed : ([*batch], *spatial) tensor weights : ([*batch], *spatial) tensor, optional dim : int, default=`f...
26540fb4455237fb6cc8b49f41499d2ac4411511
684,623
def normalize_boolean(value): """ Normalize a boolean value to a bool(). """ if isinstance(value, bool): return value if isinstance(value, str): if value.lower().strip() == "true": return True if value.lower().strip() == "false": return False raise ValueEr...
9dcc91e0e0806c7b1538cb18435857608e56d184
684,624
def performSwap( s , table ): """ Replaces a set of words """ for p in table: s = s.replace(p[0],p[1]) return s
235d841bc15821513dd862d7f0d33eb81cf7611d
684,625
def full_rgiid(rgiid, region_id): """ return the full rgiid from region and rgi_id """ full_id = f"RGI60-{region_id}.{rgiid}" return full_id
5fd2cd275c922cb84bb3d8ab3b2373ad240be160
684,626
def get_snx_host_ioc_context(indicator, ioc_type, threat_data): """ Make the dictionary for SlashNext IoC contexts for hosts :param indicator: IoC value :param ioc_type: IoC type :param threat_data: Threat data by SlashNext OTI cloud :return: SlashNext IoC context dictionary """ snx_ioc_...
9b384614d3242899d39c5105bd565520f8926fca
684,627
from datetime import datetime def convert_unix_to_demisto(timestamp): """ Convert millise since epoch to date formatted MM/DD/YYYYTHH:MI:SS """ if timestamp: date_time = datetime.utcfromtimestamp(timestamp / 1000) return date_time.strftime('%Y-%m-%dT%H:%M:%SZ') return ''
3fd33926b69af6de8763b3f0659082ba9a00a72b
684,628
from typing import Callable import inspect def filter_kwargs(func: Callable, kwargs: dict, complete: bool = False) -> dict: """ filters a set kwargs to match function args Args: func callable kwargs dict complete bool [False], if True, checks that all required arguments ...
8b8489e1070183b6efc3406356547e2f8f0619ba
684,629
def navigate_diagnosis(driver): """ Searches for submit button """ return driver.find_element_by_css_selector("input[type='submit']")
61b917be9441d897de2e4653a3d07d1f9a4642c8
684,630
def get_vehicle_attrs_url(props): """ Returns vehicle properties from dict as URL params for Routino """ param = '{key}={val};' return ''.join([param.format(key=k, val=v) for k, v in props.items()])
abeddc842dc2b62b5301a9981e852ff8fbdd898e
684,631
def S_IFMT(mode): """Return the portion of the file's mode that describes the file type. """ return mode & 0o170000
ae5fdc44ce7d7f94b04c424b5f8e885a6d0c97f1
684,632
def get_cls_import_path(cls): """Return the import path of a given class""" module = cls.__module__ if module is None or module == str.__module__: return cls.__name__ return module + '.' + cls.__name__
b90a7cc5a65166eb520aa82cc5051f95cebf3dbb
684,634
import tempfile import time def __init_logfile(): """ Private function to create a temporary log file. Returns the path to the log file. """ temp_file = tempfile.NamedTemporaryFile( prefix="Markdown_Editor_" + time.strftime("%d_%m_%y_%H_%M_"), suffix=".log" ) temp_file...
122b647a9cf196dfae848d7766071a7c097fcafd
684,635
def name_needs_rename_pred_factory(tracked_nm_structs): """Predicate factory to determine which potential name struct has is not currently in the tracked name structs but its potential reference is. Arguments: tracked_nm_structs {[type]} -- list of tracked name structs. Returns: ...
ad5ac67dc14b59c56af19791d06e6adb6a21e771
684,636
def find_colon(str): """ Args: str: Returns: """ parens_stack = [] for i, character in enumerate(str): if character in '[(': parens_stack.append(character) elif character in '])': parens_stack.pop() elif character == ':' and not parens_s...
467aa77a154998cdd73e6d97e86d2c76de5ba7e1
684,637