content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import logging import sys import json def loadSettings(): """Load settings from file.""" try: settingsFile = open("settings.json", "r") except IOError: logging.exception("Error opening settings.json.") sys.exit(1) try: settings = json.load(settingsFile) settings...
21a6cb41a418a491446802b0fa4bd34abc2bc8dc
689,011
def datetime_to_timestamp(date_time): """ Converts the given datetime to it's timestamp representation. Parameters ---------- date_time : `datetime` The datetime to convert to timestamp. Returns ------- timestamp : `str` """ return date_time.isoformat()
24127c94e947957af4bee100de064a30aab2693e
689,012
def build_group_id(ad, desc_list, prettify=(), force_list=(), additional=None): """ Builds a Group ID from information found in the descriptors. It takes a number of descriptor names, invokes and then concatenates their result (converted to string) to from a group ID. Additional parameters can be passe...
186f56058ecc7dc12bec7e1936416207a09dcdb3
689,013
import random def tirage_uniforme(min, max): """ Renvoie un nombre décimal (float) choisi de manière (pseudo)aléatoire et uniforme de l'intervalle \[``min`` ; ``max``\[. Arguments: min (float): Un nombre réel. max (float): Un nombre réel. """ return random.uniform(min, max)
3ea65fd222e7579df207c22111a405f2fee839ab
689,014
import subprocess def get_version(src): """Get version of currently builded code """ get_tag = ["git", "-C", src, "describe", "--long", "--tags"] tag_out = subprocess.check_output(get_tag) return tag_out.strip().decode('ascii')
f81f6b91b13e2cd1a3d139b82bb8a94c5a158581
689,016
def radii(mag): """The relation used to set the radius of bright star masks. Parameters ---------- mag : :class:`flt` or :class:`recarray` Magnitude. Typically, in order of preference, G-band for Gaia or VT then HP then BT for Tycho. Returns ------- :class:`recarray` ...
f90c839b47c25eb1636c5841f7faebf2200d3e18
689,017
from typing import OrderedDict def _get_parameter_space(): """Define the parameter space to explore here.""" parameter_space = OrderedDict() parameter_space.update({'embedding_size': [16 * i for i in range(1, 5)]}) parameter_space.update({'char_rnn_size': [64 * i for i in range(1, 5)]}) parameter_...
94b47f5149fa2c13b27a6869ecc01af1fcd9f004
689,018
def greet(greeting, name): """Returns a greeting Args: greeting (string): A greet word name (string): A persons name Returns: string -- A greeting with a name """ return f'{greeting} {name}'
e58041beabf77a247fb6b0edc0f5385d29934649
689,019
def get_decision(criteria, node_idx, tree_struct): """ Define the splitting criteria Args: criteria (str): Growth criteria. node_idx (int): Index of the current node. tree_struct (list) : list of dictionaries each of which contains meta information about each node of the tre...
55e99e17c90bb43a8d377c08fcd17f39fe8e4453
689,020
async def async_setup_platform(hass, conf, add_entities, discovery_info=None): """Set up the sensor platform.""" return True
8294d9034e8eb848b53369dbebe95effc528e951
689,021
from datetime import datetime from typing import List def parse_rfc_822_timezone(now: datetime, key: str, group: List[str]) -> str: """ Handles the RFC 822 Timezone presentation https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#rfc822timezone Currently only mocking data, not r...
09a5abab628d710ee89541b9cf3906a389fcdc4f
689,022
def get_schema(message_descriptor): """Builds the JSON schema for a Message. Args: message_descriptor: google.protobuf.descriptor.Descriptor. Returns: Dict of dicts; a JSON schema. Raises: NotImplementedError: If a FieldDescriptor type is not supported. """ schema = { ...
636b2e39c18d7305a86dea3e63509100c8012d83
689,023
def flatten(seq): """중첩 시퀀스를 한 층위 평평하게 한다.""" return [e for subseq in seq for e in subseq]
619bf313d552c70c70ccdc9a3d31d71f9c1bc8c6
689,025
def _is_parameter_for(name, container, docmap): """ @rtype: C{boolean} @return: True if C{name} is the name of a parameter for the routine C{container}, given the DocMap C{docmap}. """ if docmap is None or not docmap.has_key(container): return 0 container_doc = docmap.get(container) if c...
ae65511c006be2d26c6afa78444df7360319a46c
689,026
def course_header(version, units, description, filename): """ Print the standard MRC file header """ return "[COURSE HEADER]\nVERSION = " + str(version) + "\nUNITS = " + str(units) + "\nDESCRIPTION = " + description + "\nFILE NAME = " + filename + "\nMINUTES PERCENT\n[END COURSE HEADER]\n"
3ca4ccfa85d53c4d8d3b1330f3babb7439c1c483
689,028
def _join_strings(strings, delimiter = ", "): """Joins the given strings with a delimiter. Args: strings: A list of strings to join. delimiter: The delimiter to use Returns: The joined string. """ _ignore = [strings, delimiter] return ""
2917c74a3782f93d4d123d224fdcefbae360b22b
689,029
import os import re def get_dependencies(src, include_paths=['.',os.getcwd()]): """ :param include_paths: list of paths to the include search folders :param src: The text src file :return: list of paths to dependencies """ dependencies = [] for line in src.splitlines(): global lin...
d8f6531379b01305f07485a44340226ce49a9add
689,030
def is_lvm(name): """ Check if device is marked as an lvm """ if "lvm" in name: return True return False
8b29fc4b49580cb776529d573c47fdc7b47e7a71
689,031
import json def delete_req_body(reminder_id: str): """ returns the body of a delete-reminder request """ body = {'2': [{'2': reminder_id}]} return json.dumps(body)
49c6ae99b87bac5facd8d9fadb6644f626121af2
689,033
def place_figures(figures): """Generate LaTeX code for figure placement. Parameters ---------- figures : list List holding LaTeX code of individual figures to be placed in document. Returns ------- latex : str LaTeX code for figure alignment. """ latex = '' num_...
b6653eed30edd5658bc09282ff8251be4a1338ba
689,034
import random def scramble_word(word: str) -> str: """Return a scrambled version of the word.""" return ''.join(random.sample(word, k=len(word)))
36e6bb2a5e9c5978b490d8fffe52f3d03fbe4483
689,035
def _get_node_name_prefix(node_name): """ Returns the node name prefix, without phase character or trailing whitespaces. """ wows_name = node_name.strip() return wows_name[:-1]
aeef1629f098708a1d70317683f6c2b6dda5109b
689,036
import yaml def populate_from_gqa(md, gqa_file): """ :type md: eodatasets.type.DatasetMetadata :type gqa_file: pathlib.Path :rtype eodatasets.type.DatasetMetadata """ with gqa_file.open('r') as f: gqa_values = yaml.safe_load(f) # "Scene id" is just the name of the parent folder. O...
d7f94beb7d3f55da4165ce063a00a4b962b16e37
689,037
import os def get_extension_explorer_data_filename(): """ Returns the data file's path. Set it with the ``EXTENSION_EXPLORER_DATA_FILENAME`` environment variable (default: ``extension_explorer/data/extensions.json``). """ if os.environ.get('EXTENSION_EXPLORER_DATA_FILENAME'): return os.env...
ba7b305ce438b9fa5c07db0a80f17c2dc95c5e72
689,038
def file_requires_unicode(x): """ Return whether the given writable file-like object requires Unicode to be written to it. """ try: x.write(b'') except TypeError: return True else: return False
c4e287012f5c8fba594a568ac08adcf3f4ccf79a
689,039
def is_tpu_strategy(strategy): """We're executing TPU Strategy.""" return strategy is not None and strategy.__class__.__name__ == 'TPUStrategy'
c6e88c177b82e4d267196dc48ed79b7e08cb917c
689,040
def get_type_name(value_type): """Returns the name of the given type.""" return value_type.__name__
0d510c0de910d90fabbb275a418eab18dca88965
689,041
def format_currency_market_display_float(value: float, currency_symbol: str = "$", suffix: str = "") -> str: """ Formats a value according to conventional market display using floats. NOTE: Floats should not be used for calculation on currency amounts General conventions: Less than 0.000001 -> ...
c809d0ef6dc18b3a699018a306310de9029a6fa5
689,042
def toBool(value): """Convert any type of value to a boolean. The function uses the following heuristic: 1. If the value can be converted to an integer, the integer is then converted to a boolean. 2. If the value is a string, return True if it is equal to 'true'. False otherwise. Note that t...
31ad05c3cbefb5b1ed3eb69aefc914e6d8ae9c94
689,043
def partialSums(labels, data, partials,partial_labels="",datarow_labels=""): """Returns a latex table with sums of data. Data is though to be unidimensional. Each row is transposed to a column to which partial sum are added. """ lines=[] for label in labels: lines.append("{} ".form...
f1ca65176e31bd4d385fff4a25c06dda6ebf9676
689,044
def runge_kutta_fourth_xy(rhs, h, x, y): """ Solves one step using a fourth-order Runge-Kutta method. RHS expects both x and y variables. Moin, P. 2010. Fundamentals of Engineering Numerical Analysis. 2nd ed. Cambridge University Press. New York, New York. :param rhs: "Right-hand Side" of the equa...
22b8d042376501b6910ddb1511c61ed7d2282896
689,045
def rename_keys(rename_dict, map_dict): """ Recursively rename keys in `rename_dict` according to mapping specified in `map_dict` returns: dict with new keys """ if isinstance(rename_dict, dict): for k in list(rename_dict.keys()): if k in map_dict: new_label ...
fa691edcc2b2c90fa946f9c43b03506bcdb58301
689,046
def ptbunescape(token): """Unescape brackets in a single token, including PTB notation.""" if token in ('', '#FRONTIER#', None): return None elif token == '-LCB-': return '{' elif token == '-RCB-': return '}' elif token == '-LSB-': return '[' elif token == '-RSB-': return ']' return token.replace('-LRB...
b47e52812de83275b227d4483be733788a4a1fce
689,048
def mean(list): """ Calcula a média de um vetor de números. Args: list (list): vetor de números Returns: (float) média dos números """ return sum(list) / len(list)
a95825083952e529888a8d932a1e2daf2a7aac62
689,049
import os def save_uid_to_file(file_name: str, uid: str): """ Save the uid to the specified file """ try: # create directories recursively first os.makedirs(os.path.dirname(file_name), exist_ok=True) with open(file_name, 'w') as file: file.write(uid) except Exc...
336c81e2d8910c47b11e5b46f178180125889f53
689,051
def convert_by_engine_keys_to_regex(lookup_by_engine): """ Convert all the keys in a lookup_by_engine to a regex """ keys = set() for d in lookup_by_engine.values(): for k in d.keys(): if isinstance(k, str): keys.add(k) keys = list(keys) keys.sort(key=lambda item...
21774f8e32e1ee54b9c92a726476dfbc010268b9
689,052
def parse_config(configfile): """Parse the config file 'configfile' and return the parsed key-value pairs as dict""" return {k:v for k,v in map(lambda x: x.strip().split('='), filter(lambda x: not x.strip().startswith('#'), (line for line in open(configfile))))}
022243368fb63588a4bffaa6dad799e1bc5c2e66
689,053
def get_optimizer_settings(): """ Default optimizer settings (taken from https://keras.io/api/optimizers) """ d = {} d["comboBox_optimizer"] = "Adam" d["doubleSpinBox_lr_sgd"] = 0.01 d["doubleSpinBox_sgd_momentum"] = 0.0 d["checkBox_sgd_nesterov"] = False d["doubleSpinBox_lr_rmspro...
5a6fc9b774e2ed894275777256e0a25761ab0517
689,054
import json def _json_dump(i): """ pretty. """ return json.dumps(i, indent=2, sort_keys=True)
df25baf8a4ffd896711ebb6f9563c247c3ae8b0f
689,055
def get_minimun(list_values): """ function to obtain the min. score of ppmi :param list_values: :return: """ min_score = min(list_values) return min_score
7d4458c51be33eebc28a2438e1b9fc52af50f56c
689,056
def list_errors(form): """Flash all errors for a form.""" error_list = [] for field, errors in form.errors.items(): for error in errors: error_list.append( '{0} - {1}'.format(getattr(form, field).label.text, error)) return error_list
51831b410a1d9ff15f2daaa6d28c4b8132a40774
689,057
def parse_id(string): """Returns the UUID part of a string only.""" return string.split('/')[-1]
bc50d9ba09512ac9ead25822be5b0985557acbdf
689,059
def formalize_bbox(_im_summary): """ Extract bboxes from all classes and return a list of bbox. Each element of the list is in the form: [x1, y1, x2, y2, class_id, score]. The returned list is sorted descendingly according to score. """ boxes = [] # each element: x, y, w, h, class_id, score ...
d6a35972da005b89de3274a73637474986b2f0f1
689,060
def row_full(row, puzzle): """ Takes a row number, and a sudoku puzzle as parameter Returns True if there is no empty space on the row ReturnsFalse if otherwise """ for col in range(0, 9): if puzzle[row][col] == -1: return False return True
96828d1481dccce583b090a247542db87979e2ce
689,061
def collect_families_from_instances(instances, only_active=False): """Collect all families for passed publish instances. Args: instances(list<pyblish.api.Instance>): List of publish instances from which are families collected. only_active(bool): Return families only for active insta...
d47d7a0fe70feb291d55bec068b023cedbb6d1c5
689,062
def _coerce_bool(some_str): """Stupid little method to try to assist casting command line args to booleans """ if some_str.lower().strip() in ['n', 'no', 'off', 'f', 'false', '0']: return False return bool(some_str)
ced88449d4cf1e38ac444bd810a6b92cc677950d
689,063
def isvlan(value): """Checks if the argument is a valid VLAN A valid VLAN is an integer value in the range of 1 to 4094. This function will test if the argument falls into the specified range and is considered a valid VLAN Args: value: The value to check if is a valid VLAN Returns: ...
485f856330fb61fc009d6d84f4b8d71a7ee77198
689,065
def parse(utxo, offset=0): """ Parses a given serialized UTXO to extract a base-128 varint. :param utxo: Serialized UTXO from which the varint will be parsed. :type utxo: hex str :param offset: Offset where the beginning of the varint if located in the UTXO. :type offset: int :return: The extrac...
6330898ae2113370b1f1ec5e2b8ba0ec326eb48d
689,066
import math def lerfcc(x): """ Returns the complementary error function erfc(x) with fractional error everywhere less than 1.2e-7. Adapted from Numerical Recipies. Usage: lerfcc(x) """ z = abs(x) t = 1.0 / (1.0+0.5*z) ans = t * math.exp(-z*z-1.26551223 + t*(1.00002368+t*(0.37409196+t*(0.09678418+t...
26848330f51adbc866fecaf8f582c707d8e1c087
689,067
def add_numbers(x, y): """ add two numbers and return the result""" return x + y
efe642b459d0e07172129a1c921ea1899913eae9
689,068
import math def distance(a, b, fast=False) -> float: """Returns de length between points a and b.""" d = (float(b[0] - a[0]) ** 2) + (float(b[1] - a[1]) ** 2) if fast: return d return math.sqrt(d)
841619aa35f0ce7fe5ec4b2c848527fdaa9199f8
689,069
import subprocess def defaults_read(key_name, file_name): """Read the specified key from specified file""" defaults_process = ["/usr/bin/defaults", "read", file_name, key_name] p = subprocess.Popen(defaults_process, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (results, err) = p.communic...
919b0bb9ad7538fd1f9065597216470c69a61e2c
689,070
def _list_readline(x): """Given a list, returns a readline() function that returns the next element with each call. """ x = iter(x) def readline(): return next(x) return readline
f1111906b29efa44adef3d4a838eb25ed1dd0801
689,071
import argparse import os def user_input(sys_argv): """Function to parse command line arguments from user. Args: sys_argv (list): command line arguments as saved in sys.argv Returns: ArgumentParser: Object containing user arguments """ parser = argparse.ArgumentParser() # po...
00ab48b196a3549decbb1cbb437b3435462de160
689,072
import re def convertGMK(unit): """ Convert the space unit G, M, K, the unit is case-insensitive """ unitG = re.match('([1-9][0-9]*)[gG]\s?$', unit) if unitG: return int(unitG.group(1)) * (1024 ** 3) unitM = re.match('([1-9][0-9]*)[mM]\s?$', unit) if unitM: return int(unitM.group...
b2eef68dd648bf16c511d402d673cc46120d7523
689,073
import random import string def random_string(nlen): """Create random string which length is `nlen`.""" return "".join([random.choice(string.ascii_lowercase) for _ in range(nlen)])
49f63e3f8122dd886ce4cc5d3fe0b2c55c0679bb
689,074
def iterative_tree_search(x, key): """ 查询(迭代) :param x: :param key: :return: """ while x and x.key != key: if key < x.key: x = x.left else: x = x.right return x
b44be6d9a85059e53df0c9dd8faaeb18ef472d9a
689,075
def match_word(encoded_word, words_list): """ Find first probably correct word based on list of words and given encoded word. """ results = [] for word in words_list: #skip all items with different first and last char if word[0] != encoded_word[0] or word[-1] != encoded_word[-1]:...
ffea6f7042f3d8bc47e5f9335c7e944be692e9a3
689,076
def extras_equality_check(setup_extras, pipfile_extras): """ Checks that all packages that specify extras in one dependency file also specify them in the other dependency file, and that those extras match across files. Args: setup_extras (dict<str, list<str>>): Dictionary of ext...
bd4b1f485f790231096b4d511ed9a4b17602381f
689,077
def extract_meta_from_keys(keys, prefix): """Extract metadata contained in a key's name. Parameters ---------- keys : list of strings prefix : string Returns ------- meta : string """ return next(k[len(prefix):] for k in keys if k.startswith(prefix))
808101a8edf7cab38ac249959ac27f27b9020d08
689,078
def ChannelFirst(arr): """Convert a HWC array to CHW.""" ndim = arr.ndim return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3)
017b7fb8b0597c201cddd546bf47a21228f0bedd
689,079
import torch def ones_like(array, shape=None, dtype=None, device=None): """Add a shape parameter in ones_like.""" if shape is None: shape = array.shape if isinstance(shape, int): shape = (shape, ) if isinstance(dtype, str): dtype = getattr(torch, dtype) if dtype is None: ...
4689dd8ffb64d67d9ab35a91686275ba4ce9b16c
689,080
import torch def exp(x): """ The exponential link function given by $$ y = e^{x} $$ """ return torch.exp(x)
5daf001a96e3deafb8549ec73f9824d3a512fc58
689,081
def dopant_site(poscar): """ With the given VASP POSCAR file, determine the impurity location given the folder structure Inputs ------ poscar: File path for the relevant POSCAR file Outputs ------- impurity type of the defect as defined by collaborators """ if 'M_Cd/' in p...
a9d24095da1d4ae61e2b58a8dfcb99780efe9e30
689,082
def get_linef(fp, line_no): """'fp' should be (readable) file object. Return the line content at line_no or an empty line if there is less lines than line_no. """ fp.seek(0) for line in fp: line_no -= 1 if line_no == 0: return line return ''
8c73e672ccf2eaea6b1e23d7ed5b7a66385440b6
689,083
def _safe_column_indexing(X, col_idx): """Return column from X using col_idx""" if hasattr(X, "iloc"): return X.iloc[:, col_idx].values else: return X[:, col_idx]
c30031b480f96365085221a2c7a78a205fbc5a8c
689,084
def make_1024_list() : """ Generates a list of 1024 strings of numbers in the format "XXXX", filled with zeros before the number. It is here to translate integers into the format used in the dataset (+1 because the list starts at "0001"). :return: returns a list of 1024 strings """ list = [] for x in ran...
6a42dd4e0ff17a5fd84d584627338cf2975399ac
689,085
import collections def longest_path(current_state): """Find longest possible path from the current state to the final state Args: current_state: StateForGraphs The state at the beginning of the search; the root of the tree. Returns: The maximum number of steps that can be use...
8acca90179eaff3f8d06972aec0a63a8050fbcf9
689,086
def get_topic_key(project_name, topic): """ Get the topic key for a project name and a topic :param project_name: project name :param topic: topic :return: topic key """ return f"{project_name}/{topic}"
fb1e036e75e43429dc3d5f3e44c64fb7fdc62486
689,087
def nvl(*args): """ SQL like coelesce / redshift NVL, returns first non Falsey arg """ for arg in args: try: if arg: return arg except ValueError: if arg is not None: return arg return args[-1]
3f49d4c855e8e7f8e0359301acf454f731489495
689,089
def orblag(orb, match = None, reject = None): """"Return parameters indicating degree to which clients are behind""" return orb.lag(match, reject)
45745ee69d11c8ce3055ad596476a2954c9eba1e
689,090
def _get_type(s): """Reads a string to see if it can be converted into int or float. Parameters ---------- s : str A string to be parsed. Returns ------- str, int or float The parsed value. """ try: float(s) if '.' not in s: return 'i' ...
9d96fedfd1c9efc2c345f760ffcaf17fb8d54aee
689,091
def parseFields(fields, output): """ Take a string of fields encoded as key1=value1,key2=value2,... and add the keys and values to the output dict""" for field in fields.split('|'): key, value = field.split('=') try: value = int(value) except: pass output[key] = value return output
7cbe131e0f4c8df85ccc7bca52aa80f0f0d17a59
689,092
def to_camel_case(snake_str): """ Transforms a snake_case string into camelCase. Parameters ---------- snake_str : str Returns ------- str """ parts = snake_str.split("_") # We capitalize the first letter of each component except the first one # with the 'title' method ...
02e28889da2a92fc5e085ad955b11519b5069dc4
689,093
def to_bytes(s, encoding="utf-8"): """Convert a text string (unicode) to bytestring, i.e. str on Py2 and bytes on Py3.""" if type(s) is not bytes: s = bytes(s, encoding) return s
d66b0620e1c71650db11e48fe6f961289f9fed5b
689,094
def bind_var(var, db='oracle'): """Format of named bind variable""" if db == 'postgresql': return '%({})s'.format(var) elif db == 'oracle': return ':{}'.format(var) else: return ':{}'.format(var)
e89cb466c18a7cc460ff16cd5f69ed76a542aab5
689,096
from typing import List from typing import Counter def top_k_frequent_bucket_sort(nums: List[int], k: int) -> List[int]: """Given a list of numbers, return the the top k most frequent numbers. Solved using buckets sort approach. Example: nums: [1, 1, 1, 2, 2, 3], k=2 output: [1, 2] ...
94970d9c0c21a5288e52207e85f59d631e546600
689,098
def _output_len(len_h, in_len, up, down): """The output length that results from a given input. scipy.signal._upfirdn._output_len """ return (((in_len - 1) * up + len_h) - 1) // down + 1
6f62f68cae147e53ce660896aba5398542331dc0
689,099
def locate_zero_files(path_100, path_25, path_50, path_125, path_150): """locate and return the full path of the boundary condition velocity files for each of the five cases""" # path step for the zero folder zero_step = "0/" # Full respective paths for the zero folders path_0_100 = path_100 + ...
9aed175558d43ee552beedb0e484b232a6e04da4
689,100
import re def increment(s): """ look for the last sequence of number(s) in a string and increment """ lastNum = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+') m = lastNum.search(s) if m: next = str(int(m.group(1))+1) start, end = m.span(1) s = s[:max(end-len(next), start)] + next + s[en...
918c72990f04fcc36884deeb1e1d5a846b86ea12
689,101
def translate_match_attrs(loc_str, match_attrs_name, match_attrs): """Translate the passed factory/job match_attrs to a format useful for match validation step Args: loc_str: match_attrs_name: match_attrs: Returns: """ translations = {"string": "a", "int": 1, "bool": ...
d2487a79356b641cbc0ee2ba03cdfdd3eb273064
689,102
def pval_hist(pvals, bin_width=0.05): """Return a histogram of pvalues.""" nbins = int(1 / bin_width + 0.5) bins = {bin_width * i: 0 for i in range(nbins)} for pval in pvals: for bin_start in bins: bin_end = bin_start + bin_width if (pval >= bin_start) and (pv...
0d2f728383a8aa4a1676f3a42898e22df2514834
689,104
def _check_delimiter(output_filename, delim=None): """Detect delimiter by filename extension if not set""" if output_filename and (delim is None): delimiters = {"tsv": "\t", "csv": ","} delim = delimiters[output_filename.rsplit(".", 1)[-1].lower()] assert delim, "File output delimiter no...
db3cbea27c09f1ec67459cfec6e1f4fbbb1ed5c8
689,105
def pubnub_keyset(module, account, application): """Retrieve reference on target keyset from application model. NOTE: In case if there is no keyset with specified name, module will exit with error. :type module: AnsibleModule :param module: Reference on module which contain module launch...
b2f16dd3316b3cccb7ccb814f73a55d28cfa1b96
689,106
from typing import Counter def precision_recall_f1(prediction, ground_truth): """ This function calculates and returns the precision, recall and f1-score Args: prediction: prediction string or list to be matched ground_truth: golden string or list reference Returns: floats of (...
363be5c9786226d0f95a21791bd4da65623ccd80
689,107
def default(): """ Torniamo un default """ return {"messaggio": "PythonBiellaGroup!"}
5b0c423a173fde4504262fe6f372b2fa8a295777
689,108
from bs4 import BeautifulSoup import requests def fetch_page(url, method, **kwargs) -> BeautifulSoup: """Execute request for page and return as soup""" ret = requests.request(method, url, **kwargs) if ret.status_code != 200: raise Exception(f"Page {url} returned {ret.status_code}") return Be...
158c10bcdf2db4e60112f7b9a643661732ca2d29
689,110
def on_off(image, w, h, threshold=128): """ Black and white (no greyscale) with a simple threshold. If the color is dark enough, the laser is on! """ result = [] for row in image: result_row = [] for pixel in row: # We draw black, so 255 is for dark pixels ...
c9e577bf851fa972c1bbe7f8a61afc09ffb37de5
689,111
def flag(val): """Does the value look like an on/off flag?""" if val == 1: return True elif val == 0: return False val = str(val) if len(val) > 5: return False return val.upper() in ('1', '0', 'F', 'T', 'TRUE', 'FALSE', 'ON', 'OFF')
a3e60a4914521a9ae770e4bd10a0eaa19a780a8d
689,112
def notification_key_to_dict(key, ctx): """ Returns a dict representation of a User instance for serialization. Args: key (NotificationKey): User instance. ctx (SerializationContext): Metadata pertaining to the serialization operation. Returns: dict: Dict populated wi...
9114dfa3da9db87fc7b5bf41f6f54e11576cf5d5
689,113
import requests import json def do_rpc(url,headers, rpc_input): """does the rpc calls""" # add standard rpc values rpc_input.update({"jsonrpc": "2.0", "id": "0"}) # execute the rpc requrest response = requests.post( url, data=json.dumps(rpc_input), headers=headers) r...
fb0519f11c7fc844c6e396d8e5490baf998fe5ce
689,114
def get_init(order): """Return initial guess for fit parameters.""" lambda_guess = [1.0] coeff_guess = [0.0] * (2 * order) return lambda_guess + coeff_guess
6e1e7a2be2727a0f6c3fedb1ef88c45081643778
689,115
import os import urllib.parse def blender_id_endpoint(endpoint_path=None): """Gets the endpoint for the authentication API. If the BLENDER_ID_ENDPOINT env variable is defined, it's possible to override the (default) production address. """ base_url = os.environ.get('BLENDER_ID_ENDPOINT', 'https://www...
5752b5de392a566d953d7da0e9f6ae91c68c50e2
689,116
def get_caller_name(caller): """Find the name of a calling (i.e. observed) object. Args: caller: The observed object which is calling an observer. Returns: The name of the caller. If the caller is a function we return that function's .__name__. If the caller is a bound method we re...
2b5bf37a34b7b75684c5301159d461535d986f3f
689,117
def get_chains_list(mmtf_dict, groups): """Creates a list of chain dictionaries from a .mmtf dictionary by zipping together some of its fields. :param dict mmtf_dict: the .mmtf dictionary to read. :rtype: ``list``""" chains = [] for i_id, id, group_num in zip(mmtf_dict["chainIdList"], mmt...
9dea93cd2f2745ff0d093a7e1e78a57a53a79ff1
689,118
def grab_parmdict(tight_ObH=False): """ Generate the parameter dict for the MCMC run Args: tight_ObH (bool, optional): [description]. Defaults to False. Raises: IOError: [description] Returns: dict: [description] """ parm_dict = {} parm_dict['F'] = dict(dist='Unifo...
97373cca5860f417c33e08ad9d706d1d75ba998d
689,119
def wc(q,mc2,B): """ Calculate the electron gyrofrequency q is the charge in multiples of the fundamental mc2 is the particle rest mass in MeV B is the magnetic field magnitude in nT """ cof = 89.8755311 res = cof*q*B/mc2 return res
69e015a36384b9e9af07e303993cc74c2c8cae58
689,120
def binary_t1_pgm(im_data): """ :param im_data: probability gray maps :return: binarized probability gray maps """ m = im_data > 0.0 m = m.astype('float32') return m
d247b0dccb728182a86f42ccc0a2bf79932cfdb0
689,121
import logging def transfer_verification(model_state_dict, partial_state_dict, modules): """Verify tuples (key, shape) for input model modules match specified modules. Args: model_state_dict (Dict) : Main model state dict. partial_state_dict (Dict): Pre-trained model state dict. modul...
3020dd2ff40b422c01a0bb7e0001fd670937a131
689,124
def sort_name(contact): """Sort by name (case insensitive)""" return contact.name.lower() or contact.bare_jid
8d296224a9f40b50dd8a3dc4959a54ccb1ec02c2
689,125