content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def convert_design_infos_to_df(design_infos): """Convert the design infos into a dataframe. Parameters ---------- design_infos: list A list containing all design informations. """ modules = [] fifos = [] for design_info in design_infos: fs = design_info["fifos"] ...
d7fe481a5671943c5829d0ccda657edb2abe61d0
80,978
def TDataXtd_Shape_Get(*args): """ * the Shape from associated NamedShape attribute is returned. :param label: :type label: TDF_Label & :rtype: TopoDS_Shape """ return _TDataXtd.TDataXtd_Shape_Get(*args)
ad8c6df97ef50c3a5c356d2d65cbdf39a0ac0a0c
80,979
import torch import logging def distributed_init(init_method, rank, world_size): """ torch distributed iniitialized create a multiprocess group and initialize nccl communicator """ if not dist.is_initialized(): dist.init_process_group( backend='nccl', init_method=in...
ab3bdc28fc40e23c7def596e8cb729067c794382
80,980
import re def validate_uuid(hash): """Check if the user supplied valid hash to the view. That should save him the wait... :D""" regex = '^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$' if re.search(re.compile(regex), hash): return True else: return False
f89545eb249b959c837f840921339857bb8ce29f
80,981
def cos(input, name=None): """Element-wise cosine of a tensor.""" if is_tensor(input, 'tf'): return tf.math.cos(input, name=name) else: return np.cos(input)
defa77d68ffaba6c1030950395f899ed9638809a
80,982
def residual_block( x, filters: int, padding: str, normalization: bool, layers_before_pooling: int, name=None, ): """Function implementing an Identity Residual block.""" x = Conv2D(filters, 3, padding=padding, kernel_initializer="he_normal")(x) for i in range(layers_before_pooling)...
91fd3b83388b59cba2d8e9aa908fac3f970f6f84
80,983
import collections def dict_merge(dct1, dct2): """Recursively merges dct2 and dct1, ideal for merging objectFilter together. :param dct1: A dictionary :param dct2: A dictionary :return: dct1 + dct2 """ dct = dct1.copy() for k, _ in dct2.items(): if (k in dct1 and isinstance(dct1[...
cb2196fad2af8e6181119e8627d4762aa534fda9
80,984
def calcular_acumulada(dist_discreta, inicio, fin, parametros): """ Calcula la distribución acumulada dependiendo de inicio y fin params :inicio x inicial desde donde partir a calcular :fin x final hasta donde calcular :parametros parametros de la distribucion (ej, Binomial [n, p]) """ ...
0bd8aa720d2604a7c6c599161dc59912611257dd
80,987
from datetime import datetime def _add_execution_date_column(df): """ Add a column with the execution date to the dataframe :param df: DataFrame - DataFrame to be cleaned :return: DataFrame - DataFrame with the execution date """ DT = datetime.datetime.now() logger.info('Filling execution...
a076d2d29bf7344d5cb407e2732f534528b12435
80,988
def match_multiple(data, other): """Match based on name and possible synonyms.""" other_dict = defaultdict(list) for ds in other: other_dict[ds["name"].lower()].append(ds) for ds in data: to_add, to_remove = [], [] for cf in unlinked(ds["exchanges"]): if cf["name"].l...
8fb1892e527d7fdf14637fbe89c3888fb66728e2
80,989
def get_value_from_json(json_dict, sensor_type, group, tool): """Return the value for sensor_type from the JSON.""" if group not in json_dict: return None if sensor_type in json_dict[group]: if sensor_type == 'target' and json_dict[sensor_type] is None: return 0 return j...
ab8aea19a0ed4f3d581f01a206799d082e7279b1
80,990
import math def Rxyz(x, y, z, order="ZXY"): """ # Convert Euler Angles passed in a vector of Radians # into a rotation matrix. The individual Euler Angles are # processed in the order requested. # https://stackoverflow.com/questions/1568568/how-to-convert-euler-angles-to-directional-vector :p...
90c2a2d5ed5dd59d15ddece9452b5a4a76996528
80,991
def plot_cost_landscape(f, var_min, var_max, grid_size, xlabel, ylabel): """Plot f on a grid. Creates and returns a figure but does not show it. args: f: the function to plot var_min: a tuple (x_min, y_min) var_max: a tuple (x_max, y_max) grid_size: the size of the grid ...
49b098d52a9aa046ae3f497976eb4a7e0d6855c0
80,992
def change_password(request): """ :param request: :return: """ template = 'users/profile_form.html' form = ChangePasswordForm() if request.method == 'POST': pk = request.user.pk if form.is_valid(): password = form.cleaned_data['passwrord'] user = get_...
5a6ed2841531f36dce60c1267e829ce73c759db5
80,993
import copy def parse_cp_xml_output(data): """ Parse xml data data must be a single string, as returned by file.read() (notice the difference with parse_text_output!) On output, a dictionary with parsed values. Democratically, we have decided to use picoseconds as units of time, eV for energie...
208f88911e36f8c84dafd16fb077a0989f0bf03f
80,994
import ipaddress def subnet_to_ip(addr, netmask): """ Convert fortios 'subnet' (addr, netmask) to ipaddress object. :return: <ip_address_with_prefix :: str>, e.g. 192.168.1.0/24, 10.0.0.1/32 """ if not utils.is_str(addr) or not utils.is_str(netmask): raise ValueError("Should be str but: {...
e0a3e12059bc7a2423c86ca90381dd5db921291e
80,995
def send_post_request(url, params=None, payload=None): """ Return HTTP POST decoded JSON response as dict. """ response = request_post(url, params=params, json=payload) if response.status_code != HTTP_200_OK: exception(response) return '' return response.json()
170efd85c4c3bd11cd564b671b5084b252816954
80,997
def apply_gauss_smoothing(df, params): """ from https://www.kaggle.com/bpetrb/adaptive-gauss-phone-mean """ SZ_1 = params["sz_1"] SZ_2 = params["sz_2"] SZ_CRIT = params["sz_crit"] unique_paths = df[["collectionName", "phoneName"]].drop_duplicates().to_numpy() for collection, phone in un...
3f4fb8fbdd935a53feb6c2ea6edb6cda931d5d59
80,998
def login_redis_cloud(): """ connect to redis and login """ try: config.read(config_file) host = config["redis_cloud"]["host"] port = config["redis_cloud"]["port"] pw = config["redis_cloud"]["pw"] except Exception as e: print(f'error: {e}') log.info...
0358470ee8de28cda52f6edcb939f13d01d2fc76
80,999
def command_code_privileged(ev_room, ev_user_id, wrap2, *args, **kwargs): """ Tells user whether or not they have code privileges :param wrap2: :param ev_user_id: :param ev_room: :param kwargs: No additional arguments expected :return: A string """ if is_code_privileged(ev_room, ev_u...
8249652a737de5c6a8d9bbc569915af1c481a03c
81,000
from datetime import datetime def log_to_cloud_watch_input(comment_input): """Cloud Watch records my print statements, making logging easy. So, now I just log input and output.""" return print(str.join('', (str(comment_input), '\n', str(comment_input.body), '\n', ...
a73f4fba670873bf60397f0188e9bf4a0312df2e
81,001
def new_resource(dotnet, name, result, identifier = None, **kwargs): """This creates a new [DotnetLibraryInfo](api.md#dotnetlibraryinfo). Args: dotnet: [DotnetContextInfo](api.md#dotnetcontextinfo). name: name of the file to generate. result: The .resources file. identifier: Ide...
e18ff7d42f658d1ebf06149f5d86ae47b8666a28
81,002
def comp_periodicity(self): """Computes the winding matrix (anti-)periodicity Parameters ---------- self : WindingSC A WindingSC object Returns ------- per_a: int Number of spatial periods of the winding is_aper_a: bool True if the winding is anti-periodic over ...
cbe57b27def894e4e145d44a58905d243a6dd84b
81,003
def householder_hornerscheme(*args): """ householder_hornerscheme(float [] z, float const [] B, float const [] y, int const n, int const start, int const stop, int const step) householder_hornerscheme(double [] z, double const [] B, double const [] y, int const n, int const start, int const stop, int const ...
c3551d62fa4aac0160410bf0e1b804968692913e
81,005
def feature_pyramid_network(inputs, filters, data_format): """Creates convolution operations layer used after Darknet""" inputs = Conv2D(inputs, filters=filters, kernel_size=1, data_format=data_format) inputs = BatchNormalization(inputs, data_format=data_format) inputs = LeakyReLU(inputs) inputs = Conv2D(inp...
4fcf83007a9aa07ec17203441ba4956183deb5ef
81,006
import scipy def mean_confidence_interval(data, confidence=0.95): """Return confidence interval of input data, default confidence=0.95""" a = 1.0 * np.array(data) n = len(a) m, se = np.mean(a), scipy.stats.sem(a) h = se * scipy.stats.t.ppf((1 + confidence) / 2., n - 1) return m, h, m - h, m + ...
7296e5e7bf3295d008afd308176ebf8775ec6975
81,008
def Calculate(boards, num_rounds): """ Boards is a list of Boards """ team_summaries = {} for bs in boards: for bsl in bs.ScoreBoard(): hr = bsl.hr() UpdateTeamSummary(team_summaries, hr._board_no, hr.ns_pair_no(), "ns", bsl) UpdateT...
4f5aee2fa9c8c92b90270bbc7a16d8fc3bf36ddd
81,009
async def get_gmn_version(session, base_url): """Get version number returned from /home by GMN 1.x / 2.x / 3.x. Args: session: base_url (): The BaseURL of a node that may be a GMN instance. Returns: None: The node at base_url is not a functional GMN instance str: The node a...
ca5901dd0f1fd01f6f36d0735d74aee1aefb3cd1
81,010
def capture_alignment(session, gene_dict): """Takes a dictionary of gene data and captures the alignment. The dictionary should have the following format:: {'gene1': 'ATTT', 'gene2':'CCC'} It's contents will be converted to fasta files and passed to a Clustalo binary through a subpro...
254fd0ce4a9950b8d62b2074157a8d0f0195c3d0
81,011
import struct def success_target(ctx, msg): """Return a success for an analysis test. The test rule must have an executable output. """ exe = ctx.outputs.executable dat = ctx.new_file(ctx.data_configuration.genfiles_dir, exe, ".dat") ctx.file_action( output = dat, content = msg) ctx.file_action...
c4c8e7ef372c8db0c66903ef189d1fc195833786
81,012
import time def do(code='000002', window=3, days=1, wrapper=Wrapper_default(), norm=Normalize(), *args, **kwargs): """ Args: layers [dict]: 训练层定义。默认为LSTM。第一层的`input_shape`和最后一层的`unit`会自动设置。 """ dl = DataLoaderStock( code, wrapper=wrapper, app...
3df4988d3c175d9751fb067228fc762ac2633dd3
81,013
import random def sample_score_pair(guess1, guess2, wordlist, samples = 20): """Try a pair of words against a few random targets.""" targets = random.choices([w for w in wordlist], k = samples) scores = np.array([score_pair(guess1, guess2, target, words) for target in targets]) return np.mean(scores)
a2c83386056f4abcfad5ea08ebe45b555e3bb657
81,014
def _single_field_to_json(field, row_value): """Convert a single field into JSON-serializable values. Ignores mode so that this can function for ARRAY / REPEATING fields without requiring a deepcopy of the field. See: https://github.com/googleapis/python-bigquery/issues/6 Args: field (goog...
2aa35a5f790dae26e88bf642210e9e0ab0564652
81,016
import itertools def reorder_improper_torsions(i0, i1, i2, i3, bond_set): """Return j0, j1, j2, j3, where j0 is the central index and j1, j2, j3 are in sorted() order. Parameters ---------- i0, i1, i2, i3 : int, Atom indices of torsion bond_set : set containing the index pairs between...
e7676068e817fbb782e04007de6db246ffb2ca9a
81,017
import zipfile def archive_files(input_file_names, output_file_name, remove_path=True): """ Create a zipfile from a list of input files. :param remove_path: if True, the directory will be removed from the input file names before archiving. All inputs and the output ...
9d4623c3626eff8567b23f9917de65a8caa4399f
81,018
import functools def default_kwargs(**defaultKwargs): """ Decorator defining default args in **kwargs arguments """ def actual_decorator(fn): @functools.wraps(fn) def g(*args, **kwargs): defaultKwargs.update(kwargs) return fn(*args, **defaultKwargs) retu...
7dc4c446b4591004f5c6b11d6de3c32b4d3a5c86
81,019
def diaresnet110_svhn(classes=10, **kwargs): """ DIA-ResNet-110 model for SVHN from 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671. Parameters: ---------- classes : int, default 10 Number of classification classes. pretrained : bool, default False ...
112288c3d9bb30d94319742bd083ce0a4239b11b
81,021
from typing import Callable from typing import Iterable def greedy( cost: Callable[[Node, Node], float], candidates: Iterable[Node], sink: Node ) -> list[tuple[Node, Node]]: """using greedy method""" candidates = set(candidates) routes = [] while candidates: min_src, m...
d5ea821e1c7ffab5771bee3e767134e36c0b5565
81,022
import numpy def snobround(x, u, v, dx): """ function x = snobround(x, u, v, dx) A point x is projected into the interior of [u, v] and x[i] is rounded to the nearest integer multiple of dx[i]. Input: x vector of length n u, v vectors of length n such that u < v ...
ee0649251b3b0552fea28d77def7c2bb47a1ce76
81,024
def find_payment_by_pid(pid): """Find payment details entry by payment identifier""" try: p = GamePayments.objects.get(pid=pid) except ObjectDoesNotExist: error("No payment were found with pid: %s" % pid) raise ValidationError(PID_WAS_NOT_FOUND) else: return p
74b092772d961abbaca9ca450089b7a098b0ead3
81,025
def s3_bucket_suffix_for(path): """returns bucket suffix for product delivery paths""" path = path.lstrip("/") if (path.startswith("pub/firefox/bundles/") or path.startswith("pub/firefox/try-builds/")): return "archive" if path.startswith("pub/firefox/"): return "firefox" ...
d6fd0c12069dff4ff4921483f13d028a8d22f410
81,026
def encoding_space_to_vexvalid(space): """Input string, output number""" return map_info_rdr.encoding_space_to_vexvalid(space)
dcd9387540738c78c79ed81b9031ff10903c6f84
81,027
def writeMes(mesfile, mesDict): """ Write the dictionary mesDict as a mesfile. This does not presever comments (although it could if desired). Overwrites mesfile if it already exists.""" mesFile = file(mesfile, 'w') linenumbers = mesDict.keys() linenumbers.sort() for linenumber in linenumbers: mesFile.write('{...
7f9b74aef5c4c981ba87b4e11330641e2493f0b8
81,028
def decodeSurrogatePair(hi, lo): """Returns a scalar value that corresponds to a surrogate pair""" return ((ord(hi) - 0xD800) * 0x400) + (ord(lo) - 0xDC00) + 0x10000
018eb6678052af00cd1b8fe51d58230e26c44bd8
81,029
def is_supported_content_addressed_uri(uri: URI) -> bool: """ Returns a bool indicating whether provided uri is currently supported. Currently Py-PlatonPM only supports IPFS and Github blob content-addressed uris. """ if not is_ipfs_uri(uri) and not is_valid_content_addressed_github_uri(uri): ...
1ec9796b3f671c1e9947e4609a87ba3b3e2893e1
81,030
def filter_fields(data: dict, state_dataclass) -> dict: """Filter the given data using keys from a given state dataclass.""" filtered_data = {} for field in fields(state_dataclass): if field.name in data: filtered_data[field.name] = data[field.name] return filtered_data
5d815563fea12761f38329265a500768c7768a67
81,032
def equivalent(u, v, r, s, D, N): """ Returns True if two solutions `(u, v)` and `(r, s)` of `x^2 - Dy^2 = N` belongs to the same equivalence class and False otherwise. Two solutions `(u, v)` and `(r, s)` to the above equation fall to the same equivalence class iff both `(ur - Dvs)` and `(us - vr)`...
9c03365e16bcc027ef71f4b56a91bfb7aaf8dce0
81,033
def verify_field(field_name, title, allow_quote=False): """ :type field_name: str :param field_name: Display name :type title: str :param title: Field name :type allow_quote: bool :param allow_quote: If True, a single quote character (') will be allowed to pass validation. :r...
5e8f700994ec8fd85bf1da5463d0365a005d9b47
81,034
def posix_access(space, fname, mode=0): """ posix_access - Determine accessibility of a file mode can be 'POSIX_F_OK': 0, 'POSIX_R_OK': 4, 'POSIX_W_OK': 2, 'POSIX_X_OK': 1, """ r = mode & 4 != 0 w = mode & 2 != 0 x = mode & 1 != 0 try: res = os.pat...
67641e8dd053ba2fa9cc5aa02b0272a325f7a2e9
81,035
def join(L, keycols=None, nullvals=None, renamer=None, returnrenaming=False, Names=None): """ Combine two or more numpy ndarray with structured dtype on common key column(s). Merge a list (or dictionary) of numpy ndarray with structured dtype, given by `L`, on key columns listed in `keyc...
173268f7634147262d9326018dc750febd897b8a
81,036
def sizeof(t, target_arch=Arch.Unknown): """ return the number of bytes the complex-type instance represents :param t: instance of struct/union/array :param target_arch: target architecture, if required by type :return: number of bytes the container has """ sizes = t.__size__ ...
40de4dc218a57cb6606a0049d69b9619a4172083
81,037
def drop_unnecessary_columns(data_frame, columns): """ Keeps only selected columns from data_frame :param data_frame: :param columns: the columns to keep :return: data_frame with dropped columns """ missing_columns = [c for c in columns if c not in data_frame.columns] if missing_columns:...
e4008d904f78807921a5c108303b320fc0a505e7
81,038
import socket def _get_free_port(host): """ Gets a free port by opening a socket, binding it, checking the assigned port, and then closing it. """ s = socket.socket() s.bind((host, 0)) port = s.getsockname()[1] s.close() return port
85e08ba0a7832c5de0620634d2285bb317cde751
81,041
import time def magnetic_field_coupling_analytic(mesh, r, Nchunks=None): """ **DEPRECATED** Given a mesh, computes the "C matrix" which gives the magnetic field at some target points due to currents (stream function) on a surface mesh. Parameters ---------- mesh: Trimesh mesh object ...
00050b3ed36751eaea1150238cf0a31d949a6166
81,042
import json import random def generate_dict_for_json(citizen_count, error_line=None, relatives=None) -> dict: """ Generates test data :param citizen_count: number of people to generate :param error_line: number of erroneous rows :param relatives: number of links to generate :return: the data d...
7449c0b1bdd0b33c35e36b1353d870a6c7f35f64
81,043
import threading def publish(topic, msg_type): """ Create a form widget for message type msg_type. This function analyzes the fields of msg_type and creates an appropriate widget. A publisher is automatically created which publishes to the topic given as topic parameter. This allows pressing t...
e4339b2164d41afdbccb9b53c01af9e0b9774bb8
81,044
def scrolling_spinner_factory(chars, length=None, block=None, blank=' ', right=True, hiding=True): """Create a factory of a spinner that scrolls characters alongside a line.""" def inner_factory(length_actual=None): if block and not (length_actual or length): # pragma: no cover raise Value...
6efce1720e15f327e2cdc60d81c25f88a29eff28
81,045
def normalise_array(array): """ If greyscale array has a shape [a, b, 1] it must be normalised to [a, b] otherwise the pillow fromarray function will give n#an error :param array: The array :return: squeezed array if necessary, else the original array """ if array.ndim == 3 and array.shape[2...
47c1b3fcad0f96a8fcb72b7e3094a920115390a2
81,046
def get_template(config, key): """Get an interpolation template out of the config. Args: config (dict): Dictionary. key (str): Template key. Returns: str: Template. """ # Get the template out of the configuration template = config['templates'][key] # Convert list t...
1e651a76b1096a8f2e208a92ed6b6de07be4d487
81,048
def unpack(obj): """Deep copy of obj, parse any string values.""" if isinstance(obj, list): return [unpack(e) for e in obj] elif isinstance(obj, dict): rv = {} binary_keys = set() for k in obj: parsed_key = parse_str(k) if not isinstance(parsed_key, (t...
55ac21effbc395a26de362d1d128d76434984c6a
81,050
def append_argloc(*args): """ append_argloc(out, vloc) -> bool Serialize argument location. @param out (C++: qtype *) @param vloc (C++: const argloc_t &) """ return _ida_typeinf.append_argloc(*args)
48d94e696f2d35c9d34a14e7879af458fa4a32f7
81,051
def rawOptimizer(ifs,dist,bounds=None,smin=0.,smax=5.): """Assumes ifs and dist are both in slope or amplitude space. No conversion to slope will occur.""" #Create bounds list if bounds is None: bounds = [] for i in range(np.shape(ifs)[0]): bounds.append((smin,smax)) #Ge...
228dc0e25daa462610edd1c2c03806fb71c43117
81,053
def new_password(current_password): """Find the next new password starting at current_password Only valid passwords are returned, with the requirements being: * must include one increasing straight of at least three letters, like abc, bcd, cde, and so on, up to xyz. They cannot skip...
1667e19eb16bb39186bf78846cef1bb4ce51590b
81,054
import html def gen_link(text, url, color='green-text'): """ Create a html Link object, given text and url :param color: css class for text color, default green :param text: Display text :param url: url to link to :return: html.Div() """ return ( html.A(f'[{text}]', href=url, c...
56df851433b345467d65bda65846d8d647e118ec
81,055
def load_zoo_dataset( name, split=None, splits=None, label_field=None, dataset_name=None, dataset_dir=None, download_if_necessary=True, drop_existing_dataset=False, overwrite=False, cleanup=True, **kwargs, ): """Loads the dataset of the given name from the FiftyOne Datase...
defa923f016d7d04fdc52aa8163ab0ebe802b896
81,056
def fix_segments_intersections(polygons, height, width, img_name, use_background_label, threshold=0.0, ratio_tolerance=0.001, area_threshold=1): """Find all intersected regions and crop contour for back object by objects which are in front of the first one. It is related to a ...
054c55eb3f8a895a58a93f97bb12ee1a49ab95fc
81,057
def cc_to_cb(s, enc, cc): """convert char count to byte count arguments: s -- unicode string enc -- encoding name cc -- char count """ s = s.encode('UTF-32LE') clen = cc * 4 if clen > len(s): raise IndexError return len(s[:clen].decode('UTF-32LE').encode(enc))
92f91ab39ea6b6793753feb9d83b49acca32649a
81,058
def st_orientation(G): """Find an acyclic orientation of G, with one source and one sink.""" stO = STOrienter(G) if len(stO.roots) != 1: raise NotBiconnected source, dest = stO.roots[0] G = {v: set() for v in G} orientable = [] while True: G[source].add(dest) for u,...
9d1181958feca98e9a5bd3d435aa0cc0ff1c7b31
81,059
import hashlib def calculate_variant_md5(chromosome, position, reference, alternate): """Calculate MD5 hash for a variant Args: chromosome (str): Chromosome position (int): Genomic position reference (str): Reference allele alternate (str): Alternate allele Returns: ...
36a201f05a8e2a09c2e567acf02089d01462248c
81,060
from typing import cast def create_collection(catalog_id: str) -> pystac.Collection: """Creates a STAC Collection for MODIS data. """ collection = pystac.Collection( id=catalog_id, description=cast( str, MODIS_CATALOG_ELEMENTS[catalog_id]["description"], ),...
e8a3ac5f1182f59bf8e01bf62f2e032cd197519d
81,062
def load_wn11(check_md5hash=False, clean_unseen=True, add_reciprocal_rels=False): """Load the WordNet11 (WN11) dataset WordNet was originally proposed in `WordNet: a lexical database for English` :cite:`miller1995wordnet`. WN11 dataset is loaded from file if it exists at the ``AMPLIGRAPH_DATA_HOME`` locat...
b3cfe3f44810d3963c3d2013105829cb20324221
81,063
def get_default_driver_options(width=1472, height=828, headless=True) -> Options: """ Generate default Chrome driver options :param width: int :param height: int :param headless: bool :return: Options """ chrome_options = Options() chrome_options.headless = headless chrome_optio...
97f7f91717fb0f441848ef655a38e7dac0719396
81,064
import collections def recursive_dict_update(dictionary, updates): """ Internal helper function to recursively update nested dictionaries (copies the source). """ dictionary = dict(dictionary) for key, value in updates.items(): if isinstance(value, collections.abc.Mapping): dic...
1065c1f64782327dcb1ceb209ab9d008402142cb
81,065
def get_pre_check_status_code (pre_check): """ Check the pre-check result information to determine the HTTP status code result of the pre-check. :param pre_check: The result of the pre-check call. :return An HTTP status number for the pre-check result. If the pre-check passed, 200 is ...
6edfa8031d4a72d12b2552fb90c391d30943edb6
81,066
def subtract_segment(a, b): """ Subtract segment a from segment b, return 'a' if no overlap """ if a[0]>=b[0] and a[0]<=b[1] and a[1]>b[1]: return (b[1]+1,a[1]) elif a[0]<b[0] and a[1]>=b[0] and a[1]<=b[1]: return (a[0], b[0]-1) elif a[0]<b[0] and a[1]>b[1]: return ...
28c94a76694d7b061143a416596af325e15ccb7b
81,068
import torch def _find_max_response_value(train_X, train_Y): """ determines best (max) response value max_X across recorded values in train_Y, together with the corresponding X values :param train_X (torch.tensor) :param train_Y (torch.tensor) :return max_X (float): the X values corresponding ...
8be4afaa622f42f23859bb6ec5262d1cd2458781
81,070
def circ_corrcl(x, y): """Correlation coefficient between one circular and one linear variable random variables. Parameters ---------- x : 1-D array_like First circular variable (expressed in radians). The range of ``x`` must be either :math:`[0, 2\\pi]` or :math:`[-\\pi, \\...
5b9f2349775e18663ff3d48de1d87bc6c6efedce
81,071
from typing import Set from typing import Dict def get_macro_pool_nodes_count(individual: Individual, frames: Set[Frame] = None) -> Dict[Frame, int]: """Get a dict containing {Frame: number_of_macros}. Selects only MacroPools Args: frames (Set[Frame]): set of frames of which I want the number of node...
9865318bdbbaea915015499e718af7cf4c4f88bc
81,072
from typing import Callable from typing import Any def convert_recursive( is_match: Callable[[Any], bool], convert_item: Callable[[Any], Any], obj: Any ) -> Any: """Either convert a single value if it matches a given function, or recursively walk over potentially nested lists, tuples and dicts applying ...
1584d74cb3b224f14388fc6a6ddd58c87773fa88
81,074
def score(source_data: list, weights: list, *args) -> list: """Analyse and score a dataset using a range based percentual proximity algorithm and calculate the linear maximum likelihood estimation. Args: source_data (list): Data set to process. weights (list): Weights corresponding to each c...
e141bcfa9df9456fd39318ec2b9bc74e7d121c2d
81,075
def verify_vrf(pub, vrf, message): """Verify a VRF. Checks whether a VRF value and a proof correspond to the message. :param petlib.EcPt pub: VRF public key :param VrfContainer vrf: VRF value and proof :param bytes message: Message """ pp = PublicParams.get_default() G = pp.ec_group ...
27b3c3eb02ecee08dc78cc87067717881ea103f5
81,076
def SinusPositional_embed(batch_size, seq_length, num_units, zero_pad=True, scale=True, scope='Sinus_Pos_Block', reuse=None): """Sinusoidal Positional Encoding....
3093b01826719f93ee1d549831fdfdfb64c3dc97
81,077
def config_ip_igmp(dut, **kwargs): """ Config IP IGMP. Author: Sathishkumar Sivashanmugam (sathish.s@broadcom.com) :param :dut: :param :cli_type: click|klish :return: """ if 'port_alias' not in kwargs: st.error("Mandatory parameter port_alias not found") return False ...
66091a24fc9d945f361afd11d2732008dee57025
81,078
def check_entrypoints(): """ Fixture to check that loading of all the workflow, calculation and parser entrypoints through the corresponding factory works for the given (base) module name. """ def inner(module_name): # pylint: disable=missing-docstring for group, factory in [('aiida.wor...
86aa6c655fcec0a937b1d32073c397360be5673e
81,079
def create_assignment(x_sol, A): """ Given a solution from linear programming problem for paper assignments with affinity matrix A, produce the actual assignment matrix b """ n_papers, n_reviewers = A.shape i, j = A.nonzero() t = np.array(x_sol > 0.5).flatten() b = np.zeros((n_papers, n_...
b67376b6a4b2922f4982532741a7db94fbefaf52
81,080
def skill(obs, mod): """returns skill of model output arguments: obs -- the observed data (elvation change) of lenth n mod -- the modeled data of lenth n notes: skill = 1 --> perfect simulation skill = 0 --> no better than no change skill < 0 --> worse than no change """ ...
59e45614bcdf64c0bfcdb157ec3f16f7bbf8d33a
81,081
def handler(event, context): """Client with access keys to write to Dynamo tables online""" buildingTable = DynamoTable('Buildings') machineTable = DynamoTable('Machines') return scrapeLaundry(event, context, buildingTable, machineTable)
8d1e9f794e401ac4091351965a63db779c49580b
81,082
import math def n_vector(lat, lon): """Converts lat/long to n-vector 3D Cartesian representation.""" # Convert to radians. if not (-90.0 <= lat <= 90): raise ValueError("lat={:2.2f}, but must be in [-90,+90]".format(lat)) rad_lat = math.radians(lat) if not (-180.0 <= lon <= 180): raise ValueError("l...
dca7be0345b7498ece4f66cceeb6e062e9cda9a0
81,083
import logging def ReturnFlavor(machine_type): """Returns RAM and Core values based on machine_type selection.""" logging.info('Fetching flavor specs for new VM.') for flavor in FLAVORS: if(machine_type == flavor['name']): return flavor['ram'], flavor['cores']
3297b6c77da91d639e7be6e0d18ec4624cc54e1c
81,085
import logging def get_local_rank(world_size: int, rank: int) -> int: """ Get the local rank of the local processes (see https://pytorch.org/docs/stable/elastic/run.html) This is usually the rank of the worker on its node """ my_local_rank = _env2int( [ "LOCAL_RANK", ...
02eb2fa6c50444e826a3d9d9fe65f6ea8aed97c8
81,086
def free_up_disk_space(module, disk_used_pcent): """Remove old log, core and dump files.""" def get_disk_used_percent(module): output = exec_command(module, cmd="df -BM --output=pcent /host")[1] return int(output.splitlines()[-1][:-1]) if get_disk_used_percent(module) > disk_used_pcent: ...
4f7282e5a0f6fa625c9eca496a3f5cd9c979e907
81,087
def gen_mock_env_info(*args, **kwargs) -> str: """ 构造并返回 mock 的 exec_command 查询到的 env_info """ return "env1=xxx\nenv2=xxx\nenv3=xxx"
e2fc7ce00710ba1523c3efdef1f1102dfa42080e
81,088
def create_temperature_dim(df_temp, i94port_name_code_dict): """ Create Temperature dimension table using processed dataframe """ @udf() def get_i94port(city): """ Get city code for provided city name """ for name, code in i94port_name_code_dict.items(): i...
67702cd4a7ec9913f7038be153c91d036d785297
81,089
def extract_coadds(df, bands='ugrizy', verbose=False): """ Extract the coadds for each band-tract-patch combination, and compute the number of visits per coadd for resource scaling. Parameters ---------- df : pandas.DataFrame Dataframe containing the overlaps table information, i.e., ...
18ac0b108a8ada0345164cdac5a41e564d5d77ca
81,090
import time import logging import tempfile def RunConstrainedCmd(cmd, lock_file, path, inp=None, _lock_timeout=_RCMD_LOCK_TIMEOUT, _sleep_fn=time.sleep, _prepare_fn=_PrepareRestrictedCmd...
93375e0cdaaefadbe6213f99a2ea0a8ef63c1d8e
81,092
import copy def crowdsource(i): """ Input: { (local) - if 'yes', local crowd-benchmarking, instead of public (user) - force different user ID/email for demos } Output: { return - return code = 0, if successful ...
ea924259799d4cd2a6a707a24b047dd4479cacb9
81,094
def plot_box_reaction_time(config): """Plots the reaction time box plot Parameters ---------- config : yaml The yaml configuration rate. Returns ------- None """ # Using the data from MATLAB file run return None
571c5313b2f8decb5234c99cb6ab6b23bd7cc43d
81,095
def get_fields_for_l3_plot(product: str, model: str) -> list: """Return list of variables and maximum altitude for Cloudnet quicklooks. Args: product (str): Name of product, e.g., 'iwc'. model (str): Name of the model, e.g., 'ecmwf'. Returns: list: List of wanted variables """ ...
6a757c48cfb168c86912315e95e9f70c63458c6b
81,096
def input_creator(ioctx: IOContext) -> InputReader: """ The input creator method can be used in the input registry or set as the config["input"] parameter. Args: ioctx (IOContext): use this to access the `input_config` arguments. Returns: instance of ShuffledInput to work with some...
a79f22444f0d79fe5b9ce345cec9554e46e109c1
81,097
from unittest.mock import patch def hass_ws_client(aiohttp_client): """Websocket client fixture connected to websocket server.""" async def create_client(hass, access_token=None): """Create a websocket client.""" assert await async_setup_component(hass, 'websocket_api') client = await...
6b550f5c056e205a8e14fbd8eb898d7d53d88a7c
81,100