content
stringlengths
22
815k
id
int64
0
4.91M
def Chat_(request): """ { "value" : "Your query" } """ print(request.data) serializer = PatternSerializer(request.data) try: response = ChatBot(serializer.data["value"]) except: response = { "error": "Data is in wrong formate use { 'value' ...
34,700
def get_solubility(molecular_weight, density): """ Estimate the solubility of each oil pseudo-component Estimate the solubility (mol/L) of each oil pseudo-component using the method from Huibers and Lehr given in the huibers_lehr.py module of py_gnome in the directory gnome/utilities/weathering...
34,701
def build_1d_frp_matrix(func, x, sigma, B=1): """ Builds quadratic frp matrix respecting pbc. func: Kernel function x: position of points sigma: width of Kernel """ N = len(x) A = np.zeros((N, N)) shifts = np.arange(-5, 6) * B for r in range(N): for p in range(N): ...
34,702
def invalid_item(item_key, valid_flag=False): """ Update item valid_flag. """ if kind.str_is_empty(item_key): raise RequiredError("item_key") query = Registry.all() query.filter("item_key =", item_key) query.set("valid_flag", valid_flag) return query.update(conte...
34,703
def ret_str() -> str: """ # blahs blahs # blahs Returns ------- """ # blahs # blahs # blahs return ''
34,704
def delete_column(table, name): """ """ col = table.c[name] col.drop(table)
34,705
def main(): """ ---------- Author: Damon Gwinn ---------- Entry point. Generates music from a model specified by command line arguments ---------- """ args = parse_generate_args() print_generate_args(args) if(args.force_cpu): use_cuda(False) print(...
34,706
def dump_pb(dir_or_filename): """Dump the data from either a single .pb file, or all .pb files in a directory. All files must contain a serialized TensorProto.""" if os.path.isdir(dir_or_filename): for f in glob.glob(os.path.join(dir_or_filename, "*.pb")): print(f) dump_tens...
34,707
def get_wh_words(document: Union[Doc, Span]): """ Get the list of WH-words\n - when, where, why\n - whence, whereby, wherein, whereupon\n - how\n - what, which, whose\n - who, whose, which, what\n Resources:\n - https://grammar.collinsdictionary.com/easy-learning/wh-words\n - ht...
34,708
def sample_mixture_gaussian(batch_size, p_array, mu_list, sig_list, k=K, d=DIM): """ samples from a mixture of normals :param batch_size: sample size :param p_array: np array which includes probability for each component of mix :param mu_list: list of means of each component :param sig_list: lis...
34,709
def sign(x: float) -> float: """Return the sign of the argument. Zero returns zero.""" if x > 0: return 1.0 elif x < 0: return -1.0 else: return 0.0
34,710
def profile_genome_plot(bar_width,l_genome,allinsertionsites_list,allcounts_binnedlist,summed_chr_length_dict, middle_chr_position,chrom_list,variable,genes_currentchrom_pos_list,gene_pos_dict): """Plot function to show the whole insertion map throughout the genome Parameters ----...
34,711
def CalculateLocalDipoleIndex(mol): """ Calculation of local dipole index (D) """ GMCharge.ComputeGasteigerCharges(mol, iter_step) res = [] for atom in mol.GetAtoms(): res.append(float(atom.GetProp('_GasteigerCharge'))) cc = [numpy.absolute(res[x.GetBeginAtom().GetIdx()] - ...
34,712
def controller_login_fixture(event_loop, auth_token, controller_json): """Return an aresponses server for an authenticated remote client.""" client = aresponses.ResponsesMockServer(loop=event_loop) client.add( TEST_HOST, "/v1/authenticate", "post", aresponses.Response( ...
34,713
def tile1(icon="", **kw): """<!-- Tile with icon, icon can be font icon or image -->""" ctx=[kw['tile_label']] s = span(cls="icon %s" % icon) ctx.append(s) d2 = div(ctx=ctx, cls="tile-content iconic") return d2
34,714
def config_server(sender_email:str, sender_autorization_code:str, smtp_host: Optional[str] = None, smtp_port: Optional[int] = None, timeout=10): """ smtp server configuration :param sender_email: sender's email :param sender_autorization_code: sender's smtp authorization code :param smtp_host: smt...
34,715
def test_Conv3DTranspose_dilation_2_9_10_11_12(): """ api: paddle.Conv3DTranspose op version: 9,10,11,12 """ op = Net(in_channels=16, out_channels=16, dilation=3) op.eval() # net, name, ver_list, delta=1e-6, rtol=1e-5 obj = APIOnnx(op, 'nn_Conv3DTranspose', [9, 10, 11, 12]) obj.set_i...
34,716
def try_to_import_file(file_name): """ Tries to import the file as Python module. First calls import_file_as_package() and falls back to import_file_as_module(). If fails, keeps silent on any errors and returns the occured exceptions. :param file_name: The path to import. :return: The loaded mod...
34,717
def main(): """Run main function.""" txt = [] for name, help_diag in sorted(_iterhelps()): txt.append(f"*{name}*") txt.append("```") txt.append(help_diag) txt.append("```") txt.append("---") fmt = "\n".join(txt) with README.open("r+") as fileh: data = ...
34,718
def is_uppervowel(char: str) -> bool: """ Checks if the character is an uppercase Irish vowel (aeiouáéíóú). :param char: the character to check :return: true if the input is a single character, is uppercase, and is an Irish vowel """ vowels = "AEIOUÁÉÍÓÚ" return len(char) == 1 and char[0] i...
34,719
def _resolve_command(lexer, match) -> Iterator[Tuple[int, Token, str]]: """Pygments lexer callback for determining if a command is valid. Yielded values take the form: (index, tokentype, value). See: https://pygments.org/docs/lexerdevelopment/#callbacks """ command_engine: CommandEngine =...
34,720
def onerror(func, path, exc_info): """ Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. If the error is for another reason it re-raises the error. Usage : ``shutil.rmtree(path, onerror=onerror)`` ...
34,721
async def test_incorrect_modes( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, ) -> None: """Test incorrect values are handled correctly.""" with patch( "pyatag.entities.Climate.hvac_mode", new_callable=PropertyMock(return_value="bug"), ): await init_integration(ha...
34,722
def visualize_permutation_results( obs_r2: float, permuted_r2: np.ndarray, verbose: bool = True, permutation_color: str = "#a6bddb", output_path: Optional[str] = None, show: bool = True, close: bool = False, ) -> float: """ Parameters ---------- obs_r2 : float Denotes...
34,723
def htmlmovie(html_index_fname,pngfile,framenos,figno): #===================================== """ Input: pngfile: a dictionary indexed by (frameno,figno) with value the corresponding png file for this figure. framenos: a list of frame numbers to include in movie figno: integer with...
34,724
def readin_q3d_matrix_m(path: str) -> pd.DataFrame: """Read in Q3D cap matrix from a .m file exported by Ansys Q3d. Args: path (str): Path to .m file Returns: pd.DataFrame of cap matrix, with no names of columns. """ text = Path(path).read_text() match = re.findall(r'capMatrix ...
34,725
def get_DB(type='mysql'): """ Parameters ---------- type Returns ------- """ if type == 'mysql': return MySQLAdapter elif type == 'mongodb': return MongoAdapter
34,726
def movstd(x,window): """ Computes the moving standard deviation for a 1D array. Returns an array with the same length of the input array. Small window length provides a finer description of deviation Longer window coarser (faster to compute). By default, each segment is centered, ...
34,727
def test_load_dict(testdata_dir, tmp_trestle_dir): """Test loading of distributed dict.""" # prepare trestle project dir with the file test_utils.ensure_trestle_config_dir(tmp_trestle_dir) test_data_source = testdata_dir / 'split_merge/step4_split_groups_array/catalogs' catalogs_dir = Path('catalo...
34,728
def get_attribute(parent, selector, attribute, index=0): """Get the attribute value for the child element of parent matching the given CSS selector If index is specified, return the attribute value for the matching child element with the specified zero-based index; otherwise, return the attribute value for the first...
34,729
def rdd_plot( data, x_variable, y_variable, nbins=20, ylimits=None, frac=None, width=20.1, deg=1 ): """ Plots a Regression Discontinouity Design graph. For this, binned observations are portrayed in a scatter plot. Uses non-parametric regression (local polynomial estimation) to fit a curve on the or...
34,730
def collect() -> None: """运行一次垃圾回收。""" ...
34,731
def cal_head_bbox(kps, image_size): """ Args: kps (torch.Tensor): (N, 19, 2) image_size (int): Returns: bbox (torch.Tensor): (N, 4) """ NECK_IDS = 12 # in cocoplus kps = (kps + 1) / 2.0 necks = kps[:, NECK_IDS, 0] zeros = torch.zeros_like(necks) ones = tor...
34,732
def my_json_render(docs, style="dep", options=None, manual=False) -> list: """ Render nlp visualisation. Args: docs (list or Doc): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. options (dict): Visualiser-specific options, e.g. colors. manual ...
34,733
def draw_raw_data_first_try(files_location): """ first try analyze raw data - drawings from Magda""" import ast import matplotlib.pyplot as plt test_raw = pd.read_csv(files_location + "/test_raw.csv", index_col="key_id", nrows=100) # first 10 drawings first_ten_ids = test_raw.iloc[:10].index ...
34,734
def org_office_duplicate(job): """ This callback will be called when importing office records it will look to see if the record being imported is a duplicate. @param job: An S3ImportJob object which includes all the details of the record being imported If the record is a ...
34,735
def get_testcase_chain(testcase_id, case_type, chain_list=None, with_intf_system_name=None, with_extract=None, only_first=False, main_case_flow_id=None, childless=False): """ 根据testcase_id获取调用链, 包含接口用例和全链路用例 return example: [ { "preCaseId": 1, "preC...
34,736
def approximate_parameter_profile( problem: Problem, result: Result, profile_index: Iterable[int] = None, profile_list: int = None, result_index: int = 0, n_steps: int = 100, ) -> Result: """ Calculate profiles based on an approximation via a normal likelihood ...
34,737
def _process_input(data, context): """ pre-process request input before it is sent to TensorFlow Serving REST API Args: data (obj): the request data, in format of dict or string context (Context): object containing request and configuration details Returns: (dict): a JSON-ser...
34,738
def update_policies(isamAppliance, name, policies, action, check_mode=False, force=False): """ Update a specified policy set's policies (add/remove/set) Note: Please input policies as an array of policy names (it will be converted to id's) """ pol_id, update_required, json_data = _check_policies(is...
34,739
def is_bullish_engulfing(previous: Candlestick, current: Candlestick) -> bool: """Engulfs previous candle body. Wick and tail not included""" return ( previous.is_bearish and current.is_bullish and current.open <= previous.close and current.close > previous.open )
34,740
def yaw_cov_to_quaternion_cov(yaw, yaw_covariance): """Calculate the quaternion covariance based on the yaw and yaw covariance. Perform the operation :math:`C_{\\theta} = R C_q R^T` where :math:`C_{\\theta}` is the yaw covariance, :math:`C_q` is the quaternion covariance and :math:`R` is the Jacobi...
34,741
async def token(req: web.Request) -> web.Response: """Auth endpoint.""" global nonce, user_eppn, user_family_name, user_given_name id_token = { "at_hash": "fSi3VUa5i2o2SgY5gPJZgg", "sub": "smth", "eduPersonAffiliation": "member;staff", "eppn": user_eppn, "displayName"...
34,742
def split_train_test(observations, train_percentage): """Splits observations into a train and test set. Args: observations: Observations to split in train and test. They can be the representation or the observed factors of variation. The shape is (num_dimensions, num_points) and the split is over t...
34,743
def InitF11(frame): """F6 to navigate between regions :param frame: see InitShorcuts->param :type frame: idem :return: entrie(here tuple) for AcceleratorTable :rtype: tuple(int, int, int) """ frame.Bind(wx.EVT_MENU, frame.shell.SetFocus, id=wx.ID_SHELL_FOCUS) return (wx.ACCEL_NORMAL, w...
34,744
def ReadExactly(from_stream, num_bytes): """Reads exactly num_bytes from a stream.""" pieces = [] bytes_read = 0 while bytes_read < num_bytes: data = from_stream.read(min(MAX_READ, num_bytes - bytes_read)) bytes_read += len(data) pieces.append(data) return ''.join(pieces)
34,745
def indicator_collect(container=None, artifact_ids_include=None, indicator_types_include=None, indicator_types_exclude=None, indicator_tags_include=None, indicator_tags_exclude=None, **kwargs): """ Collect all indicators in a container and separate them by data type. Additional output data paths are created for...
34,746
def test_allow_multiple_creation(): """Test method""" message = "Population must be re-creatable" size = 6 test_factory = BlobFactory(n=size, scatter=12) test_factory.create_blobs() test_factory.create_blobs() rmtree(test_factory.get_population_string()) assert len(test_factory.get_popul...
34,747
def remove_duplicates(iterable): """Removes duplicates of an iterable without meddling with the order""" seen = set() seen_add = seen.add # for efficiency, local variable avoids check of binds return [x for x in iterable if not (x in seen or seen_add(x))]
34,748
def pytest_configure(config): """Disable verbose output when running tests.""" log.init(debug=True) terminal = config.pluginmanager.getplugin("terminal") terminal.TerminalReporter.showfspath = False
34,749
def verify_my_token(user: User = Depends(auth_user)): """ Verify a token, and get basic user information """ return {"token": get_token(user), "email": user.email, "is_admin": user.is_admin, "restricted_job": user.restricted_job}
34,750
def inv_partition_spline_curve(x): """The inverse of partition_spline_curve().""" c = lambda z: tf.cast(z, x.dtype) assert_ops = [tf.Assert(tf.reduce_all(x >= 0.), [x])] with tf.control_dependencies(assert_ops): alpha = tf.where( x < 8, c(0.5) * x + tf.where( x <= 4, ...
34,751
def _orbit_bbox(partitions): """ Takes a granule's partitions 'partitions' and returns the bounding box containing all of them. Bounding box is ll, ur format [[lon, lat], [lon, lat]]. """ lon_min = partitions[0]['lon_min'] lat_min = partitions[0]['lat_min'] lon_max = partitions[0]['lon_m...
34,752
def test_paragraph_series_e_rh(): """ Test case: Paragraph with raw HTML with newline inside was: test_paragraph_extra_44 """ # Arrange source_markdown = """a<raw html='cool'>a""" expected_tokens = [ "[para(1,1):\n]", "[text(1,1):a:]", "[raw-html(1,2):raw\nht...
34,753
def clear_ip_mroute_vrf(device, vrf_name): """ clear ipv6 mld group Args: device (`obj`): Device object Returns: None Raises: SubCommandFailure """ try: device.execute('clear ip mroute vrf {vrf_name} *'.format(vrf_name=vrf_name)) excep...
34,754
def GetModel(name: str) -> None: """ Returns model from model pool that coresponds to the given name. Raises GraphicsException if certain model cannot be found. param name: Name of a model. """ if not name in _models: raise GraphicsException(f"No such model '{name}'.") return _models[name]
34,755
def db_to_dict(s_str, i = 0, d = {}): """ Converts a dotbracket string to a dictionary of indices and their pairs Args: s_str -- str: secondary_structure in dotbracket notation KWargs: i -- int: start index d -- dict<index1, index2>: the dictionary so far Returns: dictio...
34,756
def identify_event_type(event): """Look at event to determine type of device. Async friendly. """ if EVENT_KEY_COMMAND in event: return EVENT_KEY_COMMAND if EVENT_KEY_SENSOR in event: return EVENT_KEY_SENSOR return "unknown"
34,757
def run_update_department_task(depart_id): """ Updates Department performance score and NFIRS counts when it is instantiated. Updates ERF and Service area """ from firecares.tasks import update from celery.task.control import inspect # Check for status of the current celery queue taskinspec...
34,758
def stopTiming( startTime ): """ Prints the elapsed time from 'startTime' to now. Useful for measuring code execution times. """ import datetime Any.requireIsInstance( startTime, datetime.datetime ) stopTime = now() logging.debug( 'elapsed time: %s', stopTime - startTime )
34,759
def export(group, bucket, prefix, start, end, role, poll_period=120, session=None, name="", region=None): """export a given log group to s3""" start = start and isinstance(start, str) and parse(start) or start end = (end and isinstance(start, str) and parse(end) or end or datetime.now(...
34,760
def pcolormesh_nan(x: np.ndarray, y: np.ndarray, c: np.ndarray, cmap=None, axis=None): """handles NaN in x and y by smearing last valid value in column or row out, which doesn't affect plot because "c" will be masked too """ mask = np.isfinite(x) & np.isfinite(y) top = None bottom = None f...
34,761
def send_message(message): """Sends a message""" title = '[{}] Message'.format(HOSTNAME) pushover.send_message(settings, message, title)
34,762
def scan_patch(project, patch_file, binary_list, file_audit_list, file_audit_project_list, master_list, ignore_list, licence_ext, file_ignore, licence_ignore): """ Scan actions for each commited file in patch set """ global failure if is_binary(patch_file): hashlist = g...
34,763
def delete_post(post_id): """Delete a post :param post_id: id of the post object :return: redirect or 404 """ if Post.delete_post(post_id): logger.warning('post %d has been deleted', post_id) return redirect(url_for('.posts')) else: return render_template('page_not_found...
34,764
def log_arguments(func: Callable) -> Callable: """ decorate a function to log its arguments and result :param func: the function to be decorated :return: the decorator """ @functools.wraps(func) def wrapper_args(*args, **kwargs) -> Any: # type: ignore result = func(*arg...
34,765
def huggingface_from_pretrained_custom( source: Union[Path, str], tok_config: Dict, trf_config: Dict ) -> HFObjects: """Create a Huggingface transformer model from pretrained weights. Will download the model if it is not already downloaded. source (Union[str, Path]): The name of the model or a path to ...
34,766
def recv_categorical_matrix(socket): """ Receives a matrix of type string from the getml engine """ # ------------------------------------------------------------------------- # Receive shape # By default, numeric data sent over the socket is big endian, # also referred to as network-byte-...
34,767
def collect_gsso_dict(gsso): """ Export gsso as a dict: keys are cls, ind, all (ie cls+ind)""" print('Importing gsso as dict') t0 = time.time() gsso_cls_dict, gsso_ind_dict = _create_gsso_dict(gsso) gsso_all_dict = _create_gsso_dict_all(gsso) print("Executed in %s seconds." % str(time.time()-t0)...
34,768
def H_squared(omega): """Square magnitude of the frequency filter function.""" return 1 / ( (1 + (omega * tau_a) ** 2) * (1 + (omega * tau_r) ** 2) ) * H_squared_heaviside(omega)
34,769
def export_to_cvs(export_df: pd.DataFrame, name): """ Export DataFrame into csv file with given name """ if not os.path.exists(EXPORTS_DIR): os.mkdir(EXPORTS_DIR) file = os.path.join(EXPORTS_DIR, name) export_df.to_csv(file, index=False) print("Output file: ", os.path.abspath(file...
34,770
def test_block_verify_work_difficulty(block_factory): """ Load a block with work, and verify it different work difficulties making it either pass or fail """ block = block_factory("send") # Passes with normal difficulty block.verify_work() with pytest.raises(InvalidWork): # Ins...
34,771
def docs(c): """Run if docstrings have changed""" c.run("poetry run sphinx-build -M html ./docs/sphinx ./docs/dist -v")
34,772
def get_neighbor_distances(ntw, v0, l): """Get distances to the nearest vertex neighbors along connecting arcs. Parameters ---------- ntw : spaghetti.Network spaghetti Network object. v0 : int vertex id l : dict key is tuple (start vertex, end vert...
34,773
def _cwt_gen(X, Ws, *, fsize=0, mode="same", decim=1, use_fft=True): """Compute cwt with fft based convolutions or temporal convolutions. Parameters ---------- X : array of shape (n_signals, n_times) The data. Ws : list of array Wavelets time series. fsize : int FFT lengt...
34,774
def is_generic_list(annotation: Any): """Checks if ANNOTATION is List[...].""" # python<3.7 reports List in __origin__, while python>=3.7 reports list return getattr(annotation, '__origin__', None) in (List, list)
34,775
def write_summary(umi_well, out_file): """write summary about edit distance among same read position""" with file_transaction(out_file) as tx_out_file: with gzip.open(tx_out_file, 'wb') as out_handle: for read in umi_well: umi_list = Counter(umi_well[read].umi) ...
34,776
def create_folder(base_path: Path, directory: str, rtn_path=False): """ Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory Parameters ----------- base_path : pathlib.PosixPath Global Path to be root of the c...
34,777
def CheckCallAndFilter(args, stdout=None, filter_fn=None, print_stdout=None, call_filter_on_first_line=False, **kwargs): """Runs a command and calls back a filter function if needed. Accepts all subprocess.Popen() parameters plus: print_stdout: If True, the command...
34,778
def test_parser_bernese_clu(): """Test that parsing bernese_clu gives expected output""" parser = get_parser("bernese_clu").as_dict() assert len(parser) == 16 assert "ales" in parser assert "domes" in parser["ales"]
34,779
def slave_node_driver(shared_job_queue, shared_result_queue, n_jobs_per_node): """ Starts slave processes on a single node Arguments: shared_job_queue -- the job queue to obtain jobs from shared_result_queue -- the queue that results are sent to n_jobs_per_node -- the number of slav...
34,780
def extract_track_from_cube(nemo_cube, track_cube, time_pad, dataset_id, nn_finder=None): """ Extract surface track from NEMO 2d cube """ # crop track time st = ga.get_cube_datetime(nemo_cube, 0) et = ga.get_cube_datetime(nemo_cube, -1) # NOTE do not include start...
34,781
def get_mean_series_temp(log_frame: pd.DataFrame): """Get temperature time series as mean over CPU cores.""" columns_temp = [c for c in log_frame.columns if re.fullmatch(r"Temp:Core\d+,0", c)] values_temp = log_frame[columns_temp].mean(axis=1) return values_temp
34,782
def new_channel(): """Instantiates a dict containing a template for an empty single-point channel. """ return { "channel_name": "myChannel", "after_last": "Goto first point", "alternate_direction": False, "equation": "x", "final_value": 0.0, "optimizer_con...
34,783
def Log1p(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ :param input_vertex: the vertex """ return Vertex(context.jvm_view().Log1pVertex, label, cast_to_vertex(input_vertex))
34,784
def test(request): """ Controller for the app home page. """ context = {} return render(request, 'ueb_app/test.html', context)
34,785
def banner(name, ver_str, extra=""): """Create a simple header with version and host information""" print("\n" + "#" * 75) print("Intel (R) {}. Version: {}".format(name, ver_str)) print("Copyright (c) 2019, Intel Corporation. All rights reserved.\n") print("Running on {} with Python {}".format(plat...
34,786
def pre_process_flights(flights_folder): """ Imports and merges flight files inside input folder. """ df_flights = pd.DataFrame() for flight_file in os.listdir(flights_folder): print('Processing flight: '+flight_file) df_flight = pd.read_csv(os.path.join(flights_folder, flight...
34,787
def get_node_backups(request, queryset): """ Return dict with backups attribute. """ user_order_by, order_by = get_order_by(request, api_view=VmBackupList, db_default=('-id',), user_default=('-created',)) bkps = get_pager(request, queryset.order_by(*order_b...
34,788
def collect_gameplay_experiences(env, agent, buffer): """ Collects gameplay experiences by playing env with the instructions produced by agent and stores the gameplay experiences in buffer. :param env: the game environment :param agent: the DQN agent :param buffer: the replay buffer :return...
34,789
def xpath(elt, xp, ns, default=None): """Run an xpath on an element and return the first result. If no results were returned then return the default value.""" res = elt.xpath(xp, namespaces=ns) if len(res) == 0: return default else: return res[0]
34,790
def discard(hand): """ Given six cards, return the four to keep """ from app.controller import Hand cut_card = { "value": 16, "suit": "none", "rank": 0, "name": "none", "id": 'uhgfhc' } max_points = -1 card_ids = [] for set_of_four in permutat...
34,791
def check_response_stimFreeze_delays(data, **_): """ Checks that the time difference between the visual stimulus freezing and the response is positive and less than 100ms. Metric: M = (stimFreeze_times - response_times) Criterion: 0 < M < 0.100 s Units: seconds [s] :param data: dict of trial d...
34,792
def get_invVR_aff2Ds(kpts, H=None): """ Returns matplotlib keypoint transformations (circle -> ellipse) Example: >>> # Test CV2 ellipse vs mine using MSER >>> import vtool as vt >>> import cv2 >>> import wbia.plottool as pt >>> img_fpath = ut.grab_test_imgpath(ut.get...
34,793
def lambda_fanout_clean(event, context): """Fanout SNS messages to cleanup snapshots when called by AWS Lambda.""" # baseline logging for lambda utils.configure_logging(context, LOG) # for every region, send to this function clean.perform_fanout_all_regions(context) LOG.info('Function lambda_...
34,794
def is_reload(module_name: str) -> bool: """True if the module given by `module_name` should reload the modules it imports. This is the case if `enable_reload()` was called for the module before. """ mod = sys.modules[module_name] return hasattr(mod, module_name.replace('.', '_') + "_DO_RELOAD_...
34,795
def get_string(string_name): """ Gets a string from the language file """ if string_name in lang_file[lang]: return lang_file[lang][string_name] elif string_name in lang_file["english"]: return lang_file["english"][string_name] else: return string_name
34,796
def build_streambed(x_max, set_diam): """ Build the bed particle list. Handles calls to add_bed_particle, checks for completness of bed and updates the x-extent of stream when the packing exceeds/under packs within 8mm range. Note: the updates to x-extent are only required ...
34,797
def rotate_around_point_highperf_Numpy(xy, radians, origin): """ Rotate a point around a given point. I call this the "high performance" version since we're caching some values that are needed >1 time. It's less readable than the previous function but it's faster. """ adjust_xy = x...
34,798
def eval(cfg, env, agent): """ Do the evaluation of the current agent :param cfg: configuration of the agent :param env: :param agent: :return: """ print("========= Start to Evaluation ===========") print("Environment:{}, Algorithm:{}".format(cfg.env, cfg.algo)) for i_episode in ...
34,799