content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import csv def fetch_products_from_csv(): """ returns 'products' : a list of ordered dictionaries""" with open('inventory.csv', newline='') as csvfile: product_list = list(csv.DictReader(csvfile)) breakpoint() return product_list
61b737e3d23465fcfec16ade192c077e5f82fd09
644,241
def slice_text(text, eos_token="<s>", sos_token="</s>"): """Slices text from <s> to </s>, not including these special tokens. """ eos_index = text.find(eos_token) text = text[:eos_index] if eos_index > -1 else text sos_index = text.find(sos_token) text = text[sos_index+len(so...
1c53cf904b44580ba9e63c293fff3a674c349267
644,242
import json def initAnnealer() : """ This function should do any initialization needed to make doing a single anneal fast. It will be called before any annealing takes place. The returned value will be passed as the first argument to the anneal function defined below. """ ...
a3eeba6262c39c17803a1646f825441fedd460e6
644,243
import os def get_name_file(path): """Get the name file clean, without extention Args: path (Path): Full path from file Returns: string: name from file """ return os.path.split(path)[-1].replace(".md", "")
a0ed668c251b670af7fc05efe3a7ba0c1ffa5e6e
644,245
def get_regions(hits): """return list of sorted start end tuples""" regions = [] for hit in hits: # for our purposes, start is the lowest overlapped position, ignoring # driection/strand start = min(hit.qstart, hit.qend) end = max(hit.qstart, hit.qend) # add to list ...
0ea6f4841ba4f995ae1245c64b224125e065e274
644,247
def after_userlogin_hook(request, user, client): """Marks Django session modified The purpose of this function is to keep the session used by the oidc-provider fresh. This is achieved by pointing 'OIDC_AFTER_USERLOGIN_HOOK' setting to this.""" request.session.modified = True # Return None to c...
8106da9387c9e2e4bac08aebe06b0e96bf1b0288
644,248
def verify_csv(data): """ Function: verify_csv Description: Verifies that CSV data retrieved through pandas matches the expected format Input: data - A Pandas Dataframe of data pulled from a CSV Output: - True if the data matches the expectation, false otherwise "...
57f7f20edad591c7d238a6639110da740fa893e1
644,249
def dist_rgb(rgb1, rgb2): """ Determine distance between two rgb colors. :arg tuple rgb1: RGB color definition :arg tuple rgb2: RGB color definition :returns: Square of the distance between provided colors :rtype: float This works by treating RGB colors as coordinates in three dimensional ...
fe170840d543d9be9347d6055631987f622daaff
644,251
def inventory_report(prod_list): """Creates an inventory report for a given product list""" prod_list = list(set(prod_list)) x = 0 price = 0 weight = 0 flammability = 0 stealability = 0 for item in prod_list: x += 1 price += item.price weight += item.weight ...
1d14df3920f31bcb9fa07c03d0da51b7b585af60
644,252
def filter_ip(origin_ip_str, filter_ip_str): """ @summary 过滤ip @param origin_ip_str: 用逗号分隔的ip字符串 @param filter_ip_str: 用逗号分隔的ip字符串 @return: 返回在filter_ip_str中的origin_ip_str中的ip """ origin_ip_list = set(origin_ip_str.split(",")) filter_ip_list = set(filter_ip_str.split(",")) return ","...
1362206bfe3898263206e569f7a59a0fadf7e808
644,253
import torch def collect(out): """ :param out: list of list of ndarrays i.e [ [rnfl, gcl, vft],.....] where each rnfl, gcl and vft are ndarrays :return: concatenate the ndarrays in the list and produces [rnfl, gcl, vft] """ collection = [[] for i in range(len(out[0]))] for i in range(len(ou...
2a8ed76bd02d4c4852283c5ce3fddbf2e4c69900
644,254
def _get_cores_and_type(config, fc_dir, run_info_yaml, numcores=None, paralleltype=None): """Return core and parallelization approach from commandline. Prefers passed commandline parameters over pre-configured, defaulting to a local run on a single core. """ config_cores = c...
abd663236a6eb6f8834ced2ae0558bdbe3768ce3
644,255
import torch def pad_inner_dims(t, pad_to): """ return padded-to-block tensor """ inner_flattened = t.view(t.shape[0], -1) co, inners = inner_flattened.shape pad_required = pad_to > 1 and inners % pad_to != 0 pad_size = pad_to - inners % pad_to if pad_required else 0 pad = torch.zeros(co, pad_...
80c5785c670191753d94940f7e3b0cf8d0f07834
644,256
def calculate_speeds(times, distances): """ :param times: A list of datetime objects which corresponds to the timestamps on transmissions :param distances: A list of calculated distances. Each I distance corresponds to location difference between I and I+1 Description: Takes a list of times and distances and...
ba86421a2b2af4ba0e6a26713721af5891a1e634
644,257
import yaml def load_config(path): """Load yaml collection configuration.""" with open(path, 'r') as stream: return yaml.load(stream, Loader=yaml.SafeLoader)
4beb9fff0d471bb23e06b55e18f4d286263fbd4e
644,258
def build_param_bul (param): """ Builds a configuration parameter documentation bullet from a parameter tuple. Args: param (tuple): The parameter tuple. Returns: string: The documentation bullet markdown. """ return param[0] + ' (' + param[1] + '): ' + param[2]
439921cd3ef588afebc000a2cdf2559711baab3e
644,259
import pytz from datetime import datetime def utc_now(): """Get current **AWARE** UTC datetime.""" return pytz.timezone('UTC').localize(datetime.utcnow())
9061e7e5a3ee5ed540c8f2be92b221220a2073b5
644,261
def output_fn(prediction, response_content_type): """ Return model's prediction """ return {'generated_text':prediction}
7be30483787747191b458f46b8d4fc215a0e7de0
644,263
def fix_UndergradMajor(r): """ Fix the UndergradMajor column """ if r.FormalEducation.strip() in [ "High school", "I never completed any formal education", "Associate degree", "Primary/elementary school", ]: r.UndergradMajor = "Not Applicable" return r
8463caa8863d9e24af1dba439c7c112aa138e401
644,264
def first(sequence, condition=None): """ Returns the first item in a sequence that satisfies specified condition or raises error if no item found. Args: sequence: iterable Sequence of items to go through. condition: callable Condition to test. ...
879c3aaf4d07e367e275227c963422f021be509f
644,265
def checkBuried(Nmass1, Nmass2): """ returns True if an interaction is buried """ if (Nmass1 + Nmass2 <= 900) and (Nmass1 <= 400 or Nmass2 <= 400): return False else: return True
25e864a855365281ca4a8db193169916c7a8a561
644,266
def to_signed_byte(num): """ Convert given byte number to signed byte number. :param num: Unsigned byte number in range from 0 to 255. :return: Signed number in range from -128 to 127. """ assert 0 <= num <= 255, 'Value out of range (0 - 255): {0}!'.format(num) if num <= 127: ret =...
174e30041921cefe02576951e3009541b228bf1e
644,267
import sqlite3 from typing import Any def transaction(conn: sqlite3.Connection, sql: str, *args: Any) -> sqlite3.Cursor: """Perform a transaction. The transaction needs to be committed or rolled back. Args: conn: database connection sql: formatted string *args: ar...
c9a27edd532fe40661b8ddab2010f45d58b1b57a
644,268
import sys def func_name(): """ Returns the name of function its called from """ return sys._getframe(1).f_code.co_name
00f6bd1b5d9aa78456e80e74085043a9976a23aa
644,269
def non_none_dict(d): """return a copy of the dictionary without none values.""" return dict([a for a in d.items() if a[1] is not None])
ab8ed0be802282864f801fb6a42a085946d5eab1
644,270
def java_class_params_to_key(package: str, class_name: str): """Returns the unique key created from a package and class name.""" return f'{package}.{class_name}'
aa602033da7618d5454eb7d7b493508fcf3103c9
644,271
def create_symbol( client, symbol_file, point, drawing=None, replace_values=None, sheet=None ): """Add a symbol instance to a drawing. Args: client (obj): creopyson Client symbol_file (str): Name of the symbol file. point (dict): Coordinates for t...
82a90571de8f3a988659d6da8b20afe37044c8eb
644,272
from typing import Set def get_all_subclasses(cls: type) -> Set[type]: """Return all subclasses of a give cls class.""" return set( cls.__subclasses__()).union( [s for c in cls.__subclasses__() for s in get_all_subclasses(c)] )
3d531ebf8f26fe5e79da17c32d039d963d38f009
644,273
import random def captcha_random_chars(): """ Return a string to use for a CAPTCHA """ chars, ret = u'abcdefghjkmnprtuvwxyz', u'' for _ in range(4): ret += random.choice(chars) return ret.upper(), ret
4ab9d470faec422368ddb25d74e010c9317380f2
644,274
def get_containers(client, pod, namespace): """ makes a request against the Kubernetes api and extracts the names of pod's containers :param client the Kubernetes api client :param str pod: the name of the pod :param str namespace: the namespace where to search for the pod :return: the...
1aee93569fbf348a48ee2b1ac9f4ae0bde6d115a
644,275
def get_intent(): """merge sys & usr intent""" return { "inform": {"description": "Inform the value for a slot."}, "request": {"description": "Request the value of a slot."}, "confirm": {"description": "Confirm the value of a slot before making a transactional service call."}, "o...
8ff640df0bcc7b38b58628d792784d81610b827c
644,276
import struct import hashlib import zlib def create_header(binary, description): """Create the upgrade binary header for given binary data. SIZE TYPE DESCRIPTION 4 uint32_t header version (1) 4 uint32_t header size in bytes 4 uint32_t data size in bytes 20 uint8_t[] SH...
466263d8eb46617c7a22c387ef76b0e81e707b30
644,277
def uniqueify(items): """Return a list of the unique items in the given iterable. Order is NOT preserved. """ return list(set(items))
b7b85edd311ec261e1db47c17386afaa44a08088
644,278
def url_replace(request, field, value): """ Returns the URL of the current page, updating the get parameter 'field' with new value 'value'. Requires the RequestContext request instance to be provided to your template: http://stackoverflow.com/questions/2882490/get-the-current-url-within-a-djang...
455e50579b8abfa5842c8d2c70b8d7838f5d79e5
644,279
def escape2null(text): """Return a string with escape-backslashes converted to nulls.""" parts = [] start = 0 while True: found = text.find('\\', start) if found == -1: parts.append(text[start:]) return ''.join(parts) parts.append(text[start:found]) ...
3d7a5b9b9c2f6d4e2deed3930cef0d85da7d96c9
644,280
import random def ndim(n, *args, **kwargs): """ Makes a multi-dimensional array of random floats. (Replaces RandomArray). """ thunk = kwargs.get("thunk", lambda: random.random()) if not args: return [thunk() for i in range(n)] A = [] for i in range(n): A.append( ndim(*arg...
c3880fae583178b10adb6b668fce6cdece0003d9
644,281
def get_pipeline_suffix(pipeline): """ # The suffix goes at the end of the pipeline name i.e. # -install -upgrade -operations -misc """ try: pipeline_suffix = pipeline.pipeline_suffix if not type(pipeline_suffix) == str: pipeline_suffix = "" except AttributeError: pipeline_suffix = "" retur...
897acefce75612134c8d5c1d3862f77cfe900c52
644,282
from typing import List def _convert_tags_to_wordpiece_tags(tags: List[str], offsets: List[int]) -> List[str]: """ Converts a series of BIO tags to account for a wordpiece tokenizer, extending/modifying BIO tags where appropriate to deal with words which are split into multiple wordpieces by the token...
127b08ac97f5c8eeaf5da7f2486ce99cc17ce8a2
644,283
import pathlib import hashlib def _md5(file: pathlib.Path) -> str: """Calculates the MD5 hash code of a file for integrity.""" hash_md5 = hashlib.md5() with file.open("rb") as f: # Read and update hash string value in blocks of 4K for chunk in iter(lambda: f.read(4096), b""): h...
189c209f1278cab2e2d81aaf6dbe2175f3b09560
644,284
def print_nums_opt(*numbers: int) -> str: """Fill numbers with zeros (optimizible). Args: *numbers: <int> sequence of numbers Returns: zero filled string. Examples: >>> assert print_nums_opt(11, 12, 23) == '11 12 23' """ return ' '.join(str(num).zfill(len(max(str(num)))) for n...
44481e557eaa87463ac3d79ebb1ce22030ad7bae
644,285
def calc_atom_mean_temp_factor(atom_iter): """Calculates the average temperature factor of all contained Atom instances and returns the average temperature factor. """ num_tf = 0 adv_tf = 0.0 for atm in atom_iter: if atm.temp_factor != None: adv_tf += atm.temp_factor ...
f0591676e5dec7b9d3eb0e468f9c7ec700e36fc9
644,286
def file_ready_string(string): """ Change a string from 'Something Like This" to "something_like_this" for ease of saving it as a filename or directory name. Args: string: Returns: """ return string.replace(' ', '_').lower()
204fb7880ecc80c00f686333dfae4b00eb13f9fc
644,288
def unnormalize(z, bounds): """Inverse of normalize""" return z * (bounds[:, 1] - bounds[:, 0]) + bounds[:, 0]
9a39768cdaaa1c169ea88b8dfcb5080a38b9e358
644,289
from datetime import datetime def to_epoch(param_date, miliseconds=True): """ The Unix epoch (or Unix time or POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 """ seconds = int((param_date - datetime(1970, 1, 1)).total_seconds()) if milisec...
812deda7b0d2dadb4c5d06cb22d4960b328fe90d
644,292
def rgb_to_ansi(r, g, b): """ Convert an rgb color to ansi color """ r, g, b = int(r), int(g), int(b) if (r == g & g == b): if (r < 8): return int(16) if (r > 248): return int(230) return int(round(((r - 8) / 247) * 24) + 232) r_in_ansi_range = int...
2db52098958434a4fe007dade9233d4a2c48a8d5
644,293
import socket def get_daemonset_node_name(v1_pods): """ return the host ip of the k8s node this pod is running on # from https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1PodStatus.md """ for i in v1_pods: if i.metadata.name == socket.gethostname(): retu...
14f2e5cc01bb27e5eb4055385371c737684c4bf4
644,294
def parse_nsvca(nsvca): """ Take module name, stream, version, context and architecture in a N:S:V:C:A format and return them as a separate values. """ split = nsvca.split(":") if len(split) != 5: raise ValueError("N:S:V:C:A in unexpected format") split[2] = int(split[2]) return ...
a8fc0d8b679c998b7984db09d3a987626f6acf82
644,295
def pic_flag(compiler=None): """ returns PIC (position independent code) flags, such as -fPIC """ if not compiler or compiler == 'Visual Studio': return "" return '-fPIC'
2419c84c9395bb2085b13ba9e8784d415897981e
644,296
def invalid_n(request): """ Fixture that returns invalid "n" values methods that perform groupings. """ return request.param
27bd6e247449896f218caa60ba8c4b20eb19dee8
644,297
import json def read_json(file_path): """Read json file from file_path.""" with open(file_path, encoding="utf-8", errors="surrogateescape") as f: return json.load(f)["data"]
67a1634b5465fe8e82e1566f47c32ce7cc48d3a9
644,299
import hashlib import os def default_token_generator() -> str: """ Generates token based on random 64-bits and BLAKE2B hashing algorithm. :return: string with generated token """ result = hashlib.blake2b(os.urandom(64)) return result.hexdigest()
317405c815095f52eb62a9666237df647af1b17c
644,300
def before_all(_method): """@before_all annotation. Such method is run right before any test methods are run.""" _method.IS_BEFORE_ALL = True return _method
049641f170fc12292917c339d9ec0b4fb0f1d4ad
644,301
import argparse def parse_arguments(): """Arg parse. Args: None Returns: args (Argparse object): Argument object which contain details of all the command line arguments. """ # Create the parser and add arguments parser = argparse.ArgumentParser() group = parser.add_mutually_exclu...
b5d0d2279c975ec981881caca9683b8f6ef865d0
644,302
def ignore_exception(*exception_classes): """ A function decorator to catch exceptions and pass. @ignore_exception(ValueError, ZeroDivisionError) def my_function(): ... Note that this functionality should only be used when you don't care about the return value of the functi...
2e007f124c84843c0abf0956a1b2b7326d7b4ec7
644,303
def ring_to_vector(z_list: list, max_size: int = 9) -> list: """ Convert the ring sizes vector to a fixed length vector For example, l can be [3, 5, 5], meaning that the atom is involved in 1 3-sized ring and 2 5-sized ring. This function will convert it into [ 0, 0, 1, 0, 2, 0, 0, 0, 0, 0]. Arg...
c90966efe5cbc2e9222a3ed3a69a620eaccd0c49
644,304
def obscured_cert(cert): """Return an obscured version of the supplied 'cert' suitable for display. :cert: a string of a conduit certificate :returns: a string of an obscured conduit certificate """ return cert[:4] + '...' + cert[-4:]
3d3291fe52224a83d4e00f99d1b0622e6def22c7
644,306
def get_mem_info_linux(): """ Get information about available memory. Returns a dict of items in /proc/meminfo """ info = {} with open('/proc/meminfo', 'r') as f: for line in f: p = line.split() info[p[0].strip(':').lower()] = float(p[1]) * 1e3 return info
7df5123316351ca6d50aed0f7f6895f7f4349c04
644,307
def mag(db_image): """Reverse of log/db: decibel to magnitude""" return 10 ** (db_image / 20)
6f8271e4e7f785a881a15f3f8fac141a02557348
644,308
import re def strip_wildcards(text): """Removes wildcards at start or ending of text. It is used to improve rule generalization power. Args: text (str): Text. Returns: str: Text without starting and ending wildcards. """ removed_start = re.sub(r'^(\*~\d+ ?)+', '', text.strip(...
44f9bf8f2b60e115ec0bd98f0990671dec8fd55d
644,309
import requests def check_aws(): """ Check if AWS termination notice exists """ base_url = 'http://169.254.169.254/latest/meta-data/spot' url = base_url + '/termination-time' try: if requests.get(url, timeout=2).status_code == 200: return True except BaseException: pass...
a9fde86672d96c9d52c7f3a06e00903a18acb5a5
644,310
import numpy def accuracy(Ntp, Ntn, Nfp, Nfn, eps=numpy.spacing(1)): """Accuracy Parameters ---------- Ntp : int >= 0 Number of true positives. Ntn : int >= 0 Number of true negatives. Nfp : int >= 0 Number of false positives. Nfn : int >= 0 Number of fa...
09d5a022263f5f0963201b831681cc3c74ecf136
644,312
from typing import Any from typing import Optional from typing import Tuple from typing import Dict import inspect def gather_init_params( obj: Any, ignore: Optional[Tuple[str, ...]] = None, ) -> Dict[str, Any]: """Extract the parameters passed to an object's ``__init__()``. Args: obj (object...
8299fd24cadfdf08e38b2f55b82ef88c0792ae13
644,313
def build_action_metrics(action, **data): """ Builds action metrics data :param action: the action :param data: the metrics data :return: """ metrics = { "Type": "action", "Action": action.__class__.__name__, "Version": action.properties["Version"], "ActionId"...
004302e034fe6be6d16eba427c93785de4678463
644,314
def add_self_loops(A, value=1.0): """Set the diagonal.""" A = A.tolil() # make sure we work on a copy of the original matrix A.setdiag(value) A = A.tocsr() if value == 0: A.eliminate_zeros() return A
efbeb156ab6f2721282c713e18e575729cd66231
644,315
def is_blacklisted(frase, palabras): """ Filtra de una lista elementos prohibidos""" for palabra in palabras: if palabra in frase: return True return False
d0f4ccef027531266258319dac995d160542b7cd
644,317
import requests import os def download(url: str, destination: str) -> bool: """ Downloads the linked image and saves to the specified filepath :param url: url directly linking to the image to download :param destination: file that the image should be saved to :return: True if the file was download...
371fd1d5a9ebca7bc3cf3dabb636fbbfb3a8a26e
644,318
def pythonize(t): """ Make valid fields ints, essentially deserialize """ t["retweet"] = True if t["retweet"] == "True" else False t["likes_count"] = int(t["likes_count"]) t["replies_count"] = int(t["replies_count"]) t["retweets_count"] = int(t["retweets_count"]) t["photos"] = t["photos"].split(",") t["hashtags"...
aa859f74b3967a3149484dbfd60f25b0914fad80
644,320
def rollback_update_rule(table_name): """Helper function to make SQL to create a rule to allow updating from the ecommerce table""" return f"DROP RULE update_protect ON ecommerce_{table_name}"
01e2ff223f37ce657b088d8234a465a0b3f8b3e4
644,321
def check_required_params(req, keys): """ Helper to check if all valid params are present """ for key in keys: if key not in req.keys(): return False return True
7e0456f7461d2c266f1f6dc44369eb560ccbb15c
644,323
import os def chop(prefix, filename): # type: (str, str) -> str """ Create 'filename' from '/prefix/filename' """ result = filename if prefix: try: result = os.path.relpath(filename, prefix) except ValueError: pass return result
8784f2300b6cf09fca728a32620e6220fb1a8bba
644,324
def min_control_name(v): """For a range, return the control that sets the minimum value v - the setting """ return "%s_min" % (str(v.key()))
03cb4f793a0ff9857feb26fe0c5b521e11786409
644,325
import torch import math def mu_transform(x): """ Forward operation of mu-law transform for 16-bit integers. """ assert x.min() >= -1 and x.max() <= 1 return torch.sign(x) * torch.log(1 + 32768. * torch.abs(x)) / math.log(1 + 32768.)
b652847ed06384ce059c1095988ae3487e900d01
644,326
import os import re def get_files_in_folder(folder_path, pattern=''): """Return a list of files inside a folder and its sub-folders with their full path :param folder_path: folder to inspect :param pattern: regex pattern to limit the files list :return: List of files paths """ files_paths = [...
9f3f331f88bc4735e36bae4fa4cee0905e9b2340
644,327
def max_min_layers(nx_graph, max_layer=True): """ Returns the maximal (highest in hierarchy) layer (those nodes with in degree = 0) or the minimal layer (k_out = 0) :param nx_graph: networkX graph :param max_layer: Bool, if True, returns maximal layer (k_in = 0), else returns nodes for which k_out = 0, ...
108bb64fd8f14d780173214e1629d00a9b1d3f72
644,328
import requests def get_users(host, port, api_key, schema='http'): """Get the all users.""" cmd = 'get_users' url = "{}://{}:{}/api/v2?apikey={}&cmd={}".format(schema, host, port, api_key, cmd) users = [] try: result = requests.get(url,...
724d5c012f6c927ab17befd1852aa399ad9a421f
644,329
def sprite(spr): """Creates a patch for to replace Link's sprite with the contents of a XSPR or SPR file. Arguments: spr {list} -- a list of bytes that depicts a ZSPR or SPR file Returns: list -- a list of dictionaries indicating which ROM address offsets to write and what to write to them...
cb2d4b615e52faca1f47fd3f2e4381540b17b8ec
644,330
from typing import Any def f(a: Any, b: Any) -> Any: """Return the sum of two elements. Args: a (Any): var1 b (Any): var2 Returns: Any: output """ return a + b
71f44863bd4603c0a2e2c97dceb1d628f1369cb2
644,331
def check_balanced_parens(parens): """ Given that a string can be composed of parentheses, brackets, and curly braces, check whether an input string has balanced brackets. """ matches = { '}': '{', ')': '(', ']': '[', } ls = [] for paren in parens: i...
655823f8e3278ec40ea8e3797e4e306e7d01f809
644,332
import re def clean_line_for_training(line): """ remove non important strings for training the model """ line = re.sub(r'\s+', ' ', line) # Eliminate duplicate whitespaces using wildcards # 1st look complete date that uses / line = re.sub(r"\d+/\d+/\d+", '', line) # complete date # then w...
c7ec29aed2765555f9573dd05fbd647ddc7ebd88
644,333
def read_file_lines(file): """Returns a list of str lines in text file""" with open(file, mode="rt", encoding="utf-8") as f: return f.readlines()
dac8acbf25c7c9833f20b913d4aff068afa57fa9
644,334
def name(layer): """Returns the class name of a protocol layer.""" return layer.__class__.__name__
1f2993fd9c00cea020898e15fb78adc912663f8a
644,335
import torch def training_collate(batch): """Custom collate fn for dealing with batches of images. Arguments: batch: (tuple) A tuple of tensor images Return: (tensor) batch of images stacked on their 0 dim """ # imgs = list() # for img in batch: # _c, _h, _w = img.sha...
0a0fa8e41d2ed3cd77e53118fc4635f672ac5aa9
644,336
import logging def calc_parameters_gev(mean_est, cov_est, big_a, big_b): """ Args: mean_est: estimated mean (can be negative) cov_est: cov big_a: A value big_b: B value CDF(x) = exp{-[1-k(x-u)/a]**(1/k)} where m = u+a*A, s = a*B, cov = s/m a = m*cov/B...
1af5ca27d80fe629eca9e26442be15ff1e8f98af
644,337
import json def JSONResponse(obj, start_response=None): """ JSONResponse """ if isinstance(obj, str): text = obj elif isinstance(obj, (dict, list)): text = json.dumps(obj) else: text = obj response_headers = [('Content-type', 'application/json'), ('Content-Length',...
dd907e671b9b9368a0933a65714a035074aff1cb
644,338
def frequency_to_probability(counts_table): """ Convert a contingency table expressed in frequencies to one expressed in probabilities. """ total = counts_table.sum() probs_table = counts_table / float(total) return probs_table
395e4fc4403d6a01d6f6d17746351c5f829433f9
644,339
def top_preds(preds, labels, k=5): """ Top 1 and top k precision :param preds: Softmax output tensor with probabilities :param labels: Labels in batch :param k: top k precision, default top5 :return: """ correct = 0 topk = 0 for i in range(len(labels)): classes = (-preds...
273f67d72509f62a6f00391588bc5a54149ab920
644,340
import os import re def get_condor_job_id() -> str: """Get the ID of the current job on the cluster.""" # $JOB_ID is set by the Condor and is used to identify the job job_id = os.environ["JOB_ID"] # The given job_id is something like "sched#12345.0". Cut out the actual # ID (the number between #...
2955230db99037b9ccdf9e1c4d49d705073f503c
644,341
import yaml def get_input_files(cfg, index=0): """ Load input configuration file. Get a dictionary with input files from the metadata.yml files. """ metadata_file = cfg['input_files'][index] with open(metadata_file) as input_file: metadata = yaml.safe_load(input_file) return metad...
3a65bcc019972de83ada05d70d8cfe04d520127e
644,342
def graphql_scalar(scalar_name, description=None): """Annotate a GraphQlScalarDescriptor as a GraphQL scalar. Decorator that annotates a GraphQlScalarDescriptor subclass as a GraphQL scalar with the specified type name. See GraphQlScalarDescriptor. At present, we do not support annotating a class...
43e415bf6988246dcde185f5065d3aa40d7b8877
644,344
import torch def clone_sample(sample): """Clone sample to save memory""" if len(sample) == 0: return {} def _clone(maybe_tensor): if torch.is_tensor(maybe_tensor): return maybe_tensor.clone() elif isinstance(maybe_tensor, dict): return {key: _clone(val) fo...
de7ade491530b381edcbe17685485171656eeceb
644,345
def SizeBenefitSurg(t): """Surgery benefit per policy""" return 0
efe92083a029a3bbca2681408d7724f449723343
644,346
def resources_of_config(config): """ Returns all resources and models from config. """ return set( # unique values sum([ # join lists to flat list list(value) # if value is iter (ex: list of resources) if hasattr(value, '__iter__') el...
a0df38ffc6fb8cadd6b5e44d700f96136594b69f
644,347
from typing import List def gauss_points( n: float, ) -> List[List[float]]: """Returns the Gaussian weights and locations for *n* point Gaussian integration of a linear triangular element. :param int n: Number of Gauss points (1, 3 or 6) :return: An *n x 3* matrix consisting of the integration w...
393faa2733a5e34b25cf5ea2ecab725e1856ec3d
644,348
def imagej_heuristic(radius): """ Copied from ImageJ "Subtract Background" command. """ if radius <= 10: shrink_factor = 1 trim = 0.12 #; // trim 24% in x and y elif radius <= 30: shrink_factor = 2 trim = 0.12 #; // trim 24% in x and y elif radius <= 100: sh...
82a62a99ae08ffb35b753eabb418faf40969322a
644,351
def _fix_json(json_string): """ The 'json' output of the label creation tool does not natively work with Python's json. This one is a quick fix to correct these issues. """ # NOTE should be applied to label files directly json_string.replace('",\n\t\t\t\t"lane_marker": {', '",\n\t\t\t\t"markers": ['...
8fdc5df9a48df05d2f6c492aae631976a60776ac
644,352
def get_game_info(game): """ Gets printable game information. """ return ( "%d (%s: %s [%d] vs. %s [%d])" % ( game['game_id'], game['date'], game['home_team'], game['home_score'], game['road_team'], game['road_score'], ))
f54027c7a8e094288ba1959b6f222526ebb5c579
644,353
def number_of_validators(): """The total amount of validator accounts""" return 5
eab410866ab067c780e9df65a1ce9f1d450e3f09
644,354
def scaleData(features): """ Normalizes features in order for gradient descent to work correctly (improves the convergence speed of the logistic regression algorithm) features is an arg containing the sample of feature data to be normalized Normalization is made using Rescaling (min-max normalization) ...
f784490423ec92e17b69a3720d1785b359711767
644,355
def dedent(string): """Remove the maximum common indent of the lines making up the string.""" lines = string.splitlines() indent = min(len(line) - len(line.lstrip()) for line in lines if line) return "\n".join(line[indent:] if line else line for line in lines)
e50b96a284b49dbd2a91aed1c1fec6d6805a03d4
644,356
def replace(original, old_word, new_word): """ If new_word is in original, this function will replace old_word with new_word. """ ans = '' for i in range(len(original)): if new_word == original[i]: ans += new_word else: ans += old_word[i] return ans
8d8432d2155984a296d5facf758488f4244cd89d
644,357