content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List from typing import Tuple def carree2pix(coord: List[float], area: List[Tuple[float]], image_size: List[int], origin: str = "upper") -> tuple: """ Convert Carree lat/long to image poxel position Arguments: coord(List[float]): (lat, l...
deebeab299f61bc28536cf44d98ae3a247615c36
58,300
import argparse def return_args(): """Get some args to start update classifiers.""" _parser = argparse.ArgumentParser(add_help=True, description=( "Get some args to pass to update_classifiers script.")) _parser.add_argument("-c", "--category", action="store", default="all", ...
0411ac2bf6ef670c8a8760e60e41c4395b67d513
58,301
import os import logging def configure_decoder(language): """Initialize a pocketsphinx Decoder with the appropriate configuration. TODO: Support language configuration """ config = pocketsphinx.Decoder.default_config() model_path = os.path.join("stt", language) logging.debug("Loading CMUSph...
740d64c8e61ec3eb3b9571f0a848a5868163ac4d
58,302
import os def get_test_lists(directory): """ Returns a list of all the files named tests under the directory @ In, directory, string, the directory to start at @ Out, dir_test_list, list, the files named tests """ dir_test_list = [] for root, _, files in os.walk(directory): if 'tests' in files...
40e26a11a7298654323e4d6277d9aeb2cac3fa26
58,303
def get_interval_scores( target_exon, left_region_start, right_region_end, interlap_scores, gene_name, interval_size, ): """ get_interval_scores =================== This method is to get regional constraint scores from left to right by a set interval. This method uses the exon s...
d0574c95e114f30b974949f61885afa6ab8f672e
58,304
def axis_angle_to_quaternion(axis, theta): """ Convert a rotation axis / angle pair to a quaternion Parameters ---------- axis : float The Rotation Axis theta : float The Angle Returns ------- array_like The Quaternion (w, x, y, z) """ # make sur...
8837b353e2e37e8122cd907f3dfac1fc0a007551
58,305
def refcount_table_clusters(current): """Fuzz refcount table clusters header field.""" constraints = UINT32_V return selector(current, constraints)
e7f2a5e0ad1fb9ab035c4bdb54e584777b999f6f
58,306
def process_weather_file(filename: str): """Process a weather file and return the dataframe. Args: filename: The name of the weather file to load, as defined in the building config file. Returns: A pd.DataFrame object with the ready to use weather information. """ logger.info("Proc...
bd918c42a704b04b38cfcf4d10c70616d0bd3711
58,307
def get_form_target(): """ Returns the target URL for the comment form submission view. """ if get_comment_app_name() != DEFAULT_COMMENTS_APP \ and hasattr(get_comment_app(), "get_form_target"): return get_comment_app().get_form_target() else: return reverse("comments-pos...
64466d524e8d15d6592e89a08b744f3d6d234c22
58,308
def custom_reduce(cls, states): """For customizing object serialization in `__reduce__`. Object states provided here are used as keyword arguments to the `._rebuild()` class method. Parameters ---------- states : dict Dictionary of object states to be serialized. Returns -----...
9afc74471feed1f89c77bee86f235fae7109b678
58,309
def compute_curvature(*args, **kwargs): """ Computes the curvature of the energy of a system as a function of the number of electrons in the system E(N). Args: args (:class:`exatomic.core.universe.Universe`): unis in ascending electron order neut (int): index of args corresponding to th...
393a44605724c54f1ae13efbf61314b702e40bd7
58,310
def tt_s_p(session,s_p,uncert): """ tt_s_p(session,s_p,uncert) Look up the distance for an S-P travel time observation and return all the nodes within the s_p +/- uncert Returns the TTtable3D_object """ nodes = session.query(TTtable3D).filter(TTtable3D.s_p<=s_p+uncert).filter(TTtable3D.s_p>=s_p-uncert...
682bd14034ccc400c710971c6e5a26caf5516ce1
58,311
def admin_index(): """Admin Index """ return render_template('index.html')
abe52416d02b00f7e2a90c5a68d05aec78025007
58,312
def _square_wave_samples(freq, rate, amp, num): """ Generates a set of audio samples taken at the given sampling rate representing a square wave oscillating at the given frequency with the given amplitude lasting for the given duration. :param float freq The frequency of oscillation of the square...
ba6c72032f08455d8064a5ce6e54e1d8d63873fa
58,313
def mybio_to_pymol_selection(entity): """Transform an :class:`~luna.MyBio.PDB.Entity.Entity` instance into a Pymol selection-expression, which can then be used to select atoms in a Pymol session. Parameters ---------- entity : :class:`~luna.MyBio.PDB.Entity.Entity` An entity to be transform...
1952af51b67676f2bf19775b52d5f721ae1e62cc
58,314
def compositionalActflowRandomSplitLOOBaselineCV(ncvs, svm_mat, nov_svm_mat, prc_svm_mat, labels, subjarray, featsel=True, nproc=5): """ Runs cross validation for an across-subject SVM analysis """ ntasks = len(np.unique(labels)) nsamples = svm_mat.shape[0] nsubjs = nsamples/ntasks sub...
9ab037d36beba8996faf380dd3805220182f3b16
58,315
def parse_pv(repo, text): """Return a CPV instance from either a cpv or a pv string. If a pv is passed it needs to match a single cpv in repo. """ try: return cpv.CPV.versioned(text) except errors.InvalidCPV: restrict = parse_match(f"={text}") result = None for match...
42414f2dc9b84095f9184fd8bf3c65d7fa591d48
58,316
def get_contact_list(txt): """Returns contacts (from autosuggest)""" txt = txt.replace('%', '') if len(txt) < 3: return None out = filter(None, frappe.db.sql_list("""select email from ( select distinct email_id as email, 2 as doctype, if (locate( %(_txt)s, concat(first_name, " ", last_name)), locate( %(_txt...
bb1f1f84854ede4b7fb75d08a7de435a65914d1f
58,317
def connect_to(name): """Creates a node instance based on an entry from the config This function will retrieve the settings for the specified connection from the config and return a Node instance. The configuration must be loaded prior to calling this function. Args: name (str): The name ...
aae624892447618194374061cf316ce2112d6275
58,318
from sys import modules import unittest def suite(): """ Create the test suite for this module. """ loader = unittest.TestLoader() suite = loader.loadTestsFromModule(modules[__name__]) return suite
1d14f1fa9fd4936ae841be11fe3bd2a37b5e421d
58,319
def tone2_to_normal(tone2, v_to_u=False): """将 :py:attr:`~pypinyin.Style.TONE2` 风格的拼音转换为 :py:attr:`~pypinyin.Style.NORMAL` 风格的拼音 :param tone2: :py:attr:`~pypinyin.Style.TONE2` 风格的拼音 :param v_to_u: 是否使用 ``ü`` 代替原来的 ``v``, 当为 False 时结果中将使用 ``v`` 表示 ``ü`` :return: Style.NORMAL 风格的拼音...
768cd8c4bd97d2a630a776d7f69941319c269692
58,320
def month_to_str_int(m): """Converts a month to an int form, str type, with a leading zero""" mi = month_to_int(m) if mi < 10: ms = "0{}".format(mi) else: ms = str(mi) return ms
8a75338e41bdb63c6f13b916688cee83bd4a220b
58,321
def tree_figure_rotations(figure): """ Find all rotations of a pentomino @param {dict} set of points on the tree @return {dict} 8 sets of points on the tree, corresponding to all rotations of the tree that are possible. """ return tuple(_shift_pent(_rotation_info(figure)))
d900b1d21650328a3ba7a0e2cabfbc76cd39eeeb
58,322
import numba import threading import functools def performance_function( _func: callable = None, *, worker_count: int = None, compilation_mode: str = None, **decorator_kwargs, ) -> callable: """A decorator to compile a given function and allow multithreading over an multiple indices. NOTE...
41a16c37ce344b59cf662d0c40802f018ee737c8
58,323
def test_dataset_ints(lengths): """Create a test dataset of int64 tensors of shape [length].""" def generator(): """Sample generator of sequences of shape [length] of type int64.""" for length in lengths: x = np.zeros([length], dtype=np.int64) yield (x, x) # Inputs and targets are the same here...
e8c0a62f22e903ff5014d0c61b24f9b641f804ce
58,324
from typing import Optional import torch def _convbot( sent: Optional[str], prev_resp: Optional[str] = "", max_length: int = 1000, do_sample: bool = True, top_p: float = 0.95, top_k: int = 0, temperature: float = 0.75, ): """Generate a response.""" # sent_ids = tokenizer.encode(sen...
256bbb2a305cfb3b50e773e8e10c0c937aaaca03
58,325
def render_block(data, pgm, param): """ render one single block """ param = np.round(param).astype(np.int32) bsz = data.shape[0] for i in range(bsz): loop_free = decode_pgm(pgm[i], param[i]) cur_pgm = loop_free[:, 0] cur_param = loop_free[:, 1:] for j in range(len...
267508fcde570e03154c6b8c52f225d69154b8ce
58,326
def q2torque( q, dq, ddq , manipulator ): """ Parameters ---------- q : numpy array float 3 x l dq : numpy array float 3 x l ddq : numpy array float 3 x l manipulator : pyro object Returns ------- tau : numpy array float 3 x l """ # Time discretization l...
ac0f32a8be67d778c925d213817e3a6c98a76ef1
58,327
def apply_filters(query, filter_spec, do_auto_join=True): """Apply filters to a SQLAlchemy query. :param query: A :class:`sqlalchemy.orm.Query` instance. :param filter_spec: A dict or an iterable of dicts, where each one includes the necesary information to create a filter to be ap...
e45940fba31ab81e1d30c5c621971c081b7d0efd
58,328
from typing import Union def _get_user_id(column: str, value: str) -> Union[int, bool]: """Get user id from any user detail and its column. :param str value: Any user value stored in the database :param str column: Database column of the given user value :returns: user id on success """ wit...
00d605bba346311441c5995c51152bc33f955a5d
58,329
import re def convert_col_string_to_list(colstr, with_format=True): """Convert a string of columns to list of columns. """ columns = re.findall(r'\$\S+\{.*\}|[^,\s]+', colstr) if not with_format: columns = remove_column_format(columns) return columns
0458ee5adbc1f19518d60b6c276864e77a6f5ed7
58,330
def mad(arr): """ Median Absolute Deviation: a "Robust" version of standard deviation. Indices variabililty of the sample. https://en.wikipedia.org/wiki/Median_absolute_deviation """ med = np.median(arr) return np.median(np.abs(arr - med))
0954682f2b0f5440ebfd9b9ab8f40d1f218a5472
58,331
import functools import time import logging def cache(obj): """modified https://wiki.python.org/moin/PythonDecoratorLibrary#Alternate_memoize_as_nested_functions""" @functools.wraps(obj) def cacher(self, *args, **kwargs): self.cache_init() now = time.time() before = len(self.cache...
1fb6be28799e9a771397776570073f9b3e0f4e15
58,332
def update_rooms_slider(area): """ Update rooms slider to sensible values. """ return [1, min(int(area / 30) + 1, 6)]
af721d72b9d122d2d129797453cee2801e45eec9
58,333
def random_molecule(draw, molecule_class=Molecule, max_nodes=5, max_meta=None): """ Strategy that builds a molecule. Parameters ---------- draw: Internal for hypothesis. molecule_class: type The class of molecule to build, :class:`vermouth.molecule.Molecule` by default. ...
58ef6c3c22ce1b225e43de8c187ccafd3c2e4e00
58,334
def find_changes(vals, threshold=None, change_pct=0.02, max_interval=None): """Returns an array of index values that point at the values in the 'vals' array that represent signficant changes. 'threshold' is the absolute amount that a value must change before being included. If 'threshold' is None, 'c...
e6c66d3636f80ee310dcb7ae790bb30a27598aaa
58,335
def configure_optimizer(): """ Configure the optimizer for Bootleg. Args: config: config """ # Specify parameter group for Adam BERT def grouped_parameters(model): no_decay = ["bias", "LayerNorm.bias", "LayerNorm.weight"] return [ { "params": ...
81f767bb819e235feb178f88b486475b8dc4c7dd
58,336
def generateDaltonInputFileText(XYZ: xyz.xyz_to, charge: int) -> str: """Makes the text for a Dalton input file Args: charge (int): The charge of the molecule Returns: str: Returns the file text """ if not hasattr(XYZ, 'atoms'): print(f'''You need to process the xyz file us...
06c48516f7ba8cab3e26ec0d36910615e9b8a6da
58,337
import argparse def _key_val_pair(value): """ Type checker to ensure that --field values are of the format key=val """ if '=' not in value: msg = 'values must be of the form `header=field`' raise argparse.ArgumentTypeError(msg) return value
eede8a3975eb58d503419a0d990115c84f72813c
58,338
from typing import List import math def standard_deviation(xs: List[float]) -> float: """ The standard deviation is the square root of the variance """ return math.sqrt(variance(xs))
6558087203aade8f8e5233c7f6ca2a1d7a8130f9
58,339
import inspect import copy def fit_ec_model(data,model,init_params=None,normalize='deg',alpha=0,n_restarts=10,est_HFR=True,weighting='modulus',return_result=False,simplex_params={},random_seed=None,**est_HFR_kw): """ Fit equivalent circuit model using Nelder-Mead downhill simplex method. Adds random noise to the i...
be10779709ac9024c83f12e7c98b23f6f4d42541
58,340
def close_run(exit_status=None, reason=None): """ Mark the end of the current 'run'. Emit a RunStop document. Yields ------ msg : Msg Msg('close_run') exit_status : {None, 'success', 'abort', 'fail'} The exit status to report in the Stop document reason : str, optional ...
07305eace0003fe1760b1bab301c7039df6d6f7d
58,341
def retrieve_row_by_pk(session, pk, _class): """Retrieve a row from the database based on it's PK components""" q = session.query(_class) # Build the base query statement pkey_cols = _class.__table__.primary_key.columns # Iterating for the case where the PK is composite for pk_col, pk_value in zip(...
f25ba01e1b437bbe45740f52e9f028d8071be374
58,342
import datasets import os def _make_data_submission(): """ Create files and a data submission. Returns an DataSubmissionForTests object. """ test_dsub = datasets.test_data_submission test_dsub.create_test_files() user = get_or_create(User, username='fred') dsub = get_or_create(DataSub...
5422d1b340dd4400241c6902902c023698e2346d
58,343
from pathlib import Path import os def module_to_path(homeassistant_root: Path, module: str) -> Path: """Convert module name to Path.""" if module.endswith(".*"): typed_path = homeassistant_root / Path(module[:-2].replace(".", os.path.sep)) assert typed_path.is_dir(), typed_path else: ...
3ab08c33922250ffda1d530a4760329410ed1ae6
58,344
def comp_nb_radial_wire(self): """Return number of adjacent wires in radial direction Parameters ---------- self : CondType12 A CondType12 object Returns ------- Nwppc_rad: int Number of adjacent wires in radial direction """ return int(sqrt(self.Nwppc))
039b54e22641e0d3cd59995e2ce5af5c222a53e4
58,345
def evaluate(board): """Evaluate a checkers board via a simple linear heuristic. Args: board: a string representing a board. Returns: an integer which is positive if black has te upper hand (negative for red). """ bcount = 30 * board.count('B') + 20 * board.count('b') i...
b609caff503fce13c6280e3253be2281c4a6eb32
58,346
from typing import Optional def jobs_list_command(client: Client, args: dict): """ This function returns a list of all existing jobs. :param client: Demisto client :param args: command's arguments :return: CommandResults object """ id_list: list = argToList(args.get("id_list", [])) gro...
aff97e7b540472bb9f0d2f7225964c150a5db820
58,347
def get_mode(array): """Find the mode in the array""" mode = None if isinstance(array, np.ndarray): counter = np.bincount(array.flatten()) mode = int(np.argmax(counter)) return mode
c1bfba16b2906a9c0b5db2b9d3285570c65b8ea0
58,348
def login_link(request): """ This assumes your login link is the Shibboleth login page for your server and uses the 'target' url parameter. """ full_path = quote(request.get_full_path()) login = reverse('shibboleth:login') ll = "%s?target=%s" % (login, full_path) return { 'login_link': ...
0b99095c989d04f5c425d5e9c4e5ee55f57665e2
58,349
from datetime import timedelta def convert_df_shifttime(df: pd.DataFrame, second: int): """ shift time by second Parameters ---------- df : second : Returns ------- """ time_shifted = df.index + timedelta(seconds=second) new_df = pd.DataFrame(data=df.values, columns=df.c...
12c615adf1052c3cd4c9896d3deff0e922885dcd
58,350
def parse_tests(testcases, debugtalk, name=None, config=None, project=None): """get test case structure testcases: list config: none or dict debugtalk: dict """ pro_map = parse_cases(testcases,debugtalk,name=None,config=None,project=None) refs = { "env": {}, "def-...
f242df905c4e7760c08da7bad0d9ba913763552f
58,351
def group_rename(request, group_id): """Rename a group. """ if request.method != 'POST': raise Http404 new_name = request.POST.get('new_name', '') next = request.META.get('HTTP_REFERER', SITE_ROOT) group_id = int(group_id) try: rename_group_with_new_name(request, group_id, ...
45dc07a9f9dd7e961fb77540b7fde95d77bc55ca
58,352
def placeholder_inputs(batch_size): """建立兩個tf placeholder來存於輸入值及標籤. These placeholders are used as inputs by the rest of the model building code and will be fed from the downloaded data in the .run() loop, below. Args: batch_size: The batch size will be baked into both placeholders. Returns: images...
b58d587dd597a370b2798446092749fb6f83e331
58,353
def reorder_atoms(mol): """Reorders hydrogen atoms to appear following their heavy atoms in a molecule. Args: mol (Mol): A molecule (RDKit format) Returns: new_Mol (mol): A molecule with hydrogens after the corresponding heavy atoms. """ # Create a list ...
cc21313d211d588228f2a57e120ed4c7c0311e29
58,354
def hinge_loss_layer(feat_anc, feat_easy, feat_hard, loss_weight, mask, name): """Loss layer.""" with tf.name_scope(name): # pylint: disable=not-context-manager def _structured_loss(dist_mat, batch_size, margin): # positive distance easy_dist = tf.matrix_diag_part(dist_mat) ...
9ce4dcd77e83f4528bd5dcb5d29885c3ead6296b
58,355
def read_data_to_dataframe(_path,**kwargs): """ Helper function that reads csv and feather formats and outputs pandas dataframe """ if _path.lower().endswith('.csv'): print('csv!') return pd.read_csv(_path,**kwargs) elif _path.lower().endswith('.feather'): return pd.rea...
b6ee651199a773fcfacb56e8bc9bf4d182f7235d
58,356
import re def split_interface(interface_regex, value): """ convert an interface based on the given regular expression to a dictionary with all components, e.g. regex: .*(?P<chassis>\d+)\/(?P<module>\d+)\/(?P<port>\d+).* value: interface gi1/2/3 will return { "chassis...
39f852333e065f80405cc603600a5673bfaf0d5f
58,357
import torch def laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.Tensor) -> torch.Tensor: """Returns orientation of the LAFs, in radians. Useful to create kornia LAFs from OpenCV keypoints. Args: xy: tensor [BxNx2]. scale: tensor [BxNx1x1]. ori: tensor [BxN...
c0b627b02cbb743a7155bb912b24ad00ee25bcc2
58,358
from msrestazure.azure_exceptions import CloudError import os def delete_resource(cmd, resource_ids=None, resource_group_name=None, resource_provider_namespace=None, parent_resource_path=None, resource_type=None, resource_name=None, api_version=None): """ Deletes the gi...
bc471cd8ac04221722081b151e7c6001283207d4
58,359
from operator import or_ def or_many_condition(condition: list): """ 有时候or能比in产生更好的性能,例如 filter(or_many_condition([UserDB.id == i for i in user_ids])) 会比 filter(UserDB.id.in_(user_ids)) 性能更加好 """ if len(condition) == 0: return True if len(condition) == 1: return co...
a707919908c42f3db62a74290a61cd8586c31213
58,360
def apwidth(img, ap_uorder_interp, offsetlim=(-8, 8), ap_npix=10, method='max'): """ automatically find ap_width for a given ap_npix """ img = np.array(img) ap_width_max = offsetlim[1] - offsetlim[0] + 1 assert 1 <= ap_npix <= ap_width_max # determine SNR of each offset ofst, medsnr_lnsum = a...
2006b2d3293981902a4e553bba29e453d473cf12
58,361
def data_value(value: str) -> float: """Convert to a float; some trigger values are strings, rather than numbers (ex. indicating the letter); convert these to 1.0.""" if value: try: return float(value) except ValueError: return 1.0 else: # empty string ...
24087c1733be5932428a63811abbb54686836036
58,362
def batch_gather(values, indices): """Gather slices from values. Args: values: a tensor in the shape of [batch_size, length, depth]. indices: a tensor in the shape of [batch_size, slice_count] where slice_count < length. Returns: a tensor in the shape of [batch_size, slice_count, depth]. ""...
ec57c5483e4cd561bf9d7c4583b1a980562d6460
58,363
import os import subprocess def compile_code(makefile_target: str = ""): """Compiles the current directory (either with Make or manually)""" ls_output = os.listdir() if "Makefile" not in ls_output: # Let's let the grader figure it out os.system("bash") p.print_cyan("[ Compiling... ]")...
3ad9229d5e0f163b3a1749b77914ed44afbf7a4e
58,364
def _prepare_signature_outputs(names: list, dtype_layer, shape, model_keys): """ Inference Engine Api does not report outputs shapes, for signature format consistency with TF Serving theres returned a dummy shape==(1,1,1). To be fixed in the future. """ signatu...
26b97ae126f8a759e970199967f5233513f431a1
58,365
import numba def grid2locs(xxi, yyi, zzi, ti, vi, xo, yo, zo, to): """Linear interpolation of gridded data to random positions Parameters ---------- xxi: array_like(nyi, nxi) Input grid longitudes in degrees, with `nyi==1` for 1D coordinates. yyi: array_like(nyi, nxi) Input grid l...
93f7cacfe216dc8f0049a098ffc6583010601c87
58,366
def _check_union(value, expected_type, path, context): """Checks `value` to a value with any of the types in `expected_type`.""" for type_option in get_generic_type_args(expected_type): try: return _convert_value(value, type_option, path, context, convert=False) except TypeError: ...
3bec745ccb74761f3acd1b59d82be74812de1a22
58,367
from OpenGL.arrays import vbo def ca(ntracers): """Initialize position, color and velocity arrays we also make Vertex Buffer Objects for the position and color arrays""" pos, col, time, props = ca_np(ntracers) #print timings #create the Vertex Buffer Objects pos_vbo = vbo.VBO(data=pos, u...
16c3f156045d2e2884ce26f0b2bc52687bfbe948
58,368
def expected_ini_dict() -> DictType: """Get the expected dictionary - content of the fixture file.""" return { "databases.postgres": { "user": "admin", "password": "admin", "host": "localhost", "port": "5432", "schema": "public", }, ...
8a34601c7aa2e40bd4fb2304b10717755a2cce7b
58,369
from typing import Tuple import logging async def mark_next_person(queue_array: list) -> Tuple[list, int]: """Mark next person in the queue (transfers current_turn to them). Parameters ---------- queue_array : list This array represents the queue Returns ------- Tuple[list, int] ...
e792dbf2ac10f44bda53a6429ba43180bdefd144
58,370
import os def WriteAsmFiles(perlasms): """Generates asm files from perlasm directives for each supported OS x platform combination.""" asmfiles = {} for osarch in OS_ARCH_COMBOS: (osname, arch, perlasm_style, extra_args, asm_ext) = osarch key = (osname, arch) outDir = '%s-%s' % key for perla...
06eb3fb752be2554bc44fd121c13ac6ac30e09a4
58,371
def svn_repos_parse_fns3_invoke_new_node_record(*args): """svn_repos_parse_fns3_invoke_new_node_record(svn_repos_parse_fns3_t _obj, apr_hash_t headers, void * revision_baton, apr_pool_t pool) -> svn_error_t""" return _repos.svn_repos_parse_fns3_invoke_new_node_record(*args)
40df4339631077ce74127b10b959f84e5bf36568
58,372
def stop_algorithm(): """ View for stopping the algorithm. If the algorithm is already stopped an exception will be thrown. Otherwise all workers will be stopped. """ if not current_app.algorithm.running: raise ApiException("Algorithm is already stopped") current_app.algorithm.stop...
c60449b78e45bf3bbd76fd1957d0de7804950f89
58,373
import os def init(name, folder='.', template='', **kwargs): """ kwargs: ======= @folder: project folder @election: (...) @questionnaire: (...) """ folder = '-f "%s"'%folder # folder = get_value(kwargs, 'folder', '.') election = get_flag(kwargs, 'election') questionnaire ...
a555ce14134ca9350c847229eda66ddc357a3341
58,374
def patch_cluster_config(cluster_id, user=None, session=None, **kwargs): """patch cluster config.""" cluster = _get_cluster(cluster_id, session=session) return _update_cluster_config( cluster, session=session, user=user, **kwargs )
f83ef5f4b10442608cefc222032d3b207bad588a
58,375
def need_new_decimal_value(old, new, delta=0.001): """ Определяет приблизительным сравнением, необходимо ли записывать новое значение в базу.""" if new is None: return False elif old is None: return True old = float(old) new = float(new) delta = float(delta) try: if...
0bf496c19555a6f8a878acb57322f266fb470f24
58,376
def classify(): """ Sample test Route to Neural Net """ image = request.files['image'] label, prob = classify_image(image) return f"{label} - {prob:.2f}"
907dbfe4149362da68da764bb44ef2ec8215185d
58,377
def kegg_get(dbentries, option=None): """KEGG get - Data retrieval. dbentries - Identifiers (single string, or list of strings), see below. option - One of "aaseq", "ntseq", "mol", "kcf", "image", "kgml" (string) The input is limited up to 10 entries. The input is limited to one pathway entry with...
4051c59831fc5e29e747bd0c0d20dcc28156d565
58,378
def generate_tutorial_data(): """ Generates tutorial data. Returns ------- datasets : dict Dictionary that contains the tutorial datasets. Dictionary keys are one of circles, linearly_separable, and moons. Dictionary values are tuples (X, y) where: X : array-like of...
5ae5745a87b9a9f8270d400e64200ee6325e25e9
58,379
from typing import Union from typing import Optional def infer_schema(data: Union[pd.DataFrame, pd.Series]) -> Optional[ProcSchema]: """ Infer the correct schema to use for this data set. Parameters ---------- data : Union[pd.DataFrame, pd.Series] Data set to test Returns -------...
b30028c354694c15e94dd55ff12ffbf7cc62585f
58,380
def post_delete(request): """ View post delete page. Param post id. Return post list page. """ post_id = request.GET["post_id"] delete_post = get_object_or_404(Post, pk=post_id) delete_post.deleted_user_id = request.user.id delete_post.deleted_at = timezone.now() delete_post.save...
eb8619b811f56a0fc5a412f11b53389d03fe09e2
58,381
def set_outerHTML(new_value, traverser): """Tests that values being assigned to outerHTML are not dangerous.""" return _set_HTML_property("outerHTML", new_value, traverser)
ba9715989d3d8dd610331155042693173ad461ef
58,382
import logging import os import json def main(req: func.HttpRequest) -> func.HttpResponse: """ Monitor Github push :param req: HttpRequest :return: HttpResponse """ logging.info('GitHub Monitor processed a request.') var = os.environ.get("VARIABLE_FOO") logging.info(var) req_body ...
73a7ddd548fc97acefa7c164ab7483033eef6079
58,383
def check_property_definitions_exist_in_scope_single( api_factory: lusid.utilities.ApiClientFactory, property_key: str ) -> (bool, str): """ This function takes a list of property keys and looks to see which property definitions already exist inside LUSID Parameters ---------- api_factory : lus...
785022aac8ff21223d495da4c34f2d5a9edced78
58,384
def xnnpack_optional_gemmlowp_copts(): """Compiler flags to optionally enable Gemmlowp benchmarks.""" return []
1f5648d61235343ebc0e3bd601a004b81e0fb65b
58,385
def interpret_obset_input(results, log_level): """ Parameters ----------- results : str or list Input poller file name or Python list of dataset names to be processed as a single visit. Dataset names have to be either the filename of a singleton (non-associated exposure) or the ...
b13242e399e5b8fd17b991c4e8d32d33f68c0732
58,386
def commitment_pattern_view(request, commitmentid): """ Show a single commitment pattern, along with instances based on startDate and endDate url parameters. """ startDate, endDate = get_dates(request) commitment = get_object_or_404(VolunteerCommitment, id=commitmentid) is_my_commitment = True if commi...
f535b4db5e2cb494843b4dc3c22215559aee9468
58,387
def custom_regularizer_to_zero(x): """ Regularizer for custom layers that enforces tensor values to go towards 0 (the same as L2 regularization). :param x: tensor of weights, which we want to regularize :return: value of the loss for the custom layer """ return 0.0001 * tensorflow.reduce_sum(te...
1455bb5c90d9d92cdc6eba647a80e0374998c4fd
58,388
def vector_attention(x, encode_dim, feature_dim, attention_dim, sequence_length=None, mask_zero=False, maxlen=None, epsilon=1e-8, seed=0, scope_name="attention", reuse=False): """ :param x: [batchsize, s, feature_dim] :param encode_dim: dim of encoder output :pa...
6cd1a51c955bf5cd4e7391239f9856def1ab5e51
58,389
def coerce_column_to_dolt(column: Column, type_mapping: dict): """ Defines how we map MySQL types to Dolt types, and removes unsupported column level constraints. Eventually this function should be trivial since we aim to faithfully support MySQL. :param column: :param type_mapping: :return: ...
c1821c7a97ed7a69f12afe297da70c54ee1a02b7
58,390
def _load_pdf_content(pdf: PdfFileReader) -> str: """ ################################# ## PDF Load content ## ################################# :param pdf: PDFFileReader object that has loaded the PDF path :return: the raw text from the PDF """ # Discerning the number of...
3b88f8e029e31063c3d7a21f43aa358cbe65b063
58,391
import re from datetime import datetime def match_to_datetime(match: re.Match) -> datetime | date: """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`. Raises ValueError if the match does not correspond to a valid date or datetime. """ ( year_str, month_str,...
1222d2b975420605ec91bc03db516e9bff97b0d1
58,392
def extend_knots_vector(order, interval, internal_knots, closed=False, multiplicities=None): """Produces an extended knots vector for BSpline functions given a simple one. This function extend the given knots partition adding auxiliary knots on the left and on the right of the given ones in order to be th...
7d29efedb07c4f72c4ba0ebec17ffa0fa8ea307a
58,393
def load_font(font_name): """Loads the given font into a font object :rtype: PIL.ImageFont. """ return create_font(font_name, 10)
ae99115fcae34b310577586aeb39b5f8b657aace
58,394
def parse_haplotypes_from_fasta(reads_location): """ # ======================================================================== PARSE HAPLOTYPES FROM READS PURPOSE ------- Builds a list of Haplotype objects from aligned FASTA reads. INPUT ----- [FILE LOCATION] [reads_location]...
0f8b7dae3a6396d733b9dc96b4c1f192a1be3341
58,395
def costs_matrix(a, b, costs): """ a = 'xyz' b = 'ayzb' m = / a y z b 0 1 2 3 4 x 1 2 3 4 5 y 2 3 2 3 4 z 3 4 3 2 3 m[row][col] -> m[2][4] == 6 """ height = len(a) + 1 width = len(b) + 1 m = [[0] * width for _ in range(height)] for row in r...
f2845efbe55a12806d3d9b464cbe2c0f8efd8c56
58,396
def _get(key): """Looks up the given key in the config singleton. """ config = _load() if key in config: return config[key] return None
5aac26e98f95d53c7348e27f6fabb5780d73268c
58,397
from typing import Optional from typing import Callable def warn_if_incorrect_typing( func: Optional[Callable] = None, join: bool = True ) -> Callable: """ Applies :func:`check_correct_typing` with warning as output. :param func: the function :param join: if True, will join all errors and raise t...
35509721d568b8aaf6f0fa33e91cd7b7a3dbb527
58,398
import time def get_process_id(id): """ get_process_id: generate a string of dmYHMS :param id: process_id :return: unique name of string and dateyeartime """ return id + "-" + str(time.strftime("%d%m%Y%H%M%S"))
22f2c88dc14b89a54651f58b03e16e167fbd640d
58,399