content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import hashlib def algorithm_check(algorithm: str) -> bool: """ Args: algorithm (str): algorithm name Returns: bool: True if algorithm is supported, False otherwise Examples: >>> algorithm_check('sha256') """ return algorithm in hashlib.algorithms_available
f99b371f0ed33ca5221e780f57dfa3965ad0e530
654,849
def image_member_update(client, memb_id, values): """Update an ImageMember object""" return client.image_member_update(memb_id=memb_id, values=values)
3a4f8b2cd87d82a9d1e7d35b75556819cc85f7f1
654,850
import os def get_package_root(node_modules, package): """ Finds the directory that the package.json is stored in for given package Args: node_modules: The absolute path to Yarn's node_modules directory package: The name of the package Returns: Absolute path to the package's root ...
af538def6a6f9eab03c3a244ba2175325e461781
654,851
import hashlib def hash_md5(filename, chunk_size=2 ** 16): """ Computes the *Message Digest 5 (MD5)* hash of given file. Parameters ---------- filename : unicode File to compute the *MD5* hash of. chunk_size : int, optional Chunk size to read from the file. Returns --...
37fb69585a8e2ef8c5428eba056f9162e681b2e0
654,852
def color_bash(string, color): """ print string with escape code for bash color """ color_code = { 'black': '\x1b[30m', 'red': '\x1b[31m', 'green': '\x1b[32m', 'yellow': '\x1b[33m', 'blue': '\x1b[34m', 'magenta': '\x1b[35m', 'cyan': '\x1b[36m', 'lightgray': '\x1b[37m', 'darkgray': '\x1b[90...
7ddd2bf202e4d4217d9788391828befe124eace5
654,853
def __readcstr(f): """ Helper function for reading in C-style string from file """ buf = b"" while True: b = f.read(1) if b is None or b == b"\0": return buf.decode("utf-8") elif b == "": raise EOFError("Buffer unexpectedly empty while trying to read null-...
c61638fedb7cf111b67c5e0b0f46e5f2d753b17b
654,854
import subprocess def get_acorn_version(): """ Get the version of installed acorn :rtype: str """ outp = subprocess.check_output(['node', '-p', 'require(\'acorn/package.json\').version']) return outp.decode().strip()
c0eca16f01db58160f79f6a838f1584ecc8eb450
654,855
from typing import Callable import click def variant_option(command: Callable[..., None]) -> Callable[..., None]: """ Option to choose the DC/OS variant for installation. """ function = click.option( '--variant', type=click.Choice(['oss', 'enterprise']), required=True, ...
b36783989911461d37e0597187e4d8999a3bc7be
654,856
def unit_length(ua): """ Computes the unit length in the given units """ return ua.solar_mass * ua.grav_constant / ua.light_speed**2
ef1b70bb65503398f99f35949bb38d460c9935f4
654,857
import base64 def csv_download_link(df, filename): """Returns a link to download the dataframe as the given filename.""" csv = df.to_csv(index=False) b64 = base64.b64encode(csv.encode()).decode() href = f'data:file/csv;base64,{b64}' return f'<a href="{href}" download="{filename}">`{filename}`</a>'
b8b21c396c310de083072d83d91e2e0e034fd8e7
654,858
def datetime_from_msdos_time(data, timezone): """ Convert from MSDOS timestamp to date/time string """ data_high = (data & 0xffff0000) >> 16 data_low = data & 0xffff year = 1980 + ((data_low & 0xfe00) >> 9) month = ((data_low & 0x1e0) >> 5) day = data_low & 0x1f hour = (data_high & ...
7326043515aa7c20ea5c87fdb8bdbafd5f98671a
654,859
def distLInf (a, b): """ Utility method to compute the L-infinity distance between the given two coordinates. """ return max (abs (a[0] - b[0]), abs (a[1] - b[1]))
912fb0284a4d5da022d53e576c71a8b0f947c5cb
654,860
def reset_slice(api, xrn): """ Not implemented """ return 1
f7792a2163c8d1838b0a39218abd11032c5dc4ad
654,861
import os def guess_shard(path): """Guess the shard from a given path.""" return os.path.split(path.split()[-1])[1]
e0807091ca049cb2da7d4861f47d26b08874e383
654,862
def has_right_component_fragment(root, comp_index): """ Return True if component at comp_index has a component to its right with same comp_num INPUT: - ``root`` -- The forest to which component belongs - ``comp_index`` -- Index at which component is present in root OUTPUT: ``True`` ...
fde0857c06907d8a7b06685b9e5d5f721f5ca1b9
654,864
import yaml import os def _env_var_yaml(loader: yaml.Loader, node: yaml.nodes.Node) -> str: """Load environment variables and embed it into the configuration YAML. :param loader: the yaml loader :param node: the current node in the yaml :return: the parsed string that contains the value of the enviro...
3fba77f93bed5738449b2ba5bbfca68357125b8d
654,866
def negative_log_likelihood(y_true, predicted_distributions): """Calculates the negative log likelihood of the predicted distribution ``predicted_distribution`` and the true label value ``y_true`` # Arguments y_true: Numpy array of shape [num_samples, 1]. predicted_distribution: TensorFlow p...
cb212b478a087cf995be84549dea1ad0869838f5
654,867
def wireTransfer(senderAccount, receiverAccount, commission, amount, database): """ This function takes two accounts and allows us to transfer money from one account to another one senderAccount and receiverAccount are two accounts as defined above amount is the amount that needs to be transfered fr...
9f7325755424b6a7a620820dd15bc4e68736130c
654,868
def MSE(x,gt): """[Compute scale invariant mean square error] Args: x ([ndarray or Tensor]): [n x b where n is number of observations and b is number of pixels] gt ([ndarray or Tensor]): [n x b where n is number of observations and b is number of pixels] Returns: [float]: [scale in...
e46925473c64e1553500086f42a5fe1f112abdd9
654,869
def output_file(output_pred, output_path): """ This outputs a .json file of the prediction list line by line. """ outF = open(output_path, "w") textList = '\n'.join(output_pred) outF.writelines(textList) outF.close() return 'output_file has been saved!'
7f976aa92f4112382cf54180d6ffd52bd080a04d
654,870
def frequency(word, histogram): """Return the frequency of that word in the whole dictogram (num_words/total_words).""" return histogram.get(word) / sum(histogram.values())
580b291551155fce99b7432679cc553fc4ad4ba7
654,871
def bitmask_to_binary(bits,width=32): """ NAME: bitmask_to_binary PURPOSE: convert the bitmask to a binary representation INPUT: bitmask value OUTPUT: binary representation, e.g., 2 = '00000000000000000000000000000010' HISTORY: 2014-08-19 - Written - Bovy (IAS)...
2136114c9f7152914e4258bfa0df9f6d7b6933a8
654,872
import csv def csv_to_markdown_table(file_name: str): """In Notion, any Database page are saved as a Folder and CSV file with same name. The Folder contains each page in database, and CSV contains the properties associated with it. This function reads the csv, and return each row as dict, with keys as the fir...
b43513dfa6a8f3781e6597c42d8bb6758385a280
654,873
def offset_axis(axis): """Axis handling logic that is generic to all reductions.""" flatten = axis is None if flatten: axis = 0 else: if axis < 0: # The case of a negative input axis needs compensation, because we # are adding a dimension by ourselves ...
4969a6cfb36c62ab7ca577303238c3ea961f1e90
654,874
from typing import Counter def char_vars(vars, genome, guppy): """ 1. what nucleotide follows the variant position? 2. is there a homopolymer of that nucleotide? a. if so, how long is it? """ insertion_error_in_homopolymer = 0 deletion_error_in_homopolymer = 0 nt_count_dict = {...
2c9b837c8479e43e3a85194bbaed7e1cb282c5c4
654,876
def calc_c02_scrubber_rating(lines): """ Calculate CO2 scrubber rating :param lines: List of lines from file :returns: CO2 scrubber rating """ # CO2 scrubber rating filtered_lines = lines.copy() index = 0 while len(filtered_lines) > 1 and index < len(filtered_lines[0]): bit_...
01bc2925fefb9a58df4415d8435420a4b24623ee
654,878
def portrange2str(port_range): """port_range is a tuple of 2 ports """ if port_range[1]: portstr = "port range %s-%s" % (port_range[0], port_range[1]) else: portstr = "port %s" % (port_range[0],) return portstr
ad736bd5197b49080a2db0012f2b8939e2e54a1e
654,880
def cull_candidates(candidates, text, sep=' '): """Cull candidates that do not start with ``text``. Returned candidates also have a space appended. Arguments: :candidates: Sequence of match candidates. :text: Text to match. :sep: Separator to append to match. >>> cull_candidat...
eec89e178e82dc798fe400825c92ab3ce806fbb5
654,881
import re def original_url_from_httrack_comment(html): """ Extracts the original url from HTTrack comment """ url = "unknown_url" for m in re.finditer( "<!-- Mirrored from ([^>]+) by HTTrack Website Copier", html): url = m.groups()[0] if not url.startswith('http://'): ...
9fd8fbd4fd7005aa42147099c6f7e331bd365144
654,882
import pathlib from typing import Union import gzip import bz2 import lzma import shutil def decompress_file(src: pathlib.Path, dest: pathlib.Path, subtype: str) \ -> Union[None, str]: """Decompress the given file according to its MIME subtype (gleaned from file magic). :returns: An error message...
2a7bbd431c506c52f0c384a5c0070602593da682
654,885
import torch def custom_collate_fn(batch): """How to return a batch from the data loader""" # Sort batch by sequence lengths batch.sort(key=lambda seq: len(seq[0]), reverse=True) inputs, targets = zip(*batch) lengths = [len(input_) for input_ in inputs] # Tensors are of shape (batch, max_seq_...
b7bd7b7c4edc719dc36be0b749ca7e01f510da46
654,886
import torch import hashlib def get_model_hash(model: torch.nn.Module) -> str: """ """ model_repr = "".join([str(a) for a in model.named_children()]) # print(model_repr) model_hash = hashlib.md5(model_repr.encode("utf-8")).hexdigest() return model_hash
75651dfbf948fbb89acf733a80727d79309ba6c1
654,888
def tag_ordinal(tag): """ Given a beautiful soup tag, look at the tags of the same name that come before it to get the tag ordinal. For example, if it is tag name fig and two fig tags are before it, then it is the third fig (3) """ return len(tag.find_all_previous(tag.name)) + 1
e9b9166979c83b0ceb577dc0edbb227d8f1f8a5b
654,889
import uuid def make_fake_id(): """Generates a 20-character UUID as str.""" s = str(uuid.uuid4()) return s[:20]
6f0faf10e56b802ad1739d8f811e5b87d3a0cc4c
654,890
from pathlib import Path import time def append_date(filename): """adds date to the end of the filename :param str filename: filename :return: """ p = Path(filename) return "{0}_{2}{1}".format( Path.joinpath(p.parent, p.stem), p.suffix, time.strftime("%Y%m%d-%H%M%S") )
ccd15fd6cfc881c380b9ca34f4b4c1da9f23167a
654,891
from functools import reduce def deep_get(dictionary, keys): """ Get the data out of the dictionary at the given nested key path. :param dictionary: Dictionary to retrieve the data from at the given keys path :param keys: ['a', 'b', 'c'] :return: Value """ return reduce(lambda d, key: d.g...
baaeecc6edd5c286afc78d186aa39a8eb362fba8
654,892
import string import secrets def get_random_string(length=12, allowed_chars=string.ascii_letters + string.digits): """Return a securely generated random string. """ return ''.join(secrets.choice(allowed_chars) for _ in range(length))
a4132ee3dc515303a3c032defec544a95aff03ad
654,894
def iterationstopixel(i, iterations): """ Assigns a color based on iteration count. You can implement your own color function here. """ d = int(i / iterations * 255) return d, d, d
e16a99bc24067fa86060cf8ad84e59a9c1966d58
654,895
def cols(matrix): """ Returns the no. of columns of a matrix """ if type(matrix[0]) != list: return 1 return len(matrix[0])
b726cc38efbeec7309c7b640bcc1c9a09e64c444
654,896
def add_next (res_comb): """ Generates all the possible permutations by calling itself""" l = [] for item in res_comb [0]: if len (res_comb) > 1: new = add_next (res_comb [1:]) for item2 in new: l.append (item + item2) else: l.append (item)...
de101a4c220fcd5cb0d855a644dba5c0a0183273
654,897
from typing import List def _find_any_one_word_from_wordlist(string_list: List[str], word_list: List[List[str]]) -> bool: """ Function that tries to match a list of strings with a list of words by trying to find any word of each given list of words in one of the string...
8235e1b82d500f60a11144bc515b6f4134a11fb3
654,898
from pathlib import Path def _setup_filetree_for_priority_test(tmp_path: Path) -> Path: """ root └─ dir_1 └─ dir_1_1 └─ file_1.py Returns: path for file_1.py """ root_dir = tmp_path / 'root' root_dir.mkdir() dir_1 = root_dir / 'dir_1' dir_1.mkdir() dir_1_1 =...
a7feb4ce8f8265ee590bbeff6e7a11c64b21ae08
654,899
def simple_incorrect_scan_and_codes(simple_scan): """ Return a scan and error codes, representing a small mesh which produces a couple of known requirement and advisory statements, and the relevant statement codes. Errors as follows: mesh missing cf_role (but identified from datavar) --> R1...
ce72a6c736a0e8bc1de29e8877ad05b32b13daed
654,900
def key(request) -> int: """Get instance key.""" return request.param
09a31f43493f65165fc8dcf32e555966d17c7e53
654,901
def _push_S_g_away_from_zero(S_g, K, W, eps=0.0001): """ If the ESS are exactly 0.0 (possible in frequentist/maximum likelihood approaches; especially after the shortish burn-in period when the M-step starts, when we might not have observed all tokens), then the smoothing recursion gets thrown off; we g...
7431259f33c419a80b29cade0c7c4969a587885d
654,902
def derive_table_from(source): """Ease the typical use case /somewhere/TAB.txt -> TAB.json.""" table = source.stem.upper() return table, f'{table}.json'
08f364d70750c887915ca8464fe76fb09e7687d8
654,903
def remove_alignments(group, min_length: int=1000, min_coverage: float=0.2): """ Since MUMmer aligns sections of a sequence, it can produce multiple regions of alignment for a given sequence. We filter out low alignments using this function. Args: group: A pandas group_by group. ...
1bc5bd3d5da0a03e4b8fbf46b123f696f61174ab
654,904
import functools def require_owner(message=None): """Decorate a function to require the triggering user to be the bot owner. If they are not, `message` will be said if given.""" def actual_decorator(function): @functools.wraps(function) def guarded(bot, trigger, *args, **kwargs): ...
dfd6f692a3816bb7e5e8498d10462928eb52ea09
654,905
import six def prefix_dict_keys(dictionary, prefix="_"): """ Prefix dictionary keys with a provided prefix. :param dictionary: Dictionary whose keys to prefix. :type dictionary: ``dict`` :param prefix: Key prefix. :type prefix: ``str`` :rtype: ``dict``: """ result = {} for ...
6476671ad908b200c87d9aa5988f4fbcf57b44ba
654,907
def netstring_from_buffer(buff): """ Reads a netstring from a buffer, returning a pair containing the content of the netstring, and all unread data in the buffer. Note that this assumes that the buffer starts with a netstring - if it does not, then this function returns ``(b'', buff)``. >>...
e992784321af637e285f93dceddf14988a0887bb
654,908
def file_count_i18n(fname): """ Determine the number of lines in a file :param fname: :return: """ with open(fname) as f: data = f.read() return data.count('${i18n().')
8f6085cf9fdcfa51bfb3eaf0e2d750c3204953d7
654,909
import re def discard_html(htmlstr): """ 去除字符串中的html标签 """ s2 = re.sub(r'<.*?>', '', htmlstr) return s2
f985734a8e18308e5aaec6009a0fce5fa27c5e2f
654,910
def reverse_single_from_multi_obj(model): """ Reverse a single from multi object conversion performed by `single_from_multi_obj`. Parameters ---------- model : :class:`cognibench.models.CNBModel`, :class:`cognibench.capabilities.MultiSubjectModel` A proxy single-subject model object that de...
b9838d4a0e86dfa572e385471bd7080af476151c
654,911
import argparse def parse_args(): """ Parse command arguments. """ parser = argparse.ArgumentParser(description='Downscale images inplace') parser.add_argument('path', help='Path to a directory with images') parser.add_argument('-target_size', type=int, default=127, help='A minimum...
42480f960e6d69f78ddff4dba746b24e40db2802
654,912
import collections def part2(entries: list, space: collections.defaultdict) -> int: """part2 solver take the entries and return the part2 solution""" for ax, ay, bx, by in entries: if ax != bx and ay != by: for i in range(abs(ax-bx)+1): if ax < bx: if ay...
e1f599e1ce1bbf8deb5b85e9c03b29349468b09c
654,913
def fake_get_artifacts(self, artifacts): """ A helper function to create valid NEVRA filenames for inserting in the artifacts section of a modulemd file """ artifacts_nevra = [] for a in artifacts: path, filename = a.rsplit("/", 1) filename = filename.rsplit(".", 1)[0] artifacts...
58e2fc93417b2714a93393cffc670f67a6908e06
654,914
import argparse def get_args() -> argparse.Namespace: """ Get Command line Arguments """ parser = argparse.ArgumentParser() parser.add_argument('-w', '--workers', type=int, default=32, help=('Number of workers to use for multiprocessing')) parser.add_argument('-c', '--c...
4e3490c9805ab1637a5ff30439b19a1a436ef220
654,915
import socket def ip_sort_key(ip_address): """Get a sort key for an IPv4 or IPv6 address""" if ':' in ip_address: # IPv6 return b'6' + socket.inet_pton(socket.AF_INET6, ip_address) # IPv4 return b'4' + socket.inet_aton(ip_address)
de8632eb66c40f4a9237ffc35757b6fdf5ce879c
654,917
def lha2scale(lha): """Extract the high scale from a dictionary eturned by pylha from a DSixTools options file.""" return dict(lha['BLOCK']['SCALES']['values'])[1]
a633e64d4cc523f31105b33aef929cb7bed73c12
654,918
def generate_dot(dc): """ Generates a dot format graph of docker-compose depends_on between services :param dict dc: Docker comppose configuration loaded as a python dict :rtype: string """ lines = [] lines.append("digraph docker {") for service_name, service in dc["services"].items(): ...
6b9fcfbb939e779593b1e559065ab7daa1a4ba28
654,919
import torch def strengthen_relu_mip_w_indices(c: float, w: torch.Tensor, b: torch.Tensor, lo: torch.Tensor, up: torch.Tensor, indices: set): """ We strengthen the big-M formulation of the leaky ReLU unit y = max(c*wᵀx+b, wᵀx+b), lo <= x ...
fc6cde2e15f283519e09bcc9e00831f73a76615d
654,920
import string import random def create_identifier(chars=string.ascii_letters): """ create the identifier for your Github issue """ retval = [] for _ in range(0, 7): retval.append(random.choice(chars)) return "".join(retval)
89cba57f95a78cddd3f05c39be939d57f09cf7d8
654,921
def split_dsn(dsns): """Produz uma lista de DSNs a partir de uma string separada de DSNs separados por espaços ou quebras de linha. A escolha dos separadores se baseia nas convenções do framework Pyramid. """ return [dsn.strip() for dsn in str(dsns).split() if dsn]
52949b5b07b7e4a9e57267d8d56839e5cbb04c2c
654,922
import math def get_angle(pointA, pointB): """ Calculates the angle between two points. """ if pointA.x >= pointB.x: distX = (pointA.x - pointB.x) distY = (pointA.y - pointB.y) else: distX = (pointB.x - pointA.x) distY = (pointB.y - pointA.y) angle = math.degr...
d2b044b9aadc655be86358926908d71b6c7d6fd0
654,923
import re def is_last_process_complete(filepath, expect_text, fail_text): """ Search the filepath in reverse order looking for expect_text before finding fail_text. This utility is used by archive_metadata. """ complete = False fh = open(filepath, 'r') fb = fh.readlines() rfb = ''.jo...
cb24603f988df8c260c008131226fb41cf1f5993
654,924
import pathlib import argparse def file_type(file_path: str) -> pathlib.Path: """Resolve a file path to a file. :param file_path: Path to file. :return: Path object. """ file = pathlib.Path(file_path).expanduser().resolve() if not file.is_file(): raise argparse.ArgumentTypeError("{} i...
be64d06cdcbbf31b482d76da15ec8548e02185b8
654,925
def find_mirror_next(seq, max_window_size, mirror_centre): """Find the next token that will lead to a mirror pattern. Searches in the range of `window_size` tokens to the left from the `mirror_centre` if it's found. E.g., in [a, b, AND, a] the next token should be 'b' to create a mirror pattern. ...
9631878ce09032c3f38405db90b1ee022698c045
654,926
def skyValue(value): """Method to return a simple scalar as a string with minor processing""" try: return str(int((value+5)/10.)) except: return "999"
2d56cb177de4e4b2b8d9cb3a9adf9d3687b3d6b1
654,927
def setters(*names): """ Yay! Metaprogramming FTW This decorator generates setters """ def make_setter(name): prop = name.capitalize() return lambda self, value: setattr(self, prop, value) def add_setters(cls): for name in names: setattr(cls, f"set{name.capi...
1af474b3370b3a7f08c2d5445685203aaf55a7d0
654,928
import requests def exchange_code_for_token(code, token_url, client_id, client_secret, redirect_uri): """exchange a OAuth2 authorization code for an access token https://docs.github.com/en/free-pro-team@latest/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github Para...
56e16585ef80c361a27bd22e88132a327a8e6bf8
654,929
def query(query_string, data): """ Return a query string for use in HTML links. For example, if query_string is "?page=foo" and data is "date=200807" this function will return "?page=foo&date=200807" while if query_string were "" it would return "?date=200807". """ if query_s...
a779834da9cea1d913dc88f5909dcaee1f35231c
654,930
def return_item(item, key, silently=False): """Depending of the type of item, return the value corresponding to `key` or the attribute `key` of the object item. Args: item (dict or object): Python object to explore key (str): key to search in the object silently (bool, optional): wh...
3d79845db67bbad68b26480c89a64a0ee4d94815
654,931
def move_column(cell, free_cell, table): """ Move cells in a column to fill the empty cell up to the cell activated. Returns, the number of cells moved. :arg cell, a Widget to move in the table. :arg free_cell, the coordinate to which move the cell. :arg table, the table in which the moving is m...
1efa0d41383228ccc1316eec3fbb52e8b558c3de
654,932
import pickle def read_transform(path): """Read and load a serialised transform from disk. Args: path (str or Path): Path to write serialised transform to. Returns: (inst of sklearn.pipeline.Pipeline): A transform that maps points in the source image onto the reference image. """ ...
a748179298544200a923aff6ecf84e5ee38eed95
654,933
import json def typeforms_embed(url, selector, options={}, mode='widget'): """Embed a typeforms form. Parameters ---------- url : str Typeform share typeform_url. selector : str CSS selector to place typeform_id into. options : dict, str Accepts a dictionary or JSON as...
d4ef65c43b9ebe52664aecf03f6d4553741522b8
654,934
def get_tiles_list(element): """ Returns the list of all tile names from Product_Organisation element in metadata.xml """ tiles = {} for el in element: g = (el.findall('.//Granules') or el.findall('.//Granule'))[0] name = g.attrib['granuleIdentifier'] name_parts = name...
863854394839fcb01671a6e968071da6e8c33dd5
654,935
def de_dup_and_sort(input): """ Given an input list of strings, return a list in which the duplicates are removed and the items are sorted. """ input = set(input) input = list(input) input.sort() return input
ed3bd85a7544e1121fcf31a3c83c0b9e6f77f229
654,936
def prepare_kmers_dict(df, column="motif_F14"): """Prepare all kmers from a DataFrame with flanking 14 nt sequences. Parameters ---------- df: pd.DataFrame A DataFrame object with X and Y column. column: str The name of column containing flanking 14 nt sequences. Returns ...
bd3a350057bd9d2f94e6fe0e7e40b8d6d16413d2
654,937
import torch def extract_feature(model_extract, dataloader, start_from_1 = False): """ model_extract: the model for extract representations. Usage: representation, prediction = model_extract(inputs) dataloader: format: noisy_label, clean_label, features(may be a tuple for NLP tasks) ""...
28b48ac4da524672dae6c9a51b62d0c4d94c5b59
654,938
def get_volume(shade_client, name_or_id, filters=None): """Get a volume by name or ID. :param name_or_id: Name or ID of the volume. :param filters: A dictionary of meta data to use for further filtering. :returns: A volume ``munch.Munch`` or None if no matching volume is found. """ return shad...
dd98d3437e18b2e9db1e587452dacf57ab2ef75b
654,939
def calculate_score(player): """Calculate the "score" of a player's deck. Their bottom card times 1 plus their second bottom card times 2 plus ... """ return sum(val * ind for ind, val in enumerate(reversed(player), start=1))
fc70169861ef0440401b89c838b2e2d68821df55
654,940
from pathlib import Path import sys import json def read_manifest(): """Read the CDK manifest file to get the stackname As of cdk 1.13.1, the stackname can be found in the manifest file as an artifact object with a type of aws:cloudformation:stack """ manifest_file = Path("cdk.out/ma...
d924be1f8bbe9bfc52a1691b2e508736bd54c075
654,941
def generate_group_by_range_and_index_str(group_by, data_str, value_str, index_str): """ Generate the range and index string for GROUP BY expression. Args: group_by (str): the column name to be grouped. data_str (str): a string that represents the t...
b3c12081747e644c1a9f5e331305846db727fc1e
654,942
def get_rendering_cache_key(placeholder_name, contentitem): """ Return a cache key for the content item output. .. seealso:: The :func:`ContentItem.clear_cache() <fluent_contents.models.ContentItem.clear_cache>` function can be used to remove the cache keys of a retrieved object. """ ...
6ba0bf5ae8fd1fb9dff844ac6595d35e4b81e5e0
654,943
def compute_xi_t(return_t, risk_free_rate, sigma_t): """ Compute innovation xi at time t as a function of return t, rf rate, and sigma t """ return return_t - risk_free_rate + 1/2 * sigma_t
f123d4e7f786455edde7b1f0cf33eb51f64910f4
654,945
def create_spell_out(text: str): """Maps the characters to the NATO words""" words_for_letters = ['Alfa', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliett', 'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo',...
fc8996b3d69fd418a2b0bed019cab032dd3d17e0
654,946
def simple_div(n): """ Calculate the divisors of n. Used to split arrays into a groups of integer size, or to asses how large the batch size should be when training a model :param n: :return: """ return [i for i in range(n, 0, -1) if n % i == 0]
1a92430f90e3fbd90b65f05c4962d95bf4bb1fb5
654,947
def _cholesky_solve(M, rhs, dotprodsimp=None): """Solves ``Ax = B`` using Cholesky decomposition, for a general square non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned. Parameters ========== dotprodsimp : bool, optional Specifies...
20be045035367b1144cdae5fc7cd4618a45cacb6
654,948
def rstrip(val: str) -> str: """Remove trailing whitespace.""" return val.rstrip()
2b844784420cd0a41e4dc46bcfb229a48d720b01
654,949
def handle_pmid_29632711(*filenames): """Nelde, ..., Walz. Oncoimmunology 2018 [PMID 29632711]""" return None
192371510653eaf9e4311ccd22f01e6b83721f1d
654,950
def intprod(xs): """ Product of a sequence of integers """ out = 1 for x in xs: out *= x return out
ba4b32876a07044b14f1af34e1f0488c30cf2d3b
654,951
def safe_float(val): """ Convert the given value to a float or 0f. """ result = float(0) try: result = float(val) except (ValueError, TypeError): pass return result
1da3879fb93a5d8bf0cde98b5032e211743866fe
654,952
import requests def get_html(url, session_obj=None, headers=None): """ Request to the server and receiving a response, in the form of an html code of a web page. """ try: request = session_obj if session_obj else requests response = request.get(url, timeout = 5, headers=headers) ...
80bc1ba9babbebde0b6fef61c21ac008b484789b
654,953
import os def is_node_running_dqlite(): """ Check if we should use the dqlite joining process (join api version 2.0) :returns: True if dqlite is to be used, otherwise False """ ha_lock = os.path.expandvars("${SNAP_DATA}/var/lock/ha-cluster") return os.path.isfile(ha_lock)
3c8291cf39184389e741fc6d7f13b7a35dd30f9e
654,954
import collections def default_nested_dict(): """ Default nested dictionary with undefined depth """ return collections.defaultdict(default_nested_dict)
dfc6a6dd3b66f79c36402f6bd7fbb1efd355b00f
654,955
def _MetadataMessageToDict(metadata_message): """Converts a Metadata message to a dict.""" res = {} if metadata_message: for item in metadata_message.items: res[item.key] = item.value return res
a68ea5fcd46ce110f247bd8e60dc068acd8a6210
654,956
from pathlib import Path def get_abs_path_from_here(relative_path: str, calling_file_name: str) -> Path: """ return absolute path to file, based on path from the calling location :param calling_file_name: optional name of the calling script that will serce as reference :param relative_path: relative p...
5dab7f30b67d7e574d929b630a97c482e4584ac8
654,957
def ponzo_compute(difficulty=0, illusion=0, distance=10, minimum_length=5, bottom_line_thickness=14, vertical_lines_thickness=5): """ Ponzo Illusion Parameters ---------- difficulty : float Real difference of top line. illusion : float Distance between lines. minimum_length ...
c5f25b23ae031e8518e4aea54d02a395c9a1e861
654,958
def lerpv3(a,b,t): """linear interplation (1-t)*a + (t)*b""" return ( (1-t)*a[0] + (t)*b[0], (1-t)*a[1] + (t)*b[1], (1-t)*a[2] + (t)*b[2] )
f82021ccfd0f71abfec6d7c724e03a4a400ed6bd
654,959
def _resolve_walltime(walltime): """ ensure wall time is in format HH:MM:SS Parameters ---------- walltime: str Returns ------- """ components = walltime.split(":") for c in components: try: int(c) except ValueError: raise ValueError("the wa...
984567108037543df4fe40b7a2e02152f6ed9b78
654,960