content
stringlengths
22
815k
id
int64
0
4.91M
def NDVI(R, NIR): """ Compute the NDVI INPUT : R (np.array) -> the Red band images as a numpy array of float NIR (np.array) -> the Near Infrared images as a numpy array of float OUTPUT : NDVI (np.array) -> the NDVI """ NDVI = (NIR - R) / (NIR + R + 1e-12) return NDVI
5,350,000
def get_nearby_stations_by_number( latitude: float, longitude: float, num_stations_nearby: int, parameter: Union[Parameter, str], time_resolution: Union[TimeResolution, str], period_type: Union[PeriodType, str], minimal_available_date: Optional[Union[datetime, str]] = None, maximal_avail...
5,350,001
def test_new_hero(new_hero): """ GIVEN a Hero model WHEN a new Hero is created THEN check name, hash_password, group_id, health, permissions, is_participant """ assert new_hero.name == 'test_user' assert new_hero.password_hash != 'password' assert new_hero.check_password('password') ...
5,350,002
def get_state(tau, i=None, h=None, delta=None, state_0=None, a_matrix=None): """ Compute the magnetization state. r(τ) = e^(Aτ)r(0) eq (11) at[1] """ if a_matrix is not None: # get state from a known A matrix # A matrix can be shared and it takes time to build return np.matm...
5,350,003
def get_version(): """Returns version number, without module import (which can lead to ImportError if some dependencies are unavailable before install.""" contents = read_file(os.path.join('webscaff', '__init__.py')) version = re.search('VERSION = \(([^)]+)\)', contents) version = version.group(1).r...
5,350,004
def convert_latlon_arr(in_lat, in_lon, height, dtime, code="G2A"): """Converts between geomagnetic coordinates and AACGM coordinates. Parameters ------------ in_lat : (np.ndarray or list or float) Input latitude in degrees N (code specifies type of latitude) in_lon : (np.ndarray or list or ...
5,350,005
def get_entsoe_renewable_data(file=None, version=None): """ Load the default file for re time series or a specific file. Returns ------- Examples -------- >>> my_re=get_entsoe_renewable_data() >>> int(my_re['DE_solar_generation_actual'].sum()) 188160676 """ if version is No...
5,350,006
def getPredictedAnchor(title: str) -> str: """Return predicted anchor for given title, usually first letter.""" title = title.lower() if title.startswith('npj '): return 'npj series' title = re.sub(r'^(the|a|an|der|die|das|den|dem|le|la|les|el|il)\s+', '', title) return ti...
5,350,007
def get_contact_flow(contact_flow_id: Optional[str] = None, instance_id: Optional[str] = None, name: Optional[str] = None, tags: Optional[Mapping[str, str]] = None, type: Optional[str] = None, opts: Optional[pulumi....
5,350,008
def jensen_alpha_beta(risk_returns ,benchmark_returns,Rebalancement_frequency): """ Compute the Beta and alpha of the investment under the CAPM Parameters ---------- risk_returns : np.ndarray benchmark_returns : np.ndarray Rebalancement_frequency : np.float64 ...
5,350,009
def cycles_run() -> int: """Number of cycles run so far""" return lib.m68k_cycles_run()
5,350,010
def plot_result(result, prefix='', comparison_data={}, direction='xy', plot_flags='mcdtvs'): """ plot cobea results. Parameters ---------- result : object A :py:class:`cobea.model.Result` object. prefix : str if print_figures=True, prefix contains the relative path to t...
5,350,011
def loop_and_return_fabric(lines): """ loops lines like: #1196 @ 349,741: 17x17 """ fabric = {} for line in lines: [x, y, x_length, y_length] = parse_line(line) i_x, i_y = 0, 0 while i_y < y_length: i_x = 0 while i_x < x_length: thi...
5,350,012
def get_sample(id): """Returns sample possessing id.""" for sample in samples_global: if sample.id == id: return sample raise Exception(f'sample "{id}" could not be found')
5,350,013
def test_parse_null_as_none(): """ Tests whether None may be passed via yaml kwarg null. """ initialize() yamlfile = """{ "model": !obj:pylearn2.models.autoencoder.Autoencoder { "nvis" : 1024, "nhid" : 64, "act_enc" : Null, ...
5,350,014
def plot_reion_properties(rank, size, comm, reion_ini_files, gal_ini_files, model_tags, reion_plots, output_dir, output_format): """ Wrapper function to handle reading in of data + calculating reionization properties, then calling the specified plotting routines. Paramete...
5,350,015
def transcriptIterator(transcriptsBedStream, transcriptDetailsBedStream): """ Iterates over the transcripts detailed in the two streams, producing Transcript objects. Streams are any iterator that returns bedlines or empty strings. """ transcriptsAnnotations = {} for tokens in tokenizeBedStream(transcriptDe...
5,350,016
def convert_check_filter(tok): """Convert an input string into a filter function. The filter function accepts a qualified python identifier string and returns a bool. The input can be a regexp or a simple string. A simple string must match a component of the qualified name exactly. A regexp is ...
5,350,017
def region_stats(x, r_start, r_end): """ Generate basic stats on each region. Return a dict for easy insertion into a DataFrame. """ stats = Munch() stats["start"] = r_start stats["end"] = r_end stats["l"] = r_end - r_start stats["min"] = np.min(x[r_start:r_end]) stats["max"] = np.ma...
5,350,018
def test_value_with_brackets(): """ Value is a dict Expected Status : True """ log.info("Executing test_value_with_regex") command_line = {"cmdline" : 'mesos-journald-logger --journald_labels={"labels":[{"key":"DCOS_PACKAGE_IS_FRAMEWORK","value":"false"}]} --logrotate_max_size={"size":"5...
5,350,019
def resnet_v1_generator(block_fn, layers, num_classes, data_format='channels_first', dropblock_keep_probs=None, dropblock_size=None): """Generator for ResNet v1 models. Args: block_fn: `function` for the block to use within the model. Either `residual_blo...
5,350,020
def read_hotw(filename): """ Read cross-section file fetched from HITRAN-on-the-Web. The format of the file line must be as follows: nu, coef Other lines are omitted. """ import sys f = open(filename,'r') nu = [] coef = [] for line in f: pars = line.split() ...
5,350,021
def _sql_type(ptype): """Convert python type to SQL type""" if "Union" in ptype.__class__.__name__: assert len(ptype.__args__) == 2, "Cannot create sql column with more than one type." assert type(None) in ptype.__args__, "Cannot create sql column with more than one type." return f"{pty...
5,350,022
def rescale_data(data: np.ndarray, option: str, args: t.Optional[t.Dict[str, t.Any]] = None) -> np.ndarray: """Rescale numeric fitted data accordingly to user select option. Args: data (:obj:`np.ndarray`): data to rescale. option (:obj:`str`): rescaling strate...
5,350,023
def extract_labels(text, spacy_model): """Extract entities using libratom. Returns: core.Label list """ try: document = spacy_model(text) except ValueError: logger.exception(f"spaCy error") raise labels = set() for entity in document.ents: label, _ = Label.o...
5,350,024
def variant_option(command: Callable[..., None]) -> Callable[..., None]: """ An option decorator for a DC/OS variant. """ function = click.option( '--variant', type=click.Choice(['auto', 'oss', 'enterprise']), default='auto', help=( 'Choose the DC/OS variant. ...
5,350,025
def GetSegByName(name): """ @return Address of the first byte in the Segment with the provided name, or BADADDR """ for Segment in ida.Segments(): if ida.SegName(Segment) == name: return Segment return ida.BADADDR
5,350,026
def sample_points_from_plateaus(all_plateaus, mode, stack_size=10, n_samples=1): """ Samples points from each plateau in each video :param all_plateaus: dictionary containing all plateaus, keys are plateaus's ids, values are the plateau objects :param mode: either `flow` or `rgb` :param stack_size:...
5,350,027
def debug(debug): """ Prints debug to stdout, flushing the output. """ print("DEBUG: {}".format(debug), flush = True)
5,350,028
def mobile_user_meeting_list(request): """ 返回用户会议列表 :param request: :return: """ dbs = request.dbsession user_id = request.POST.get('user_id', '') start_date = request.POST.get('start_date', '') end_date = request.POST.get('end_date', '') error_msg = '' if not user_id: ...
5,350,029
def get_current_thread_cpu_time(): """ <Purpose> Gets the total CPU time for the currently executing thread. <Exceptions> An AssertionError will be raised if the underlying system call fails. <Returns> A floating amount of time in seconds. """ # Get the current thread handle current_thread =...
5,350,030
def get_data_upload_id(jwt: str) -> str: """Function to get a temporary upload ID from DAFNI data upload API Args: jwt (str): Users JWT Returns: str: Temporary Upload ID """ url = f"{DATA_UPLOAD_API_URL}/nid/upload/" data = {"cancelToken": {"promise": {}}} return dafn...
5,350,031
def StationMagnitudeContribution_TypeInfo(): """StationMagnitudeContribution_TypeInfo() -> RTTI""" return _DataModel.StationMagnitudeContribution_TypeInfo()
5,350,032
def _get_operations(rescale=0.003921, normalize_weight=0.48): """Get operations.""" operation_0 = { 'tensor_op_module': 'minddata.transforms.c_transforms', 'tensor_op_name': 'RandomCrop', 'weight': [32, 32, 4, 4, 4, 4], 'padding_mode': "constant", 'pad_if_needed': False, ...
5,350,033
def itm_command( ticker: str = None, ): """Options ITM""" # Check for argument if ticker is None: raise Exception("Stock ticker is required") dates = yfinance_model.option_expirations(ticker) if not dates: raise Exception("Stock ticker is invalid") current_price = yfinanc...
5,350,034
def click(context): """ Locate the desired hyperlink """ context.browser.find_element_by_partial_link_text('2').click() # context.browser.get('http://localhost:5000/genres_details')
5,350,035
def create_nx_suite(seed=0, rng=None): """ returns a dict of graphs generated by networkx for testing, designed to be used in a pytest fixture """ if rng is None: rng = np.random.RandomState(seed) out_graphs = {} for N in [1, 2, 4, 8, 16, 32, 64, 128]: for dtype in [np...
5,350,036
def test_get_countries_by_country_codes(nigeria, egypt, kenya): """ Test that multiple countries can be retrieved by multiple country codes. """ countries = rapi.get_countries_by_country_codes(["ng", "eg", "ken"]) assert sorted(countries) == sorted([nigeria, egypt, kenya])
5,350,037
def main(): # pragma: no cover """test example for AnimationWindow""" # kills the program when you hit Cntl+C from the command line # doesn't save the current state as presumably there's been an error import signal signal.signal(signal.SIGINT, signal.SIG_DFL) import sys # Someone is launch...
5,350,038
def test_egg(virtualenv, cache_dir, use_static_requirements, src_dir): """ test building and installing a bdist_egg package """ # TODO: We should actually disallow generating an egg file # Let's create the testing virtualenv with virtualenv as venv: ret = venv.run( venv.venv_...
5,350,039
def _nearest_neighbor_features_per_object_in_chunks( reference_embeddings_flat, query_embeddings_flat, reference_labels_flat, ref_obj_ids, k_nearest_neighbors, n_chunks): """Calculates the nearest neighbor features per object in chunks to save mem. Uses chunking to bound the memory use. Args: ...
5,350,040
def heap_pop(heap): """ Wrapper around heapq's heappop method to support updating priorities of items in the queue. Main difference here is that we toss out any queue entries that have been updated since insertion. """ while len(heap) > 0: pri_board_tup = heapq.heappop(heap) ...
5,350,041
def _variant_po_to_dict(tokens) -> CentralDogma: """Convert a PyParsing data dictionary to a central dogma abundance (i.e., Protein, RNA, miRNA, Gene). :type tokens: ParseResult """ dsl = FUNC_TO_DSL.get(tokens[FUNCTION]) if dsl is None: raise ValueError('invalid tokens: {}'.format(tokens))...
5,350,042
def project(name, param): """a tilemill project description, including a basic countries-of-the-world layer.""" return { "bounds": [-180, -85.05112877980659, 180, 85.05112877980659], "center": [0, 0, 2], "format": "png", "interactivity": False, "minzoom": 0, "maxz...
5,350,043
def writescript( fname, content ): """ same as writefile except the first line is removed if empty and the resulting file is made executable to the owner """ m = pat_empty_line.match( content ) if m: content = content[ m.end(): ] writefile( fname, content ) perm = stat.S_IMODE(...
5,350,044
def get_deepest(): """Return tokens with largest liquidities. Returns: str: HTML-formatted message. """ url = config.URLS['deepest'] api_params = {'limit': 5, 'orderBy': 'usdLiquidity', 'direction': 'desc', 'key': POOLS_KEY ...
5,350,045
def _grompp_str(op_name, gro_name, checkpoint_file=None): """Helper function, returns grompp command string for operation.""" mdp_file = signac.get_project().fn('mdp_files/{op}.mdp'.format(op=op_name)) cmd = '{gmx} grompp -f {mdp_file} -c {gro_file} {checkpoint} -o {op}.tpr -p'.format( gmx=gmx_exec,...
5,350,046
def run( master_cls: typing.Type[master.Master], make_parser: typing.Callable[[options.Options], argparse.ArgumentParser], arguments: typing.Sequence[str], extra: typing.Callable[[typing.Any], dict] = None ) -> master.Master: # pragma: no cover """ extra: Extra argument proc...
5,350,047
def get_role_with_name(role_name: str) -> Role: """Get role with given name.""" role = Role.query.filter(Role.name == role_name).one() return role
5,350,048
def namespace_store_factory( request, cld_mgr, mcg_obj_session, cloud_uls_factory_session, pvc_factory_session ): """ Create a NamespaceStore factory. Calling this fixture lets the user create namespace stores. Args: request (object): Pytest built-in fixture cld_mgr (CloudManager): ...
5,350,049
def get_user(request, username): """ Gets a user's information. return: { status: HTTP status, name: string, gender: string, marital_status: string, first_name: string } """ data = get_user_info(username) if data: ...
5,350,050
def find_changes(d_before, d_after): """ Returns a dictionary of changes in the format: { <system id>: { <changed key>: <Change type>, ... }, ... } The changes should describe the differences between d_before and d_after. ...
5,350,051
def check_vector_inbetween(v1, v2, point): """ Checks if point lies inbetween two vectors v1, v2. Returns boolean. """ if (np.dot(np.cross(v1, point), np.cross(v1, v2))) >= 0 and (np.dot(np.cross(v2, point), np.cross(v2, v1))) >= 0: return True else: return False
5,350,052
def accuracy(y_preds, y_test): """ Function to calculate the accuracy of algorithm :param y_preds: predictions for test data :param y_test: actual labels for test data :return: accuracy in percentage """ return np.sum(np.where(y_preds == y_test, 1, 0)) * 100 / len(y_test)
5,350,053
def make_forecasts_at_incidents_for_mala(get_new=False): """Lager csv med alle varsomhendelser sammen med faregrad og de aktuelle skredproblemene (svakt lag, skredtype og skredproblemnavnert). Der det er gjort en regObs observasjon med «hendelse/ulykke» skjema fylt ut har jeg også lagt på skadeomfangsvurder...
5,350,054
def get_all(factory='official', **kwargs): """Construct and return an list of Class `Event`. hookを呼び出す. Args: factory: `Event` の取得用マネージャ 今のところ,京大公式HP用のみ. EventFactoryMixin classを継承したクラスか 'official' に対応 date (:obj:`datetime`, optional): 欲しいイベントのdatetime. `month` , `y...
5,350,055
def gpu_queue(options): """ Queued up containers waiting for GPU resources """ import docker import json import os import time from vent.helpers.meta import GpuUsage status = (False, None) if (os.path.isfile('/root/.vent/vent.cfg') and os.path.isfile('/root/.vent/plugin_manifes...
5,350,056
def nudupl(f): """Square(f) following Cohen, Alg. 5.4.8. """ L = int(((abs(f.discriminant))/4)**(1/4)) a, b, c = f[0], f[1], f[2] # Step 1 Euclidean step d1, u, v = extended_euclid_xgcd(b, a) A = a//d1 B = b//d1 C = (-c*u) % A C1 = A-C if C1 < C: C = -C1...
5,350,057
def remove_schema(name): """Removes a configuration schema from the database""" schema = controller.ConfigurationSchema() schema.remove(name) return 0
5,350,058
def test_get_row_mask_with_min_zeros(): """Tests the `get_row_mask_with_min_zeros` function.""" zeros_mask = tf.constant( [[True, False, False], [True, True, False], [True, True, True]] ) actual = get_row_mask_with_min_zeros(zeros_mask) expected = tf.constant([[True], [False], [False]], tf.b...
5,350,059
def get_unassigned_independent_hyperparameters(outputs): """Going backward from the outputs provided, gets all the independent hyperparameters that are not set yet. Setting an hyperparameter may lead to the creation of additional hyperparameters, which will be most likely not set. Such behavior happens...
5,350,060
def get_theta_benchmark_matrix(theta_type, theta_value, benchmarks, morpher=None): """Calculates vector A such that dsigma(theta) = A * dsigma_benchmarks""" if theta_type == "benchmark": n_benchmarks = len(benchmarks) index = list(benchmarks).index(theta_value) theta_matrix = np.zeros(n...
5,350,061
def get_plugins(plugin_dir=None): """Load plugins from PLUGIN_DIR and return a dict with the plugin name hashed to the imported plugin. PLUGIN_DIR is the name of the dir from which to load plugins. If it is None, use the plugin dir in the dir that holds this func. We load plugins and run them in ...
5,350,062
def reorder_points(point_list): """ Reorder points of quadrangle. (top-left, top-right, bottom right, bottom left). :param point_list: List of point. Point is (x, y). :return: Reorder points. """ # Find the first point which x is minimum. ordered_point_list = sorted(point_list, key=lambd...
5,350,063
def ppg_acoustics_collate(batch): """Zero-pad the PPG and acoustic sequences in a mini-batch. Also creates the stop token mini-batch. Args: batch: An array with B elements, each is a tuple (PPG, acoustic). Consider this is the return value of [val for val in dataset], where dataset...
5,350,064
def test_atomic_unsigned_int_enumeration_3_nistxml_sv_iv_atomic_unsigned_int_enumeration_4_4(mode, save_output, output_format): """ Type atomic/unsignedInt is restricted by facet enumeration. """ assert_bindings( schema="nistData/atomic/unsignedInt/Schema+Instance/NISTSchema-SV-IV-atomic-unsigne...
5,350,065
def problem004(): """ Find the largest palindrome made from the product of two 3-digit numbers. """ return largest_palindrome_from_product_of_two_n_digit_numbers(3)
5,350,066
def salt_minion(salt_minion_factory): """ A running salt-minion fixture """ with salt_minion_factory.started(): # Sync All salt_call_cli = salt_minion_factory.get_salt_call_cli() ret = salt_call_cli.run("saltutil.sync_all", _timeout=120) assert ret.exitcode == 0, ret ...
5,350,067
def validate_params(service_code: str, params: dict) -> None: """ Check that query inputs are of the correct format. Will fail on missing arguments, """ if service_code not in REQUIRED_D.keys(): raise ElexonAPIException(f"Unknown service_code: {service_code}.") passed_set = set(params....
5,350,068
def residual_l1_max(reconstruction: Tensor, original: Tensor) -> Tensor: """Construct l1 difference between original and reconstruction. Note: Only positive values in the residual are considered, i.e. values below zero are clamped. That means only cases where bright pixels which are brighter in the input (...
5,350,069
def build_url(path): """ Construct an absolute url by appending a path to a domain. """ return 'http://%s%s' % (DOMAIN, path)
5,350,070
def get_registration_url(request, event_id): """ Compute the absolute URL to create a booking on a given event @param request: An HttpRequest used to discover the FQDN and path @param event_id: the ID of the event to register to """ registration_url_rel = reverse(booking_create, kwargs={"event_i...
5,350,071
def create_no_args_decorator(decorator_function, function_for_metadata=None, ): """ Utility method to create a decorator that has no arguments at all and is implemented by `decorator_function`, in implementation-first mode or usage-first mode. T...
5,350,072
def load_electric_devices_segmentation(): """Load the Electric Devices segmentation problem and returns X. We group TS of the UCR Electric Devices dataset by class label and concatenate all TS to create segments with repeating temporal patterns and characteristics. The location at which different class...
5,350,073
def reshape( w, h): """Reshapes the scene when the window is resized.""" lightPos = (-50.0, 50.0, 100.0, 1.0) nRange = 2.0 if h==0: h = 1 glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() if w <= h: glOrtho(-nRange, nRange, -nRange*h/w, nRange...
5,350,074
def compute_batch_jacobian(input, output, retain_graph=False): """ Compute the Jacobian matrix of a batch of outputs with respect to some input (normally, the activations of a hidden layer). Returned Jacobian has dimensions Batch x SizeOutput x SizeInput Args: input (list or torch.Tens...
5,350,075
def glIndexdv(v): """ v - seq( GLdouble, 1)""" if 1 != len(v): raise TypeError(len(v), "1-array expected") _gllib.glIndexdv(v)
5,350,076
def is_associative(value): """Checks if `value` is an associative object meaning that it can be accessed via an index or key Args: value (mixed): Value to check. Returns: bool: Whether `value` is associative. Example: >>> is_associative([]) True >>> is_ass...
5,350,077
def list_notebook(): """List notebooks""" COLS_TO_SHOW = ["Name", "ID", "Environment", "Resources", "Status"] console = Console() # using user_id hard coded in SysUserRestApi.java # https://github.com/apache/submarine/blob/5040068d7214a46c52ba87e10e9fa64411293cf7/submarine-server/server-core/src/mai...
5,350,078
def test_dispersion_curve_calculation(hlm): """ Test the method for calculating dispersion curves. """ # TODO: come up with a way to test this pass
5,350,079
def join_audio(audio1, audio2): """ >>> join_audio(([1], [4]), ([2, 3], [5, 6])) ([1, 2, 3], [4, 5, 6]) """ (left1, right1) = audio1 (left2, right2) = audio2 left = left1 + left2 right = right1 + right2 audio = (left, right) return audio
5,350,080
def csi_from_sr_and_pod(success_ratio_array, pod_array): """Computes CSI (critical success index) from success ratio and POD. POD = probability of detection :param success_ratio_array: np array (any shape) of success ratios. :param pod_array: np array (same shape) of POD values. :return: csi_array: ...
5,350,081
def portrait_plot( data, xaxis_labels, yaxis_labels, fig=None, ax=None, annotate=False, annotate_data=None, annotate_fontsize=15, annotate_format="{x:.2f}", figsize=(12, 10), vrange=None, xaxis_fontsize=15, yaxis_fontsize=15, cmap="RdBu_r", cmap_bounds=None, ...
5,350,082
def compute_secondary_observables(data): """Computes secondary observables and extends matrix of observables. Argument -------- data -- structured array must contains following fields: length, width, fluo, area, time Returns ------- out -- structured array new fields are ad...
5,350,083
def get_account_number(arn): """ Extract the account number from an arn. :param arn: IAM SSL arn :return: account number associated with ARN """ return arn.split(":")[4]
5,350,084
def get_hashtags(tweet): """return hashtags from a given tweet Args: tweet (object): an object representing a tweet Returns: list: list of hastags in a tweet """ entities = tweet.get('entities', {}) hashtags = entities.get('hashtags', []) return [get_text(tag) for tag in ha...
5,350,085
async def get_organization_catalogs(filter: FilterEnum) -> OrganizationCatalogList: """Return all organization catalogs.""" logging.debug("Fetching all catalogs") async with ClientSession() as session: ( organizations, datasets, dataservices, concepts...
5,350,086
def get_appliance_ospf_neighbors_state( self, ne_id: str, ) -> dict: """Get appliance OSPF neighbors state .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - ospf - GET - /ospf/state/neighbors/{neId} :param n...
5,350,087
def filter_toolchain_files(dirname, files): """Callback for shutil.copytree. Return lists of files to skip.""" split = dirname.split(os.path.sep) for ign in IGNORE_LIST: if ign in split: print('Ignoring dir %s' % dirname) return files return []
5,350,088
def info(obj): """Return info on shape and dtype of a numpy array or TensorFlow tensor.""" if obj is None: return 'None.' elif isinstance(obj, list): if obj: return 'List of %d... %s' % (len(obj), info(obj[0])) else: return 'Empty list.' elif isinstance(obj, tuple): if obj: ret...
5,350,089
def flowing(where, to, parallel_converges): """ mark target's stream from target :param where: :param to: :param parallel_converges: :return: """ is_parallel = where[PE.type] in PARALLEL_GATEWAYS stream = None if is_parallel: # add parallel's stream to its converge ...
5,350,090
def first_index_k_zeros_left(qstr, k, P): """ For a binary string qstr, return the first index of q with k (mod P) zeros to the left. Return: index in [0, qstr.length] """ num_zeros_left = 0 for j in range(qstr.length+1): if (num_zeros_left - k) % P == 0: return j if ...
5,350,091
def transform_points(points, transf_matrix): """ Transform (3,N) or (4,N) points using transformation matrix. """ if points.shape[0] not in [3, 4]: raise Exception("Points input should be (3,N) or (4,N) shape, received {}".format(points.shape)) return transf_matrix.dot(np.vstack((point...
5,350,092
def obter_resposta(escolha_nivel): """ Entrada: Parâmetro do nível (facil, médio, difícil) Tarefa: Avaliar resposta do usuário e informar estado atual Saída: Parâmetros do dicionário do menu QUIZ """ os.system('clear') escolha = escolha_nivel.lower() if escolha == '': nav...
5,350,093
def get_lat_long(zip): """ This function takes a zip code and looks up the latitude and longitude using the uszipcode package. Documentation: https://pypi.python.org/pypi/uszipcode """ search = ZipcodeSearchEngine() zip_data = search.by_zipcode(zip) lat = zip_data['Latitude'] long =...
5,350,094
def propose_perturbation_requests(current_input, task_idx, perturbations): """Wraps requests for perturbations of one task in a EvaluationRequest PB. Generates one request for each perturbation, given by adding the perturbation to current_input. Args: current_input: the current policy weights task_idx...
5,350,095
def validateJson(js, schema): """ Confirms that a given json follows the given schema. Throws a "jsonschema.exceptions.ValidationError" otherwise. """ assert type(js) == dict or type(js) == str, "JSON must be a dictionary or string JSON or path!" assert type(schema) == dict or type(schema) == st...
5,350,096
def process_enable(ctx, process): """Enable process maintenance""" ctx.obj["output"](enable_process(ctx.obj["cfg"], process))
5,350,097
def id_token_call_credentials(credentials): """Constructs `grpc.CallCredentials` using `google.auth.Credentials.id_token`. Args: credentials (google.auth.credentials.Credentials): The credentials to use. Returns: grpc.CallCredentials: The call credentials. """ request = google.auth...
5,350,098
def delete_note(note_id): """Delete note by id""" print(req.delete(f'http://{host}/notes/{note_id}').status_code)
5,350,099