content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def fip_constant(data): """FIP Constant = lgERA – (((13*lgHR)+(3*(lgBB+lgHBP))-(2*lgK))/lgIP) :param :returns: """ return data["era"] - ( ((13 * data["hr"]) + (3 * (data["bb"] + data["hbp"])) - 2 * data["so"]) / data["ip"] )
45022a01ff7f581bdfc523f5e5b3697d6561c1df
44,211
import subprocess def get_conf_peer_key(config_name): """ Get the peers keys of wireguard interface. @param config_name: Name of WG interface @type config_name: str @return: Return list of peers keys or text if configuration not running @rtype: list, str """ try: peers_keys = ...
1a78c28ac3bd3e587732ec80d709d2a5b6caed25
44,213
def logged_in(cookie_string, prefix='', rconn=None): """Check for a valid cookie, if logged in, return user_id If not, return None.""" if rconn is None: return if (not cookie_string) or (cookie_string == "noaccess"): return cookiekey = prefix+cookie_string try: if n...
60f0ea3c0ab28d375cc7e63e561dc636b41451df
44,214
def txn_data(df, txns): """Return dataframe with supplied transactions.""" return df[df.transaction_id.isin(txns)].copy()
7236c912a6e1120e2b893cf6018ca2b09ad4a558
44,217
def is_odd(x): """Returns a True value (1) if x is odd, a False value (0) otherwise""" return x % 2
1cd311d10409807010d064b8ff0692614af4e78e
44,219
def build_module_instances(config, callee): """ Construct a specific module instance from a config. If the callee is needed for the initialisation needs to be passed and reflected in config :param config: module configuration :type config: dict :param callee: optional calling class :type cal...
f71ebee0dcb132cf2faee4d7eaf64b9e85014190
44,220
import time def run(foo=.2, bar=1): """This method 'sleeps' for the specified duration""" print(' - `minimal`: sleeping for {} seconds ...'.format(foo)) time.sleep(foo) return {'sleep': [foo]}
f54cbdb7e3c2c5555598f21c2110af66e8225b8f
44,221
def get_number_rows(ai_settings, starship_height, alien_height): """Определяет количество рядов, помещающихся на экране.""" available_space_y = (ai_settings.screen_height - (3 * alien_height) - starship_height) number_rows = int(available_space_y / (2 * alien_height)) return num...
c6d63a9656b944c8c3c013a502f1736f9efa76f9
44,223
def _parse_nyquist_vel(nyquist_vel, radar, check_uniform): """ Parse the nyquist_vel parameter, extract from the radar if needed. """ if nyquist_vel is None: nyquist_vel = [radar.get_nyquist_vel(i, check_uniform) for i in range(radar.nsweeps)] else: # Nyquist velocity explic...
b5b56ad2c350873831a0574c98b4920d2abba5ac
44,224
def applyBandOffset(C, height, bandName, lines, inter=False): """Produce bands from a list of lines. Bands are defined relative to lines by means of offsets of the top and bottom heights of the lines. Bands may also be interlinear: defined between the bottom of one line and the top of the next lin...
90f5db0f04b30be774f2f87310baf90ac5f4962d
44,225
def magToFlux(mag): """ Convert from an AB magnitude to a flux (Jy) """ return 3631. * 10**(-0.4 * mag)
6dba3d34772ea8df41d82d9cf40f83dbd9efa4c1
44,228
def filter_df_on_case_length(df, case_id_glue="case:concept:name", min_trace_length=3, max_trace_length=50): """ Filter a dataframe keeping only the cases that have the specified number of events Parameters ----------- df Dataframe case_id_glue Case ID column in the CSV min_...
a3eadc9534b41c62f895def2611a68157abfe091
44,229
def fastmrca_getter(tn, x): """Helper function for submitting stuff.""" taxa = tn.get_taxa(labels=x) mask = 0 for taxon in taxa: mask |= tn.taxon_bitmask(taxon) return mask
b8ee0aff449185498c0b58e8a0716e22940f1cf5
44,230
def helper(n, largest): """ :param n: int, :param largest: int, to find the biggest digit :return: int, the biggest digit in n Because digit < 10, this function recursively check every digit of n """ remainder = n % 10 if n < 10: # Base case! if remainder > largest: return remainder else: return larg...
a441ee9f7712b426db8f2f0a677941c0be44cc0e
44,232
import re def get_param(regex, token, lines): """ Get a parameter value in UCINET DL file :param regex: string with the regex matching the parameter value :param token: token (string) in which we search for the parameter :param lines: to iterate through the next tokens :return: """ n =...
3fb64bf325c2f4082237b838b024b0c3f2cd6ec1
44,233
def restart_omiserver(run_command): """ Restart omiserver as needed (it crashes sometimes, and doesn't restart automatically yet) :param run_command: External command execution function (e.g., RunGetOutput) :rtype: int, str :return: 2-tuple of the process exit code and the resulting output string (r...
8e15e3ab405601f4de4b4cdf0a0ce82241943b85
44,234
def generate_header(sample_name): """Function for generating the header for output VCF file. Args: sample_name (str): Name of the sample. Returns: str: Header for the VCF file. """ fin = open("header", "rt") data = fin.read() data = data.replace('SAMPLENAME', sample_name) ...
d8690521d32da1df43253d7cb2ea95590c3becf5
44,235
def distance(point, line): """ Returns the delta y offset distance between a given point (x, y) and a line evaluated at the x value of the point. """ return point.y - line(point.x)
5353ea7197fa4a5d3e8d538462baba54357dad26
44,236
import os def get_volume(path): """Get the underlying volume from a path. :param path: the path to evaluate :returns: the path to the volume :rtype: str """ abspath = os.path.abspath(path) while not os.path.ismount(abspath): abspath = os.path.dirname(abspath) return abspath
f767e8c4246b052b7a47b9519c49c0159c2468dc
44,237
def upper(_, text): """ Convert all letters in content to uppercase. """ return text.upper()
b2832b5f07d2f564e11c745669d31d86f014eaa1
44,238
def build_gidx_and_mapping_graph(graph): """Build immutable graph index of the whole graph. Parameters ---------- graph : GraphAdapter Graph Returns ------- graph : utils.CtxCachedObject Function that generates a immutable graph index on given context edge_map : utils.C...
a0017ba5d03a9a3f51a83e9d931dedd2400a1b5c
44,239
def training(es, model, model_name, epochs, batch_size, train_set, labels_train_set, validation_set, labels_validation_set): """ Function that return the trained Convolutional Neural Network. Args: es: Contains the Elasticsearch object. model: Contains the model as defined by ...
10751eef0226aeda0651f3afa3535785807d12a4
44,240
def from_c_str(v): """ C str to Python str """ try: return v.decode("utf-8") except Exception: pass return ""
1a8026386a4575a3fcb7be6a15e47bf6a2ba4b97
44,241
def parse_relatedcontent_data(data): """ Given encoded related content data form a hidden input field, parse it into a list of tuples (content_type, object_id). """ final_data = [] parts = [x.strip() for x in data.split(",") if x.strip()] for part in parts: data = part[1:-1].split(" ...
78adae2f892f01cf12b85b26054ec87adc370952
44,242
def read_build_vars(path): """Parses a build_vars.txt into a dict.""" with open(path) as f: return dict(l.rstrip().split('=', 1) for l in f)
b36b1f16111b5c8afbe038bf82df2dd13517a1a7
44,243
import math def compass(azimuth, radians=False): """ Get named direction from azimuth. """ if radians: azimuth *= 180.0 / math.pi names = ( 'N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', ) return n...
2f50430899ade2b5c95d1a5223772a6ca6e055b0
44,244
def _strip_string(*string): """Strips each element of the given list Arguments ------------------ *string : str string to be stripped Returns ------------------ stripped : list Stripped strings """ return [x.strip() for x in string]
d95761e182671193c5491a98ec3ca5f4a7f925f7
44,245
import torch def collate_fn(items): """ Creates mini-batch tensors from the list of tuples (image, caption). Args: data: list of tuple (image, caption). - image: torch tensor of shape - caption: torch tensor of shape (?); variable length. Re...
0ce25f1d030b88636334dbc0d1eef1ec954d8b89
44,246
def read_string(stream, size): """ Reads an encoded ASCII string value from a file-like object. :arg stream: the file-like object :arg size: the number of bytes to read and decode :type size: int :returns: the decoded ASCII string value :rtype: str """ value = '' if size > 0: value = stream.read(siz...
5c18e208dee2cf8e0977b6dabde5e0c5de46eac9
44,250
def g_add(a, b): """Add two polynomials in GF(2^m)""" c = [] idx = 0 for c1, c2 in zip(a, b): c.append((c1 + c2) % 2) return c
53eff23f171ff91878584f9fc6a0c44164beea51
44,251
def _comment(string: str) -> str: """Return string as a comment.""" lines = [line.strip() for line in string.splitlines()] sep = "\n" return "# " + f"{sep}# ".join(lines)
c8919933f2737528ec6c8a0c3fbb4b1f9767a398
44,252
def palindrome(integer): """überprüft, ob eine Zahl ein Palindrom ist Ausgabe 0: kein Palindrom 1: Palindrom""" erg = 1 string = str(integer) for i in range(int(len(string)/2)): if string[i] != string[-i-1]: erg = 0 break return erg
a15e4d8e3b4dc0087fc078240831626bd7cfd2fa
44,254
def remove_overlapping_ems(mentions): """ Spotlight can generate overlapping EMs. Among the intersecting EMs, remove the smaller ones. """ to_remove = set() new_mentions = [] length = len(mentions) for i in range(length): start_r = mentions[i]['start'] end_r = mentions[i]...
3fc87834c0387150079e96003e7707df42712e78
44,255
def get_poi_info(grid_poi_df, parameters): """ ['company','food', 'gym', 'education','shopping','gov', 'viewpoint','entrance','house','life', 'traffic','car','hotel','beauty','hospital','media','finance','entertainment','road','nature','landmark','address'] """ types = parameters.poi_type.split(',')...
71f7ee274d59de13e591394ad122339d15328af3
44,257
def cocos_min_strategy(w, h, sch_resolution, src_resolution, design_resolution=(960, 640)): """图像缩放规则: COCOS中的MIN策略.""" # 输入参数: w-h待缩放图像的宽高,sch_resolution为待缩放图像的来源分辨率 # src_resolution 待适配屏幕的分辨率 design_resolution 软件的设计分辨率 # 需要分别算出对设计分辨率的缩放比,进而算出src\sch有效缩放比。 scale_sch = min(1.0 * sch_resol...
3d35b87f8d1fe1b7dad35438e90ed01969d87a15
44,262
from typing import Iterable from typing import Dict from typing import List def compute_battery_statistic(rows: Iterable[Dict]) -> List[Dict]: """计算电池统计数据。注意:若 row 字段顺序改变,算法必须修改,所以添加新字段要追加在最后""" battery_statistic = {} for row in rows: max_t_s_b_num = row['最高温度电池号'] if max_t_s_b_num is not...
6cb2b498ae0ba3ad1872d0ec7a9006d014797c18
44,263
def get_config_options(otype): """ Return list of valid configuration options for nodes and dispatcher.""" if otype is 'node': return ['node_name', 'node_type', 'node_id', 'node_description', 'primary_node', 'ip', 'port_frontend', 'port_backend', 'port_publisher', 'n_responders', 'lsl_stream_name', 'pri...
8909a07b54353343b0be2c73b370e3fa4c1f0daf
44,264
def del_webf_obj(server, session, obj_type, obj_name, *args): """ Remove and object from the server. A simple wrapper for the "delete_XXX" API methods. """ obj = getattr(server, "delete_%s" % obj_type)(session, obj_name, *args) return obj
81c56d432d5c1cbd5826f999e27f227712cfbf21
44,266
def _get_upload_to_path(instance, filename): """ Returns an upload path using the instance slug. This function keeps file uploads organized. """ return "img/portfolio/%s/%s" % (instance.slug, filename)
24c8ec6fa60c1c733d3db4fb81f4e31f6de9c3a8
44,267
def _sort_and_merge_sub_arrays(left_array, right_array): """This method assumes elements in `left_array` and `right_array` are already sorted. Parameters ---------- left_array: list[int] right_array: list[int] Returns ------- list: merged and sorted list """ left_array_le...
3663097132e530f19d2692cb3492e0cd9008fcfc
44,268
import random def executeScriptToGetData(): """ Choose randomly a iframe widget from the beautiful matomo project """ url1 = 'https://demo.matomo.org/index.php?module=Widgetize&action=iframe&disableLink=0&widget=1&' + \ 'moduleToWidgetize=Live&actionToWidgetize=getSimpleLastVisitCount&idSite=62&per...
5334614dc2b5dc885e94c30282827a5941eb132d
44,269
import requests def get_geo_data(ip_address, provider): """Get geo data for an IP""" result = {"result": False, "data": "none"} if provider == 'ipapi': api = 'https://ipapi.co/' + ip_address + '/json' try: data = requests.get(api, timeout=5).json() if 'reserved' in ...
abea4e890ccdf99e18c9e27d4c9db6a5f72ba2c6
44,270
def correct_by_length(rna_type, sequence): """ This will correct the miRNA/precursor_RNA conflict and ambiguitity. Some databases like 'HGNC' will call a precursor_RNA miRNA. We correct this using the length of the sequence as well as using the length to distinguish between the two. """ if ...
888743df065fb52831c32e3e8b5a845fd362878f
44,272
def to_rating(value): """ Converts the given value to a valid numerical skill rating. Args: value (str, int, or float): The value to convert. Returns: float: The converted value. Raises: ValueError: If ``value`` cannot be converted to a float, or if the converted value is ...
b4ceb5accd9def6331a84ed4427fe88add216679
44,273
from hashlib import md5 # for md5 ID of compounds def add_compounds(smiles): """given SMILES, generate a list of dictionaries, one for each compound, ....in format that is accepted at the client side""" ret = [] for (i, c) in enumerate(smiles.splitlines()): md5id = md5(c).hexdigest() try...
d3e90ae187cb5898be2775d8a66aaafef4769b24
44,275
import os def create_label(filename): """ create label from the file name """ keys = {"Sphere": 0, "Vertical": 1, "Horizontal": 2} names = filename.split(os.sep) names = names[4].split() return keys[names[0].strip()]
a49cf4d07a07c924d6e2f30132a10f6048df19ac
44,276
def knots2m_s(knots): """knots -> m/s""" return 0.51444444*knots
f6f1e6e6e1359fa4a444a45dfdc27a900c9a5a08
44,277
import numpy def getFuzzyValue(arrPredict, arrReal, frameSize=(0,0), nSize=1, banList=[0]): """ Return a fuzzy value. Compares each cell of the two arrs. It finds the shortest distance within the nSize neighborhood where the value in the arrReal is present in arrPredict (if present). The longer the di...
12e8a816dd93189296a3051ab6733ced410de424
44,279
def validate_price(price): """ validation checks for price argument """ if isinstance(price, str): try: price = int(price) except ValueError: # fallback if convert to int failed price = float(price) if not isinstance(price, (int, float)): raise TypeError('Price should be a number: ' + repr(price)) retur...
605dc9a622f5d7fd15a9e2985d772c19ee7103ec
44,281
def clean_jaspar_names(uncleaned_jaspar_ids): """ Clean names of jaspar transcription factor names. MSX3 <- lost in humans. RHOX11 <- only present in 3 species. DUX <- mouse only gene. EWSR1 <- didn't end up in the Ensembl BioMart export. MIX-A <- jaspar says present in xenopus laevis, but n...
06869ad68b2139a455cbb1db01bacdf75a1a8882
44,282
import torch def transcribe(model, device, wav): """Calculate score on one single waveform""" # preparation inputs = model["tokenizer"]( wav, sampling_rate=16000, return_tensors="pt", padding="longest") input_values = inputs.input_values.to(device) attention_mask = inputs.attention_mask.to...
3574ed183e80b9fc34afe511e8c11c4bad70b859
44,284
import numpy def is_array(arr): """Returns True if the passed `arr` is a numpy array or a List.""" if issubclass(type(arr), (numpy.ndarray, list)): return True return False
72f7e20e0536b61f680b3592119e825333acdcb2
44,285
def gas_stations(gas, cost): """ There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of ...
494027e62da79f325ffd163f33f9924a9b88c549
44,286
def browser_labels(labels): """Return a list of browser labels only without the `browser-`.""" return [label[8:].encode('utf-8') for label in labels if label.startswith('browser-') and label[8:] is not '']
d61b26a599d240918798f74b387e09427984c6e8
44,287
def no_heading(dstr): """ Try to get just the first paragraph of a numpydoc docstring. I'm going to make some assumptions about how the docstring is formatted to make this easy. I'll assume there's a docstring heading with 2 newlines after it and that there are another 2 newlines after the first par...
ffe7c269e3f2861cc182968b2b07dcae15e1ec60
44,288
def f(x): """ int -> int Destruction of a non-tuple type """ a, b = x return a + b > 0
e5824a474d7010889344511fff53d3dd60e0aca6
44,289
def verify_graph(G, num_vehicles): """ This function verifies that the graph generated is appropriate for the LMRO problem Args: G (object): the graph as a networkx graph object Returns: is_feasible (bool): whether the graph is feasible for the project """ is_feasible = False ...
00cc3b8b0847fda7f7e44b99869a13424c589cee
44,290
from typing import Union def _get_paths(symbol: Union[str, int]) -> str: """Get the javascript pen paths associated with a given symbol. These are adapted from plotly.js -> src/components/drawing/symbol_defs.js Args: symbol: The symbol whose pen paths should be retrieved. Returns: A...
2e9a40a5e55bf1a406655bb91fa298cb0657d9ef
44,291
import base64 import struct def _decode_ints(message): """Helper for decode_qp, decodes an int array. The int array is stored as little endian 32 bit integers. The array has then been base64 encoded. Since we are decoding we do these steps in reverse. """ binary = base64.b64decode(message) ...
c30816e52ffd9336ac94026611bfe5ae869a4e8c
44,292
def strict_dict(pairs): """Creates a dict from a sequence of key-value pairs, verifying uniqueness of each key.""" d = {} for k,v in pairs: if k in d: raise ValueError("duplicate tupkey '%s'" % k) d[k] = v return d
11690b8cde2fb2163f9c07001dc5864f21e0339f
44,293
def generate_dummy_batch(num_tokens, collate_fn, src_vocab, tgt_vocab, src_len=128, tgt_len=128): """Return a dummy batch with a given number of tokens.""" bsz = num_tokens // max(src_len, tgt_len) return collate_fn([ { 'id': i, 'source': src_vocab.dummy_sentence(src_len), ...
7de3b36c57e73382a574bec599e2e62bcf8961a9
44,294
def bitmap_sum(band1, band2): """ a functions that marks occupied bitmap by 0 if the slot is occupied in band1 or in band2 """ res = [] for i, elem in enumerate(band1): if band2[i] * elem == 0: res.append(0) else: res.append(1) return res
e9a7739c8f7d04d83cede13daf1342383ba544d1
44,295
def create_env_index(replay_buffer): """Creates the mapping from env_name to their index in the replay buffer.""" env_index = {} buffer_items = sorted( replay_buffer.traj_buffer.iteritems(), key=lambda k: k[0]) for idx, (env_name, _) in enumerate(buffer_items): env_index[env_name] = idx return env_i...
9391e139cb66031fcaf50c1871f8f14ab0adb7f8
44,296
import re def hasSpecialSymbols(passW): """ Checks if the password has special characters """ if(re.match(r'^_-:,;<>+"*ç%&/()=?"',passW)): return True return False
eca5e44353f239e372dc186a9b86f865c214578c
44,297
def millisToString(millis): """Taken from Rivalis OV1Info""" hours, x = divmod(int(millis), 3600000) mins, x = divmod(x, 60000) secs, x = divmod(x, 1000) x, y = divmod(x, 10) #return "%d.%02d" % (secs, x) if mins == 0 else "%d:%02d.%03d" % (mins, secs, x if mins==0: return " %02d:%...
d96ff3f473201aef95eb6a8b6caed371ac234060
44,299
import os import random import string def _get_temporary_symlink_name(branch_builds_location, length=10): """ Returns a temporary and random symbolic link name which starts with 'last-' :param branch_builds_location: - the base path or the parent folder to the symlink file :param length: length of the ran...
070333bda43dee1e5982cae90b00a7e55bacc7d7
44,303
import random def get_code(): """ 生成随机的六个数,用来当作验证码 :return: """ code = random.randint(100000, 999999) return code
0dabd45d0ed259669534b0276902512e40e0e940
44,304
def blank_string(str, start, end, full=True): """replaces the text between the start and end with spaces.""" return str[:start] + " " * (end - start) + str[end:]
12c8ca34503cf2d5164573d4c29784531a99d2a5
44,305
import json def convert_json_to_dict(json_data): """Converts JSON data containing location info on an IP address to a Python dictionary""" loc_dict = {} # Replace default key:'ip' with new key:'source_ip' to match the other data new_key = "source_ip" old_key = "ip" try: loc_dict = jso...
aee4c5d2d643ba25f6c66d222a1aeb3a86611ab8
44,307
def number_of_tweets_per_day(df): """ Return a dataframe containing the dates and number of tweets per day. The format of date is to be yyyy-mm-dd. Args: df(dataframe): pandas dataframe Return: dataframe with columns containing the date and tweets """ df['Date'] = [i.split()[0]for i i...
2f01baffd44d904a8288cf83a8adbcdbf7b3f115
44,308
import codecs def hex_to_base64_str(hex_str: bytes) -> str: """Covert a hexadecimal string into a base64 encoded string. Removes trailing newline character. :param hex_str: the hexadecimal encoded string. :return: the base64 encoded string. """ string = codecs.decode(hex_str, "hex") base64 =...
1f8f58e94f846c9fc12cfb2b023fa2fde286fc35
44,310
def DetailedHelp(version): """Construct help text based on the command release track.""" detailed_help = { 'brief': 'SSH into a virtual machine instance', 'DESCRIPTION': """\ *{command}* is a thin wrapper around the *ssh(1)* command that takes care of authentication and the translation o...
b0afca55c5538ce903fd3c2a2175e7df57c71c7c
44,311
from typing import Any def is_byte_data(data: Any): """ Checks if the given data is of type byte :param data: The data to check :return: Whether the data is of type bytes or not """ return type(data) is bytes
3b04758f812220b97f21c15cacc4773c92b5bb30
44,312
def find_matrix(matrix): """finds smallest array without empty rows/colums""" min_row = len(matrix) min_col = len(matrix[0]) max_row = max_col = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j]: min_row = min(min_row, i) ...
9ee377964a4d254a2fdb4d36100fdc9fad2f7097
44,313
import tempfile import tarfile def extract(filepath): """uncompress and extract file""" tmpdir = tempfile.gettempdir() with tarfile.open(name=filepath, mode='r:gz') as tf: for ti in tf.getmembers(): if ti.name.endswith('.mmdb'): tf.extract(ti, tmpdir) re...
cf22a215921d2f6b47499d7d160c813baf309f33
44,314
import requests def check_http_connectivity(url, timeout=None): """Check HTTP connectivity.""" try: return requests.get(url, timeout=timeout, stream=True).ok except requests.RequestException: return False
b756d11c47352cb0f5966a71203e6b757f79598e
44,315
def insertion_sort(arr): """Refresher implementation of inserstion sort - in-place & stable. :param arr: List to be sorted. :return: Sorted list. """ for i in range(1, len(arr)): tmp = arr[i] j = i # find the position for insertion for j in range(i, len(arr)): ...
2d969c0f1cfeb85a093cf28663bf2ca940dc9d7c
44,316
import math def damage_function(variables): """ The damage that the attacking pokemon inflicts to the defending pokemon. The formula is as described by: https://www.math.miami.edu/~jam/azure/compendium/battdam.htm The variable dictionary has the following keys ---------- level : int ...
f23a3a89c8486abab7a0bd0ae6d0d50a8b17c3c8
44,317
def contain_all_elements(lst, other_lst): """ checking whether the second contains a list of all the elements of the first :param lst: first list :param other_lst: second list :return: check result """ diff = set(other_lst) diff -= frozenset(lst) return not len(diff)
d7e62d7ed2b163b6ed70d339f0e944c01b8f4ca7
44,319
import statistics def stdeviation(data): """ Returns standard deviation of the data """ return statistics.stdev(data)
77bf744f553713a02505934488bcfa1cd0242674
44,321
def header_transform(key: str) -> str: """ Function returns header key in human readable :param key: header key :return: translated headers """ header_dict = { 'Cve': 'CVE ID', 'CVSS': 'CVSS Score', 'VRR': 'VRR Score', 'ThreatCount': 'Threat Count', 'Vuln...
d5c654dc9c31b2fbbe412487692e2052810dde10
44,322
def getAxisVector(axis, sign=1): """ Return a vector for a signed axis """ i = int(axis) v = [0, 0, 0] v[i] = 1 * (1 if sign >= 0 else -1) return tuple(v)
8f223b0ce843a21ab5fd4403bbc9dc31fa1ca819
44,323
def _dist(p, q): """Returns the squared Euclidean distance between p and q.""" dx, dy = q[0] - p[0], q[1] - p[1] return dx * dx + dy * dy
da387e1e8298e962add266d131528ffc435de10d
44,324
def dec_to_set(row): """Convert the dec columns into a set, and fix the sign. """ if '-' in row['sign']: return (-1*row['dec_deg'],row['dec_minutes'],row['dec_seconds']) else: return (row['dec_deg'],row['dec_minutes'],row['dec_seconds'])
115b27c2ab96857bdc05dc9975b6e2d010522b6f
44,325
def is_numpy(value): """Check 'value' is numpy array or not. Args: value (any, required): The value to check. Returns: bool: True if 'value' is valid, False if it is not. """ if f"{type(value).__module__}.{type(value).__name__}" == 'numpy.ndarray': return True return ...
56df30320d9484bfe3b7330c078e65cdc3648b0d
44,326
def _calculate_score_for_underpaid(current_salary, level_salary): """ Maximize how much each dollar reduces percent diff from level salary. Higher scores get raise dollars first :param current_salary: :param level_salary: :return: """ assert current_salary <= level_salary absolute_diff =...
08e1346df66f4ac913f01e9a19baa7e6e6455f2f
44,327
import itertools def hamming(a, b): """Compute the hamming distance between 2 int. :param a: a 64 bits integer :param b: a 64 bits integer :type a: int :type b: int :return: the hamming distance between a, b :rtype: int """ a = bin(a)[2:][::-1] b = bin(b)[2:][::-1] it = ...
95b9f6658421a0976840a3e0e474729d94c4fbe4
44,328
import textwrap def wrap(s: str) -> str: """Dedent and wrap a string to 79 characters.""" return textwrap.fill(textwrap.dedent(s), width=79)
0622063a144fbeba677d8bb02b9af01d9576515f
44,330
async def searchtasknumber(tasknumber: str) -> str: """search tasknumber""" if tasknumber[1] == '0': tasknumber = tasknumber[0]+tasknumber[2:] #if tasknumber[2] == '0': # tasknumber = tasknumber[0]+tasknumber[1]+tasknumber[3:] with open("./data/task.csv", 'r', encoding="utf-8-sig") as csv...
bf211af4a62ac362424ff1aa202492ff63b43fec
44,331
def get_overlap(time_window0, time_window1): """ get the overlap of two time windows :param time_window0: a tuple of date/datetime objects represeting the start and end of a time window :param time_window1: a tuple of date/datetime objects represeting the start and end of a time window :retu...
c267287b4aaa543f6ebeef5c34ca0e349153dc4b
44,332
def _is_scan_complete(hdr): """Checks if the scan is complete ('stop' document exists) Parameters ---------- hdr : databroker.core.Header header of the run hdr = db[scan_id] The header must be reloaded each time before the function is called. Returns ------- True:...
2616d6c504e7648d18af2789f69608bd8da9eccc
44,333
import os def split(path): """Return dir, name, ext.""" dir, name_ext = os.path.split(path) name, ext = os.path.splitext(name_ext) return dir, name, ext
0533ed12a0015a6e99e9dba1ec619f60a9d4f5e1
44,334
import subprocess def transform_data(transform_shell_cmd, input_data): """Transform the ``input_data`` using the ``transform_shell_cmd`` shell command. """ proc = subprocess.Popen( transform_shell_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ...
f3dd46175fdf7a70d8aac75193f8a4852b34c3dc
44,335
def get_avg_fps(PIL_Image_object): """ Returns the average framerate of a PIL Image object """ PIL_Image_object.seek(0) frames = duration = 0 while True: try: frames += 1 duration += PIL_Image_object.info['duration'] PIL_Image_object.seek(PIL_Image_object.tell...
be5c5cd976cd7e08e21b0f402e991954b0f42ecc
44,336
def index(): """ Main index page """ response = { 'status': 'success!!!' } return (response, 200)
b0418dfdfddc62d62bd9ad26b07b55c55ed7b50a
44,337
def read_pgroups(in_file): """Read HLAs and the pgroups they fall in. """ out = {} with open(in_file) as in_handle: for line in (l for l in in_handle if not l.startswith("#")): locus, alleles, group = line.strip().split(";") for allele in alleles.split("/"): ...
9d1a2da00b457a50576e7e7b26eaffb4fa5018af
44,338
def parse_args(param_string): """Parse a string of comma separated arguments such as '42,43,key=abc' into a list of positional args [42, 43] and a dict of keyword args {key: abc}""" if not param_string: return [], {} posargs = [] kwargs = {} param_strings = param_string.split(',') f...
f6e9257cce7ec0eae8767e5daea6966c47416f1d
44,339
import re def cityscape_structure(filename): """ Parse the structure of Cityscape file names. :return: city, seq:0>6, frame:0>6, type, ext """ regex = r"([a-zA-Z]+)_(\d+)_(\d+)_([a-zA-Z0-9]+)_*([a-zA-Z]*.[a-zA-Z]+)" elems = re.compile(regex).findall(filename)[0] return elems
dd08832282bc1d840c5eb912bb09770da87376e8
44,342
import os def _to_abspath(base_path, dir_path): """Return an absolute path within dir_path if the given path is relative. Args: base_path (str): a path to the file to be examined. dir_path (str): a path to the directory which will be used to create absolute file paths. Return...
3b0229d71c7ce77ff59f598aebc2e0395b85eee7
44,343
def _regret_matching(cumulative_regrets, legal_actions): """Returns an info state policy by applying regret-matching. Args: cumulative_regrets: A {action: cumulative_regret} dictionary. legal_actions: the list of legal actions at this state. Returns: A dict of action -> prob for all legal actions. ...
5772907c78e18895561729eb39185cf4a1dee281
44,344