content
stringlengths
22
815k
id
int64
0
4.91M
def xy_to_rho(pt1, pt2): """convert two points of line into rho, theta form""" # find inverse of slope of line m, b = xy_to_mb(pt1, pt2) minv = -1 / m if m else None if m == 0 else 0 # find intersection point of line with line defined by rho, theta intersection = line_intersection(m, b, ...
5,312,200
def generate_image(image_parameters): """Generate image with particles. Input: image_parameters: list with the values of the image parameters in a dictionary: image_parameters['Particle Center X List'] image_parameters['Particle Center Y List'] image_parameters['Particle Radius ...
5,312,201
def gaussian_filter(input, sigma, order=0, output=None, mode="reflect", cval=0.0, truncate=4.0): """Multidimensional Gaussian filter. Parameters ---------- %(input)s sigma : scalar or sequence of scalars Standard deviation for Gaussian kernel. The standard deviations of the Gaussian...
5,312,202
def tests_raise_error(): """raise error the right way""" with pytest.raises(escpos.exceptions.Error): raise escpos.exceptions.Error("This should raise an error.")
5,312,203
def run_test(target_call, num_steps, strategy, batch_size=None, log_steps=100, num_steps_per_batch=1, iterator=None): """Run benchmark and return TimeHistory object with stats. Args: target_call: Call to execute for each step. nu...
5,312,204
def remove_punctuation_from_text(data): """ Enriches a dataframe or Anytree structure containing "text" field with "clean text" field See utils.clean_text for more information Returns: [pd.DataFrame or dictionary] -- conversations with new clean text field """ if isinstance(data, pd.DataFrame): ...
5,312,205
def querystring_parse(parameter_data): """Parse dictionary to querystring""" data = parameter_data return urlencode(data).replace("%2F","/")
5,312,206
def _deployment_rollback(deployment_id): """ :param deployment_id: the application id :type deployment_di: str :returns: process return code :rtype: int """ client = marathon.create_client() deployment = client.rollback_deployment(deployment_id) emitter.publish(deployment) retu...
5,312,207
def find_regular_bin_edges_from_centers(centers): """ Finds bin (grid cell) edges from center positions. Assumes a regular grid. Inputs: centers = bin/grid center position vector of current grid, shape [nb] Returns: edges = edge positions of bins (grid), shape [nb+1] """ edges =...
5,312,208
def postordereval(parseTree): """Compute the result inline with postorder""" ops = {'+': op.add, '-': op.sub, '*': op.mul, '/': op.truediv} if parseTree: evalLeft = postordereval(parseTree.getLeftChild()) evalRight = postordereval(parseTree.getRightChild()) if evalLeft and evalRight...
5,312,209
def _remove_old_kernels(_log): """Remove old kernels which could not be removed during update process. It is in general a bad idea to remove a running kernel from 'underneath' a running system. Hence we remove old kernel(s) on the next boot. To make this check reasonably fast, we check for extra kern...
5,312,210
def non_max_suppression(boxes, scores, threshold, max_num): """Performs non-maximum suppression and returns indices of kept boxes. boxes: [N, (z1, y1, x1, z2, y2, x2)]. Notice that (z2, y2, x2) lays outside the box. scores: 1-D array of box scores. threshold: Float. IoU threshold to use for filterin...
5,312,211
def mask2rle(img): """ - https://www.kaggle.com/paulorzp/rle-functions-run-lenght-encode-decode img: numpy array, 1 -> mask, 0 -> background Returns run length as string formated """ pixels= img.T.flatten() pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[...
5,312,212
def raw_data_from_socket(ip_addr, buff, port=9750): """establish socket connection to [tsh] (ip_addr)ess on data port (9750) and show pertinent data""" print_header() previous_count = -1 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((ip_addr, port)) while not b...
5,312,213
def fp(path): """Prepends SEIR_HOME to path and returns full path.""" return os.path.join(SEIR_HOME, path)
5,312,214
def rgb_to_hsv(color: np.ndarray) -> np.ndarray: """ Convert a color from the RGB colorspace to the HSV colorspace >>> rgb_to_hsv(np.array([10, 20, 30], np.uint8)) array([105, 170, 30]) Args: color: Color as numpy array. Can either have shape (X, Y, 3) if it is a whole image, (...
5,312,215
def plot_params(model): """Print parameters """ x0 = 0.05 y0 = 0.95 dy = 0.03 fig = plt.figure(1, figsize=(10, 10)) plt.subplots_adjust(left=0.1, top=0.95, bottom=0.05, right=0.95) ax_lab = fig.add_subplot(111) ax_lab.xaxis.set_visible(False) ax_lab.yaxis.set_visible(False) ...
5,312,216
def class_avg_chainthaw(model, nb_classes, loss_op, train, val, test, batch_size, epoch_size, nb_epochs, checkpoint_weight_path, f1_init_weight_path, patience=5, initial_lr=0.001, next_lr=0.0001, verbose=True): """ Finetunes given model using c...
5,312,217
def quality_scrub(df, target_cols = ['quality_1', 'quality_2', 'quality_3']): """ Definition: Filters a dataframe where each target_col does not contain 'no_cough' Args: df: Required. A dataframe containing the target columns target_cols: default = ['quality_1', 'quality_2', 'quality_3']. Returns: Re...
5,312,218
def create_arrival_timer(model, name, descr = None): """Return a new timer that allows measuring the processing time of transacts.""" y = ArrivalTimerPort(model, name = name, descr = descr) code = 'newArrivalTimer' y.write(code) return y
5,312,219
def ApplyMutation(Mutation, MolName, ChainID, ResName, ResNum, NewResName): """Apply mutatation. """ MiscUtil.PrintInfo("\nApplying mutation %s" % Mutation) # Setup wizard for amino acid mutagenesis... pymol.cmd.wizard("mutagenesis") pymol.cmd.refresh_wizard() # Setup residue to be m...
5,312,220
def get_default_transforms() -> Dict[T.Compose, T.Compose]: """augmentationを取得 Returns: Dict[T.Compose, T.Compose]: 学習用,検証用のaugmentation """ transform = { "train": T.Compose( [ T.RandomHorizontalFlip(), T.RandomVerticalFlip(), ...
5,312,221
def plot_time_across_repetitions(root_path_lst, result_path, dataset='standardized_MNIST_dataset', scenario=1, architecture='FC', epochs=500): """ For ...
5,312,222
def load_solution(path: Path = Path(".")) -> DACPolicy: """ Load Solution. Serves as an entry point for the competition evaluation. Place your code loading your policy here. Parameters ---------- path: Path The path to your submission directory. Returns ------- DACPol...
5,312,223
def simple_shell(args, stdout=False): """ Simple Subprocess Shell Helper Function """ if stdout: rc = subprocess.call(args, shell=False) else: rc = subprocess.call(args, shell=False, stdout=open(os.devnull, "w"), stderr=subprocess.STDOUT) return rc
5,312,224
def print_decorator(fct): """dento dekorator pouzivam, na to aby som dokazal testovat aj vypisy na standardny vystup""" original_fct = fct output = [] def wrapper(*args): output.append((args)) return original_fct(*args) return wrapper
5,312,225
def parse_testresults(xml, test_id, domain): """ Parse the given XML file and build mappings """ global_lookup = {} global_testresults = {} for event, element in etree.iterparse(xml, events=("start", "end")): try: global_id, global_title, global_fixtext = \ build_l...
5,312,226
def _print_benchmark_fuzz_target(benchmarks): """Prints benchmark variables from benchmark.yaml files.""" for benchmark in benchmarks: benchmark_vars = yaml_utils.read( os.path.join(BENCHMARK_DIR, benchmark, 'benchmark.yaml')) print(benchmark + '-fuzz-target=' + benchmark_vars['fuzz_...
5,312,227
def test_sir_vs_penn_chime_no_policies(penn_chime_raw_df_no_policy, sir_data_wo_policy): """Compares local SIR against penn_chime SIR for no social policies """ x, pars = sir_data_wo_policy sir_model = SIRModel() predictions = sir_model.propagate_uncertainties(x, pars) assert_frame_equal( ...
5,312,228
def remodel_matrix(matrix, new_fire_cells, moisture_matrix): """ matrix: Array of the fire spread area new_fire_cells: list of tuples, each tuple representing the x,y coordinates of a new cell that has been affected by the fire spread. """ for cell in new_fire_cells: x = int(cell[0]...
5,312,229
def getOffers(session, city): """ Parameters ---------- session : ikabot.web.session.Session city : dict Returns ------- offers : list[dict] """ html = getMarketHtml(session, city) hits = re.findall(r'short_text80">(.*?) *<br/>\((.*?)\)\s *</td>\s *<td>(\d+)</td>\s *<td>(.*?)/td>\s *<td><img src="skin/resour...
5,312,230
async def start(ws): """Lance le bot sur l'adresse Web Socket donnée.""" global last_sequence # global est nécessaire pour modifier la variable with aiohttp.ClientSession() as session: async with session.ws_connect(f"{ws}?v=5&encoding=json") as ws: async for msg in ws: ...
5,312,231
def add_final_training_ops(class_count, final_tensor_name, bottleneck_tensor): """ 给训练添加一个新的softmax和全连接层, 我们需要重新训练顶层来识别我们的新类,所以这个函数为graph添加了正确的操作 :param class_count: 多类的事物总数 :param final_tensor_name: 生成结果的新的最终节点的名称字符串。 :param bottleneck_tensor: 主CNN图的输出。 :return: The tensors for the training...
5,312,232
def generate_northern_ireland_data(directory, file_date, records): """ generate northern ireland file. """ northern_ireland_data_description = lambda: { # noqa: E731 "UIC": _("random.custom_code", mask="############", digit="#"), "Sample": _("random.custom_code", mask="#&&&", digit="#",...
5,312,233
def view_config_changes(config, num=None): """View checkpoints and associated configuration changes. .. note:: This assumes that the installation is using a Reverter object. :param config: Configuration. :type config: :class:`certbot.interfaces.IConfig` """ rev = reverter.Reverter(config) ...
5,312,234
def put(array, data): """Put the data returned from the PostGIS query into the output array. The returned data is a list of tuples (row, col, value). """ y = tuple(map(lambda x: x[0] - 1, data)) x = tuple(map(lambda x: x[1] - 1, data)) v = tuple(map(lambda x: 0.0 if x[2] < 1 else x[2] / 1000, data)) try: ...
5,312,235
def print_result(l_d, tablefmt="simple", type_=None): """ >>> print_result([Counter({'runtime error': 1, 'test': 1, 'pass rate': '0%'})],type_="no_folder") language category name pass rate(%) test(#) success(#) compilation error(#) runtime error(#) wrong value(#) timeout(#) ...
5,312,236
def create_message(address, subject, message_text, html=True, attachments=None): """Create a message for an email, using the low-level API. Arguments: address (str): Email address(es) of the receiver. subject (str): The subject of the email message. message_text (str): The text of the e...
5,312,237
def whole_appendix(xml, cfr_part, letter): """Attempt to parse an appendix. Used when the entire appendix has been replaced/added or when we can use the section headers to determine our place. If the format isn't what we expect, display a warning.""" xml = deepcopy(xml) hds = xml.xpath('//HD[contain...
5,312,238
def read_image_files(image_files,image_shape=None, crop=None, label_indices=None): """ :param image_files: :param image_shape: :param crop: :param use_nearest_for_last_file: If True, will use nearest neighbor interpolation for the last file. This is used because the last file may be the label...
5,312,239
def wrap_unexpected_exceptions(f, execute_if_error=None): """A decorator that catches all exceptions from the function f and alerts the user about them. Self can be any object with a "logger" attribute and a "ipython_display" attribute. All exceptions are logged as "unexpected" exceptions, and a request is ...
5,312,240
def store_topology(topology_file_string: str, fileformat="pdbx"): """Store a file (containing topology, such as pdbx) in a topology XML block.""" root = etree.fromstring(f'<TopologyFile format="{fileformat}"/>') root.text = topology_file_string return root
5,312,241
def zeros_like(tab): """ Wrapper to numpy.zeros_like, force order to hysop.constants.ORDER """ return np.zeros_like(tab, dtype=tab.dtype, order=ORDER)
5,312,242
def get_bert_embeddings(input_ids, bert_config, input_mask=None, token_type_ids=None, is_training=False, use_one_hot_embeddings=False, scope=None): """Returns embeddings for ...
5,312,243
def blind_deconvolution_multiple_subjects( X, t_r, hrf_rois, hrf_model='scaled_hrf', shared_spatial_maps=False, deactivate_v_learning=False, deactivate_z_learning=False, deactivate_u_learning=False, n_atoms=10, n_times_atom=60, prox_z='tv', lbda_strategy='ratio', lbda=0.1, rho=2.0, delta...
5,312,244
def _TestRemovePhotos(tester, user_cookie, request_dict): """Called by the ServiceTester in order to test remove_photos service API call.""" validator = tester.validator user_id, device_id = tester.GetIdsFromCookie(user_cookie) request_dict = deepcopy(request_dict) user = validator.GetModelObject(User, user_i...
5,312,245
def get_author_book_publisher_data(filepath): """ This function gets the data from the csv file """ with open(filepath) as csvfile: csv_reader = csv.DictReader(csvfile) data = [row for row in csv_reader] return data
5,312,246
async def update_workflow_revision( # pylint: disable=W0622 id: UUID, updated_workflow_dto: WorkflowRevisionFrontendDto, ) -> WorkflowRevisionFrontendDto: """Update or store a transformation revision of type workflow in the data base. If no DB entry with the provided id is found, it will be created...
5,312,247
def tf_repeat(tensor, repeats): """ Args: input: A Tensor. 1-D or higher. repeats: A list. Number of repeat for each dimension, length must be the same as the number of dimensions in input Returns: A Tensor. Has the same type as input. Has the shape of tensor.shape * repeats """ ...
5,312,248
def apply_slim_collections(cost): """ Add the cost with the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``. Args: cost: a scalar tensor Return: a scalar tensor, the cost after applying the collections. """ regulization_losses = set(tf.get_collection(tf.GraphKeys.REGULAR...
5,312,249
def isGoodResult(name, show, log=True, season=-1): """ Use an automatically-created regex to make sure the result actually is the show it claims to be """ all_show_names = allPossibleShowNames(show,season=season) showNames = map(sanitizeSceneName, all_show_names) + all_show_names for curName i...
5,312,250
def get_configuration(configuration_schema, command_line_options=None, environment_variables=None, config_content=None, django_settings=None): """Get configuration from all sources. Notes: * The priority is as follo...
5,312,251
def convert_descriptor_to_type(desc: str) -> Tuple[str, int]: """ Converts a java descriptor to the java type, in the inverse of convert_descriptor_to_type() Returns the type, and the number of array levels (e.g. [[Z would return ('boolean', 2), not 'boolean[][]' Optionally will remap objects using the prov...
5,312,252
def _normalize_similarity(df: pandas.DataFrame) -> None: """Normalizes similarity by combining cls and transformation.""" df["params.similarity"] = (df["params.similarity.cls"] + "_" + df["params.similarity.transformation"]) # transformation only active if similarity in {l1, 2} unused_transformation_ma...
5,312,253
async def test_good_query(hass: HomeAssistant, hass_client_no_auth: Any) -> None: """Test good callbacks.""" await async_setup_component(hass, "http", {"http": {}}) device_registry = await dr.async_get_registry(hass) client = create_mock_motioneye_client() config_entry = await setup_mock_motioneye_...
5,312,254
def density_bounds(density, wi, vo=.49, ve=.5, dt=.1, exact=False): """THIS IS A BOUND, NOT THE ACTUAL VELOCITY. Min density bound for nnovation front as derived from MFT and compared with simulation results. Depends on ob...
5,312,255
def process_instructions(instructions): """Process instructions in order, starting from line 0""" line = 0 instructions_executed = set() accumulator = 0 while line not in instructions_executed: try: instruction = instructions[line] except IndexError: print(f'E...
5,312,256
def check_absence_of_skip_series( movement: int, past_movements: List[int], max_n_skips: int = 2, **kwargs ) -> bool: """ Check that there are no long series of skips. :param movement: melodic interval (in scale degrees) for line continuation :param past_movement...
5,312,257
def try_to_save_error(client, exec_id, state=-1): """ Attempt at saving that the execution failed """ try: client.put_api_for_id("dag/", id=exec_id, payload=dict(state=state)) except Exception as e: print(f"An exception trying to register the failed status: {e}")
5,312,258
def initialize_isotope_model(rmg, isotopes): """ Initialize the RMG object by using the parameter species list as initial species instead of the species from the RMG input file. """ # Read input file rmg.loadInput(rmg.inputFile) # Check input file rmg.checkInput() # Load databases ...
5,312,259
def get_preview_images_by_rootname(rootname): """Return a list of preview images available in the filesystem for the given ``rootname``. Parameters ---------- rootname : str The rootname of interest (e.g. ``jw86600008001_02101_00007_guider2``). Returns ------- preview_images : ...
5,312,260
def get_discharge_measurements(sites=None, start=None, end=None, **kwargs): """ Get discharge measurements from the waterdata service. Parameters (Additional parameters, if supplied, will be used as query parameters) ---------- sites: array of strings If the qwdata parameter site_no is supp...
5,312,261
def get_full_frame_size(body_size): """ Returns size of full frame for provided frame body size :param body_size: frame body size :return: size of full frame """ return eth_common_constants.FRAME_HDR_TOTAL_LEN + \ get_padded_len_16(body_size) + \ eth_common_constants.FRAME...
5,312,262
def paf(print_string): """ Print and file: everything printed to stdout is also written in logfile. """ print(print_string) with open(logfile, "a") as outfile: outfile.write(str(print_string) + "\n")
5,312,263
def is_iterable(obj): """ Returns *True* when an object *obj* is iterable and *False* otherwise. """ try: iter(obj) except Exception: return False return True
5,312,264
def vels2waves(vels, restwav, hdr, usewcs=None, observatory="SPM"): """Heliocentric radial velocity (in km/s) to observed wavelength (in m, or whatever units restwav is in) """ # Heliocentric correction vels = np.array(vels) + helio_topo_from_header( hdr, usewcs=usewcs, observatory=observat...
5,312,265
def make_blueprint(db_connection_string=None, configuration={}): # noqa """Create blueprint. """ controllers = Controllers(configuration=configuration, connection_string=db_connection_string) # Create instance blueprint = Blueprint('pipelines', 'pipelines') @che...
5,312,266
def jsonable(obj: Any): """Convert obj to a JSON-ready container or object. Args: obj ([type]): """ if isinstance(obj, (str, float, int, complex)): return obj elif isinstance(obj, Path): return str(obj.resolve()) elif isinstance(obj, (list, tuple)): return type(o...
5,312,267
def read_data_from(file_: str) -> dict: """Load image tiles from file.""" tiles = {} tile = [] for line in open(file_, "r").read().splitlines(): if "Tile" in line: idx = int(line[5:-1]) elif line == "": tiles[idx] = np.array(tile) tile = [] els...
5,312,268
def create_graph(A, create_using=None, remove_self_loops=True): """ Function for flexibly creating a networkx graph from a numpy array. Params ------ A (np.ndarray): A numpy array. create_using (nx.Graph or None): Create the graph using a specific networkx graph. Can be used for forcing an ...
5,312,269
def test_README_as_PyPi_landing_page(monkeypatch): """Not executing `setup.py build-sphinx` to control log/stderr visibility with pytest""" long_desc = subprocess.check_output( "python setup.py --long-description".split(), cwd=proj_path ) assert long_desc is not None, "Long_desc is null!" e...
5,312,270
def delete(*tables): """ Returns :py:class:`~.Delete` instance and passed arguments are used for list of tables from which really data should be deleted. But probably you want to use :py:func:`~.delete_from` instead. """ return Delete(*tables)
5,312,271
def create_string_for_failing_metrics(hpo_objects): """ Function is used to create a string for the failing metrics that can ultimately be inserted into the email output. Parameters ---------- hpo_objects (list): contains all of the HPO objects. the DataQualityMetric objects will now be ...
5,312,272
def _main(argv, standard_out, standard_error, standard_in): """Run internal main entry point.""" import argparse flargs = {} if "--config" in argv: flargs = find_config_file(argv) parser = argparse.ArgumentParser(description=__doc__, prog='docformatter') changes = parser.add_mutually_e...
5,312,273
def current_effective_deadline() -> Coroutine[Any, Any, float]: """ Return the nearest deadline among all the cancel scopes effective for the current task. :return: a clock value from the event loop's internal clock (``float('inf')`` if there is no deadline in effect) :rtype: float """ ...
5,312,274
def from_openid_response(openid_response): """ return openid object from response """ issued = int(time.time()) sreg_resp = sreg.SRegResponse.fromSuccessResponse(openid_response) \ or [] ax_resp = ax.FetchResponse.fromSuccessResponse(openid_response) ax_args = {} if ax_resp is not No...
5,312,275
def dcos_login_pw_option(command: Callable[..., None]) -> Callable[..., None]: """ A decorator for choosing the password to set the ``DCOS_LOGIN_PW`` environment variable to. """ function = click.option( '--dcos-login-pw', type=str, default=DEFAULT_SUPERUSER_PASSWORD, ...
5,312,276
def validate_package_deployments(package_data: Dict[str, Any]) -> None: """ Validate that a package's deployments contracts reference existing contract_types. """ if set(("contract_types", "deployments")).issubset(package_data): all_contract_types = list(package_data["contract_types"].keys()) ...
5,312,277
def get_default_triggers() -> Dict[Tuple[Tuple[str, Any]], Dict[str, Any]]: """Make _triggers read only""" return _default_triggers
5,312,278
def yesno_choice(title, callback_yes=None, callback_no=None): """ Display a choice to the user. The corresponding callback will be called in case of affermative or negative answers. :param title: text to display (e.g.: 'Do you want to go to Copenaghen?' ) :param callback_yes: callback function to be...
5,312,279
def is_tensor_object(x): """ Test whether or not `x` is a tensor object. :class:`tf.Tensor`, :class:`tf.Variable` and :class:`TensorWrapper` are considered to be tensor objects. Args: x: The object to be tested. Returns: bool: A boolean indicating whether `x` is a tensor objec...
5,312,280
def slack(text: str, webhookAddress: str) -> str: """Send a slack message""" data = bytes(json.dumps({"text": text}), "utf-8") handler = urlopen(webhookAddress, data) return handler.read().decode('utf-8')
5,312,281
def wrap_col(string, str_length=11): """ String wrap """ if [x for x in string.split(' ') if len(x) > 25]: parts = [string[i:i + str_length].strip() for i in range(0, len(string), str_length)] return ('\n'.join(parts) + '\n') else: return (string)
5,312,282
def tokenize_text_with_special(text): """ Tokenizes a string. Does not filter any characters. :param text: The String to be tokenized. :return: Tokens """ token = [] running_word = "" for c in text: if re.match(alphanumeric, c): running_word += c else: ...
5,312,283
def rms_slope_from_profile(topography, short_wavelength_cutoff=None, window=None, direction=None): """ Compute the root mean square amplitude of the height derivative of a topography or line scan stored on a uniform grid. If the topography is two dimensional (i.e. a topography...
5,312,284
def _get_exec_driver(): """ Get the method to be used in shell commands """ contextkey = "docker.exec_driver" if contextkey not in __context__: from_config = __salt__["config.option"](contextkey, None) # This if block can be removed once we make docker-exec a default # option...
5,312,285
def combine_results_jsons(drtdp_json, psrtdp_json, vi_json): """ takes overall results jsons and combines them to one json :param drtdp_json a json for drtdp overall results :param psrtdp_json a json for ps-rtdp overall results :param vi_json a json for value iteration overall results :return co...
5,312,286
def preprocess_data(data_path, embeds_path, lang='fr'): """ Loads pre-embedded dataset and labels, in a random (but consistent) order. :param data_path: (str) filepath to csv :param embeds_path: (str) filepath to json :return: X (list of list of list), y (len(train) x 2) np array """ ...
5,312,287
def test_removing_value_with_priority_removes_from_queue(filled_queue): """Test that removing from the queue with a priority works.""" filled_queue.remove('d', 1) assert filled_queue.priority('d') is None
5,312,288
def text_comp19_to_df(): """ Returns a pandas Dataframe object with the data of the TextComplexityDE19 dataset """ # Path to relevant csv file csv_path = join( dirname(dirname(dirname(abspath(__file__)))), "data", "TextComplexityDE19/ratings.csv", ) # read in c...
5,312,289
def test_so2(): """ Checks that answer at https://stackoverflow.com/a/58383062/7262247 is ok """ from pyfields import field class Position(object): x = field(validators=lambda x: x > 0) y = field(validators={'y should be between 0 and 100': lambda y: y > 0 and y < 100}) p = Position()...
5,312,290
async def test_5e850i(hass): """Test creation of 5E850I sensors.""" config_entry = await async_init_integration(hass, "5E850I") registry = er.async_get(hass) entry = registry.async_get("sensor.ups1_battery_charge") assert entry assert entry.unique_id == f"{config_entry.entry_id}_battery.charge"...
5,312,291
def from_relay(func: relay.Function) -> IRModule: """Convert a Relay function into a Relax program. Parameters ---------- func : relay.Function Relay function to be converted Returns ------- mod : tvm.IRModule The Relax IRModule for compilation """ # A map to store ...
5,312,292
def get_list_of_all_data_file_names(datadirectory): """ Return list of all data files (.txt) in specified directory """ print('get_list_of_all_data_file_names', datadirectory) list_of_files = [] for file in os.listdir(datadirectory): if file.endswith('txt'): list_of_files.app...
5,312,293
def _validate_string(input, param_name): """Assert input is a non-empty string.""" assert input and isinstance(input, str), "Invalid input {} for {}".format( input, param_name )
5,312,294
def function_profiler(naming='qualname'): """ decorator that uses FunctionLogger as a context manager to log information about this call of the function. """ def layer(function): def wrapper(*args, **kwargs): with FunctionLogger(function, naming): return function(...
5,312,295
def mock_data_manager(components): """Return a mock data manager of a general model.""" dm = Mock() dm.components = components dm.fixed_components = [] return dm
5,312,296
def testcase_caplog(request, caplog): """Adds the `caplog` fixture to TestCase-style test classes. This fixture should only be used on cros_test_lib.TestCase test classes, since it doesn't yield anything and just attaches the built-in pytest `caplog` fixture to the requesting class. Tests written as standalone...
5,312,297
def load_data_fashion_mnist(batch_size, resize=None): #@save """下载Fashion-MNIST数据集,然后将其加载到内存中""" trans = [transforms.ToTensor()] if resize: trans.insert(0, transforms.Resize(resize)) trans = transforms.Compose(trans) mnist_train = paddle.vision.datasets.FashionMNIST(mode="train", transform=...
5,312,298
def moeda(n=0): """ -> Formata um número como moeda :param n: número :return: número formatado """ return f'R$ {n:.2f}'
5,312,299