content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def validate(args): """ Check that the CLI arguments are valid. """ if not args.source_path: print("Error: You need to specify a source path.") return False else: if not os.path.isdir(args.source_path): print("Error: Source path is not a folder.you can...
5d140178fd803f882e273f36bdf59e73135550ef
3,622,200
def freq_correctionbis(cpt_matrice, beta) : """ Corrige les counts avec equiprobabilites """ for i in range(cpt_matrice.shape[0]) : for j in range(cpt_matrice.shape[1]) : cpt_matrice[i,j] = ((cpt_matrice[i,j] + (1/20) )/(1+beta)) return(cpt_matrice)
570393b8df2a3a8bf675d7ce47950d8290680779
3,622,201
def bit_to_long(bits: str) -> Decimal: """ Converts a bit string in the format '01' to a float, representing the NTP long format (64bit) """ ints = int(bits, 2) result = Decimal(ints) / Decimal(_max_32bit) return result
f3a353113fddfc8134f574c988f373de7ba2e1bc
3,622,202
def scale_from_internal(vec, scaling_factor, scaling_offset): """Scale a parameter vector from internal scale to external one. Args: vec (np.ndarray): Internal parameter vector with external scale. scaling_factor (np.ndarray or None): If None, no scaling factor is used. scaling_offset (...
c7f2471d2a7776f8756d709d0288163aab3594ae
3,622,203
def apply_dhondt( list_of_parties=['PRD','ARV','PSI','PNR'], list_of_votes=[2015,1786,1540,1223], num_of_chairs=12): """ list_of_parties: ['PRD','ARV','PSI','PNR'] list_of_votes: [2015,1786,1540,1223] num_of_chairs: 12 output: (DataFrame) PRD 4 ARV ...
0e5e32d4cf7323414c88e837297739029b6e90fb
3,622,204
def get_temp() -> tuple: """ Retrieves the CPU temperature of the Raspberry Pi and turns the fan on or off based on the read value. :return: An empty tuple. """ cpu_temp = float(get_cpu_temperature()) if cpu_temp > maxTMP: fan_on() elif cpu_temp < stopTMP: fan_off() r...
e4754d51847961d035860633780f679492b07002
3,622,205
import argparse def parse_arguments(argv): """Parse command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '--verbosity', help='Set logging level.', choices=['DEBUG', 'ERROR', 'FATAL', 'INFO', 'WARN'], default='INFO', ) parser.add_argume...
ab87b47f7a0d184ed8fd33faf2880acc051fd362
3,622,206
def level_image(image: Image.Image, adjustments: list[LevelsAdjustment]) -> Image.Image: """ Apply the specified levels adjustments to each band of an image. :param image: The input image, with values in the range [0, 255]. :param adjustments: The levels adjustments to apply for each band. :return:...
5cbf10275642f81c0ca5117bce192a8e9fa9e57c
3,622,207
def extract_network_information(shape, properties, fid, zoom): """ Take the triples of (route_type, network, ref) from `mz_networks` and extract them into two arrays of network and shield_text information. """ mz_networks = properties.pop('mz_networks', None) if mz_networks is not None: ...
0bfb0926c5eef46734cfd87c8ab03891c91d5110
3,622,208
def filter_pre_string(_string: str, lines_to_cut: int) -> str: """ Filter the xml out of html :param str _string: :param int lines_to_cut: """ filtered_array = _string.splitlines()[lines_to_cut:] filtered_string = "".join(filtered_array) filtered_string = filtered_string.strip() re...
1bde68fbfa3f87360b47ece45b64782dcc3bcde6
3,622,209
def extract_ontology_terms(spark_session: SparkSession, input_path) -> DataFrame: """ :param spark_session: :param ontologies_path: :return: """ ontology_terms = [] if ImpcConfig().deploy_mode in ["local", "client"]: for ontology_desc in ONTOLOGIES: print(f"Processing {o...
91f37011ed95470be98e6613868d61718f843cf2
3,622,210
def get_one_example_from_examples_path(source, proto=None): """Get the first record from `source`. Args: source: str. A pattern or a comma-separated list of patterns that represent file names. proto: A proto class. proto.FromString() will be called on each serialized record in path to parse it....
384194d68f22f73ece806cf0b0aabd0721e5bd5f
3,622,211
def ssum(self, **kwargs): """Calculates and prints the sum of element table items. APDL Command: SSUM Notes ----- Calculates and prints the tabular sum of each existing labeled result item [ETABLE] for the selected elements. If absolute values are requested [SABS,1], absolute values are u...
299a14a2e21454a304d6d023d2b3a3709b24eb18
3,622,212
def get_nth_combination( iterable, *, items: int, index: int, ): """ Credit to: https://docs.python.org/3/library/itertools.html#itertools-recipes Examples: >>> wallet = [1] * 5 + [5] * 2 + [10] * 5 + [20] * 3 >>> get_nth_combination(wallet, items=3, index=...
6ed186d260ca86c0f16d383576e69402d079ed9b
3,622,213
def fft2(x, shape=None, axes=(-2, -1), overwrite_x=False): """Compute the two-dimensional FFT. Args: x (cupy.ndarray): Array to be transformed. shape (None or tuple of ints): Shape of the transformed axes of the output. If ``shape`` is not given, the lengths of the input along ...
a86c2fbac32debe754ed283b2b5f63d8ccfb5cba
3,622,214
def equalize(pair, bias_axis, word_to_vec_map): """ Debias gender specific words by following the equalize method described in the figure above. Arguments: pair -- pair of strings of gender specific words to debias, e.g. ("actress", "actor") bias_axis -- numpy-array of shape (50,), vector correspon...
858f6f43d799973c3314aa184e64caed3cdbc77a
3,622,215
def test_text_angle_30(region, projection): """ Print text at 30 degrees counter-clockwise from horizontal """ fig = Figure() fig.text( region=region, projection=projection, x=1.2, y=2.4, text="text angle 30 degrees", angle=30, ) return fig
1add55f5465c5285bfb7b626f6c4259d4189240d
3,622,216
def edit_cmd(args): """Builds and returns 'edit' command.""" cmd = commands.Edit(args.args, color=args.color) return cmd
11e766fd1e348584f5aed965788c06b54dca551c
3,622,217
def get_image_band(filepath, modis_config=None): """Helper function to get bands for a particular modis scene Args: modis_config (dict): dictionary of configuration for a particular MODIS datasource filepath (str): path to file to get image band for """ bands = list(modis_config["bands"...
796734a9e666e2e6a5467c8ae2d80ffceab6e9d7
3,622,218
import six from datetime import datetime import re def create_mock_engine(bind, stream=None): """Create a mock SQLAlchemy engine from the passed engine or bind URL. :param bind: A SQLAlchemy engine or bind URL to mock. :param stream: Render all DDL operations to the stream. """ if not isinstance...
7ad7e528041a899268bdf796893d633909a6ea54
3,622,219
from typing import Tuple from typing import List def rst_table(header: Tuple[str, ...], rows: List[Tuple[str, ...]]) -> List[str]: """Create a ReST table from header and rows.""" blocks = [".. list-table::\n :header-rows: 1\n"] num_columns = len(header) for row in [header] + rows: template =...
461ecb7bbe99752d1ef5c9341cd53c2c7c3752bf
3,622,220
def get_model(args): """"Get model according to args.arch""" print("==> Creating model '{}'".format(args.arch)) model = models.__dict__[args.arch](args) return model
ed4d1a8eb5dad2beb0968be5318dd706a3f34cf3
3,622,221
def truncate_note_sequence_op(sequence_tensor, truncated_length_frames, hparams): """Truncates a NoteSequence to the given length.""" def truncate(sequence_tensor, num_frames): sequence = music_pb2.NoteSequence.FromString(sequence_tensor) num_secs = num_frames / hparams_frames_...
34276444a0e338c0fa81f6cde8d5932e86bfa1a4
3,622,222
def compute_mse_labels(params, delta, X, Y, labels, use_sigmoid): """ assume a, b, c, delta, X, Y are all in the right dimensions """ if use_sigmoid: sig0, sig1 = params else: a,b,c = params N_patients, N_visits, N_dims = Y.shape all_mse = 0. for i in range(...
6c8778cd40ef6af6949089afed3adfcb56b945c4
3,622,223
def produce_columns(df): """Reports columns for use in model.""" columnsNames = [] for i in df.columns: if i == 'Survived' or i == 'PassengerId': pass else: columnsNames.append(i) return columnsNames
ce527118fc099ac05d20dbb981f5f3231e9070fa
3,622,224
def fixture_ref_6_2_3_5(): """Reference for (load, bins) of 6, [2, 3, 5].""" ref = { "load": 6, "bins": [2, 3, 5], "solutions": { key: [(3, 3)] for key in ["length", "capacity", "combo"] } } return ref
7b7121e404b4daf3277a4ab6f33eb955cd6d47e7
3,622,225
def compute_population_threshold(df_entire, base_population_threshold=500): """Computes a population threshold to use when deciding whether or not to display a sub-dimension's anomaly detection analysis :param df_entire: Entire pandas DataFrame which anomaly detection is run on :type df_entire: pandas.core...
049b5a827d2a24ce5c01084721d222cf94feb5a9
3,622,226
import time def read_variable_bounds(filename, verbose=False): """Read permissible lower and upper bounds for decision variables used in forcefields optimization :param filename: Name of text file listing bounds for each decision variable that must be optimized :type filename: str :param verbose: Pr...
c8207d291ce0b698bbf1eacb920d0c787d2b7eb3
3,622,227
def parse_spec_storage_location(location: str) -> SpecStorageLocation: """ Parse the spec storage location into components. Args: location: The spec storage location to parse. Returns: The parsed spec storage location. """ sub, spec_id, filename = location.split("/") versi...
96f70c82bcaf3f971d109e043794815760529d45
3,622,228
def datastore(plugin, key, string=None, hex=None, mode="must-create", generation=None): """Add/modify a {key} and {hex}/{string} data to the data store, optionally insisting it be {generation}""" key = normalize_key(key) khex = key_to_hex(key) if string is not None: if hex is not None: ...
428adb35c4fe58c4f794055f20735aa42f93d0e8
3,622,229
def recreate_knob_from_optimizer_values(variables, opti_values): """ recreates knob values from a variable """ knob_object = {} # create the knobObject based on the position of the opti_values and variables in their array for idx, val in enumerate(variables): knob_object[val] = opti_values[idx] ...
8c253ea75f1dbb8c27cde21b2208b5386d75930e
3,622,230
def make_cube_marker(box_center, box_dim): """ a reasonable default box marker. """ marker = CubeMarker(box_dim) marker.set_translation(box_center) marker.set_color_float([1., 0., 0.]) marker.set_alpha(0.80) return marker.to_msg()
f3c643c9f52fb0876643fc1b3acc3dcbfc12dce2
3,622,231
def KDPReadPhysMEM(address, bits): """ Setup the state for READPHYSMEM64 commands for reading data via kdp params: address : int - address where to read the data from bits : int - number of bits in the intval (8/16/32/64) returns: int: read value from memory. ...
7eae9f5a74e5788775c132d8766e244e8d2878f1
3,622,232
import typing import sys import argparse import multiprocessing def parse_args(args:typing.Sequence[str]=sys.argv[1:]): """ Parse the command-line arguments :param args: argument strings :return: the options dictionary """ parser = argparse.ArgumentParser() parser.add_argument( "-...
6088425154379e77752ff4dfa52b86fbba8df429
3,622,233
import sqlite3 def query_for_requests(last_time, new_last_time, logger): """ Return the rows from the sqlite database after last_time (and before new_last_time if test mode) """ database = SQL_DATABASE if TEST_MODE: database = TEST_SQL_DATABASE conn = sqlite3.connect(database) ...
29247b8380d5276015d16567b835d9ef9deb497d
3,622,234
from typing import List from typing import Optional from typing import Iterable def combine( meshes: List[pv.PolyData], data: Optional[bool] = True, clean: Optional[bool] = False, ) -> pv.PolyData: """ Combine two or more meshes into one mesh. Only meshes with faces will be combined. Support ...
b219f9d408c4494373e65048d59ff62fae92d422
3,622,235
def magician(*cards, n=1): """Determine the fifth card with only four cards.""" # Obviously not a random card, put your code here instead. show = cards[(n-1)%4] pile1 = [i for i in cards] pile1.pop((n-1)%4) pile2 = deepcopy(pile1) pile2.sort(key = lambda i: (RANKS.index(i[:i.index(' ')]),SU...
5181658579b41d8676e7af78175f1d6eba13af7d
3,622,236
from typing import List def create_users_from_csv(connection: "Connection", csv_file: str) -> List["User"]: """Create new user objects from csv file. Possible header values for the users are the same as in the `User.create()` method. Args: connection: MicroStrategy connection object returned by ...
32c991cd82c0c314e4c9ec2bfe6ba586e0e26425
3,622,237
def catl_keys_prop(catl_kind, catl_info='members', return_type='list', Program_Msg=fd.Program_Msg(__file__)): """ Dictionary key sfor the different galaxy/group properties of catalogues Parameters ---------- catl_kind: string, optional (default = 'data') type of catalogue to use ...
f57c7316d0cc7a418a699d00535af63ea9c9dd5b
3,622,238
def pa_max_pool(in_dict): """Implement `local max pooling` as `masking + global max pooling`. Args: feat: pytorch tensor, with shape [N, C, H, W] mask: pytorch tensor, with shape [N, pC, pH, pW] Returns: feat_list: a list (length = pC) of pytorch tensors with shape [N, C] vis...
39d78b691f9358b3e6820ace54fbb69845934a9f
3,622,239
def _create_validate(cls, validators): """ Create a new validate method with extra validator functions. """ def validate(self, value): super(cls, self).validate(value) for validator in validators: validator(value) validate.__doc__ = validators[0].__doc__ return vali...
a3f8b1ef5255f1c2f359b82539aa911b6d136514
3,622,240
def predict_roi(roi, ground_truth, model, device, in_trans=None, batch_size=1, tile_size=256, overlap=0, n_jobs=1, zoom_level=0): """ Parameters ---------- roi: BaseCrop The polygon representing the roi to process ground_truth: iterable of Annotation|Polygon The groun...
9c55c3b0f87a2b23794eaaf6ff8d364955ab6404
3,622,241
from typing import Iterable from typing import Type def get_ceed_stages( stage_factory: StageFactoryBase) -> Iterable[Type[StageType]]: """Returns all the stage classes defined and exported in this file (currently none for the internal plugin). :param stage_factory: The :class:`~ceed.function.Fun...
41717ed8f700cd08e2d1728616259a09b8a8434f
3,622,242
import logging def scale_quote_of_type( df: pd.DataFrame, mapping: dict, file_type: str = "quotes" ) -> (pd.DataFrame, dict): """ Scales quote values of quotes of a specified type This function appends an extra row (__adjusted_quote) to a dataframe that contains quotes that have been scaled by a ...
85d7edc762fc29eb03d77495a4100b57f2d735ea
3,622,243
def mysql_metadata_connection_config(host: Text, port: int, database: Text, username: Text, password: Text ) -> metadata_store_pb2.ConnectionConfig: """Convenience function to create mysql-based metadata connection config. Args: host: The...
9349f5a720b99629e1f24a2367cd35b9246fadbb
3,622,244
def _status(self): """status -> Returns the Shot status. None if no Status is set.""" status = None tags = self.tags() for tag in tags: if tag.metadata().hasKey('tag.status'): status = tag.metadata().value('tag.status') return status
eb8fd85218f6e745f09e4984db8b6c74ba464dcb
3,622,245
def convert_onnx_less(operator, device=None, extra_config={}): """ Converter for `ai.onnx.Less`. Args: operator: An operator wrapping a `ai.onnx.Less` model device: String defining the type of device the converted operator should be run on extra_config: Extra configuration used to s...
62c15f872efad8a30496a6cd018ae085d0a790b4
3,622,246
import os def instantiator(objects): """ Returns list of java source lines, which encode an instantiator that binds classes in the root package (and subpackages) to exported objects with the same name. """ j = os.path.join src_root = ut.src_root() relevant_dirs = ut.listdir(src_root, d...
0d24c522027c1c5174b112b1b22240b569d37eb5
3,622,247
def capped(value, minimum=None, maximum=None, key=None, none_ok=False): """ Args: value: Value to cap minimum: If specified, value should not be lower than this minimum maximum: If specified, value should not be higher than this maximum key (str | None): Text identifying 'value' ...
663a63041699f4e4f52886adbd49423bf52c0282
3,622,248
def conditional_MARC21(record, rule): """Function takes a conditional and a mapping dict (called a rule) and returns the result if the test condition matches the antecedient Parameters: record -- MARC21 record rule -- Rule to match MARC field on """ output = [] if rule.has_key('cond...
5618fbe5bec61379b106c3caa2b3330fa5900b89
3,622,249
def row(ctx): """Get this cell's row.""" return ctx["cell"].row
4cfc89daa3ca771359acd762d716316209ca0eb4
3,622,250
import joblib import numpy as np import tqdm import sys def apply_parallel_iter(items, num_procs, func, *args, progress_bar=False, total=None, num_groups=None, backend='loky'): """ This function parallelizes applying a function to all items in an iterator using the joblib library. In particular, func is ...
86817e1247928182bef82dc70710aa2818ff5020
3,622,251
def get_external_admin_connection_string(db_name=None, db_prefix=None): """Get an admin connection string for access from outside the cluster""" admin_user, admin_password, admin_db_name = get_admin_db_credentials(db_prefix=db_prefix) if not db_name: db_name = admin_db_name db_host, db_port = ge...
b0678960aa9f7e8b3bb1ba33245d761281ce2c8e
3,622,252
import math def calc_room_positions_square(side_length, num_rooms): """ Calculate the central positions of the square rooms. """ sqrt_num_rooms = int(math.sqrt(num_rooms)) if sqrt_num_rooms ** 2 != num_rooms: raise ValueError("num_rooms must be a perfect square number") int_positions...
c4e2cc4338339ce10877ad920500124beb612aa5
3,622,253
def logout(request: HttpRequest, default_redirect="/"): """ This function logs a user out and redirect him to a certain location :param request: the current HTTP request :param default_redirect: The location to redirect if no next GET request is given :return: The HTTP_RESPONSE containing the redire...
b53bc3de1973a67792da7e5623930772545929bc
3,622,254
def cell_slice(payload): """Retrieve the next cell from the payload and truncate that one. :param payload: bytearray """ payload_len = len(payload) if payload_len < 7: # (payload too small, need data) return None, payload cmd = cell_get_cmd(payload) if cell_is_variable_length(cmd):...
79208936e020dabde1e99507d3886fd09c134948
3,622,255
import math def approx_equal(x, y, tol=1e-12, rel=1e-7): """approx_equal(x, y [, tol [, rel]]) => True|False Test whether x is approximately equal to y, using an absolute error of tol and/or a relative error of rel, whichever is bigger. >>> approx_equal(1.2589, 1.2587, 0.003) True If not gi...
474254bc46c27bc52da88a8c4d80db2b461a5255
3,622,256
def calc_entropy(logits): """ Calculates the entropy of the output values of the network :param logits: (TensorFlow Tensor) The input probability for each action :return: (TensorFlow Tensor) The Entropy of the output values of the network """ # Compute softmax a_0 = logits - tf.reduce_max(i...
d60c4e1fba7098167d9e48ae8bdcfcfd6a159ba8
3,622,257
def make_environment(domain_name, task_name, rng, frame_stack, action_repeat): """Create a visual DMC environment""" env = suite.load( domain_name=domain_name, task_name=task_name, environment_kwargs={"flat_observation": True}, task_kwargs={"random": rng}, ) camera_id = 2...
7c55e3d7e0829287c8b9dd69c3c8f4821584b715
3,622,258
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" label_map = {label: i for i, label in enumerate(label_list)} features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) ...
a77ffa87357c5615d8435dc6903a857607bea4e4
3,622,259
from re import A def org_resource_list_layout(list_id, item_id, resource, rfields, record): """ Default dataList item renderer for Resources on Profile pages @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3Resource to render ...
2c981ca6d3afe9cafd93c07135e73d7feeb9c86a
3,622,260
def get_post_by_id(request, post_id): """Read: Get a post with given event_id e.g. http://127.0.0.1:8000/api/post/2 """ if request.method == 'GET': # key_flag = len(request.GET['eventID']) # if key_flag: # record = GISource.objects.filter(event_id=post_id) # ser...
b86751630ceb018889cbc2abef8f6f6fa3ee7d8e
3,622,261
def fetch_created_ruleset(creator_id): """ Get a user ID that want to filter the ruleset that this user make and return a list of ruleset with the User object of that ruleset. If the program cannot find the User object,it will append `None` to the return value. :param creator_id: A user ID ...
7513ed96af4cb69f6176c63ddef85bf4662ff2ef
3,622,262
from datetime import datetime import copy import logging def Run(benchmark_spec): """Executes the given jar on the specified Spark cluster. Args: benchmark_spec: The benchmark specification. Contains all data that is required to run the benchmark. Returns: A list of sample.Sample objects. ""...
12e9e31349434cffb90a1c89ac599666e4ee348e
3,622,263
def threshold_stats_img(stat_img=None, mask_img=None, alpha=.001, threshold=3., height_control='fpr', cluster_threshold=0, two_sided=True): """ Compute the required threshold level and return the thresholded map Parameters ---------- stat_img : Niimg-like...
a29da195a4178b798da929b25bb0c28715d55ae1
3,622,264
import pathlib def _export_doc_requirements(toml: dict, file: pathlib.Path, *packages) -> int: """ Export the provided packages versions. Return values: 0 no changes 1 exported new requirements 2 file does not exist 3 invalid packages """ file = pathlib.Path(file) if not file....
bc1eb73737b4674f9e66590d714614da04e77bdf
3,622,265
import re def _extract_function_from_js(name, js): """ Find a function definition called `name` and extract components. Return a dict representation of the function. """ dbg("Extracting function '%s' from javascript", name) fpattern = r'function\s+%s\(((?:\w+,?)+)\)\{([^}]+)\}' m = re.searc...
74159764aff104d7910d258644a6272f1d33e1ac
3,622,266
import os def edit_files(files: dict, path: str, clear_all: bool, do_rename: bool): """ Set, edit or delete the metadata of the selected file and rename these files :param files: information from user about the metadata of each file :param path: the directory where these files are located :param ...
845647fa07133d7d6d5aff3ad58e04a7ddafe650
3,622,267
import os import uuid import time import shutil import subprocess import sys def bootstrap(opt, logger): """Bootstrap the engine.""" if not opt.conda_available and not opt.freeze: logger.warning( "Command `pip install` may not work, " "in that case you may want to add `--freeze...
ba9787b5a015f58c910eec8cdbff390dcfb9d3b8
3,622,268
def above_the_line(x_array, x1, x2): """ Return states above a specified line defined by (x1, x2). We assume that a state has only two coordinates. Parameters ---------- x_array: `np.array` A 2-d matrix. Usually, an embedding for data points. x1: `np.array` A list or array ...
d20b5d462b7254a93f7896b592ae25eae26075a7
3,622,269
import subprocess def run_exec(exec_path,exec_options_list,input_data=None, stdout=None, stderr=None): """Basic function to run an executable using `subprocess` (only tested with .exe files). Parameters ---------- exec_path : str/os.path path to an executable. exec_options_list : list ...
44e82d0ceb93b002c94a04a2132d9aedd956b304
3,622,270
import torch def cel_num_div(cel_mat: Tensor, rc: float) -> Tensor: """Number of percel for each direction. Args: cel_mat: cell. rc: cutoff radius. Returns: num_div(int[bch, dim]): number of percel for each direction. """ num_div = ((cel_mat / rc).norm(p=2, dim=-1) - 1e-4...
768a10cb68243f17a8e51f10092d90bb119c9a47
3,622,271
def confusion_samples(prediction, truth, names): """ Computes the confusion matrix and returns a list with the TP/FP/TN/FN names """ confusion_vector = prediction / truth # Element-wise division of the 2 tensors returns a new tensor which holds a # unique value for each case: # 1 wher...
6d3bd82f1ea695345a30a75be6642328a393a1de
3,622,272
def post_upload_finished(uid): """ ask the server to finish the upload :param uid: upload session ID :return: status of upload """ uploaded = require_integer_array_json_parameter("uploaded") with slycat.web.server.upload.get_session(uid) as session: return session.post_upload_finishe...
4d8ea1b6283e9de339010ce1adc275f76edc78b4
3,622,273
def info(): """Returns information about a worker. Useful for testing that the system is functioning. Returns ------- metadata: :class:`dict` A collection of key-value pairs containing information describing the local worker. """ return buildcat.info()
0f3f75555e2ec289b1422e17e8f06c2ce45565e3
3,622,274
def parse_xml(path): """ Returns representation of the root node in the XML file. """ try: return XMLElement(ET.parse(path).getroot()) except ET.ParseError as e: raise XMLParseError(str(e))
3e129e3ba5a66560c3f9a67df0e6cc76ecefbb47
3,622,275
def fastq_pe_pipeline(project, sample_identifier=None, end_identifier=None): """Functional profiling pipeline for entire project Args: project (:obj:Project): current project sample_identifier (str, optional): sample identifier end_identifier (str, optional): end identifier """ ...
b7046214ee156497e869fd37f5c5ab8c17c3c085
3,622,276
import logging def lpp_voltage_to_bytes(data): """Encode voltage into CayenneLPP and return byte buffer.""" logging.debug("lpp_voltage_to_bytes") data = __assert_data_tuple(data, 1) val = data[0] if val < 0: logging.error("Negative Voltage value is not allowed") raise AssertionErro...
574198f332f01f24db80a8e0431dd9e10932d61c
3,622,277
from pathlib import Path def test_data_path() -> Path: """Fixture to Fetch reports for unit testing.""" return repo_path / 'tests' / 'data'
b7ad565f0e77bba6d3ff74ba0318df8742061597
3,622,278
def createSequentialVector(size, vector_type, communicator=None): """Create a sequential vector in petsc format. :param int size: vector size. :param int vector_type: vector type for parallel computations. :param str communicator: mpi communicator. :return: sequential vector. :rtype: petsc sequ...
15328b4ac90754ee7ff8c4c2556aee859a2f252e
3,622,279
def create_gunicorn_worker(): """ follows the gunicorn application factory pattern, enabling a quay worker to run as a gunicorn worker thread. this is useful when utilizing gunicorn's hot reload in local dev. utilizing this method will enforce a 1:1 quay worker to gunicorn worker ratio. """ ...
cea3812243406b069049ed9c9965713514e80bae
3,622,280
import tensorflow as tf def downsampler_gpu(input, down_scale, kernel_name='bspline', normalize_kernel=True, a=-0.5, default_pixel_value=0): """ Downsampling wiht GPU by an integer scale :param input: can be a 2D or 3D numpy array or sitk image :param down_scale: an integer value! :param kernel_na...
c92641aae2ced49b84c33bdb4b272bb4ce255f90
3,622,281
from unittest.mock import patch async def test_setup_component_with_config(hass, config_entry): """Test setup of the netatmo component with dev account.""" fake_post_hits = 0 async def fake_post(*args, **kwargs): """Fake error during requesting backend data.""" nonlocal fake_post_hits ...
fb012643ab460de3c50cbb69ace113933a6ee4f1
3,622,282
def numerical_grad(theta, f, dx=1e-3, order=1): """ return numerical estimate of the local gradient The gradient is computer by using the Taylor expansion approximation over each dimension: f(t + dt) = f(t) + h df/dt(t) + h^2/2 d^2f/dt^2 + ... The first order gives then: df/dt = (f(t +...
bc9686f264acb5cf8a643355e95386b99b8c554b
3,622,283
def putIterationsPerSec(frame, iterations_per_sec): """Add iterations per second text to lower-left corner of a frame.""" cv2.putText(frame, "{:.0f} iterations/sec".format(iterations_per_sec), (10, 450), cv2.FONT_HERSHEY_SIMPLEX, 1.0, ...
56172565ba2fc8c08eb9d13464f8c866caecc4de
3,622,284
def _filter_by_filename(kind, universe, include_files, exclude_files): """ Filters out what tests to run solely by filename. Returns either the set of files from 'universe' that are present in 'include_files', or the set of files from 'universe' that aren't present in 'exclude_files', depending on whic...
af646932ee740e63e630ebd885f4d6b708876f6a
3,622,285
def eqPoints(POINT): """ Get point and make all combinations of ones and zeros by addding numbers in binary """ zera = np.where(POINT == 0)[0] ilepow = 2**zera.size mylist = np.empty((ilepow-1,3)) for n in range(1,ilepow): val = f"{n:b}" jkl = zera.size - len(val) ...
a68ab7cc64f21bf2bd67a0b5918267e6f1873893
3,622,286
def clip(base, color): """Gamut clipping.""" channels = util.no_nan(color.coords()) gamut = color._range fit = [] for i, value in enumerate(channels): a, b = gamut[i] is_bound = isinstance(gamut[i], GamutBound) # Wrap the angle. Not technically out of gamut, but we will cl...
8603da1fbe00747f21284fdb4ce077c819d47825
3,622,287
import os def load(name): """The function 'load(filename)' loads prepared data basing on its 'name' and returns stacked points and the target cluster; this works for 2D data""" script_dir = os.path.dirname(__file__) rel_path = name+".txt" abs_file_path = os.path.join(script_dir, rel_path) data...
f4cc09e98c2586c1d003efc747ad09bf10226ee1
3,622,288
def clustal_omega_alignment(seqrecs, preserve_order=True, **kwargs): """Align sequences using Clustal Omega :param seqrecs: a list or dict of SeqRecord that will be aligned to ref :param preserve_order: if True, reorder aligned seqrecs to match input order. :param **kwargs: additional arguments for ali...
d756f5c9b1a6986f75ff89f89f6ab96a15e8b515
3,622,289
import typing import os import re def guess_track_title(fname: str) -> typing.Tuple[int, str]: """ Get the track number and title from a filename """ basename, _ = os.path.splitext(fname) if match := re.match(r'([0-9]+)([^0-9]*)$', basename): return int(match.group(1)), match.group(2).strip().titl...
7a45243b33239cfc137318e7118f32e8b114a492
3,622,290
def hass_tz_info(hass): """Return timezone info for the hass timezone.""" return dt_util.get_time_zone(hass.config.time_zone)
1cea4a41e283bba104fb125b35ca66d0e1ebf989
3,622,291
def _get_lq_l(m: np.ndarray) -> np.ndarray: """ Calculate L term from LQ decomposition, ensuring the diagonal is non-negative. Parameters ---------- m Matrix to process. Returns the L term in the LQ decomposition, using the convention that all diagonal elements are non-negative. This i...
99cac99cd3ac88c938bc41be1eb271a4e81267ed
3,622,292
def csv_serving_input_fn(): """Build the serving inputs.""" csv_row = tf.placeholder(shape=[None], dtype=tf.string) features = _decode_csv(csv_row) features.pop(constants.LABEL_COLUMN) return tf.estimator.export.ServingInputReceiver(features, {'csv...
dec6901f279ff555322a9fb6cd90f075d6281f3f
3,622,293
def fix_literals(args): """make up argument names for literals in call""" res = args[:] index = 0 for i, el in enumerate(res): if not (identifier(el) or keyword_argument(el)): while f'arg{index}' in res: index += 1 res[i] = f'arg{index}' return res
872f720768331a714abaa88e9b3ac92fe10014c5
3,622,294
def EVLAUVLoadArch(dataroot, Aname, Aclass, Adisk, Aseq, err, \ selConfig=-1, selBand="", selChan=0, selNIF=0, selChBW=-1.0, \ dropZero=True, calInt=0.5, doSwPwr=False, Compress=False, \ logfile = "", check=False, debug = False): """ Read EVLA archive in...
71a4706dbe3b342931e70465f2d75dbbcfc9ddfc
3,622,295
def declarative_base(bind=None, metadata=None, mapper=None, cls=object, name='Base', constructor=_declarative_constructor, metaclass=DeclarativeMeta, engine=None): """Construct a base class for declarative class definitions. The new base class will be given a metaclass...
1f794131e7455ceb76bcb93163e35a3fe86883c9
3,622,296
def detect_encoding(bytesobject): """Read the first chunk of input and return its encoding""" # unicode-test if isutf8(bytesobject): return 'UTF-8' # try one of the installed detectors if cchardet is not None: guess = cchardet.detect(bytesobject) LOGGER.debug('guessed encodin...
e1f14bb8a86d9ae3bd6d8b339c83f065e68203e1
3,622,297
def complete_graph(n): """ returns a complete graph with n vertices """ return wgraph_from_adjacency(np.ones((n, n)))
a9ce64cc77412942b6ce428f32f64fa22831a49f
3,622,298
def get_P_HP_cm_d(q_HP_sum_std_test, q_HP_win_std_test, A_p, B_p, theta_hat_bw_cm_d, theta_ex_Nave_d, theta_star_bw_std, theta_star_ex_sum, P_HP_sum_std_test): """日付dにおける制御モードcmのヒートポンプの消費電力(13) Args: q_HP_sum_std_test(float): 試験時の夏期標準加熱条件におけるヒートポンプの加熱能力 q_HP_win_std_test(float): 試...
498beb875396ec43140aaf0612984fb6520ac08e
3,622,299