content
stringlengths
22
815k
id
int64
0
4.91M
def pre_network_init(config_file): """Perform a partial initialization, with no network.""" settings.load_properties(config_file)
51,900
def make_grayscale(img: np.ndarray) -> np.ndarray: """Turns BGR image into grayscale.""" if len(img.shape) == 3 and img.shape[2] == 3: return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: return img
51,901
def GetKM3NeTOMGelAbsorptionLength(): """ A function to return the absorption length the gel of an KM3NeT OM Note: The file hit-ini_optic.f has three different datasets for this absorption length! However in the file hit.f it always is initialized with the same (gel_id=1). Thus this one is ...
51,902
def align_frontiers_on_bars(frontiers, bars): """ Aligns the frontiers of segments to the closest bars (in time). The idea is that frontiers generally occurs on downbeats, and that realigning the estimation could improve perfomance for low tolerances scores. Generally used for comparison with techni...
51,903
def sudo_command(cmd, user=None, password=None, extraopts=None): """Run a command with sudo and return the output, a tuple of (stdout, stderr). """ proc = sudo(cmd, user=user, password=password, extraopts=extraopts) return process.run_process(proc)
51,904
def DPO(df, col_name, intervals): """ Detrended Price Oscillator DPO is positive when price is above displaced moving average. DPO is negative when price is below displaced moving average. Reference: https://school.stockcharts.com/doku.php?id=technical_indicators:detrended_price_osci...
51,905
def FK42FK5Matrix(t=None): """ ---------------------------------------------------------------------- Purpose: Create a matrix to precess from B1950 in FK4 to J2000 in FK5 following to Murray's (1989) procedure. Input: t, a Besselian epoch as epoch of observation. Returns: Transformation matrix M...
51,906
def _rec_superdense(packet): """ Receives a superdense qubit and decodes it. Args: packet (Packet): The packet in which to receive. Returns: dict: A dictionary consisting of decoded superdense message and sequence number """ receiver = packet.receiver sender = packet.sender ...
51,907
def count_ubelt_usage(): """ import sys, ubelt sys.path.append(ubelt.expandpath('~/code/ubelt/dev')) from gen_api_for_docs import * # NOQA """ from count_usage_freq import count_ubelt_usage usage = count_ubelt_usage() # Reorgnaize data to contain more information rows = [] unse...
51,908
def menu_install(): """ Installing menu into Hiero """ from . import ( publish, launch_workfiles_app, reload_config, apply_colorspace_project, apply_colorspace_clips ) # here is the best place to add menu from avalon.tools import creator, sceneinventory from openpype.too...
51,909
async def test_return_true_with_awaited_future_result_container(): # noqa: E501,WPS118 """Ensures `is_io` function will return False for FutureResult.""" assert is_io(await FutureResult.from_failure('failure')) is True
51,910
def _high_bit(value): """returns index of highest bit, or -1 if value is zero or negative""" return value.bit_length() - 1
51,911
def parse_round(bsoup, rnd, gid, airdate): """Parses and inserts the list of clues from a whole round.""" round_id = "jeopardy_round" if rnd == 1 else "double_jeopardy_round" r = bsoup.find(id=round_id) # The game may not have all the rounds if not r: return False # The list of categorie...
51,912
def on_end_validation(func): """ The :func:`on_end_validation` decorator is used to initialise a :class:`.Callback` with :meth:`~.Callback.on_end_validation` calling the decorated function Example: :: >>> import torchbearer >>> from torchbearer import Trial >>> from torchbearer.cal...
51,913
def transpose_checker( attrs: Any, args: List[relay.expr.Expr], op_name: str ) -> bool: # pylint: disable=unused-variable """Check if transpose is supported by TensorRT.""" if get_tensorrt_use_implicit_batch_mode() and int(attrs.axes[0]) != 0: logger.info(f"{op_name}: can't modify batch dimension."...
51,914
def project_root() -> Path: """Returns project root folder.""" return Path(__file__).parent
51,915
def qual(obj): """ Return fully qualified name of a class. """ return u'{}.{}'.format(obj.__class__.__module__, obj.__class__.__name__)
51,916
def treefactorial(high: int, low: int=None) -> int: """Pure Python factorial, no imports by Daniel Fischer @stackoverflow.com Daniel Fischer says algorithm is old. """ if high < 2: return 1 if low is None: return treefactorial(high, 1) if low + 1 < high: mid: int...
51,917
def parse_args(): """ Parses command line :return: Dictionary with different options """ global LOGGER # pylint: disable=global-statement values = {} values['input_paths'] = [] values['recurse'] = False values['show_hashes'] = False values['check_updated'] = False values['d...
51,918
def find(file_filter=None, output=None): """ finds files """ # find base directory path = os.getcwd() directories = [] for root, _, files in os.walk(path): # filter out hidden files and files that dont end in the extension for file in files: if extract_extension(file, f...
51,919
def squarish_factors(x): """Returns the closest pair of factors of x. Parameters ---------- x : int Examples -------- >>> squarish_factors(20) (5, 4) >>> squarish_factors(36) (6, 6) >>> squarish_factors(53) (53, 1) >>> squarish_factors(0) (0, 0) """ ...
51,920
def get_evidence(row: pd.Series) -> Evidence: """Return evidence for a Statement. Parameters ---------- row : Currently investigated row of the dataframe. Returns ------- : Evidence object with the source_api, the PMID and the original sentence. """ pmid = s...
51,921
def bulk_add_restaurants(places_names, client): """ Call Google API to get places information. """ for i, name in enumerate(places_names): if not i % 10: print(f'{i} places processed') res = client.search_add_restaurant(name) if res["message"] == "Success": ...
51,922
def create_and_save_nifti(mat, path_target): """ Creates a nifti image from numpy array and saves it to given path. :param mat: Numpy array. :param path_target: String, path where to store the created nifti. """ new_nifti = nib.Nifti1Image(mat, np.eye(4)) # create new nifti from matrix nib.save(new_nifti, path_...
51,923
def _add_new_sheet(spreadsheet_id, title): """ Add new sheet to spreadsheet Return: False - Failed to add sheet True - Add sheet success """ global service # Todo: Format sheet column when new sheet is created # Column A: Type DATE # Column C: Type STRING # Request define ...
51,924
def config_bgp(dut, **kwargs): """ config_bgp(dut = DUT1, router_id = '9.9.9.9', local_as='100', neighbor ='192.168.3.2', remote_as='200', config = 'yes', config_type_list =["neighbor"]) config_bgp(dut = DUT1, local_as='100', remote_as='200', neighbor ='2001::2', config = 'yes', config_type_list =["neighbor"] ...
51,925
def get_single_notification(session, notification_id): """Helper method to extract a single notification from notification table.""" return session.execute(text("""SELECT * FROM public.notification WHERE id='{0}'""".format(notification_id)))...
51,926
def test_wps_ext_proto_ack_m3_no_e_nonce(dev, apdev): """WPS and ACK M3 missing E-Nonce""" eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev) logger.debug("Send NACK to STA") msg, attrs = build_ack(eap_id, None, r_nonce) send_wsc_msg(dev[0], bssid, msg) dev[0].request("WPS_CANCEL") de...
51,927
def register(): """Registration form handler.""" def fail_validate(msg): flask.flash(msg, 'danger') return flask.redirect(flask.url_for('home')) username = request.form.get('username', '') if not re.match(r'[A-Za-z0-9_]+$', username): return fail_validate('Invalid username.') if models.User.query...
51,928
def default_reply(event, message): """Default function called to reply to bot commands.""" return event.unotice(message)
51,929
def itinerate_temp_file(file_name,temp_dict): """ Extract from file_name a section defined by i into temp.txt""" with open(file_name) as fp: temp_file = open("temp.txt", "w") for num, line in enumerate(fp): # Is not the last one if i[0] != sorted(temp_dict)[-1]: ...
51,930
async def list_products(): """API for listing all the products.""" return await paginate(ProductGinoModel.query)
51,931
def shortest_path_between_atoms(gra, key1, key2): """ shortest path between a pair of atoms """ return shortest_path_between_groups(gra, [key1], [key2])
51,932
def register_parameters(node: Node): """ Register all parameters. This should be called after module initialization. :param node: The gameplay node """ global param_node, parameters assert param_node is None for param_name in parameters: value, param_type, description = parameters...
51,933
def test_predictOutageProba_bg(): """Test probability outputs of the model""" # Bagging zeroPredict = predictOutageProba(weather0,'bg') assert math.isclose(0.9, zeroPredict[0,0], rel_tol=1e-05) assert math.isclose(0.1, zeroPredict[0,1], rel_tol=1e-05) assert math.isclose(0, zeroPredict[0,2],...
51,934
def help(update, context): """ 'help' provides information about the use of the bot :param update: bot update :param context: CallbackContext :return: None """ msg = "*Very short guide*.\n\n" #1)upload a file with the netlist (don't know what a netlist is? Run `/tutorial` in the bot)\n2) en...
51,935
def _safe_divide(num, denom, replace=0): """Safe division when elements in the denominator might be zeros. Returns the division of the numerator by the denominator, but replaces results which have a zero in the denominator by a specified value. The default is to replace bad divisions with zeros. ""...
51,936
def making_change(amt: int, coins: list) -> int: """Iterative implementation of the making change algorithm. :param amt (int) : Amount, in cents, to be made into change. :param coins (list) : List of coin denominations :return (int) : Number of different combinations of change. """ # calc[i...
51,937
def pdf_to_text(pdf): """Return extracted text from PDF. Warning: This function can be slow... up to 300ms per page This function does not perform optical character recognition. Args: pdf: bytestring of PDF file Returns: str of text extracted from `pdf` contents. """ # make input and output buff...
51,938
def pendulum_sunny(p): """sunny constraint for gravity Pendulum""" return np.abs(p[:, 1])<0.5
51,939
def PGetSkyModel (inUVSelfCal): """ Return the member sky model returns ImageMosaic inUVSelfCal = Python UVSelfCal object """ ################################################################ # Checks if not PIsA(inUVSelfCal): raise TypeError("inUVSelfCal MUST be a Python Obit UVSe...
51,940
def CGaussFilter_DImage_getGaussianFuncValue(dX, dY, dSigma): """CGaussFilter_DImage_getGaussianFuncValue(dX, dY, dSigma) -> double""" return _ImageFilters.CGaussFilter_DImage_getGaussianFuncValue(dX, dY, dSigma)
51,941
def get_credstash_config(key): """Retrieves a single secret from AWS via credstash, assumes the string returned is a list of newline-separated export statements export FOO='some-hush-hush-info-here' export BAR='some-other-secret-here' and parses these lines into a configuration dictionary. Ar...
51,942
def test_tegraplugin_collect_stats(tegrastats_mock): """ TegrastatsCollector's 'collect_stats' method returns an Iterator over WrappedMetrics. GIVEN: There is a valid Tegrastats utility. WHEN: TegrastatsCollector's 'collect_stats' method is called. THEN: It returns an Iterator over WrappedMetri...
51,943
def aggregate_stats(stats: List[deephol_stat_pb2.ProofStat] ) -> deephol_stat_pb2.ProofAggregateStat: """Merge a list of proof log statistics. Args: stats: List of individual proof log statistics. Returns: Aggregated proof statistics. """ result = deephol_stat_pb2.ProofAggregate...
51,944
def align_beam(A, B, C, D, _beam, _r, _s): """ """ #if abs(_r) > abs(_s): _normalized = _r.normalized() _L1 = A.distance(C) _L2 = A.distance(D) # swap nodes? if _L1 > _L2: _L1 = A.distance(D) _L2 = A.distance(C) coord = [0, 0, 0] for x in range(3): co...
51,945
def logged(message=None): """Logs the invoked function name and arguments.""" # TODO: Options - prevent sub @logged to output anything # TODO: Message - allow to specify a message # TODO: Category - read/write/exec as well as mode # [2013-10-28T10:18:32] user@host [sudo|user] [R/W] cuinine.function(xx,xxx,xx) [tim...
51,946
def get_requires_for_build_wheel( config_settings: Optional[Mapping[str, Any]] = None ) -> List[str]: """ Returns an additional list of requirements for building, as PEP508 strings, above and beyond those specified in the pyproject.toml file. When C-extension build is needed, setuptools should be r...
51,947
def fisher(high_vals: pd.Series, low_vals: pd.Series, length: int = 14) -> pd.DataFrame: """Fisher Transform Parameters ---------- high_vals: pd.Series High values low_vals: pd.Series Low values length: int Length for indicator window Returns ---------- df_ta...
51,948
def is_extension_supported(request, extension_alias): """Check if a specified extension is supported. :param request: django request object :param extension_alias: neutron extension alias """ extensions = list_extensions(request) for extension in extensions: if extension['alias'] == ext...
51,949
def _linear_wcs_fit(params, lon, lat, x, y, w_obj): # pragma: no cover """ Objective function for fitting linear terms. Parameters ---------- params : array 6 element array. First 4 elements are PC matrix, last 2 are CRPIX. lon, lat: array Sky coordinates. x, y: array ...
51,950
def resample(feature_index, labels, balance='auto'): """use oversampling to balance class, after split of training set.""" from imblearn.over_sampling import RandomOverSampler ros = RandomOverSampler(ratio=balance) feature_index = np.array(feature_index).reshape(-1, 1) resampled_index, _ = ros.fit...
51,951
def dal_resolver(ctx, request_path): """ This function resolves a dal method call to its underlying service """ service_or_method = None for (path, service_or_method) in resolve(ctx, request_path): if not ( service_or_method and isinstance(service_or_method, (Callable, Servic...
51,952
def parse_csv(csv, out, bench, bench_out): """Inspect a CSV file to figure out about the dialect, comment and header lines and the overall structure.""" click.echo("Input CSV {}".format(csv)) table = anycsv.reader(csv) if out: if out.endswith(".gz"): fout = gzip.open(out, 'wt', new...
51,953
def guess_key_size(ciphertext, max_key_size=40): """Given sentence xored with short key, guess key size From: http://trustedsignal.blogspot.com/2015/06/xord-play-normalized-hamming-distance.html Args: ciphertext(string) max_key_size(int) Returns: list: sorted list of tuples (...
51,954
def AddWorkerpoolCreateArgs(parser): """Set up all the argparse flags for creating a workerpool. Args: parser: An argparse.ArgumentParser-like object. Returns: The parser argument with workerpool flags added in. """ return AddWorkerpoolArgs(parser, update=False)
51,955
def table_dispatch(kind, table, body): """Call body with table[kind] if it exists. Raise an error otherwise.""" if kind in table: return body(table[kind]) else: raise BaseException, "don't know how to handle a histogram of kind %s" % kind
51,956
def compute_dot_sim_matrix(node_features): """Compute edge scores with dot product.""" sim = tf.matmul(node_features, tf.transpose(node_features, perm=[1, 0])) return sim
51,957
def main(): """Test module functions.""" os.system("clear") print("\n\n--- EEG microstate analysis ---\n\n") parser = argparse.ArgumentParser(description='EEG microstate analysis') parser.add_argument('-i','--input', help='.edf file name', required=False) parser.add_argument('-f','--filelist', ...
51,958
def load_param_file(filename): """ Loads a saved parameter dictionary from filename. """ return pickle.load(open(filename))
51,959
def get_data_definitions(report_schedule_id, startDate, endDate): """ Takes a report schedule id and returns a dictionary/json of the necessary data definitions to be used by the transformation layer. """ # Setup the dictionary/json object d = dict() d["Meta"] = dict() d["ReportInfo...
51,960
def strip_block_comments(text: str) -> str: """ Remove any block-style comments from a text. """ return strip_comments(text, [(COMMENT_BLOCK_PATTERN, None)])
51,961
def optim_solver(grad, diff, radius, device, gamma=2): """ Solver for the optimization problem presented in Proposition 1 in https://arxiv.org/abs/2002.12718 """ lamda, mhlnbs_dis = compute_mahalanobis_distance(grad, diff, radius, device, gamma) lamda_lower_limit = range_lamda_lower(grad).detach...
51,962
def download_daily_bars(instrument, year, csvFile): """Download daily bars from Tushare Library for a given year. :param instrument: Instrument identifier. :type instrument: string. :param year: The year. :type year: int. :param csvFile: The path to the CSV file to write. :type csvFile: str...
51,963
def send_sms(domain, contact, phone_number, text, metadata=None, logged_subevent=None): """ Sends an outbound SMS. Returns false if it fails. """ if phone_number is None: return False if isinstance(phone_number, int): phone_number = str(phone_number) phone_number = clean_phone_nu...
51,964
def u_diff(Exact, U_pred, x, t, nu, beta, rho, seed, layers, N_f, L, source, lr, u0_str, system, path, relative_error = False): """Visualize abs(u_pred - u_exact).""" fig = plt.figure(figsize=(9, 5)) ax = fig.add_subplot(111) if relative_error: h = ax.imshow(np.abs(Exact.T - U_pred.T)/np.abs(E...
51,965
def com_google_fonts_check_metadata_match_fullname_postscript(font_metadata): """METADATA.pb font.full_name and font.post_script_name fields have equivalent values ? """ import re regex = re.compile(r"\W") post_script_name = regex.sub("", font_metadata.post_script_name) fullname = regex.s...
51,966
def test_loading_ruledef_only_once(get_ruleset): """ Check if ruledefs are loaded only once """ get_ruleset.return_value = ['ru:test', 'tst-ruledef:test', 'ru:test1', 'ru:test2'] with patch('richtypo.Richtypo.build_rule_chain'): # dont actualy build rule chain with patch('richtypo.Richtypo...
51,967
def Seq(sequence, annotations=None, block_length=10, blocks_per_line=6, style=DEFAULT_STYLE): """ Pretty-printed sequence object that's displayed nicely in the IPython Notebook. :arg style: Custom CSS as a `format string`, where a selector for the top-level ``<pre>`` element is substitu...
51,968
def boundary_condition(): """ Factory associated with DirichletBC. """ return DirichletBC()
51,969
def rm_scripts(scripts): """Remove files from scripts directory.""" for filename in scripts: os.remove(os.path.join(PROJECT_DIRECTORY, 'scripts', filename))
51,970
def upgrade_available(): """ Detect if a new kernel version is available in the repositories. Returns True if a new kernel is available, False otherwise. CLI Example: .. code-block:: bash salt '*' kernelpkg.upgrade_available """ return _LooseVersion(latest_available()) > _LooseVer...
51,971
def get_testcases(problem): """ Gets testcases for problem, which are then displayed if user is Apprentice. :param problem: id of problem :return: array of testcases """ testcases_dir = os.path.join(os.popen('echo $CG_FILES_TESTCASES').read().strip(), problem) testcases_dir_sol = os...
51,972
def ss_error(observed_values, estimated_values): """Sum of squared error function.""" sse = np.sum((observed_values - estimated_values) ** 2) return sse
51,973
def _generate_gherkin_feature_files( gherkin_templates: list, properties_list: list[dict] ) -> list[TemplateOutputFile]: """ Compile templates with variable properties information. Args: gherkin_templates: templates to generate against. (Should only be one template) properties_list: a l...
51,974
def run(): """ 启动机器人 """ # @机器人后推送被动消息 qqbot_handler = qqbot.Handler( qqbot.HandlerType.AT_MESSAGE_EVENT_HANDLER, _message_handler ) # 私信消息 qqbot_direct_handler = qqbot.Handler( qqbot.HandlerType.DIRECT_MESSAGE_EVENT_HANDLER, _message_handler ) qqbot.async_lis...
51,975
def sync_configs(units: tuple[str, ...], shared: bool, specific: bool) -> None: """ Deploys the shared config.ini and worker specific config.inis to the workers. If neither `--shared` not `--specific` are specified, both are set to true. """ import paramiko logger = create_logger( "syn...
51,976
def _get_base64(data: str) -> str: """Base 64 encodes data.""" ebytes = base64.b64encode(data.encode("utf-8")) estring = str(ebytes, "utf-8") return estring
51,977
def parse_datetime(value): """Parses a string(ISO_8601) and return a datetime.datetime base UTC, or parse datetime.datetime base other timezone and return a datetime.datetime base UTC timezone """ if isinstance(value, datetime.datetime): if not value.tzinfo: value = value.repla...
51,978
def _dev_http_archive_impl(ctx): """Implementation of the http_archive rule.""" if not ctx.attr.url and not ctx.attr.urls: fail("At least one of url and urls must be provided") if ctx.attr.build_file and ctx.attr.build_file_content: fail("Only one of build_file and build_file_content can be ...
51,979
def setup_auth(key, val, section, pjsip, nmapped): """ Sets up authentication information for a specific endpoint based on the 'secret' setting on a peer in sip.conf """ set_value('username', section, section, pjsip, nmapped, 'auth') # In chan_sip, if a secret and an md5secret are both specified...
51,980
def setSortGroups(sortGroups=None): """ Return the sorting groups, either user defined or from the default list """ if sortGroups is None: # Default groups return [('-inf', '+inf'), ('-inf', 100), (101, '+inf')] else: sortGroups.insert(0, ('-inf', '+inf')) return sortGr...
51,981
def putenv(key, value): """putenv(key, value) Change or add an environment variable. """ environ[key] = value
51,982
def attach_clipped_regions_to_surface(surface, clipped, center): """Check the connectivty of a clipped surface, and attach all sections which are not closest to the center of the clipping plane. Args: surface (vtkPolyData): clipped (vtkPolyData): The clipped segments of the surface. ...
51,983
def ubuntu_spec(**kwargs): """Ubuntu specs.""" # Setup vars from kwargs builder = kwargs['data']['builder'] builder_spec = kwargs['data']['builder_spec'] distro = kwargs['data']['distro'] version = kwargs['data']['version'] bootstrap_cfg = 'preseed.cfg' # https://github.com/mrlesmithj...
51,984
def ds_as_cds(dataset): """ Converts Vega dataset into Bokeh ColumnDataSource data """ if len(dataset) == 0: return {} data = {k: [] for k, v in dataset[0].items()} for item in dataset: for k, v in item.items(): data[k].append(v) data = {k: np.asarray(v) for k, v ...
51,985
def displayFeetTrajFromResult(gui, sceneName, res, Robot): """ Display all effector trajectories stored in a mlp.utils.wholebody_result.Result struct :param gui: a gepetto.corbaserver.GraphicalInterface instance :param sceneName: the node group used to add the new graphical objects :param res: a mlp...
51,986
def genPubKey(privkey): """ 生成公钥 """ bio=BIO.MemoryBuffer(privkey) key=EVP.load_key_bio(bio, util.no_passphrase_callback) return key.get_rsa().as_pem()
51,987
def test_Image_from_landsat_c1_sr_image(): """Test instantiating the class from a Landsat ee.Image""" image_id = 'LANDSAT/LC08/C01/T1_SR/LC08_044033_20170716' output = utils.getinfo(model.Image.from_landsat_c1_sr(ee.Image(image_id)).ndvi) assert output['properties']['system:index'] == image_id.split('/'...
51,988
def CI_calc(mean, SE, CV=1.96): """ Calculate confidence interval. :param mean: mean of data :type mean: float :param SE: standard error of data :type SE: float :param CV: critical value :type CV:float :return: confidence interval as tuple """ try: CI_down = mean - C...
51,989
def bivecvec_invariants(q): """Calculates rotation-invariant attributes of a (vector, trivector) quantity. Returns a 2D output: the norm of the vector and the trivector. """ result = [custom_norm(q[..., :3]), q[..., 3:4]] return tf.concat(result, axis=-1)
51,990
def run(cmd): """Run a command on the command line.""" proc = subprocess.Popen(['sh', '-c', cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, stderr = proc.communicate() return proc.returncode, stdout, std...
51,991
def resolve_margins(margins: Optional[Sequence[float]]) -> Tuple4f: """ Returns the box margins in CSS like order: top, right, bottom, left. """ if margins is None: return 0, 0, 0, 0 count = len(margins) if count == 4: # CSS: top, right, bottom, left return margins[0], margins[1], m...
51,992
async def channel_archive(event, slack): """ Use the channel archive event to delete the channel from the ChannelManager """ await slack.channels.get(event['channel'], fetch=True)
51,993
def check_cookie_auth(api_key, required_scopes): """ Although OpenAPI explicitly supports JWT - we don't enforce this - simply use it as a quick way to mock the behaviour of a more advanced system :param api_key: :param required_scopes: :return: the decoded security token """ try: ...
51,994
def on_event(stats, start_screen, high_score_screen, ship): """Handles user input.""" for event in pygame.event.get(): if event.type == KEYDOWN and stats.game_active: on_key_down(event, ship) elif event.type == KEYUP and stats.game_active: on_key_up(event, ship) e...
51,995
async def validate_input( hass: core.HomeAssistant, data: dict[str, Any] ) -> dict[str, Any]: """Validate the user input allows us to connect.""" session = async_get_clientsession(hass, verify_ssl=data[CONF_VERIFY_SSL]) protocol = "https" if data[CONF_SSL] else "http" url = f"{protocol}://{data[CON...
51,996
def resize_cube(cube, shape): """Return resized cube with the define shape""" zoom = [float(x) / y for x, y in zip(shape, cube.shape)] resized = sp.ndimage.zoom(cube, zoom) assert resized.shape == shape return resized
51,997
def load_image_from_cifar(image_id): """This is to load the image from CIFAR numpy and pre-process. :param image_id: An integer as the image id to load from CIFAR. :return img: A PyTorch Tensor. """ image = CIFAR[image_id] image = image / 255.0 # Normalize image = torch.from_numpy(image) ...
51,998
def valueToCharacter(value): """ Returns the respective character for a value. Returns 'highest' character if no match is found Args: value ([int]): Value that should be mapped to a character Returns: [char]: Respective character for the given value """ for bar_threshold in BA...
51,999