content
stringlengths
22
815k
id
int64
0
4.91M
def binary_close(fig, size=5): """ Joins unconnected pixel by dilation and erosion""" selem = disk(size) img = pad(fig.img, size, mode='constant') img = binary_closing(img, selem) img = crop_skimage(img, size) return Figure(img, raw_img=fig.raw_img)
5,297,800
def build_delete_item(obj): """Build div tag for delete details""" parent = "None" if obj.parent is not None: parent = obj.parent.name return ( "<ul><li>Serial: %s</li><li>Subject: %s</li><li>Parent: %s</li><li>Description: %s</li>" "<li>x509 Extension: %s</li><li>Created: %s</...
5,297,801
def get_user_token(user, purpose, minutes_valid): """Return login token info for given user.""" token = ''.join( dumps([ user.get_username(), get_auth_hash(user, purpose), ]).encode('base64').split('\n') ) return { 'id': get_meteor_id(user), 'token...
5,297,802
def commonChild(s1, s2): """ Finds the longest substrings of s1 and s2 that match and returns its length. """ # Traceback approach only needs to hold two rows of s2 (we assume characters in s2 make up the columns) tb = [[0 for _ in s2] for _ in range(2)] # DEBUG_MATRIX(s1, s2, tb) # Loop ...
5,297,803
def exm_put_map(arg0, arg1, arg2, arg3): """ exm_put_map(int exoid, int map_type, int map_id, const int* map_values) exoid: an open exodus file descriptor map_type: one of EX_NODE_MAP, EX_EDGE_MAP, EX_FACE_MAP, EX_ELEM_MAP map_id: the target map id map_values: the map values; length is t...
5,297,804
def cell_content_to_str(v): """ Convert the value of a cell to string :param v: Value of a cell :return: """ if v: if isinstance(v, float) or isinstance(v, int): return str(int(v)) else: return str(v).strip() else: return None
5,297,805
def create_haar_state(num_qubits: int): """Create a random Haar quantum state Args: num_qubits (int): number of qubits Returns: qiskit.QuantumCircuit """ psi = 2*np.random.rand(2**num_qubits)-1 psi = psi / np.linalg.norm(psi) qc = qiskit.QuantumCircuit(num_qubits, num_qubit...
5,297,806
def partition_layers(layers, split=2): """ partitions the each layer of a list according to the layer # and number of elements """ layers_partitioned = [] for i in range(len(layers)): num_parts = split ** i layer_partitioned = partition_list(layers[i], num_parts) layers_partitioned....
5,297,807
def enter_file(file_type, file_path=""): """Request file path from user until path exists. Parameters ---------- file_type: str Type of file to display in input line file_path: str (optional) Initial file path to try """ while not os.path.exists(file_path): file...
5,297,808
def __hamming_distance_with_hash(dhash1, dhash2): """ *Private method* 根据dHash值计算hamming distance :param dhash1: str :param dhash2: str :return: 汉明距离(int) """ difference = (int(dhash1, 16)) ^ (int(dhash2, 16)) return bin(difference).count("1")
5,297,809
def _van_es_entropy(X, m): """Compute the van Es estimator as described in [6].""" # No equation number, but referred to as HVE_mn. # Typo: there should be a log within the summation. n = X.shape[-1] difference = X[..., m:] - X[..., :-m] term1 = 1/(n-m) * np.sum(np.log((n+1)/m * difference), axi...
5,297,810
def insert_coke(message): """Function to add ingested coke. Parameters ---------- message : telebot.types.Message The message object. Returns ------- msg : success or failure message - to be displayed at Telegram's chat. """ message_text = message.text.lower().split(' ') ...
5,297,811
def exit(): # real signature unknown; restored from __doc__ """ exit() (exit_thread() is an obsolete synonym) This is synonymous to ``raise SystemExit''. It will cause the current thread to exit silently unless the exception is caught. """ pass
5,297,812
def safelyexecutenativecode(binary_file_name, arglist): """ <Purpose> Experimental! Executes code in an arbitrary programming language that was compiled using the toolchain. <Arguments> binary: The file name of the binary to launch. arglist: A list of strings that should be used as the comman...
5,297,813
async def async_browse_media( hass: HomeAssistant, media_content_type: str, media_content_id: str, cast_type: str, ) -> BrowseMedia | None: """Browse media.""" if media_content_type != DOMAIN: return None try: get_url(hass, require_ssl=True, prefer_external=True) except ...
5,297,814
def main(): """Main function""" module = GcpModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent'], type='str'), name=dict(type='str'), access=dict( type='list', elements='dict', options...
5,297,815
def is_internal_ip(ip): """ 判断是否为内网ip :param ip: :return: """ if ip in ('127.0.0.1', '0.0.0.0', 'localhost'): return True ip = ip_into_int(ip) net_a = ip_into_int('10.255.255.255') >> 24 net_b = ip_into_int('172.31.255.255') >> 20 net_c = ip_into_int('192.168.255.255') >>...
5,297,816
def include_agents(agent_ids): """ Include agents in scheduling, meaning that the given agents will be considered to be ready for creating new session containers. """ try: with Session() as session: session.Manager.scheduler_op('include-agents', agent_ids) print_done('The...
5,297,817
def part_3b_output_equilb_NVT_started(job): """Check to see if the equilb_NVT (set temperature) gomc simulation is started.""" return gomc_simulation_started(job, equilb_NVT_control_file_name_str)
5,297,818
def readAllSopv(sopvFilepath, logger = None): """Return information of all registered scanposes in VOCS.""" sopvs = [] first_line = True with open(sopvFilepath, 'r') as f: for line in f: if first_line: first_line = False continue sopvs.appe...
5,297,819
def _min_to_sec(minutes): """converts minutes to seconds, assuming that input is a number representing minutes""" return minutes*60
5,297,820
def get_ip(request) -> str: """ 获取当前请求的ip地址 :param request: :return: """ if request.META.get('HTTP_X_FORWARDED_FOR', None): ip = request.META['HTTP_X_FORWARDED_FOR'] else: ip = request.META['REMOTE_ADDR'] return ip
5,297,821
def make_figure_template(data_dir): """ make_figure_template """ colors, markers, _ = get_colors_markers_linestyles() # x axis file name f_n_x = "fname_x.csv" # y axis file name f_n_y = "fname_y.csv" # figure name fig_name = "test.jpg" data_x = np.loadtxt(os.path.join(data_d...
5,297,822
def aggregate_argmax(z_mean, z_logvar, new_mean, new_log_var, labels, kl_per_point): """Argmax aggregation with adaptive k. The bottom k dimensions in terms of distance are not averaged. K is estimated adaptively by binning the distance into two bins of equal width. Args: z_mean: Mean...
5,297,823
def file_list_check(list_name): """检查分割符是否复合要求""" if len(list_wrong) == 0: logger.info( correct_print( list_name.split(os.sep)[-1] + " DATASET.SEPARATOR check")) else: logger.info( error_print( list_name.split(os.sep)[-1] + " DATASET.SE...
5,297,824
def get_user(): """ Get a single user from the database. """ wilbur = Person.fetch_one({'name':u'Wilbur'}) if not wilbur: print 'No result.' return for field in Person.fields(): print '%s: %s' % (field, getattr(wilbur, field))
5,297,825
def get_file_data_old(archivo): """ Separa del nombre del archivo y extrae nombre de Centroide (ctrd) y cultivo (clt) """ diccionario = {} listado = archivo.split('-') diccionario['ctrd'] = listado[0] condicion = 'TS(S2)' in listado[1] or\ 'TS(TC)' in listado[1] or\ ...
5,297,826
def compress_launchers(input_dir: Path, output_dir: Path, launcher_paths: List[str]): """ create directories & zip :param input_dir: :param output_dir: :param block_name: :param launcher_paths: :return: """ for launcher_path in launcher_paths: out_dir = Path(output_dir) / ...
5,297,827
def mask_rcnn_loss(mask_outputs, mask_targets, select_class_targets, params): """Computes the mask loss of Mask-RCNN. This function implements the mask loss of Mask-RCNN. As the `mask_outputs` produces `num_classes` masks for each RoI, the reference model expands `mask_targets` to match the shape of `ma...
5,297,828
def get_error_handler( request: web.Request, config: Optional[Config] ) -> Optional[_Handler]: """Find error handler matching current request path if any.""" if not config: return None path = request.rel_url.path for item, handler in config.items(): if match_path(item, path): ...
5,297,829
def py_typed(**kwargs): """Creates a `resources` target for the `py.typed` file in this directory.""" if "name" not in kwargs: kwargs["name"] = "py_typed" if "sources" not in kwargs: kwargs["sources"] = ["py.typed"] resources(**kwargs)
5,297,830
def add_pacman_stuff(maze, max_food=60, max_capsules=0, toskip=0): """ add pacmen starting position add food at dead ends plus some extra """ ## parameters max_depth = 2 ## add food at dead ends depth = 0 total_food = 0 while True: new_grid = copy_grid(maze.grid) depth += 1 num_added =...
5,297,831
def test_add_to_dirty_repo(directory_tree, runner, project, client): """Test adding to a dataset in a dirty repo commits only added files.""" with (client.path / 'tracked').open('w') as fp: fp.write('tracked file') client.repo.git.add('*') client.repo.index.commit('tracked file') with (clie...
5,297,832
def subject_stats_comparison(combined_df): """ Calculates the percentage of subjects with an exclusion and the rate of exclusions per patient. Parameters: combined_df: A DataFrame in the format provided by prepare_for_comparison Returns: A DataFrame with run names as the index and the colu...
5,297,833
def flip_randomly_left_right_image_with_annotation(image_tensor, annotation_tensor): """Accepts image tensor and annotation tensor and returns randomly flipped tensors of both. The function performs random flip of image and annotation tensors with probability of 1/2 The flip is performed or not performed fo...
5,297,834
def dict_squares(n: int) -> Dict[int, int]: """Generates a dictionary with numbers from 0 to n as keys which are mapped to their squares using dictionary comprehension. doctests: >>> dict_squares(2) {0: 0, 1: 1, 2: 4} >>> dict_squares(5) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} ...
5,297,835
def tproject ( tree , ## the tree histo , ## histogram what , ## variable/expression/list to be projected cuts = '' , ## selection/weighting criteria nentries = -1 , ## number ...
5,297,836
def dfl_local_dir(): """ Infers a default local directory, which is DFL_DIR_PARENT/<project name>, where the project name is guessed according to the following rules. If we detect we're in a repository, the project name is the repository name (git only for now). If we're not in a repository, a...
5,297,837
def main(): """ Build NamedBird objects :return: """ # Read Clements list CSV data clements_csv = open('clements_usca_mod.csv') csv_reader = csv.reader(clements_csv) # List for new NamedBirds built_birds = [] # Build NamedBirds for r in csv_reader: new_bird = NamedBi...
5,297,838
def factor_cartesian(table): """Factor a cartesian products of lists The function unrolls a cartesian product of lists. The table argument is a list of sequences and the output is a tuple of lists Example: >>> factor_cartesian([('a1','b1'),('a1','b2'),('a2','b1'),('a2','b2')])...
5,297,839
def saveTrainingValidationSplit(train_indices, val_indices, outputFolder): """ Saves the training/validation split into MATLAB. Parameters ---------- train_indices : float array Original indices that have been put into the training data set. val_indices : float array Original indices that have been put into ...
5,297,840
def parse_args(): """ Initializes command line arguments and parses them on startup returning the parsed args namespace. """ parser = argparse.ArgumentParser() bot = parser.add_argument_group('Discord Bot') bot.add_argument( '--token', '-t', required=True, type=str, ...
5,297,841
def _palettize_seq(seq): """" seq must be a sequence of 3-d numpy arrays with dtype np.uint8, all with the same depth (i.e. the same length of the third dimension). """ # Call np.unique for each array in seq. Each array is viewed as a # 2-d structured array of colors. depth = seq[0].shape[-...
5,297,842
def convert_params_headers(incoming: Optional[MutableMapping[str, Any]]) -> None: """ Converts a str, Any mapping to a str, str mapping. :param incoming: :return: Useful for converting header and param dicts for requests before send, as many libraries require all values be strings. Di...
5,297,843
def _fetch_bundle_contents_blob(uuid, path=''): """ API to download the contents of a bundle or a subpath within a bundle. For directories, this method always returns a tarred and gzipped archive of the directory. For files, if the request has an Accept-Encoding header containing gzip, then th...
5,297,844
def get_parents(model): """ Return the list of instances refered as "parents" of a given model instance. """ result = list() options = getattr(model, 'RoleOptions', None) if options: parents_list = getattr(options, 'permission_parents', None) if parents_list: for ...
5,297,845
def main() -> None: """main.""" parser = argparse.ArgumentParser( description="Synchronize Scoutnet email lists with GSuite groups." ) parser.add_argument( "--limit", dest="limit", metavar="N", type=int, help="Only process n groups (dangerous!)", ) ...
5,297,846
def leave_timestamp(f): """Write the current date & time to a file""" with open(f, 'w') as f_out: f_out.write(str(datetime.datetime.now()))
5,297,847
def _setDNSCache(): """ DNS缓存 """ def _getaddrinfo(*args, **kwargs): if args in _dnscache: # print str(args) + " in cache" return _dnscache[args] else: # print str(args) + " not in cache" _dnscache[args] = socket._getaddrinfo(*args, **kwargs) ...
5,297,848
def test_get_flux_directions_exception(): """Tests whether thermal flux files note found exception is raised correctly""" k_par = k_parameters.copy() k_par['prefix'] = 'wrong-name' with pytest.raises(FluxFileNotFoundError): get_flux_directions(os.path.join(trial_dir, 'Run1'), k_par=k_par)
5,297,849
def create_word2vec(all_questions, embeddings_dim, window, workers, min_count): """ Create the word2vec model""" model = gensim.models.Word2Vec(sentences=all_questions, size=embeddings_dim, window=window, workers= workers, min_count=min_count) # vocab size words = list(model.wv.vocab) print("vocab...
5,297,850
def velocity_line_trajectory(start, end, velocity, sampling_rate=0.01): """ start and end being n dimentional points, velocity a float value (meter per seconds) and the sampling rate between two points, returns a list of instance of States corresponding to a point going from start to end at the...
5,297,851
async def test_dhcp_discovery(hass): """Test we can process the discovery from dhcp.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_DHCP}, data={ ...
5,297,852
def test_role_owner_and_mem(): """Create a new fake role and try to add yourself to role you created""" with requests.Session() as session: # create test user user_payload = { "name": "Susan S", "username": "susans2224", "password": "12345678", "em...
5,297,853
def isEqual(*, value): """ Check that a numeric value is equal to {value} """ from .Equal import Equal return Equal(value)
5,297,854
def wrap_coro(coro, unpack, *args, **kwargs): """ building a coroutine receiving one argument and call it curried with *args and **kwargs and unpack it (if unpack is set) """ if unpack: async def _coro(value): return await coro(*args, *value, **kwargs) else: async def _co...
5,297,855
def rasterizeSourcePositionList(shape, led_pattern, illumination_source_position_list_na=[], objective_numerical_aperture=0.25, objective_magnification=10, syst...
5,297,856
def list_to_dict(list: List, name_key: str = "name", value_key: str = "value"): """ Returns a key-value pair dictionary with given list of dictionary having `name` and `value` keys or custom keys. """ if not is_list(list): raise AttributeError( "Argument must be a list, invalid a...
5,297,857
def _one_grid_to_points( axes: GridPointsLike, *, dim_domain: int, ) -> Tuple[np.ndarray, Tuple[int, ...]]: """ Convert a list of ndarrays, one per domain dimension, in the points. Returns also the shape containing the information of how each point is formed. """ axes = _to_grid_poi...
5,297,858
def mAP(results, k=200, AP=True): """ Arguments : results = related images list for sorted file list k = mAP@k AP = whether return AP list for each images return : mAP value """ aps = [] for truth, result in enumerate(results): result = result[:k] ...
5,297,859
def hint_is_specialized(hint: Any, target: Any) -> bool: """Checks if a type hint is a specialized version of target. E.g., hint_is_specialized(ClassVar[int], ClassVar) is True. isinstance will invoke type-checking, which this methods sidesteps. Behavior is undefined for simple type hints that don't t...
5,297,860
def compute_selection_criteria( blast: Dict[str, Union[int, float]] ) -> Dict[str, Union[int, float]]: """Calculate a series of parameters used to discriminate which entries should be kept to search for a core genome from a series of blast files (*.bl)""" criteria = dict() criteria["coverag...
5,297,861
def _stack_init_aicpu(): """StackInit aicpu register""" return
5,297,862
def _get_matching_project_config(cfg, prj): """ Returns best match project configuration for given solution configuration. """ with error_context(prj): # If the project doesn't have any configurations, it means that we # failed to parse it properly, presumably because it defines its ...
5,297,863
def test_RunAssembly_defaults(util, short_read_mngs_bench3_viral_outputs): """ On default settings, the assembly_out_contigs_fasta and assembly_out_contigs_all_fasta files should be identical (because all contigs for this test dataset pass the default min_contig_length filter) """ assembly_conti...
5,297,864
def build_spc_queue(rxn_lst): """ Build spc queue from the reaction lst for the drivers :return spc_queue: all the species and corresponding models in rxn :rtype: list[(species, model),...] """ if 'all' in rxn_lst: # First check if rxn_lst is a bunch of species spc_queue = r...
5,297,865
def patch_telomeres(bands_by_chr): """Account for special case with Drosophila melanogaster """ for chr in bands_by_chr: first_band = bands_by_chr[chr][0] start = first_band[1] if start != '1': stop = str(int(start) - 1) pter_band = ['pter', '1', stop, '1', st...
5,297,866
def cluster_sites(mol, tol, give_only_index=False): """ Cluster sites based on distance and species type. Args: mol (Molecule): Molecule **with origin at center of mass**. tol (float): Tolerance to use. Returns: (origin_site, clustered_sites): origin_site is a site at the cente...
5,297,867
def get_comment_notification_targets(comment): """ Gets a list of comments that should get a notification about this new comment :param PostComment|AnswerComment comment: :param set user_ids: set of user_ids to exclude :return: returns a tuple, first item is comments to notify, sec...
5,297,868
def build_model(params: dict, build_options: dict = None) -> CompartmentalModel: """ Build the compartmental model from the provided parameters. """ params = Parameters(**params) # Get country/region details country = params.country pop = params.population # Create the model object ...
5,297,869
def gen_spewer_method(name, args): """Generates spewer code for a single opcode.""" method_name = "spew" + name # Generate code like this: # # void spewGuardShape(CacheIRReader& reader) { # spewOp(CacheOp::GuardShape); # spewOperandId("objId", reader.objOperandId()); # spe...
5,297,870
def cir_LRsRQRQ(w, Rs, L, R1: Optional[float] = None, Q1: Optional[float] = None, n1: Optional[float] = None, fs1: Optional[float] = None, R2: Optional[float] = None, Q2: Optional[float] = None, n2: Optional[float] = None, fs2: Optional[float] = No...
5,297,871
def test_only_fatal(emitter, config, monkeypatch, tmp_path): """Show only fatal lint results (the rest may be ignored).""" # fake results from the analyzer linting_results = [ linters.CheckResult( name="check-lint", check_type=linters.CheckType.lint, url="url", ...
5,297,872
def smallest_positive_integer_not_in_array(arr: List[int]) -> int: """ [1..N] can cover everything from 1 to (N * (N+1) / 2) """ res = 1 for num in arr: if num > res: return res else: res += num return res
5,297,873
def module_enclosing_func(offset): """ Test function to see if module-level enclosures are detected """ def module_closure_func(self): """ Actual closure function, should be reported as: putil.tests.my_module.module_enclosing_func.module_closure_func """ self._exobj.add_e...
5,297,874
def out_of_bounds_replace(llhs, params, out_of_bounds): """ replace out of bounds llh evals with large, valid values""" llhs[out_of_bounds(params)] = NAN_REPLACE_VAL return llhs
5,297,875
def fourier_sum ( func , N , xmin , xmax , fejer = False ) : """Make a function/histiogram representation in terms of Fourier series >>> func = lambda x : x * x >>> fsum = fourier_sum ( func , 4 , -1 , 1 ) >>> print fsum >>> x = ... >>> print 'FUN(%s) = %s ' % ( x , fsum ( x ) ) """ ass...
5,297,876
def get_retrieval_model(params): """ This method returns the Retrieval class requested in the parameter dict. Args: params(dict): A dict of parameters. In this method, the parameters 'logger' and 'query_generation', and 'search_engine' are required. Based on the requested retrievel model, so...
5,297,877
def trigrams(docs): """create trigrams""" return [trigram_model[bigram_model[doc]] for doc in docs]
5,297,878
def test_pandas(test_data): """Test creating chart data source from existing dataframe.""" ds = ChartDataSource.from_data(test_data.pd_data) assert len(ds.columns) == 2 assert len(ds.index) == 4 ds = ChartDataSource(test_data.pd_data) assert len(ds.columns) == 2 assert len(ds.index) == 4
5,297,879
def optimize(name: str, path: str, clazz: Type[ClassifierMixin], extra: Dict[Any, Any], space: Dict[str, Any], x_train: DataFrame, y_train: DataFrame, x_dev: DataFrame, y_dev: DataFrame, numbers: bool, scaler: StandardScaler, timeout: int, window_size: int) -> None: """ Trains a single...
5,297,880
def concat_imgs(in_files, out_file=None): """ Use nilearn.image.concat_imgs to concat images of up to 4 dimensions. Returns ------- out_file: str The absolute path to the output file. """ import nilearn.image as niimg return niimg.concat_imgs(in_files)
5,297,881
def conv_2d(in_nodes, nb_filter, filter_size, strides=1, padding='same', activation='relu', bias=True, weights_init='truncated_normal', bias_init='truncated_normal', regularizer=None, weight_decay=0.001, trainable=True, restore=True, reuse=False, name="conv_2d"): """ ...
5,297,882
def newWindow(): """Create a new tmux window and make it current.""" global totalPanes global MAX_PANES if totalPanes < MAX_PANES: tcmd("new-window") totalPanes += 1
5,297,883
def run(args=None, cwd=None): """Run a cake build with the specified command-line args. @param args: A list of command-line args for cake. If this is None sys.argv is used instead. @type args: list of string, or None @param cwd: The working directory to use. If this is None os.getcwd() is used instead. ...
5,297,884
async def reboot(machine): """Reboot the named machine. :param machine: Machine to reboot :type machine: str :returns: Nothing :rtype: None """ try: await model.async_run_on_machine(machine, 'sudo init 6 & exit') # await run_on_machine(unit, "sudo reboot && exit") except...
5,297,885
def tensor_repr(fra_data, dtype=None): """Creates a tensor representation of the FRA.""" dtype = dtype or tf.float64 res = dict() res["fixing_date"] = tf.convert_to_tensor( fra_data["fixing_date"], dtype=tf.int32) res["fixed_rate"] = tf.convert_to_tensor( fra_data["fixed_rate"], dtype=dtype) con...
5,297,886
def sleep(x): """Sleep that works in both coro and non-coro environments.""" if GOT_CORO and coro.coro_is_running(): coro.sleep_relative(x) else: time.sleep(x)
5,297,887
def update_static_nodes(dag, nodes, funcs, col): """ Updates the non-root nodes for a static DAG factory """ with col: for node in [node for node in nodes if node not in dag.roots]: kwargs = get_kwargs(node, funcs) val = funcs[node].func(**kwargs) if isinstanc...
5,297,888
def find_section_clamping_values(zlevel, lowerfract, upperfract): """Find int8 values that correspond to lowerfract & upperfract of zlevel histogram From igneous (https://github.com/seung-lab/igneous/blob/master/igneous/tasks/tasks.py#L547) """ filtered = np.copy(zlevel) # remove pure black fr...
5,297,889
def get_levels(content, language=None): """ Returns a list of integers whose value is for the content of the same index. :param content: Either a list of strings, or a list of dictionaries that contain 'content' and 'language' keys. :param language: Optional, only needed if only passing in a list of str...
5,297,890
def OP_stop(FF_state): """Exits the state machine, allows us to output data""" print("We have executed ", FF_state.counter, " Flip Flops")
5,297,891
def test_similar_duds(): """Run test low/high similar duds to ensure correct between size.""" tester = tester = gi_components.Components(ewlaps, DEFAULT_EASY) assert len(tester.low_similar_duds) + len(tester.high_similar_duds) >= 25 # LOW for low in tester.low_similar_duds: assert isinstance...
5,297,892
def losses(args): """Set up ``losses`` dict which stores model losses per epoch as well as evaluation metrics""" losses = {} keys = ["D", "Dr", "Df", "G"] if args.gp: keys.append("gp") eval_keys = ["w1p", "w1m", "w1efp", "fpnd", "coverage", "mmd"] if not args.fpnd: eval_keys.r...
5,297,893
def read_search(search_id: int, search_repository: repository.search_repository.SearchRepository = fastapi.Depends(), user: auth.authentication.User = fastapi.Depends(auth.authentication.get_current_user)): """ Get the details for a previously submitted search request. Parameters: ...
5,297,894
def mask_colorize(mask, num_classes, color_map): """ transfor one mask to a maske with color :param mask: mask with shape [h, w] :param num_classes: number of classes :param color_map: color map with shape [N, 3] """ color_mask = Image.fromarray(mask.astype(np.uint8)).convert('P') color...
5,297,895
def parse_config(filename): """Parses github-snooze-button configuration files. Args: filename: The name of a file in ConfigParser .ini format, described below. Returns: A dictionary of dictionaries, one inner dictionary per repository. Default values from the [default]...
5,297,896
def load_vehicles(country, vehicles, last_updated): """Load list of vehicles from given country into database.""" clean_vehicles(country) with elastic() as client: for vehicle in vehicles: vehicle.save(using=client) upsert_metadata(country, last_updated) return True
5,297,897
def get_ini_conf(fname): """ Very simple one-lined .ini file reader, with no error checking """ with open(fname, "r") as handle: return {i.split("=")[0].strip(): i.split("=")[-1].strip() for i in handle.readlines() if i.strip()}
5,297,898
def calc_ratios2(roi,edict,which=0): """ edict is a dictionary containing the event information. Calculate for each photon the ratio of the source to the background. """ #ens = [[b.emax for b in roi.bands if b.ct==0],[b.emax for b in roi.bands if b.ct==1]] ens = [[b.emax for b in roi.bands if b...
5,297,899