content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def calculate_precision_recall_f1score(y_pred, y_true, entity_label=None): """ Calculates precision recall and F1-score metrics. Args: y_pred (list(AnnotatedDocument)): The predictions of an NER model in the form of a list of annotated documents. y_true (list(Annotat...
8352285bb099230e9bd5b2fd4d9244c95c4f3ed0
689,582
def db_object_to_dict(row): """ turn custom database table object into a dict so it can be sorted in template """ return dict((col, getattr(row, col)) for col in row.__table__.columns.keys())
4475385e84cca0edb5f21055f3e1a9bf9dd37232
689,583
import sys import subprocess def cygpath_u(pathname): """Convert a pathname to Cygwin style /cygpath/X/foo/bar.""" if sys.platform == "cygwin": pipe = subprocess.Popen( ["cygpath", "--unix", pathname], stdout=subprocess.PIPE ).stdout for line in pipe: ...
6fdfd312437259ab8d15e18f5445a5ba3195061e
689,584
def association_rules(freq_sets, supports, min_conf): """ 生成满足最小置信度的关联规则 :param freq_sets: :param supports: :param min_conf: :return: """ rules = [] max_len = len(freq_sets) # 生成关联规则,筛选符合规则的频繁集计算置信度,满足最小置信度的关联规则添加到列表 for k in range(max_len - 1): for freq_set in freq_set...
71960dba16d8e142403d99307622662df075dd87
689,585
def parse_varint(tx): """ Parses a given transaction for extracting an encoded varint element. :param tx: Transaction where the element will be extracted. :type tx: TX :return: The b-bytes representation of the given value (a) in hex format. :rtype: hex str """ # First of all, the offset o...
b77b58efd8bd5fa9d69b302f403a6f7632c045b0
689,586
import webbrowser import sys import os def launch_browser(attempt_launch_browser=True): """Decide if we should launch a browser""" _DISPLAY_VARIABLES = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"] _WEBBROWSER_NAMES_BLACKLIST = ["www-browser", "lynx", "links", "elinks", "w3m"] launch_browser = attemp...
74700e46162a89e6b0f935ca74535a53cd637ae5
689,587
def my_over_sample(row_integers_list_to_balance, df_in, feature_to_balance_on='TARGET', ret='row_integers_list'): """Parameters: row_integers_list_to_balance: list or numpy array list of indices we are balancing df_in : Pandas Dataframe ...
5f8e0e620f80a841731b4fb5987166be3869b9f5
689,588
def get_func_and_args_from_str(call_str): """Parse call string to get function and argument names. Args: call_str: Call string must be in the form: `tf.foo(arg1=val1, arg2=val2, ...)`. Returns: (function_name, list of arg names) tuple. """ open_paren_index = call_str.find("(") close_...
8224aaf86335cd1112673e98da3f827c51aed42e
689,589
import json def read_from_json(full_path_with_name): """Read from an arbitrary JSON and return the structure""" with open(full_path_with_name, 'r') as mjson: return json.load(mjson)
8a547311689229ff707d19049d9eac5d016f99c0
689,590
def parse_host(host, default_port=None): """Parse a canonical 'host:port' string into parts. Parse a host string (which may or may not contain a port) into parts, taking into account that the string may contain either a domain name or an IP address. In the latter case, both IPv4 and IPv6 addresses ...
d328b940484680a6fe15ca301f9eb855232735b3
689,591
def _check_db_type(db_dict, ref): """Function to access reference links, and handle when those links are not in DB table""" if ref in db_dict: return db_dict[ref]["!IsOrIn"] else: return "Is"
45f757506f72e9113492b721e8dfcec684e3e11d
689,592
def xml_tag_name(tag_name: str) -> str: """Cleans anonymous tag-names for serialization, so that the colon does not lead to invalid XML:: >>> xml_tag_name(':Series') 'ANONYMOUS_Series__' :param tag_name: the original tag name :returns: the XML-conform tag_name """ if tag_name[:...
7fe39805cb1711d88b7f5c07cf90259eb6ab11b9
689,594
import os def dir_to_list(directory, filetype): """ Function to find a filetype in a directory and place the filename in a list that is returned. """ filenamelist = set() for file in os.listdir(directory): if file.endswith(filetype) and not file.startswith('.'): filenamelis...
2d896ce7de0d7cd332d5fbfabcb15be06edf2642
689,595
import uuid def default_test_msg(prefix='', suffix='', sep=' '): """Create a random test string""" return sep.join([prefix, uuid.uuid4().hex, suffix])
945c6aac41cb4e1d6a87af8461b0fdafea8150b9
689,596
import re def polished(summary): """ Polish summary, e.g. by cutting and trimming it. Args: summary: summary text to polish Returns: (part of) polished summary """ first_sentence = re.search('.*\.', summary) if first_sentence: return first_sentence.group().str...
85388465a78d7e669c0fc0f35ad27ac19b35d807
689,597
def sample_exposure(image, sample_indices): """ A helper function which samples the given image at the specified indices. :param image: a single RGB image to be sampled from :param sample_indices: an array of the length N with the indices to sample at. N is the number of pixels :return: sampled_re...
e2aec26e6be74d49c35e7ea80f894fe873817e86
689,598
def triangular(n): """Gives the n-th triangle number.""" return n*(n+1)/2
17b5cbd0f690dbf0043ea84da3fef56c82812599
689,599
def _get_command_prefix(properties): """ If multiple commands are registered with the same name, attempt to construct a unique prefix from other information in the command's properties dictionary to distinguish one command from another. Uses the properties' ``app`` and/or ``group`` keys to create the ...
881765a59fdf34c6789f341cb8d60ca5dd6a2725
689,600
import os import codecs def local_read(filename): """Convenience function for includes.""" full_filename = os.path.join( os.path.abspath(os.path.dirname(__file__)), filename ) return codecs.open(full_filename, "r", "utf-8").read()
aa822897c462776a6086ddf11254e86bdd94fdc9
689,601
import os def os_conditional_compile_block(config): """For use as a mako filter. That wraps a block of text in #if blocks based on the config's OS support. """ windows_only = config.get("windows_only", False) def windows_only_block_impl(text): # Pure python code, by default, will convert...
63af0b6f35764981af721de159fb8471771e2267
689,602
def inline_eq(): """Finds inline equations. """ return r'\$[^\$]+\$'
87b1c5c5da48036b39467140c8ee52c00bddb8c4
689,603
from pathlib import Path def in_qmk_firmware(): """Returns the path to the qmk_firmware we are currently in, or None if we are not inside qmk_firmware. """ cur_dir = Path.cwd() while len(cur_dir.parents) > 0: found_lib = cur_dir / 'lib/python/qmk/cli/__init__.py' found_quantum = cur_di...
989aa42520de5694fa96e22afcd3cf692e55e519
689,606
from typing import List def extract_words(input_file_name: str) -> List[str]: """ Extracts a list of words from a word list. Expects one word per line. :param input_file_name: the path of the file to extract the words from :return: a list of words """ input_tokens = [] with open(input_file...
9cfe983f7e148c60a551ddd87bfcaa8ed02598a6
689,607
def checkbox_result_to_bool(res): """ Takes in a checkbox result from a form and converts it to a bool Params: res (str): the result string from a checkbox Returns: bool: the boolean value of res """ if res == "on": return True elif res == "off" or res is None: ...
67b1c1a17a0b7f41ee5ed66a64641f0104acf8b7
689,608
def EQUAL(x, y): """checks if both given arguments are equal""" return x == y
64c1029ec8b98177ed3210743a020fd950b61fcd
689,609
import torch def batchLSIGF(h, SK, x, bias=None): """ batchLSIGF(filter_taps, GSO_K, input, bias=None) Computes the output of a linear shift-invariant graph filter on input and then adds bias. In this case, we consider that there is a separate GSO to be used for each of the signals in the bat...
b7481ee2264185862f3f0d14141bc9bce0147e29
689,610
def save_student_priorities(request): """save the Student internship priorities in the DB """ return NotImplemented
416ea8be22d5819cd31d12fb43764a5842e21397
689,611
def alphaB(T): """ Returns Case B recombination coefficient (Osterbrock 1989; Krumholz+07) 2.59e-13*(T/1e4)**(-0.7) """ return 2.59e-13*(T/1e4)**(-0.7)
e5e5a870f2bc50948648dd5ad9ba5a608315e70f
689,612
def cmd_injection_check(data): """OS Cmd Injection from Commix.""" breakers = [ ';', '%3B', '&', '%26', '&&', '%26%26', '|', '%7C', '||', '%7C%7C', '%0a', '%0d%0a', ] return any(i in data for i in breakers)
3883703dc25aac1454b8917049aca58e94c7fca7
689,613
def lock_held(): """Return False since threading is not supported.""" return False
7d42dc60fa791fa4b022df411907b65a0db04333
689,614
def parseDialogScriptMenu(filename, defchoices=[]): """This function parses a disk file specified by the filename. The file is parsed such that comments ('#') are stripped and lines containing exactly 2 arguments are printed out. Quotes are handled. The function can be used by dialog s...
fe9b376fb95a0a544ae0c3a20c9df7a36cc5793e
689,615
from typing import List def get_output(expression: str, input_names: List[str]) -> str: """Get expression for outputs.""" output_value = "" # for parameter references # might have to change, In case there's more than one ~{} if "~" in expression: start_index = expression.find("~{") ...
07744c844d921d57807802d5591428189a09a107
689,616
def first_non_repeating_letter(the_string): """ Find first non-repeating letter in a string. Letters are to be treated case-insensitive, which means 't' = 'T'. However, one must return the first non-repeating letter as it appears in the string, either in uppercase or lowercase. 'sTress'...
b3faf048b1e81e48f9af7b0f295bf60f9bfde4f9
689,617
def sj_error(errorprofile): """Find characters that are not _""" errorset = set(errorprofile.split(">")[0][21:31]) errorset.update(set(errorprofile.split(">")[1][0:10])) return not {"_"} == errorset
6a275a2d2330d2dbc8a680e00d7ac7e135c0001c
689,618
def is_perim_link(link, grid): """Return True if both nodes are boundaries; False otherwise. Examples -------- >>> from landlab import HexModelGrid >>> import numpy as np >>> mg = HexModelGrid( ... (3, 4), spacing=1.0, orientation="vertical", node_layout="rect" ... ) >>> is_peri...
6393cc77eae7ab656fa5d5dea14481b5fc612a5a
689,619
def weak_pareto_dominates(vec1, vec2): """ Returns whether vec1 weakly dominates vec2 """ for i in range(len(vec1)): if vec1[i] < vec2[i]: return False return True
ed5b6ea17bb8a12bb6deef430dec996c7363be3d
689,620
def HtmlString_to_HtmlFile(html_string,file_name="test.html"): """Saves an html string as a file with the default name """ out_file=open(file_name,'w') out_file.write(html_string) out_file.close() return file_name
bc4eca26877053f3eddd9ffd42bfd5801bf11c74
689,621
import requests import tempfile def download_file(url): """ Download and return temporary file """ print("url detected, downloading...") response = requests.get(url) # detect file type from MIME-TYPE of request content_type = response.headers['content-type'] if content_type == 'application/pdf': ...
a7aeb60dbc06764fb131dfb27cd73ec0023b56e4
689,622
import struct def signed_word2py_int(data, be=False): """ Converts word of bytes to Python int value. """ sig = '>h' if be else '<h' return struct.unpack(sig, data)[0]
81016cbdba812b501cc8aa05d1e4237e5f75c7f7
689,623
def comma_list_to_shape(s): """Parse a string of comma-separated ints into a valid numpy shape. Trailing commas will raise an error. Parameters ---------- s : str A string of comma-separated positive integers. Returns ------- tuple """ if not isinstance(s, str): ...
6ca5358336e0356e8c7c540fb5dd977d0dbe07f9
689,624
import os def fetch_image_paths(images_dir, image_uids): """Fetch Flickr 8K image paths corresponding to the list of image UIDs.""" image_paths = [] for uid in image_uids: image_paths.append(os.path.join(images_dir, f"{uid}.jpg")) assert os.path.exists(image_paths[-1]) # lazy check :) ...
64c84f5c7b29163f598496fef3ca2fe1026b15d3
689,625
def to_edge(x): """to_edge""" r = x[:, 0, :, :] g = x[:, 1, :, :] b = x[:, 2, :, :] xx = 0.2989 * r + 0.5870 * g + 0.1440 * b xx = xx.view((xx.shape[0], 1, xx.shape[1], xx.shape[2])) return xx
00c1a6bec52af166b85f6d9013c4a92895f94366
689,626
def compress_column(col): """takes a dense matrix column and puts it into OP4 format""" packs = [] n = 0 i = 0 packi = [] while i < len(col): #print("i=%s n=%s col[i]=%s" % (i, n, col[i])) if col[i] == n + 1: #print("i=n=%s" % i) packi.append(i) ...
37a397df9c432e5dd977faeb65f71f44a1361bd1
689,627
import requests import logging def trash_single_email(id, access_token): """ Will get messages for a user """ url = f"https://www.googleapis.com/gmail/v1/users/me/messages/{id}/trash?access_token={access_token}" headers = {"Content-Type": "application/json"} payload = {} r = requests.reque...
1d7ee9cf3e83df90410119a36cba5c154c9b903f
689,628
def has_juniper_error(s): """Test whether a string seems to contain an Juniper error.""" tests = ( 'unknown command.' in s, 'syntax error, ' in s, 'invalid value.' in s, 'missing argument.' in s, ) return any(tests)
5363806c8e7f0f791cffd5614626198ff323e27f
689,629
def factorial(num): """ (int) -> int Calcula el factorial de un número entero >>> factorial(3) 6 >>> factorial(4) 24 :param num: int el numero a evaluar :return: int el resultado del factorial """ if num == 1 or num == 0: return 1 elif num < 0: raise Va...
13ab92c6462ac180340097726d16ff9d898ca04d
689,630
import argparse def parse_args(args): """Parse command line parameters Args: args ([str]): command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser( description="An example with Snels...
45aa7f015b658fb393f67a91eb84a6174546b527
689,631
def condition(cond, rule): """ Only apply rule if condition is true """ def conditioned_rl(expr): if cond(expr): return rule(expr) else: return expr return conditioned_rl
cfa8af9362fa2e8bf5f50cb7d08454ef0d241d7b
689,632
import json def to_json(obj): """ Converts the given object to a json string :param obj: The input object :type obj: object :return: object as json string :rtype: str """ return json.dumps(obj)
db66422fe3d87fe2469a1d2b4cfaa3ab81cd1eb0
689,633
def is_tricyl_facegroup(faces): """ is the face group a tri cylinder Returns a bool, true if the faces make an extruded tri solid """ # tricyl must have 5 faces if len(faces) != 5: # print('1') return False # Check for quads and that there are 6 unique verts verts = {}...
df485cfe78418dd929ad46a141191e868e334208
689,635
from datetime import datetime def set_date_from_string(value: str, format_: str = "%Y-%m-%dT%H:%M:%S"): """Generic function to format a string to datetime Args: value: The value to be validated. format_: A regex pattern to validate if the string has a specific format Returns: A datetime obje...
a5b1bf0356952d1faf4c61815bb8b6e4e0b50f9d
689,636
def create_software() -> bytes: """ software string * 32 bits [4 bytes] value boundary """ text = 'Python Stun Mock Server v1.0' hex_text = text.encode('utf-8').hex() pad = len(hex_text) % 4 and 4 - len(hex_text) % 4 return bytes.fromhex(hex_text) + pad * bytes.fromhex('00')
73466a49d5d887cc4425de5d2ed39fa38db02aed
689,637
def ChkCTStarOnly(cron_time_field): """Checks if a crontab field is only a *. Args: cron_time_field: Parsed cron time field to check. Returns: True if there's only a * in this field. """ if not cron_time_field: return True if len(cron_time_field) == 1 and cron_time_field[0].Kind == 'star': ...
127eb83646315fc5e4917fa9ece4aab790035d71
689,638
def _stripBold(s): """Returns the string s, with bold removed.""" return s.replace('\x02', '')
da94e26846091ac3c4a501b86cd00a18bf06b1c1
689,640
def capitalize_title(title): """Convert the first letter of each word in the title to uppercase if needed. :param title: str - title string that needs title casing. :return: str - title string in title case (first letters capitalized). """ return title.title()
38334a5d7e7ceb76f87df8ff00f77da5c9c4ca88
689,641
def perspectiveTransform(x, y, M): """ Implementation of the perspective transform (homography) in 2D. **Parameters**\n x, y: numeric, numeric Pixel coordinates of the original point. M: 2d array Perspective transform matrix. **Return**\n xtrans, ytrans: numeric, numeric ...
28bdc116a515d5fc7fee41335c6960d3e18e1114
689,642
def get_user_plist_path(): """ Helper function returning the path to the user account property list. """ user_plist_path = "/private/var/db/dslocal/nodes/Default/users/" return user_plist_path
4f378843016c1604b08dded048e5287957146707
689,643
import collections def _transform_allocation_requests(alloc_reqs): """Turn supplied list of AllocationRequest objects into a list of dicts of resources involved in the allocation request. The returned results is intended to be able to be used as the body of a PUT /allocations/{consumer_uuid} HTTP requ...
84492de0e11c2ceaff1a3c25adea32c239342744
689,644
def get_output_size(labels): """ Gets the output layer's size of a model from the set of training labels Args: labels: list of labels Return: an int, the number of output units required """ if isinstance(labels[0], float): # regression task return 1, "regression" classes = len(set(labels)) out_size...
dc5ea3bc8321f9673a3c17b47744b971701d2824
689,645
def decode_time(value): """time decoder Used for fields such as: duration=1234.123s """ if value == "never": return value time_str = value.rstrip("s") return float(time_str)
ef03545b3653dfdbd91e64de06a08bb25e8ea396
689,646
import os import tempfile import shutil import subprocess def zip_directory_to_blob(source_dir, name): """Copy a directory, zip it, and return the zip-file as a binary blob.""" source_dir = os.path.abspath(source_dir) with tempfile.TemporaryDirectory() as temp_dir: original_working_directory = os....
0e26cd270a80ed33e0afd29bac0905c374f014ed
689,647
import json def recv_client_event(ws): """ Reads an event off the websocket. """ return json.loads(ws.recv())
6550162b5274f46521fb0031c41a0445664d28e7
689,649
def inverse_distance_weight_1d(value_array, sample_value, value_domain=(0, 1), cycle_value=False): """ Returns the inverse distance weight for a given sample point given an array of scalar values :param value_array: list<float>, value array to calculate weights from :param sample_value: float, sample po...
f313e0df56de6fb58f1a4cd34278fb18f55a8e73
689,650
import argparse def get_command_line_args(): """ Read command line args, of course.""" parser = argparse.ArgumentParser() parser.add_argument("-n", "--no-checkbox", action="store_true") parser.add_argument("-c", "--cumulative", action="store_true", help="Plot cumulative values") parser.add_argumen...
0933527e5a19eff7fc81e13ae1b19c723d17d53c
689,652
def InstanceOverlap_OLD(instance1,instance2): """Returns True if given instances share a vertex.""" for vertex1 in instance1.vertices: if vertex1 in instance2.vertices: return True return False
0bbc42cc09ea0f67b8a04772eb0581b081dbb6dd
689,653
import torch def evaluate(data_loader, model, device): """ This function does evaluation for one epoch :param data_loader: this is the PyTorch DataLoader :param model: pytorch model :param device: cuda/cpu """ # put model in evaluation mode model.eval() # init lists to store targe...
27d13a284779cc6c118c16a2616d40165bc94a12
689,654
import numbers import string def build_coder(shift): """ Returns a dict that can apply a Caesar cipher to a letter. The cipher is defined by the shift value. Ignores non-letter characters like punctuation and numbers. The empty space counts as the 27th letter of the alphabet, so spaces should be m...
6d5df2c482fbce402ace08b4eda2e163f8352a2b
689,656
def apply_ucrow_aggregation(X): """ Given a tensor of activations, aggregate by sum-pooling without weighting. :param ndarray X: 3d tensor of activations with dimensions (channels, height, width) :returns ndarray: unweighted global image feature """ return X.sum(axis=(1, 2))
3094104c5eca326016825554f2429729822c10fe
689,657
def get_latest_instance_site(site, model): """ Returns latest instance for models with site """ latest_instance_site = model.objects.filter(site=site).order_by('-id') if latest_instance_site: return latest_instance_site[0] else: return None
85d77cc8dfcaac4179d4e173a3f2cedc3e245568
689,658
def update_sex_freqs(record, pop=None): """ Recompute allele frequencies for variants on sex chromosomes outside of PARs """ if pop is not None: m_prefix = '_'.join([pop, 'MALE']) f_prefix = '_'.join([pop, 'FEMALE']) else: m_prefix = 'MALE' f_prefix = 'FEMALE' m...
a661e5a2944931fdb2a7d8c5ecbb0fc389533e91
689,659
def sw_delete_lag(sw, lag_name): """Deletes LAG from OVSDB.""" cmd = 'del-port ' + lag_name return sw(cmd, shell='vsctl')
83910404b1a655c47cfb0caf0f60d517d5a6646c
689,660
def apply_policy_substitution (compartment_name :str, parent_compartment_name:str, group_name, policy): """ performs the value substitutions into the policy statement Args: compartment_name (str): compartment name to apply parent_compartment_name (str): parent compartment name group_name ([type...
035036f50db7061b63bbdb9abefa4f0d6ffd4092
689,661
def primes_sieve(limit): """ Sieve of Eratosthenes. """ limitn = limit + 1 not_prime = set() primes = [] for i in range(2, limitn): if i in not_prime: continue for f in range(i * 2, limitn, i): not_prime.add(f) primes.append(i) return primes
1075c4e713e6fd0a5c1bfb18da231a2957fd981c
689,662
def create_groupings_columns(groupings_params): """ Strips all other parameters from groupings except name and columns """ new_groupings={} for grouping_name, grouping_values in groupings_params.items(): for values_name, values in grouping_values.items(): if values_name is 'colum...
249964be2d6077a251cc7bf5751d38ac9cff1c2b
689,663
def _container_exists(blob_service_client, container): """Check if container exists""" return next(blob_service_client.list_containers(container), None) is not None
d59f7e517876f093bbba8a580dd3fe31895075e2
689,664
import re def parse_doi(doi: str) -> str: """Parses a DOI from e.g. a URL. Args: doi: DOI string. Returns: The (possibly trimmed) DOI. Raises: ValueError: if the DOI cannot be parsed. """ # See https://www.doi.org/doi_handbook/2_Numbering.html#2.2. match = re.sea...
af636a3b220cafbfbcbc58ee1c3591ce6bb1fb2c
689,665
import itertools def four_body_sum(spins): """Calculate four body term in the periodic lattice Input: spins: spins configuration matrix. Output: sum of four body terms. """ size = len(spins) Sum = 0 for i,j in itertools.product(range(size), repeat=2): Sum += spins[i,j] * s...
3e1408e1618db137489d29b0ee93b1ee7d88564f
689,667
def _get_positive_int(raw_value): """Convert the raw value for api/patch into a positive integer.""" value = int(raw_value) if value < 0: raise ValueError('negative') return value
c7a1e380c2b7f0cc40f7ed6c9027cdca7cad98a0
689,668
import os import time def catalog_creation_payload(**kwargs): """ :return: dict representing the payload """ catalog_type = kwargs['repo_type'] source = None source_path = "" filename = "" user = "" domain = "" password = "" if catalog_type == 'DELL_ONLINE': source ...
346e904d421a81618bfb8e577246da349f93534b
689,669
import random import socket def get_random_port(): """Find a random port that appears to be available""" random_port = random.randint(25000, 55000) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: result = sock.connect_ex(("127.0.0.1", random_port)) finally: sock.close...
70955c382f95a313a9e10447be998f701574c4a9
689,670
def sanitize_evar(envv): """Checks an environment variable definition and ensures that it is compatible with ariadne's pipeline module. """ toks=envv.split('=') pathappend=toks[1].split(':') print(pathappend) if len(pathappend)>1: print("yarr"+toks[0]+'='+pathappend[1]) re...
4a25d4cbdcd5ae61d7b71e1df94ec3120f9f7b31
689,671
def is_token_subtype(ttype, other): """ Return True if ``ttype`` is a subtype of ``other``. """ return ttype in other
b96471a5c1f8e7bbc2c7e9628c86bf31797c60ee
689,672
from hashlib import md5 def part2_adventcoin_miner(secret_key, match='000000'): """ --- Part Two --- Now find one that starts with six zeroes. """ for x in range(99999999): newkey = md5(secret_key + str(x)).hexdigest() if newkey[:len(match)] == match: return (x)
50bd8fffab429be86dd62e7c438ae703acc383da
689,673
import argparse def parse_command_line() -> object: """Parse the command line for inbound configuration parameters.""" parser = argparse.ArgumentParser(description="Falcon Flight Control child host CID lookup.") parser.add_argument( '-k', '--client_id', help='CrowdStrike Falcon API...
ddc441fa43ff2cf41c807ce14a1fe8d8917c8a98
689,674
def listify(item_or_list): """ This function converts single items into single-item lists. """ return item_or_list if isinstance(item_or_list, list) else [item_or_list]
733ac29f204bdf856a9c23ef4ed6558b6eeb59cc
689,675
def duration(duration_ms: float) -> str: """ Formats duration into a string logged in stats :param duration_ms: Duration in milliseconds :return: formatted duration """ return "{:.2f}ms".format(duration_ms)
1eb79456bc3ec2c37fda07f8eac719cf6591da5f
689,676
def ratio_transform(factor): """ Factory function for ratios per population transformers. """ return lambda model, col, idx: factor * model[col, idx] / model.population
7028100b5bae096e8907a3bc11cc800a51217403
689,677
import os def appendExtensionToPathSpec(dataPath, ext=None): """Helper function for consistent handling of paths given with separately passed file extensions Returns ------- result: string dataPath dataPath string formed by concatenating passed `dataPath` with "*" and passed `ext`, with some ...
816527f7263614a88b826cc857d00d3b05fa5a34
689,678
import argparse def create_parser(): """ Creates a parser program """ parser = argparse.ArgumentParser(description='RSA Algorithm') parser.add_argument('-e', '--encrypt', help='encrypt data', default=False, action='store_true') parser.add_argument('-d', '--decrypt', he...
84947304788f0e787ac1e812f5c653e850501dac
689,680
def decrypt_block(n, suffix, pre_len, length, oracle): """ Decrypts a 16-byte block of the hidden suffix appended to the user input in the encryption oracle. """ for i in range(16): # If length of suffix is equal to the pre-determined suffix length, # return the suffix. if le...
856d5a342e0949622fd907dc84b77cb303428b25
689,681
def sum_weighted_losses(losses, weights): """ Args: losses: Dict of scalar tensors. weights: Dict of weights. """ loss = 0 for k in losses.keys(): if weights is None: loss = loss + losses[k] else: loss = loss + weights[k] * losses[k] ...
01361eec59203708541c3ded44cad774b5ac8746
689,682
def compare_probs(post_a, post_b): """Compute P(A > B) probability.""" return (post_a > post_b).sum() / post_a.size
fc85a1bd25130f9d473ab2d9578ff3edaf9b0795
689,683
def _format_left_fields(status_information): """Format the unformatted fields. :param status_information: The various fields information :type status_information: :class:`collections.defaultdict` :returns: The updated status informations :rtype: :class:`collections.defaultdict` """ for key,...
cb9a9c638f0dbf64313f30e5ef051e222d09f379
689,684
from typing import Dict def getCosponsors(fileDict: Dict, includeFields = []) -> list: """ Gets Cosponsors from data.json Dict. `includeFields` is a list of keys to keep. The most useful are probably 'name' and 'bioguide_id'. Args: fileDict (Dict): the Dict created from data.json includeFields (li...
06f74c63d63db5d5377efcefbfc4a01e1a11d6b1
689,685
def feature_entropy(features): """ Calculates the entropy of all the features. Parameters ---------- features : dictionary a dictionary of features with keys as feature name and values as objects of feature class. Returns ------- features : dictionary a...
234ca8eda3b082a7702b71f1fcba4905d8bd816e
689,686
from typing import Literal import os def _get_filename(character, size: Literal["small", "medium", "large"] = "medium"): """Get the file where a character is saved and return the ``space`` file if the character doesn't exist. :param character: The character to find :param size: The size of the charac...
81121f3eccf4cd47a35da3bc59c3e12b6b488dcd
689,687
import optparse def init_parser(): """parser command""" parser = optparse.OptionParser(conflict_handler='resolve') parser.disable_interspersed_args() parser.add_option('--param_file', dest='param_file', help='json file path') return parser
dfb3f5c660a7931acba6fcb061b8fcaa801d0d61
689,688
import os def expand_path(path, follow_links=False): """ Expand shell variables ("$VAR"), user directory symbols (~), and return absolute path >>> path0 = '~/whatever.txt' >>> path = expand_path(path0) >>> path.endswith(path0[2:]) True >>> len(path) > len(path0) True >>> '~' in path ...
22d9ea1f4b0f2d9041e62cf8648e3c87a4e2fbea
689,689
def ternary_search(f, xmin, xmax, epsilon=1e-6): """Ternary search. Args: f: An objective function. Must be convex downward. xmin: The lower bound of the range to search. xmax: The upper bound of the range to search. epsilon: The epsilon value for judging convergence. """ l, r =...
6157d3ca011fe11415b8efdef015d850f5b852e0
689,690
from typing import Callable def _go_to_group(name: str) -> Callable: """ This creates lazy functions that jump to a given group. When there is more than one screen, the first 3 and second 3 groups are kept on the first and second screen. E.g. going to the fourth group when the first group (and...
b79f0dbf374e376114ee724ec6a7563a1b993f75
689,691