content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Tuple from typing import List from typing import Dict def find_folders(root: str, file_client: FileClient) -> Tuple[List[str], Dict[str, int]]: """Find classes by folders under a root. Args: root (string): root directory of folders Returns: Tuple[List[...
d01c41a6fad24c1d869042b1af5980f099510e2d
3,616,200
import torch def matrix_to_homogeneous(batch: torch.Tensor) -> torch.Tensor: """ Transforms a given transformation matrix to a homogeneous transformation matrix. Args: batch: the batch of matrices to convert [N, dim, dim] Returns: torch.Tensor: the converted batch of matrices ...
ab3bf1acf1e8fab2d4a4fcdcfd062821bc891b9d
3,616,201
from typing import Callable def council_member(func: Callable[..., R]) -> CouncilMember[R]: """ a function decorator to create an appropriate member :param func: the function to wrap :return: a CouncilMember that will call func, ignoring council_state unless a parameter of that name exists in fu...
5aad18808b62dba6de1ea586f60e2d33ffe8da9a
3,616,202
def setup(hass, config): """Setup the Buspro component. """ host = config[DOMAIN][CONF_HOST] port = config[DOMAIN][CONF_PORT] name = config[DOMAIN][CONF_NAME] hass.data[DOMAIN] = "<buspro>" #load_platform(hass, 'light', DOMAIN, {'optional': 'arguments'}) #load_platform(hass, 'light', ...
5c7fcdce7e0b8ee87b598c1fb0ba53e0ef4720ef
3,616,203
import time import yaml def LoadScene(filepath: str): """ Loads spyke scene from given file and makes the scene current. param filepath: Scene filepath. """ def readline(): nonlocal file line = file.readline() if not line: raise EOFError return line.replace('\n', '') start = time.perf_counter() ...
a445a79448480296621975352da544c587b3fe59
3,616,204
def check_output(output): """Check if output contains any error. Several commands return output which we need to return back to the caller. But, before we return anything back we want to perform a sanity check on on the output in order to catch wrong input as it is impossible to perform any sanitiz...
f1d4e64bd6a98cae23ae6c536dcb85c2d4c38024
3,616,205
import json def englishToFrench(EnglishText): """Translate english to french.""" translation = language_translator.translate( text=EnglishText, model_id='en-fr').get_result() jsonStr = json.dumps(translation, indent=2, ensure_ascii=False) data = json.loads(jsonStr) for i in data['translat...
626f8e813b6316143afc147395cc4827406b48dd
3,616,206
def nulls_first(column: _ColumnExpressionArgument[_T]) -> UnaryExpression[_T]: """Produce the ``NULLS FIRST`` modifier for an ``ORDER BY`` expression. :func:`.nulls_first` is intended to modify the expression produced by :func:`.asc` or :func:`.desc`, and indicates how NULL values should be handled whe...
cd3f9cdcb8120cab3cdf38b4b370d64ba97bf97d
3,616,207
import struct def readHeader(fd): """read protocol header""" data = fd.recv(6) value = struct.unpack(">bib", data) return value
6f1ac379f9eb1f5862754dd10fced9a817bb664a
3,616,208
def load_default_item(monkeypatch) -> Item: """Save a default item object, and return the object""" default_category = MockCategory.default_category() save_mock_category(monkeypatch, default_category) default_item = MockItem.default_item(parent_category=default_category) save_mock_item(monkeypatch, ...
0f6085e592b9318418477a6eded7ec65778bbbc7
3,616,209
import tqdm def encode_vocab(data, word2ind): """Converts string tokens to indices based on given dictionary.""" dialogs = data['data']['dialogs'] print("[%s] Encoding caption tokens..." % data['split']) for i, dialog in enumerate(tqdm(dialogs)): dialogs[i]['caption_tokens'] = [word2ind.get(wo...
cc67720badc41d8f46af361e5efad4ea2aed7e2a
3,616,210
def get_RSI(df, column='Close', time_window=14): """Function to make the RSI values for a given stock dataframe""" # Differential between the Column diff = df[column].diff(1) # Integrity of the difference values up_chg = 0 * diff down_chg = 0 * diff # We consider the upchange as positive...
dca6f44062b8dbc04444f033d2e3b54075ad2ca6
3,616,211
def text_classification_mappings(): """Text classification index mappings""" return { "_source": mappings.source( excludes=[ # "words", # Cannot be exclude since comment text_length metric is computed using this source fields "predicted", "pre...
da83494f73308bec0c7e56ff196d44cfa1902e03
3,616,212
def use_mapping(*args): """ use_mapping(ea) -> ea_t Translate address according to current mappings. @param ea: address to translate (C++: ea_t) @return: translated address """ return _ida_bytes.use_mapping(*args)
1fdab28dbbba25d33a01e1f53a81f46f5ce99cbc
3,616,213
def get_oldest_timestamp(data, additional_groups_to_ignore, additional_tags_to_ignore, print_all_tags=False): """data as dictionary from json. Should contain only time stamps except SourceFile""" # save only the oldest date date_available = False oldest_date = None oldest_keys = [] # save src...
fa2212adebacc2713b76ad436b354fec6e733de3
3,616,214
def get_pascal_voc_colors(): """Load the mapping that associates pascal classes with label colors Returns: np.ndarray with dimensions (21, 3) """ num_cls = 21 colors = [0] * (num_cls * 3) colors[0:3] = (0, 0, 0) # 0: 'road' colors[3:6] = (128, 0, 0) # 1 'sidewalk' colors[6:9] ...
5638e802587763d77350ad0642cadae54167a6b7
3,616,215
def orth_complement(A, B): """Returns the orthogonal complement of A in B """ rank_a = A.shape[1] C = jnp.hstack([A, B]) Q, R = jnp.linalg.qr(C) return Q[:, rank_a:]
53f0317c38d81113f616927d56661de139c8c278
3,616,216
import json import sys def __api_operation_prep(log, arguments): """ API Operation Common Functionality """ # Parse the user data example_user_config_json = "{\n 'user': <username>," \ "\n 'apikey': <apikey>\n}\n" try: user_data = json.load(argument...
703ca6ba3b1d2472c8acbbadb41dc18cc1a69e9d
3,616,217
def get_grouped_data(input_data, feature, target_col, bins, cuts=0): """ Bins continuous features into equal sample size buckets and returns the target mean in each bucket. Separates out nulls into another bucket. :param input_data: dataframe containg features and target column. :param fe...
f63bf9680107f1fc6f50d5e79faa64d29ce9db00
3,616,218
from typing import List def get_trajectory_from_environment( environment: tf_py_environment.TFPyEnvironment, observation: List[List[float]], predicted_action: int) -> trajectories.Trajectory: """Gets trajectory data from `environment` based on observation and action. Aligns `environment` observation ...
6dcd4d9b4f2628d560f7cca0234453d5af69d259
3,616,219
def resize_nd_skimage(img, size, order=1, **kwargs): """ Resize the input numpy array image to the given size. Args: img (numpy array): Image to be resized. size (tuple): Desired output size. order (int, optional): Desired interpolation. Default is 1 kwargs: other parameters for...
df34f5717b6699687279b8aef3b111994f6956c2
3,616,220
def MAXA(*args) -> Function: """ Returns the maximum numeric value in a dataset. Learn more: https//support.google.com/docs/answer/3094016 """ return Function("MAXA", args)
5f19796115365c0b7e19fd0c6529d22d28d5998c
3,616,221
def row_data(data): """handle tuple (row) data arrival""" if is_ok(data): return OK(data) if is_eof(data): if len(data) < 9: return EOF(data) return OK(data) return Packet(data)
d34873a082071a51c2dcbf269c1c74a76e2e3be8
3,616,222
def timelined_cb(data, command, rc, stdout, stderr): """Very generic callback in case timelined acts weird.""" global buffers buf = buffers[data] name = wc.buffer_get_string(buf, "name") stream = data + "STREAM" del(hooks[stream]) wc.buffer_close(buf) print_error("timelined for %s exited...
8510f6715773af5290d947963412cd63aa138023
3,616,223
import os import io def cli(kilosort_folder=None, do_parallel=True, do_pc_features=True, do_silhouette=True, do_drift=True, fs=3e4): """ Calculate metrics for all units on one probe""" # kilosort_folder = '~/res_ss_full/res_ss/tcloop_train_m022_1553627381_' if kilosort_folder is None: kilosort_fol...
4553a590bc70fddce3fab7df993e28ae132d6b83
3,616,224
import re import logging def get_gpu(): """Returns video device as listed by WMI. Not cached as the GPU driver may change underneat. """ wbem = _get_wmi_wbem() if not wbem: return None, None client = _get_win32com() dimensions = set() state = set() # https://msdn.microsoft.com/library/aa394512...
653c99f5539fafda3a7d8a641adc08c14b7b732b
3,616,225
def tfnormalize(X): """ Skip connection layer normalization. """ sh = np.shape(X) X_norm = tf.contrib.layers.layer_norm(X, trainable=False) return X
5eabf19bc7cd376af6638c092b452a239b5650d3
3,616,226
def do_filter(parser, token): """ Filters the contents of the block through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter force_escape|lower %} This text will be HTML-escape...
edd2b6ee87615a24f7f9124da5eb95b3752d7028
3,616,227
def find_ch_interest_dict(show_channel_dict : dict, usr_pref_dict : dict): """Pass in show_channel_dict {show:channels} and usr_pref_dict {show: rating}. Returns dictionary {channel : total rating}""" ch_interest_dict = {} for show in usr_pref_dict: if show in show_channel_dict: if show_...
9928b03c0ceea3ea38c3808a5fd4053553f4e5c4
3,616,228
async def discover_source_aliases(serial_port=None): """ Discover the alias configured for each input Cycle through the device sources and get the alias from the feedback message Restore the original source (which we can only do once we know its alias) Note that: - the device will be powered o...
e3a8ae0eb07d9ccc53b3150e4ad547398c4b2697
3,616,229
def compute_average_embedding(input_embeddings, input_lengths): """Computes bag-of-words embedding. Args: input_embeddings: <tf.float32>[bs, max_seq_len, emb_dim] input_lengths: <tf.int64>[bs, 1] Returns: bow_embedding: <tf.float32>[bs, emb_dim] """ max_seq_len = tf.shape(input_embeddings)[1] ...
471a56d680ec3194a48300f0d573bc54ab2708b7
3,616,230
def is_valid_int(s: str) -> bool: """ Return true if s can be converted into a valid integer, and false otherwise. :param s: value to check if can be converted into a valid integer :return: true if s can be converted into a valid integer, false otherwise >>> is_valid_int("hello") False >>> ...
9d2c849839f6fdcf729a7c1503a3eac3daa5f000
3,616,231
def validate_report_input(X, y_true=None, y_pred=None, y_prob=None, prtc_attr=None, priv_grp:int=1): """ Raises error if data are of incorrect type or size for processing by the fairness or performance reporters Args: X (array-like): Sample features prtc_attr...
d159ad9cec76e0030b881545f82f5aea81cb9849
3,616,232
def gap_statistic(X, Wk, n_components, n_trials=100, reference='uniform', n_jobs=1, random_state=None): """Calculate gap statistic for k-means clustering.""" rng = check_random_state(random_state) random_seeds = [] for _ in range(n_trials): has_seed_already = True wh...
c31bf0ac3ed664a43e49d73b514c62ca76b9f976
3,616,233
from datetime import datetime import pytz def date_to_milliseconds(date_str): """Convert UTC date to milliseconds If using offset strings add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/ :param date_str: date in r...
2d9d4142627f10a8691280f10ead852ce5b1d2ee
3,616,234
import argparse def _build_validator_subparser( subparser_action: argparse._SubParsersAction, base_subparser: argparse.ArgumentParser, ) -> argparse.ArgumentParser: """Returns the base subparser with arguments required for every validator. Returns: argparse.ArgumentParser: validator subparser...
12a532e260f1ae5fb766c5686988425ddea52b19
3,616,235
import re def InstanceNameRegexpValidator(): """Returns a function that validates an instance name using predefined rules. Returns: function: str -> str, usable as an argparse type """ # : and . are not valid characters, but we allow them through this regex so # that we can give a better error message...
57b8004a4023bb5011f1ecabb8658785c396cead
3,616,236
def segmentation_metrics_blend( isolated_images, detected_segmentations, matches, noise_threshold, meas_band_num ): """Calculates segmentation metrics given information from a single blend. The true segmentation is obtained from the isolated images by setting to True the pixels above the noise_threshol...
8993780ab0d1c170bfc369d96cdc38f0b14ac087
3,616,237
def convert_RGB_to_OD(I): """ Convert from RGB to optical density (OD_RGB) space. RGB = 255 * exp(-1*OD_RGB). :param I: Image RGB uint8. :return: Optical denisty RGB image. """ mask = (I == 0) I[mask] = 1 return np.maximum(-1 * np.log(I / 255), 1e-6)
5e22600f1985aebe10a2472fb98f664facbd0f0a
3,616,238
def delete_profession(profession_id): """delete_profession Delete profession # noqa: E501 :rtype: Response """ # Remove evidences of this profession evidences = DBEvidence.query.filter(DBEvidence.evidence_profession == profession_id).all() for evidence in evidences: delete_evidenc...
9195220969d759d57f5f4412b1772b51f205b7ee
3,616,239
def process_remaining_mult_cases(chrom, positions, strand, edge_IDs, vertex_IDs, transcript_dict, gene_starts, gene_ends, edge_dict, locations, vertex_2_gene, run_info, cursor, tmp_gene): """ This function is a catch-all for multiexonic transcripts t...
b1afa70df1f3e1836c6a05bd6b85d97c21f656fb
3,616,240
def read_xlsx(filename: str, rows_count: int): """Читает документ xlsx и записывает данные в глобальную переменную названия телеграм каналов, локации и ссылки""" tg = [] worksheet = xlrd.open_workbook(filename, on_demand=True).sheet_by_index(0) for i in range(rows_count): tg.append({'name': work...
2ff498b9f942d0f91c8a4d4a679dcdfa9e4c0e3c
3,616,241
def HammerProj( lonlat, lon0=0.0 ): """Takes a point at the (longitude, latitude) point in lonlat (arg 1, in radians) and returns the (x,y) coordinates of the Hammer projection of that point. lon0 is the central longitude for the projection process (in radians). The x coordinate is in the range [-2*...
262623305e0ee794259446ecc5d470c39efd01ec
3,616,242
def confusion_matrix_to_accuracy(conf_mat): """ Convert confusion matrix to accuracy Parameters conf_mat: np.ndarray | pd.DataFrame: confusion matrix, length of columns and that of rows must be same. Returns accuracy: float64: accuracy """ if type(conf_mat) is pd.DataFrame: ...
2acb8bd8e2301b5f56c3371671a1ccb7c36848eb
3,616,243
import shutil def make_valid_param_card(path, restrictpath, outputpath=None): """ modify the current param_card such that it agrees with the restriction""" if not outputpath: outputpath = path cardrule = ParamCardRule() cardrule.load_rule(restrictpath) try : cardrule....
1c2111eacaa8afb1748581e7ceb3d25724c849b2
3,616,244
import socket from contextlib import closing from typing import Generator from typing import Any import time def multidevice_test_context(server_configuration: dict) -> Generator[MultiDeviceTestContext, None, None]: """Get generator for MultiDeviceTestContext.""" def _get_port() -> int: with closing...
c6b1eb644133b8ed927729269fab45851495ab94
3,616,245
from typing import Optional from typing import Any def deeplabv3_mobilenet_v2( pretrained: bool = False, progress: bool = True, num_classes: int = 21, aux_loss: Optional[bool] = None, **kwargs: Any ) -> nn.Module: """Constructs a DeepLabV3 model with a MobileNetV2 backbone. Args: ...
5a1dc413c3754d7b80aff584a7442ebd4af49564
3,616,246
def evaluate_compliance(configuration_item): """Check if given IAM user has a MFA device and return a string to be used for AWS config put_evaluations.""" if configuration_item['resourceType'] not in ['AWS::IAM::User']: return 'NOT_APPLICABLE', 'Not applicable.' if DEBUG_MODE is True: print(...
9cbf90090f0e2c0bbde1dae263a346bf730cc874
3,616,247
import os def process_sub_image(i, input_filepath, output_location, date_string, coords_string): """ Read file and run network centrality """ # open BWNDVI image sub_image = Image.open(input_filepath) image_array = pillow_to_numpy(sub_image) # run network centrality feature_vec, _ = ...
aac7ecd0330e597b64ce7b8707391e20c7ec4a07
3,616,248
from REDACTED.minigo.dual_net_edge_tpu import DualNetworkEdgeTpu from REDACTED.minigo.dual_net import DualNetwork import os def make_gtp_instance(load_file, cgos_mode=False, kgs_mode=False, minigui_mode=False): """Takes a path to model files and set up a GTP engine instance.""" # Here so we ...
c250992c0ef9f48412355d12f6beb3dfa1f6a940
3,616,249
import requests def fetch_minion_pool() -> dict: """ Fetch a new minion pool """ minions = [ minion for minion in requests.get(settings.CARD_DB_ENDPOINT).json() if minion.get("battlegroundsPremiumDbfId") ] pool = defaultdict(list) for minion in minions: pool[minion....
92539fc27f3c55058be72c00e4b37498fd306d64
3,616,250
def supprCouloir(grapheAmodif, noeud): """renvoie le graphe sans le couloir dans lequel se trouvait noeud""" #un noeud-couloir est un noeud qui a seulement 2 voisins, qui ne contient pas de pièce. #et aussi qui ne soit ni la position de départ du joueur, ni la position de départ de l'adversaire #supprim...
b9f36776b1afaeea4721d23968843d72e0bc1569
3,616,251
import os import errno import time from datetime import datetime def make_notebook(data, train_type='conv', field_size=61, ndim=2, transform='pixelwise', epochs=10, optimizer='sgd', skips=0, ...
78ab93871760d9e3b6c29c2a13a6c2b629434b94
3,616,252
def API_StackDriver(config, auth, iterate=False): """StackDriver helper configuration for Google API. Defines agreed upon version. """ api = { 'api': 'logging', 'version': 'v2', 'auth': auth, 'iterate': iterate } return API(config, api)
1c7125dddf7e822b60082f755e0af6cfea3486bd
3,616,253
import re import os import ast def from_file(f): """ Reads a namelist/configuration file and generates a Namelist object. Anything enclosed in ${...} will be expanded to a environment variable, while anything enclosed in %(...) will be expanded to a previously defined variable within the file....
9fc209c70fe81176b818525d793ca89e8c8c10b0
3,616,254
def con_K(x, y, beta, method='cdist', return_d=False): """con_K constructs the kernel K, where K(i, j) = k(x, y) = exp(-beta * ||x - y||^2). Arguments --------- x: :class:`~numpy.ndarray` Original training data points. y: :class:`~numpy.ndarray` Control points used t...
6f608bb7958b5756456d3c6cf3d4b3223ec1aea5
3,616,255
import torch def gin_predictor_nasbench_nlp(search_space, num_init=10, k=10, total_queries=150, acq_opt_type='mutation', allow_isomorphisms=False, ...
8025f8ec847531ef75213233d3f0df89c0db572f
3,616,256
def main(request: Request): """ Responds to an HTTP request. Parameters: ---------- request (flask.Request): HTTP request object. """ a.generate() return jsonify({"sucess": True})
eeb2317faeafcb141844c2a0ef2e0d20963bdc73
3,616,257
def manage(request): """ All-encompassing view for management stuff """ assert isinstance(request, HttpRequest) return render( request, 'app/manage.html', { 'title':'Dashboard', } )
b5bf4b86c58d21b29ea6c81d105dcc05f0a0c9e5
3,616,258
def accuracy_score(y_true: np.ndarray, y_pred: np.ndarray) -> float: """Accuracy classification score. Args: y_true (np.ndarray): correct target values. y_pred (np.ndarray): estimated targets as returned by a classifier. Returns: float: proportion of correctly classified samples. ...
24d5d6a113896d5c243ae492323c4d425179a8ec
3,616,259
def setup_logging_server(): """ Gets a testing server ready to go and returns the port being used""" port_to_try = 5000 # Try to get an open port 32 times for _ in range(0, 32): try: server = LoggingHTTPServer(('', port_to_try), UpdatingWebsite) return server ...
225a436ab95bb1ec4706a59020e67d8807a77d21
3,616,260
from typing import List from typing import Tuple def make_source_and_target_plates(target_df_list: List[pd.DataFrame], max_volume_ul: float = MAX_WORKING_VOLUME_UL ) -> Tuple[pd.DataFrame, pd.DataFrame]: """Generates optimized source and target pla...
d123584e9f4737809c77beb355c2dcd16f444b04
3,616,261
def path_along_circles( arc_angle: float, circles_centers: np.ndarray, axis: np.ndarray = OUT ) -> PATH_FUNC_TYPE: """This function transforms each point by moving it roughly along a circle, each with its own specified center. The path may be seen as each point smoothly changing its orbit from its starting...
885e2e3770f9bc2e53d2062a43fe404cb192b529
3,616,262
def svn_wc_create_notify_url(*args): """svn_wc_create_notify_url(char url, svn_wc_notify_action_t action, apr_pool_t pool) -> svn_wc_notify_t""" return apply(_wc.svn_wc_create_notify_url, args)
36a42320c94f29516cdc401a9f0e0e35d477cd60
3,616,263
def make_model(n_size, n_output): """Create Keras model.""" model = Sequential() model.add(LSTM(n_size)) model.add(Dense(n_output)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ret...
5c1c4bbc71f5b3fee81e7b3150c6277eb56c08c8
3,616,264
def humanize_seconds(total_seconds, frmt='{hours:02d}:{minutes:02d}:{seconds:02d}', negative_frmt=None): """Given time in int(seconds), return a string representing the time. If negative_frmt is not given, a negative sign is prepended to frmt and the result is wrap...
86b58fe361382671f744529c676cc6cd16c877a6
3,616,265
def joint_residual(params, args): """ Residual for joint_fit Input: param_dict - suggested parameters of the functions Sigma and eta to be fit args - arguments which remain fixed (e.g. r values) Output: residual - residual of the fit for the given parameters """ rA, Sigma...
12b4ba12dad0ab8f97e721b73dede80987c2caab
3,616,266
def _batch_gather(params, indices, axis, batch_dims): """Helper that implements the body for ragged gather() when batch_dims>0. Args: params: The tensor from which to gather values. indices: The indices of values to gather. axis: The axis in `params` to gather `indices` from. batch_dims: The number...
a7a73514ce7382fd67e0471792a27bc6e4502819
3,616,267
import typing import re def search(pattern: typing.Union[str, int], **kwargs): """Compare value to pattern using search.""" value = kwargs.pop('value') # type adaptation only if value is int if isinstance(value, int): value = type(pattern)(value) if config.TYPE_CHECK_LEVEL > 0...
e6989b053da4960f9cfb29fd4b0d21e8c2d31855
3,616,268
def get_base_info_for_selector(selection_dict, selector_type): """ Sets up the basic dictionary for data filters to be added on the data :param selection_dict: :param selector_type: :return: """ base_info_dict_for_selector = { OPTION_TYPE: selector_type, COLUMN_NAME: selectio...
c08fc9a95517c3388da69e3f9935c255ce0d73c6
3,616,269
def make_datasets(dataset, train_batch=None, test_batch=None, train_transforms=None, test_transforms=None, num_workers=1, **custom_args): """ Helper to make new instances of training and testing datasets. Args: dataset Case-sensitive dataset name train_batch Training batch size, None or 0 for ...
5c2090b9cbfb52c4cdb42f632dfe883c21465e9b
3,616,270
def get_sentiment_by_id(sentiment_id): """ Returns the sentiment with given id :param: sentiment_id ID of the sentiment :returns: Sentiment with given ID """ sentiments = [] cursor = current_app.mongo.keywords.find({"request_id": sentiment_id}) for record in list(cursor...
38fab08784267498fa09e1de35cd286c4a03f786
3,616,271
def clean_software_config(config): """Take an individual `config` data structure (as specified by config_validation.SoftwareSchema) and return a 'clean' version suitable for internal use. This allows for a simplified schema to be available to users whilst preserving consistent internal data structures b...
c89ad5a4b61e4214d4b79ce6782e4fe5a86311bf
3,616,272
def distance_A(A, D): """Takes distance matrix D and material attribute/category matrix A and finds the sum of the pairwise distances of each entry compared to D. This function should be used in an optimizer to generate an optimal A matrix. Implements first term of Equation 4 Parameters: D...
dd896e36565a8daf5951fac3ceb29594c70707bb
3,616,273
def get_word_by_name(name): """Get word detail by name As title --- tags: [word] parameters: - name: name description: 单词名字 in: path type: string required: true responses: 200: description: Word matched. schema: $ref: '#/defin...
d76eacc085d24f6c71ffe8ced3fe55f0933ff153
3,616,274
def group_peaks_naive_1pass_centroid(df, ppmtol=1.0): """Compute groups of peaks, naive, one-pass, control distance to centroid .""" # compute group indexes glabel = 0 start = 0 glabels = [0] reltol = ppmtol * 1.0e-6 m1 = df.loc[0, 'm/z'] samples = [df.loc[0, '_sample']] masse...
055f69644dc12d28fc6c477d497f2f32b6a8a593
3,616,275
import time def run_firfilter(no_trick, duration=0.000001): """[summary] Arguments: no_trick ([type]): [description] Keyword Arguments: duration (float): [description] (default: {0.000001}) Raises: Exception: [description] """ h0 = np.zeros(n) # initial x0 E = e...
fc2a223ce85113f8f8514cbae7e6688744b30214
3,616,276
def cdfinv_r(fName=None,pdf=None): """ Calculates the inverse of the cumulative distribution function for probability as a function of r. *** Arguments *** * fName * File name for retrieving sigma(r). If None, the user must define a function to calculate the inverse CDF. Otherw...
498a2960cbede769eac396130ec5e306a0978bf3
3,616,277
def _base_down(x, base=10): """ Floor `x` to the nearest lower ``base^n``, where ``n`` is an integer. Parameters ---------- x : float Number to calculate the floor from. base : float, optional Base used to calculate the floor. Return ------ float The nearest...
0489809838c9377b4114c751db34a4a81941ae57
3,616,278
def get_periodic_frame(): """ Construct a simple periodic table dataframe organised by group and row. Note that the lanthanides and actinides are each found in a single cell. Returns ------- :class:`pandas.DataFrame` """ table = pd.DataFrame(columns=np.arange(1, 19), index=np.arange(1,...
b5db8f2a0373c19fcea7ab0fe78cb8a4b7f0ade8
3,616,279
def miller_rabin_d(n: int) -> bool: """Check if n is a prime number via deterministic Miller-Rabin test. Miller showed that it is possible to make the algorithm deterministic by only checking all bases ≤ O(lg(n)^2). Bach later gave a concrete bound, it is only necessary to test all bases a ≤ 2lg(n)^...
ac668cb55e417a6784ba52d1c5da1dc26d3693ad
3,616,280
def get_path_upload_avatar(instance, file): """Построение пути к файлу, format: (media)/avatar/user_id/photo.jpg""" return f"avatar/user_{instance.id}/{file}"
d3169d68e4abee31ee9649548892c2dc960717cc
3,616,281
def is_category_url(url, ignore_exceptions=False): """This function identifies if a provided URL is for a category in the environment. .. versionadded:: 2.1.0 :param url: The URL to be evaluated :type url: str :param ignore_exceptions: Determines if exceptions should not be raised :type ignore...
53127f4eaa23d5c8029ab0e6783be026d6a7328e
3,616,282
import re def maximum_time(time: str) -> str: """ Takes in a time with a single digit of either the hour part or minute part hidden with ?. The format of the time is hh:mm. This returns the maximum possible time from the given input. @param time: time of format hh:mm with a single digit of either the ...
9bef83c27e7911c67172dbe41ca616c5adda1b17
3,616,283
def get_fd(file_or_fd, default=None): """Helper function for getting a file descriptor.""" fd = file_or_fd if fd is None: fd = default if hasattr(fd, "fileno"): fd = fd.fileno() return fd
7e8a5b91d010878bcc091fa9ef3b281431e34e19
3,616,284
from typing import List from typing import Callable def evaluate_predictions(preds: List[List[float]], targets: List[List[float]], metric_func: Callable) -> List[float]: """ Evaluates predictions using a metric function and filtering out invalid targets. ...
7b7f550a0983cbb8af90f13b214a195cdb8cbfe3
3,616,285
def recommend_size(args, img): """ Recommend size (in pixels) for populated image to reach 300 dpi""" current_ppi = 72.0/img.scale target_ppi = args.normal_ppi scale = target_ppi/current_ppi return (int(img.image.width*scale), int(img.image.height*scale))
b32a0520586984124ba2134dc99ecc0b71cd01df
3,616,286
def retain_top_pct(vals, pct_keep): """ Retain as many components as you need to capture `pct_keep` proportion of the overall value """ if pct_keep > 1 or pct_keep <= 0: raise ValueError( "Must set pct_keep between 0 and 1 be when using " "'retain_top_pct' retention ...
6530550c8c31a708806e035196a59cb76010221b
3,616,287
def test_curve_plot(): """ Tests mpl image of curve. """ well = Well.from_las(FNAME) fig = well.data['GR'].plot(return_fig=True) return fig
077ad46ea7012f032d85ebe92b9e9633b7228535
3,616,288
from pgdumplib import dump def new(dbname: str = 'pgdumplib', encoding: str = 'UTF8', converter=None): """Create a new :py:class:`pgdumplib.dump.Dump` instance :param str dbname: The database name for the dump (Default: ``pgdumplib``) :param str encoding: The data encoding (Default: ``UTF8``) ...
c41cffcc961b7a273bf9b7402af7a22401a738db
3,616,289
def audio(sec=3): """ Record audio for a given duration """ display(Javascript(RECORD_AUDIO)) s = output.eval_js('record(%d)' % (sec*1000)) b = b64decode(s.split(',')[1]) return Audio(b)
c4b6c43aa75a44a785b9f920e5e276a3d318847a
3,616,290
import sys def rename(location: str, file: str, new_name: str) -> str: """ Change file name via copy old file to file with new_name and delete(old_file) :param location: :param file: :param new_name: :return: str - new file path in s3 storage """ try: location = remove_start(st...
2b89fb16dfa7b4c36c30ebc18c998d8f102729fe
3,616,291
import os def get_latency(email, photo_name, processType): """This function returns latency for a processed image Args: email (string): user email for ID photo_name (string): which photo to load latency for processType (string): which process type to load Returns: latency...
a34a8c02dc0645e4d947c198c9b54c8d8c4f7d86
3,616,292
from .core import SegmentedImage from recipes import pprint import logging def detect_loop(image, mask=None, snr=3, npixels=3, deblend=True, dilate=0, edge_cutoff=None, max_iter=np.inf, group_name_format='sources{count}', model=None, opt_kws=None, report=None): """ ...
9eaa8e7cab463d7c7831565e6d662de796f0f98c
3,616,293
def isinstalled(name: str, lib_loc=None): """ Find whether an R package is installed :param name: name of an R package :param lib_loc: specific location for the R library (default: None) :rtype: a :class:`bool` """ instapack = InstalledPackages(lib_loc) return instapack...
a05dce14c5280aa96113933bf9dfd0141ffd2d5b
3,616,294
import math def create_experiment(run_config, hparams, model_name, problem_name, data_dir, train_steps, eval_steps, min_eval_frequency=2000, s...
31cbb1ba9948af5a3e84e864271e0888f4fdf448
3,616,295
def quit_hermit(): """usage: quit Exit Hermit. """ clear_screen() return True
1b27fdcb6a1fe69541f5f388e05e70b3731a5239
3,616,296
from typing import Union def flatten(x: Union[list, tuple]) -> list: """ Flattening function for nested lists and tuples Args: x: List or tuple Returns: object (list): Flat list """ if not isinstance(x, list) and isinstance(x, tuple): raise TypeError("input must be a ...
36c35dfbef4214ccf0f6d355f36865996fd6d88e
3,616,297
from typing import Mapping def update_nested(original_dict, update_dict): """Update a nested dictionary with another nested dictionary. Has equivalent behaviour to :obj:`dict.update(self, update_dict)`. Args: original_dict (dict): The original dictionary to update. update_dict (dict): The...
a1a372ac4d26066c3fe32cd4ee1a49fff6972cd9
3,616,298
def model(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 1500, minibatch_size = 32, print_cost = True): """ Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX. Arguments: X_train -- training set, of shape (input size = 1...
c45624090d044dcafaa254f8fb3c5a5340c3efaf
3,616,299