content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_vggm_rcnn_test(num_classes=config.NUM_CLASSES): """ Fast R-CNN Network with VGG :param num_classes: used to determine output size :return: Symbol """ data = mx.symbol.Variable(name="data") rois = mx.symbol.Variable(name='rois') # reshape rois rois = mx.symbol.Reshape(data=ro...
f24522fb0eab9655efc34e44ae754248e5837861
3,613,600
def generative(f): """ A decorator to wrap query methods to make them automatically generative. """ @wraps(f) def wrapped(self, *args, **kwargs): self = self._generate() f(self, *args, **kwargs) return self return wrapped
1181b622fdf61f163bad7a20596e1ecc614a82f0
3,613,601
def get_aws_region(): """ Get the caller's AWS region from the environment variable AWS_REGION :return: the AWS region name (e.g. us-east-1) """ region = environ.get("AWS_REGION") if not region: raise EnvironmentVariableError("Missing AWS_REGION environment variable.") return region
46917b0d515fe1da3986cb3ff3c9b5895378c45e
3,613,602
def flat(list_object): """ [(1,2), (3,4)] -> [1, 2, 3, 4]""" return sum([list(item) for item in list_object], [])
e78dc614a42b0acf2858601b38052f8509053a45
3,613,603
from typing import Mapping from typing import Sequence def json_doc_replace(doc, pointer, value=None, search=None): """ Search and replace list element while iterating through the list and keep its index. :param doc: :param pointer: :param value: :param search: :return: """ re...
b2f62cbb75ced82e8bf8402a0abae6f251913c61
3,613,604
def get_download_variables(dataset: str, country: str, end_date: str, config_path: str): """ Function to get downlaod variable for a particular dataset from config file This could be simplified """ # Get config variables from repository config = get_config(config_path) # Extract dataset i...
ff4c2e65a59caf26bfd0e433fb30a784b0c78202
3,613,605
def get_subpattern_mutations(subpattern: dict) -> list: """Get rotated variations of given subpattern""" flattened = format_subpattern(subpattern) mutations = [flattened] for i, layers in enumerate(flattened): copied_layers = flattened[:] # copy original layers rotated = rotate_la...
513f521c13d61160c5a7397664c8bd86618c1d39
3,613,606
def tokenize(text): """ Creates tokens from sentences using WordNetLemmatizer :param text: string :return: list of tokens """ tokens = word_tokenize(text) lemmatizer = WordNetLemmatizer() clean_tokens = [] for tok in tokens: clean_tok = lemmatizer.lemmatize(tok).lower().stri...
e8b25dc1da2476948010ed0d368ad6d2ccf107bb
3,613,607
import numpy def is_same_transform(matrix0, matrix1): """Return True if two matrices perform same transformation. >>> is_same_transform(numpy.identity(4), numpy.identity(4)) True >>> is_same_transform(numpy.identity(4), random_rotation_matrix()) False """ matrix0 = numpy.array(matrix0, d...
5b2d9eeffb314a54f1cb41d6e58f2aedce0e78de
3,613,608
import os import subprocess def _run_pandoc(uploaded_file, new_file_name, file_path): """ Run pandoc and report output messages :param uploaded_file: uploaded file :param new_file_name: converted file name :param file_path: source path :param options_json: optional path to the `converti` comm...
2cfb290693ea878fae0b968bc4c9e999afebccc4
3,613,609
def composable(func): """ Decorates a callable to support function composition using ``|``. For example: .. code-block:: python @Composable.decorate def add1(x): return x + 1 def mult2(x): return x * 2 composed = add1 | mult2 """ return Co...
2d970a7b4719834dc9c8c01804ee807c18de14a1
3,613,610
import pathlib def hg_remote_repo(remote_repos_path: pathlib.Path): """Pre-made, file-based repo for push and pull.""" return _create_hg_remote_repo( remote_repos_path=remote_repos_path, remote_repo_name="dummyrepo", remote_repo_post_init=hg_remote_repo_single_commit_post_init, )
a6a7c7e49f822fcafa052e4b662497d1b70ab4e2
3,613,611
def index(): """Sign In controller""" return render_template('signin.html')
fa3497324fa7a6c092d4a7deadf5d6856d9bec5d
3,613,612
def q_parse_color(color): """ Convert a color string into a QColor. Parameters ---------- color : string A CSS3 color string to convert to a QColor. Returns ------- result : QColor The QColor for the given color string """ rgba = parse_color(color) if rgba is N...
2d462af78848785d432e3d78864d6a0d1dbd1af7
3,613,613
def draw_right_hand_box(data): """ Displays the cropped image with a red box around the right hand. Parameters ---------- data : dict The input data. Returns ------- hand : numpy.ndarray The cropped image with the right hand boxed in red. """ box = data['rhb'][d...
e7b7a36a578e5655472ffca3542675387537a7e0
3,613,614
def get_instance(api): """ Generate a TrelloCard instance """ return TrelloCard('card_id', api, '123', '987')
ec9aaf32b522282a24539ac546366dce2c8ff559
3,613,615
def nrWords(text): """Scrieti o functie care returneaza numarul de cuvinte din string. Cuvintele sunt separate de spatii, semne de punctuatie (, ;, ? ! . ). """ list = text.replace(',', ' ').replace('.', ' ').replace(';', ' ') list = list.replace('!', ' ').replace('?', ' ').split() return len(...
5703481391d3a4043df070e8f224a136e4023fe1
3,613,616
import sys from datetime import datetime def execute(command_line, directory = None, \ print_timing_info = False, shell='/bin/bash', \ grab_output = True, ignore_exit_code = False, \ input_string = None, auto_decode=True, decode_using=sys.stdout.encoding): """Run an operating syste...
af393e23b55fd49881da86655ae8f7f8487590dd
3,613,617
def create_or_update_product(request, product_id): """ Implements POST /products/<id> and PUT /products/<id> """ try: user = Token.objects.get(key=request.META[AUTH_TOKEN_LABEL]).user data = get_request_data(request) tags = get_tags(request) if request.method == 'POST': # TODO Remove price and shop try...
fe5db7d2dd7196a2a75e06d2e3f7c1634d4ae735
3,613,618
def maskfalse(array: np.ndarray, mask: np.ndarray) -> np.ndarray: """ Replace False-masked items with zeros. >>> array = np.arange(10) >>> mask = np.random.binomial(1, 0.5, len(array)).astype(bool) >>> masked = maskfalse(array, mask) >>> (masked[mask] == array[mask]).all() True >>> (mask...
31d9f85c9a0d1298008554d4e5ec9dd08ee444f2
3,613,619
def read_file_by_line(filename) -> list: """Read the contents of the file by line :param filename: path to the file to be read :return: list with each line of the file in a different node """ return read_file(filename).splitlines()
e75d933d79b8cc1b967d13645e160c5e43a0fdd2
3,613,620
from swamp.wrappers.gesamt import Gesamt def Gesamt(*args, **kwargs): """:py:obj:`~swamp.wrappers.gesamt.Gesamt` instance""" return Gesamt(*args, **kwargs)
dde98595a90402ebb7ecc64e3de24a7a4894fecf
3,613,621
from typing import IO from re import U def prefetch_buffer(PULP_OBI=0): """ args: PULP_OBI: Legacy PULP OBI behavior """ # local parameters # FIFO_DEPTH also controls the number of outstanding memory requests # FIFO_DEPTH > 1 -> respect assertion in prefetch controller # F...
b6a979c735125d06728731860799e5f537c29185
3,613,622
def _RIPPER_growphase_prune_metric(rule, pos_pruneset, neg_pruneset): """ RIPPER/IREP* prune metric. Returns the prune value of a candidate Rule. Cohen's formula is (p-n) / (p+n). Unclear from the paper how they handle divzero (where p+n=0), so I Laplaced it. Weka's solution was to ...
5f6d4fefa0a1b06658309fcc882bd889791648d8
3,613,623
def clim_regr_values(n_cascade_levels, outdir_path, n_model=0, skill_kwargs=None): """Obtains the climatological correlation values and regression parameters from a file called NWP_weights_window.bin in the outdir_path. If this file is not present yet, the values from :cite:`BPS2004` are used. Paramet...
6104fa89f20c43dad4813bac974c55059b390ef4
3,613,624
import os import subprocess def create_srpm(dist='el7'): """Create an srpm Requires that sources are available in local directory dist: set package dist tag (default: el7) """ if not RPM_AVAILABLE: raise RpmModuleNotAvailable() path = os.getcwd() try: specfile = spec_fn() ...
aa8ce173b790b1ae8e8c78b825b4324769294b40
3,613,625
def variational_loss(input, img, model, beta_ten, z=None): """ Computes negative ELBO loss with scaling beta for KL part. :param input: [mean, logarithm of the covariance diagonal] :param img: datapoints :param model: vae model for probability computations :param beta_ten: tensor with scaling p...
33cbdf11f7b0b9bee15766d51642133e6d4ad9be
3,613,626
def get_collect(): """ Returns: obj (Collect) """ return Collect()
54bf6292604fc50ce3fe236607d5813c6c17097d
3,613,627
def rid(num): """Translate from id to rid""" return num-1
9080d1d2fa9329ee5678800c2d55f3228d0ffb79
3,613,628
from typing import Sequence import glob async def notes(p: 'Player', c: Messageable, msg: Sequence[str]) -> str: """Retrieve the logs of a specified player by name.""" if len(msg) != 2 or not msg[1].isdecimal(): return 'Invalid syntax: !notes <name> <days_back>' if not (t := await glob.players.ge...
7a82933cfa3c95c80ab4a439de292c8c0d2ff274
3,613,629
def revert_dict(dct): """Revert {a: [lits of b's]} to {b: [list of a's]}.""" reverted = defaultdict(list) for k, value in dct.items(): for v in value: reverted[v].append(k) verbose(f"chain_genes_data dict reverted, there are {len(reverted.keys())} keys now") return reverted
80c2f89ddd2c472cf34a0b40ca8fec39fb0396c5
3,613,630
def close_up_to_column_sign(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): """SVD can produce sign flips on a per-column basis.""" kwargs = dict(rtol=rtol, atol=atol, equal_nan=equal_nan) if np.allclose(a, b, **kwargs): return True ret = True for acol, bcol in zip(a.T, b.T): ret &=...
f041ee3ce9e1e36c877ef7bc5ec271e04099322f
3,613,631
import requests def postSync(content: str, *, url: str = None, retry: int = 5, find_fallback_on_unavailable: bool = True, find_fallback_on_retry_runout: bool = False): """ Creates a new haste :param content: Union[str, Iterable] - the content to post to hastebin. If this is a list, it will ...
24b8494ecfa99362c15eb50e0d78ec12cfaea120
3,613,632
def sketch_2x1s(pixel_positions, mpl_axes=None): """ Draw a rough sketch of the layout of the CSPAD Parameters ---------- pixel_positions : np.ndarray The x,y,z coordinates of the pixels on the CSPAD """ if pixel_positions.shape not in [(4,8,185,388,3), (4,8,185,388,3), (4,8,185...
7fc01ef29b02cef864556a62e5642f529d7af9cc
3,613,633
from typing import Tuple def stack_fixture(stack_function_fixture) -> Tuple[str, str]: """ Fixture that creates a dummy stack with dummy resources. :return: Tuple, where first element is stack name, and second element is stack id. """ return stack_function_fixture()
379d4f4202bcf197d855efe72ca84c7c1a319acd
3,613,634
import sqlite3 def create_connection(db_file): """ Create a database connection to the SQLite database specified by the db_file db_file: database file return: Connection cursor or None """ try: c = sqlite3.connect(db_file) conn = c.cursor() return conn except Error as e: print(e) return None
b1f4b7bbd3e32a907dbf66970c17296921387317
3,613,635
import os import urllib def get_resource(x, fmt='text'): """Return contents of file or URL x :param binary: Resource is binary. Return bytes instead of a string. """ is_binary = fmt != 'text' # Try to retrieve from in-memory cache if x in cache_dict: return cache_dict[x] if '://'...
746c26360334e89588bc46291a3f42dce59a563e
3,613,636
def decode_logs(logs): """ Decode logs to events and enrich them with additional info. """ decoded = _decode_logs(logs) for i, log in enumerate(logs): setattr(decoded[i], "block_number", log["blockNumber"]) return decoded
adae93ca35897ff7fcf28abbfde6c61502e2be02
3,613,637
def make_decorator(func): """ Wraps a test decorator so as to properly replicate metadata of the decorated function, including nose's additional stuff (namely, setup and teardown). """ def decorate(newfunc): if hasattr(func, 'compat_func_name'): name = func.compat_func_name ...
bb76f9589abd0b31d008072664e470f16000e208
3,613,638
def calendar_from_alias(calendar_alias): """Get a Calendar object from its alias. Parameters ---------- calendar_alias : str Returns ------- out : Calendar object Notes ----- This is mostly a mapping from the calendars of the CF conventions to built-in calendars. """ ...
81e02f486abae4f3eb50eb4a827a92b8c6bfec28
3,613,639
import logging def edge_select_transform(data, edge): """ Data selection and transformation between tasks Data transfer between tasks is handled by edges that define rich data mapping and selection criteria to match input of the next tasks to the output of the previous task. Supported transf...
6f092fd9558b6aa0262f7aacc94e77bac125b0c2
3,613,640
def add_allocation_config(config, cache): """ config["components"] maps Allocation name that can be found in csv to allocation_id :param config: :param cache: :return: """ allocation_root = cache.get_xml_tree("allocation") allocation_config = {} for allocation in allocation_root.find...
63df5aaf0b70dbdb17da8a706480be4baa7570d0
3,613,641
import logging import torch def model_training_earlystopping( data_loader_train, data_loader_valid, ml_model_name, ml_model, loss_function, nb_epochs, is_cuda, smiles_dictionary, max_length_smiles, device_to_use, learning_rate, path_to_parameters, patience=10, ): ...
8820f6707aa9619d202dbdb93e695ef0386699d8
3,613,642
def set_setup_py_version(version, content): """ Replace version in setup.py file using regex, g<1> contains the string left of version g<3> contains the string right of version :param version: string :param content: content of setup.py as string :return: content of setup.py file with 'versio...
0c59e72c5eb52f3a46a12f1c33b8e26c81ebca1e
3,613,643
def tile(x: Tensor, n_tile: int): """Tiles Tensor x n_tile times in dimension 0. :param x: [N x n] input to tile :param n_tile: number of times x will be repeated in dim 0 :returns: [N * n_tile x n] """ assert x.dim() == 2 assert n_tile >= 1 return x.repeat(1, n_tile).view(-1, x.size(1)...
9cb41c133387da4c66a44d79464e256cd804fac7
3,613,644
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI ...
48814a2de61d88a4c12fd88989d472358f549ec0
3,613,645
import time import json from pathlib import Path def create_index(): """Create a new relationships index with a timestamp suffix.""" # Get the mapping mapping_path = current_search.mappings['relationships-v1.0.0'] # Create a timestamp-suffixed index ts = str(time.time()) index_name = f'relati...
4356db18f3ea6b1f25fbe2433ee19d9bdee1de1e
3,613,646
def find_downstroke_indexes(v, t, peak_indexes, trough_indexes, clipped=None, filter=10., dvdt=None): """Find indexes of minimum voltage (troughs) between spikes. Parameters ---------- v : numpy array of voltage time series in mV t : numpy array of times in seconds peak_indexes : numpy array of...
7eef10d8b2be604ee3fe0fda7cd3c7d330441213
3,613,647
import os def train_model(base_model, training_generator, validation_generator, output_dir, loss=None, batch_size=64, num_epochs=100, patience=20, learning_rate=1e-4): """ Train a model with the given data. Parameters ---------- model X_train y_train out...
9ae4dbba35e6795e7d781d3c9cc947a93e611338
3,613,648
def get_trace_component_for_trigger_instance(trigger_instance_db): """ Returns the trace_component compatible dict representation of a triggerinstance. :param trigger_instance_db: The TriggerInstance to translate :type trigger_instance_db: TriggerInstanceDB :rtype: ``dict`` """ trace_compo...
227ad1cd5ed8bafd1fc2904f78d8bc9114b7eb0e
3,613,649
def smart_merge(guesses): """First tries to merge well-known similar properties, and then merges the rest with a merge_all call. Should be the function to call in most cases, unless one wants to have more control. Warning: this function is destructive, ie: it will merge the list in-place. """ ...
1b73dd74b399d300817c74a716ca5eb3c26fe90f
3,613,650
def arrange_df(df, df_type, relevant_col_idx=None, items_to_delete=None, assembly_df=None, bom_trim=False): """ :param bom_trim: :param df: pandas.DataFrame object that contains the raw format that is read from the file. :param df_type: File type of :param relevant_col_idx: :param items_...
d81547a87386cf0970bfe52c4efebfdda6993cc2
3,613,651
def postvar(sum2, n, a, b): """ Parameters ---------- sum2 n a b Returns ------- out """ return (0.5 * sum2 + b) / (n / 2.0 + a - 1.0)
be89d743f79771c78ca45b98df4ac8f6a39ac971
3,613,652
import httpx def _handle_retry(exc, no_of_retries): """Handle errors which qualify for retry""" retry = False no_of_retries += 1 sleep_time = _get_sleep_time_seconds(no_of_retries) msg = f"Got error: {exc} Retrying in {sleep_time} secs, attempt {no_of_retries}" if isinstance(exc, httpx.HTTPSta...
23ed7ac5e5c211e2d4fc510bbca35c8db9f74616
3,613,653
def get_sqrt_square_average(read_data_list): """ sqrt(x1^2 + x2^2 + ... + xn^2) """ tx_len = len(read_data_list[0]) rx_len = len(read_data_list[0][0]) sqrt_square_average = [([0.0] * rx_len) for i in range(tx_len)] for i in range(len(read_data_list)): for j in range(len(read_data_lis...
27433cdd9c3ffbf3da234b67149ffdf4d457af46
3,613,654
from typing import Optional def get_ols_url_prefix(prefix: str) -> Optional[str]: """Get the URL format for an OLS entry. :param prefix: The prefix to lookup. :returns: The OLS format string, if available. .. warning:: This doesn't have a normal form, so it only works for OBO Foundry at the moment. ...
b979697f9646df6d460397bcfa963350b0e1fa78
3,613,655
import json def write_msg(msg): """ Add a new message to database """ if 200 in msg: msg = json.loads(str(msg[200])) for i in msg: """ insert each unique app into db """ msg = {"event_type": i['id'], "event_description"...
b0827abeb7a0dff48610723d7480e5a92162d755
3,613,656
from datetime import datetime import dateutil def create_trial_name(exp_name, exp_id=0, seed=0): """ Create a semi-unique experiment name that has a timestamp :param exp_name: :param exp_id: :return: """ now = datetime.datetime.now(dateutil.tz.tzlocal()) timestamp = now.strftime('%Y_%m...
983f538c8c1f61022815860bc351fb8d4fad5826
3,613,657
def move_to_rough_home(esp, rig_ax): """Move calibration rig to desired rough home position (i.e. "move to TSH +X UP or TSH -Y UP, etc."). Parameters ---------- esp : ESP object driver for Newport's ESP 301 motion controller. rig_ax: str designation for rough home position (+x, -...
a3e831334fed8c44bcd49b89d7a0882393383da6
3,613,658
def new_case_study_from_file(): """ Check that the user is authorized to submit a new case study Open a reproducible session Send the file to the service Close the reproducible session :return: """ # Check Interactive Session is Open. If not, open it isess = deserialize_isession_and...
34797f88f25138f07dc32742019b5ccea208946c
3,613,659
import os def _extract_trend_params(): """ Extract required parameters for tools task like forecast algorithm and database path. :return: parameter dict. """ return {'forecast_alg': config.get('forecast', 'forecast_alg'), 'database_dir': os.path.realpath(config.get('database', 'dat...
466b2f7d29ba00aa682cef7d97f182f1cd09c706
3,613,660
def _make_decimal(n: str, b: int, pos: int) -> int: """Suppose we have a number n=xyz (represented as string) in base b. The algorithm of converting it to a decimal representation is as follows. b⁰ * decimal_value(z) + b¹ * decimal_value(y) + b² * decimal_value(x), where decimal_value(z) is the d...
0f57d34d46746a0eaa956165485f58e0b1313b94
3,613,661
def argmax(l,f=None): """http://stackoverflow.com/questions/5098580/implementing-argmax-in-python""" if f: l = [f(i) for i in l] return max(enumerate(l), key=lambda x:x[1])[0]
51e480cc579b5be37266fecd44359a4984c9ac6e
3,613,662
def IsEnabled(test, possible_browser): """Returns True iff |test| is enabled given the |possible_browser|. Use to respect the @Enabled / @Disabled decorators. Args: test: A function or class that may contain _disabled_strings and/or _enabled_strings attributes. possible_browser: A PossibleBrow...
a51835a29cdc0b6909986af7a698cc9d40213f39
3,613,663
def flatten_list(a_list): """Given a list of sequences, return a flattened list >>> flatten_list([['a', 'b', 'c'], ['e', 'f', 'j']]) ['a', 'b', 'c', 'e', 'f', 'j'] >>> flatten_list([['aaaa', 'bbbb'], 'b', 'cc']) ['aaaa', 'bbbb', 'b', 'cc'] """ # isinstance check to ensure we're not iteratin...
49baca675cfa59a4cf7b813bc10c12f16d0960bd
3,613,664
import math import random def connected_double_edge_swap(G, nswap=1): """Attempt nswap double-edge swaps in the graph G. A double-edge swap removes two randomly chosen edges u-v and x-y and creates the new edges u-x and v-y:: u--v u v becomes | | x--y x y ...
00c83c2ce4e4e40cfa955128de884979cb68966e
3,613,665
def up(user_version: int) -> str: """Return minimal up script SQL for testing.""" return f""" BEGIN TRANSACTION; PRAGMA user_version = {user_version}; CREATE TABLE Test (key PRIMARY KEY); COMMIT; """
2cd7f9204bddeea94d392f40dc91fcfcb9464632
3,613,666
def _generateVariants(seq, possibleAA = None): """Given peptide seq, return all POSSIBLE single AA mutants OR 2 random single AA mutants per position in seq Return a list of variants and a dictionary of variants:(posi,newAA)""" variantsInfo = {seq:(np.nan,'ORIGINAL')} """If we know possibleAA then r...
b265a15a90b0511e76a53f15f632190d300dc400
3,613,667
import pathlib def indexRepo(repo=None, redisGraphConn=None, rediSearchConn=None): """ do indexing on repository object with redisConn connection """ if(repo != None): client = None _repo = repo if(redisGraphConn != None and rediSearchConn!=None): graphName = _repo....
2c6901af1641530815428099d02e84c2ff5c2ac4
3,613,668
from typing import Union def mask_to_seeds(mask: np.ndarray, method: str = 'sitk', output: str = 'mask', binary: bool = True ) -> Union[np.ndarray, list]: """Find centroid of all objects and return, either as list of points or labeled mask ...
33e85b99cc352630b24b997977503889b42b8209
3,613,669
import tensorflow as tf def assign_weights(pt_state_dict, pretrained_prefix=None): """Load pytorch state_dict and assign to tensorflow model.""" vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) vars.pop(0) pt_state_dict = {k: v for k, v in pt_state_dict.items() if 'num_batches_tracked' not in k...
e6ef944fb692ee9f4110d355f8512640f145e912
3,613,670
def create(*, db_session, **kwargs) -> Storage: """Create a new storage.""" storage = Storage(**kwargs) db_session.add(storage) db_session.commit() return storage
e25cf5163c45847b7842f679321db7442519ebbe
3,613,671
def magic_foo5(self, args): """ A docstring. """ return parse_argstring(magic_foo5, args)
3c3da95ac5fad5792b8448a6adf92a4b6790a0f0
3,613,672
from typing import Tuple import math def make_coef_surface(p1: Point, p2: Point, p3: Point) -> (float, float, float, float, Tuple[float, float, float]): """ Вычисление коэффициентов плоскости A, B, C, проходящую через три точки p1, p2 и p3, и вектора нормали N к этой плоскости. :param p1: Первая точка...
7ec385ba83a994a688ae43b276635c44fa9021f7
3,613,673
import types def populate_array(array, data, shape, strides, itemsize, meminfo, parent=None): """ Helper function for populating array structures. This avoids forgetting to set fields. """ context = array._context builder = array._builder datamodel = array._datamodel ...
d01058fd78a4f7fc16114531868f6e4da9ee2723
3,613,674
def bubbles_from_kmeans(data, upper_lim=True, n_jobs=1, n_clusters=3): """ @ Giri at al. (2018a) It is a method to identify regions of interest in noisy images. The method finds the optimal threshold using the 1D PDF of the image. It gives similar results compared to the Otsu's method. Parameters ---------- d...
674c28300547dfffac9d2f6c6ad755c4082f6475
3,613,675
def clean_and_reformat_mapping(in_fp, out_fp, body_site_column_name, exp_acronym): """Simplify the mapping file for use in figures in_fp : input file-like object out_fp : output file-like object body_site_column_name : specify the column name for body exp_acronym : sh...
2d7a20b796aac6f4f40e767cc593addefc3b22ac
3,613,676
import time def one_model(input_val, y_val, fn, fn_kwargs={}, k_folds=1, random_state=15, verbose=False): """ 1-fold task, mean and std of results are calculated over 1 folds Params: input_val: (np.array) 2-D array holding instances (features) of validation set. y_val: (np.array) ...
51d2cab990307695bc32360f1bb964f9e2d4b641
3,613,677
from .utility import Utility def hash256_result(func): """Secure the return string of the annotated function with SHA256 algorithm. If the annotated function doesn't return string or return None, raise ValueError.""" @wraps(func) def _wrapped_func(*args, **kwargs): val = func(*args, **kwargs) ...
26f8daaa02b0e96406ab30494fa2b0bb55a26e36
3,613,678
def resize_walls(walls: np.array, factor: int): """ Increase the environment size by rescaling. Parameters ---------- walls : np.array 0/1 array indicating obstacle locations. factor : int Factor by which to rescale the environment Returns ------- walls : np.array ...
47b4a1fd8cb3dd1c3ae47301a51ff6656f44fb07
3,613,679
import math def _dp_graph31_ ( dp , npoints = 250 , masses = False ) : """Make a graph of Dalitz plot: s3 vs s1 >>> d = Dalitz (5 , 0.1 , 0.2 , 0.3 ) >>> graph = d.graph31 () >>> graph.draw ('al') """ points = _dp_points_ ( dp , npoints ) pnts = [ ( p[0], dp.s3( p[0] , p[1] )...
e4a6ee493f77ad7daea59e2a453a080a4a3d5324
3,613,680
def meters_to_pixels(meters_x, meters_y, level_of_detail): """converts XY point from Spherical Mercator EPSG:900913 to ZXY pixel coordinates """ res = ground_resolution(0, level_of_detail) # ground resolution at equator x = int((meters_x + origin_shift) / res) y = int((meters_y + origin_shift) / re...
350b0e365aab38f8495b346ecb838a3a24bb979e
3,613,681
def get_matches(lf, candidate_set, match_values=[1,-1]): """ A simple helper function to see how many matches (non-zero by default) an LF gets. Returns the matched set, which can then be directly put into the Viewer. """ matches = [] for c in candidate_set: label = lf(c) if label...
d541719409b07c95b3327315999066336f9438f3
3,613,682
def get_credential_options(user, *, challenge, rp_name, rp_id, icon_url): """ Returns a dictionary of options for credential creation on the client side. """ options = pywebauthn.WebAuthnMakeCredentialOptions( challenge, rp_name, rp_id, str(user.id), user.username, user.name, icon_url ) ...
658c23a002bf9721c5f21e067adc94c46bdb30c3
3,613,683
import requests def get_store_inventory(username): """ Fetches the inventory of the Bricklink store with the given username. """ # 1: fetch the whole store front (because BL sucks) front_url = 'https://store.bricklink.com/{username}#/shop?o={opts}'.format(username=username, ...
c43d3279efe05e0de4e05f1d96da05581b3195d6
3,613,684
def audioSample(fileOne, fileTwo, name_prefix, time_manager, controller=None, arguments={}, analysis={}): """ Confirm fileTwo is sampled from fileOne :param fileOne: :param fileTwo: :param name_prefix: :param time_manager: :param arguments: :return: @type time_manager: VidTimeManager...
114d37462c3a45430723d3167d05584191650f4f
3,613,685
def get_meraki_switchports_status(org_name, device_name): """Query Meraki for Port Status for a Switch.""" dashboard = meraki.DashboardAPI(suppress_logging=True) return dashboard.switch.getDeviceSwitchPortsStatuses(_name_to_serial(org_name, device_name))
d1f3c64edbdc455797d8edbbc1429a8534c1a1e1
3,613,686
def metaclass(inherit=object): """Create a custom metaclass to make the attribute use the `__set__` method. Normally `class.variable = value` would simply change the class value. By using a metaclass you can force `class.variable = value` to call the variable's `__set__` method. Args: inherit ...
51480c1d5226a94938367fff7d8ca556be7aa793
3,613,687
import re import collections def get_noun_term_freq(df, option='N'): """ Returns noun morphemes and freqeuncy - input : dataframe, {option : compound noun decomposition flag, default : N} - output : list of tuples(morpheme, frequency) """ _noun_type = ['NNG', 'NNP'] _terms = [] fo...
33d711207955e457aab8d83757eb2fea642e07d7
3,613,688
def swish(x): """Swish activation function. Arguments: x: Input tensor. Returns: The swish activation applied to `x`. """ return nn.swish(x)
0cccd66f95d9b3fd4d822d328472c3a8e757f755
3,613,689
def get_connection_string(): """ Reads from the local FS to get the RabbitMQ location to connect to. Returns: A string representing the location of RabbitMQ. """ rabbitmq_ip = file_io.read(RABBITMQ_LOCATION_FILE) return 'amqp://guest:guest@' + rabbitmq_ip + ':' + \ str(RABBITMQ_PORT) + '/...
deb6fbc7d43d343bd12b8410ae3eaaa749296171
3,613,690
def getRecipients(test_data): """ Returns, as a string, the email addresses of the student's parents for the given test """ recipients = [] if test_data["MotherEmail"] != "": recipients.append(test_data["MotherEmail"]) if test_data["FatherEmail"] != "": recipients.appen...
d4b7896a0a4293601031463240c85001ce8430de
3,613,691
def get_kitti_frame(sample): """ Get KITTI depth image and point cloud Args: sample: KITTI sample object Returns: scene depth and point cloud """ H, W, _ = sample['image'].shape # Filter out lidar points outside field of view scene_lidar = sample['lidar'] frustum = build_v...
bab3311a06708a6a32b5245d22ee7bbf09daa989
3,613,692
def haddock_ref(haddock_host, haddock_root, pkg, module, func_name): """ Return a reference link to Haddocks for pkg/module#func_name. """ if module == None and func_name == None: return pkg_root_ref(haddock_host, haddock_root, pkg) else: func_name = convert_special_chars_to_ascii(f...
674ef7065d54fae0053a6f2945d53bed7f27983d
3,613,693
from .config import Section def format_print_text(text: str, *, color_fg: str = None, color_bg: str = None) -> str: """Format given text using ANSI formatting escape sequences. Could be useful for print command. :param text: :param color_fg: text (foreground) color :param color_bg: text (backgro...
5e988bb693d9c4ad1efd9a2718c72eba1d27c9b2
3,613,694
def get_emb_sz_list(dims: list): """ For all elements in the given list, find a size for the respective embedding through trial and error Each element denotes the amount of unique values for one categorical feature Parameters ---------- dims : list a list containing a number of integers....
65509869e99f08bbbd1fbaf7a7d3fe364e55b053
3,613,695
def evaluate_topic_models(data, varying_parameters, constant_parameters=None, n_max_processes=None, return_models=False, metric=None, **metric_kwargs): """ Compute several Topic Models in parallel using the "gensim" package. Calculate the models using a list of varying parameters `...
5cec9eeb505bffd6d8300b787c14f8823d28bd0d
3,613,696
from typing import Union def convert_weblogo_color(color: Color, color_format: str) -> Union[tuple, str]: """Convert weblogo Color to Bokeh color object Note: Weblogo colors are RGB but fractional [0, 1], whereas Bokeh and draw_alignment are [0, 255] :sa: https://github.com/WebLogo/weblogo/blob/mast...
56838285486880cd04a036c19989d5f0ee6f6307
3,613,697
def BenfordDQ(impath): """ Main driver for ADQ3 algorithm. Args: impath: Input image path, required to be JPEG with extension .jpg Returns: OutputMap: Output of ADQ3 algorithm (2D array). """ if impath[-4:] == '.jpg': try: im = jio.read(impath) excep...
59dec79063c84a3e9d8608e8d6af2400641113ae
3,613,698
def yuanshan_weir_ecological_base_stream_flow(): """ Real Name: YuanShan Weir Ecological Base Stream Flow Original Eqn: 198720 Units: m3 Limits: (None, None) Type: constant 2.3cms, equals 198720 m^3 per day """ return 198720
adebe3b4b18400903a54cf9d537ec6d8ec57c9a0
3,613,699