content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
async def create_cart_button() -> InlineKeyboardButton: """Makes cart button.""" return InlineKeyboardButton( text=emojize('🛒 Корзина'), callback_data='go_to_cart', )
964e6b1ab55bdcb36d6072ff650bff8ec9453ed9
61,424
def entities_or_platform(obj): """Get entities, or platform if no entities.""" entity_ids = get_entity_ids(obj) if entity_ids: return entity_ids return [obj[const.CONF_PLATFORM]]
4917d6241cd317de59b0c457fdd52036279adaa0
61,425
import torch def simulate( num_time_steps, num_regions, num_strains, *, num_transit_covariates=4, overdispersion=0.5, transit_rate=1e-2, mutation_rate=1e-2, initial_infected=10, min_total_infected=1000, max_total_infected=10000, case_rate=0.25, death_rate=0.03, ...
19d76a43419a6a61daaf96992b504e53dc4ec441
61,426
def dnnlib_shadow_submit_convert_path(txt): """Not sure what this really does, so just a no-op.""" return txt
9a883453edeb6171386dca221557eead8f9058b2
61,427
def security_group_set(port): """ Returns the security group set for a port. A security group set is a comma-separated, sorted list of security group ids """ # There are 36 chars to a uuid, and in the description fits 255 chars security_groups = sorted(port['security_groups']) num_group...
d55930f85219b31cf7b68c4b3136c4a3edfbf1a2
61,428
def getcompression(): """ Returns default compression filter. """ return NX_COMPRESSION
938a060d5cd771f14c64eb2094ff8c3816e1b897
61,431
from datetime import datetime def get_duration_and_dead_ratio(file_name): """Takes a log filename and extracts the amount of wasted core hours. :returns: A tuple containing the sim duration, percent of time lost, number of cores with valid times and the time lost for each core""" with open(file_name) as f...
0a6e335a892b248669662861daa0719424076677
61,432
def make_request(address): """ Set the lat_long field, if the appropriate fields are filled """ geolocator = Nominatim() try: location = geolocator.geocode(address) lat_long = {"type": "Point", "coordinates": [location.longitude, location.latitude]} except (Ge...
1a74fdf10a812c72f6eddf4f2fa5b0c9079d01d0
61,433
import re def read_html(htmlfile): """ Reads the HTML file to a string. Removes some potential trouble makers. """ with open(htmlfile, "r") as infile: html = infile.read() # Clean out some unnecessary stuff html = re.sub("<div class=\"wp-about-author.*?</div>", "", html, re...
bb0f724792cd817464a8720199ce7c7035e6b0f1
61,434
def customise_org_office_controller(**attr): """ Customise org_office controller - Marker fn """ current.s3db.configure("org_office", marker_fn = org_office_marker_fn, ) return attr
f0cbfd9eacf4dd8d560129a52ce99e9f7d24cba7
61,436
def fdr_bh(fdr, p_values): """ Benjamini-Hochberg false-discovery rate adjustment procedure. pdfs.semanticscholar.org/af6e/9cd1652b40e219b45402313ec6f4b5b3d96b.pdf Parameters ---------- fdr : float False Discovery Rate (q*), proportion of significant results that are actually f...
d41bff53a9a0df9a16b9163361041465be653ec6
61,437
import json def get_new_username(): """提示用户输入名户名""" username = input("What is your name? ") filename = 'username.json' with open(filename, 'w') as file_object: json.dump(username, file_object) return username
2d0f87131f551c135a229b48783886d533b81dd9
61,438
import re def getCustomRead(alngt, compareList, readdic): """ Funtion which transforms an HTSeq alignment to a CustomRead class. @type alngt: alignment @param alngt: alignment from the sam file. @type compareList: list @param compareList: list which indicates differences between reference /...
2c58db01d3a49a1753671b67ef448fc20238dfba
61,439
import random def set_new_cherry_pos(snake_lst): """ Sets new cherry position. :param snake_lst: List, containing all snake instances present in the game. This is needed to check that cherry will not be placed onto a snake. :type snake_lst: list of Snake """ new_cherry_...
2a495a4e70635dc4722344d62bd29c893f15c43a
61,441
def edit_description(request, pk): """ Edit the description attached to an action :param request: AJAX request :param pk: Action ID :return: AJAX response """ # Try to get the workflow first workflow = get_workflow(request) if not workflow: return JsonResponse({'form_is_val...
b5897e8730cb5369866b832110016cc4c9a07d1e
61,442
import json def newBatch(batchName, seq, org, pam, skipAlign=False): """ obtain a batch ID and write seq/org/pam to their files. Return batchId, position string and a 100bp-extended seq, if possible. """ batchId = makeTempBase(seq, org, pam, batchName) if skipAlign: chrom, start, end, stra...
da2d0f87e0716d34bd0c8e062cf1078b277138b3
61,443
def testconf_dict(testgrid) -> dict: """Returns a mock of the contents expected in `config.yml`.""" # Copy the base config testconf = deepcopy(CONFIG_BASE) testconf["path"] = TEST_HEROGRID_PATH return testconf
cd6e7f010a3b1c8658bc8837c36b42336a5abe85
61,444
def se_block(input_feature, name, ratio=8): """Contains the implementation of Squeeze-and-Excitation block. As described in https://arxiv.org/abs/1709.01507. """ kernel_initializer = tf.contrib.layers.variance_scaling_initializer() bias_initializer = tf.constant_initializer(value=0.0) with tf.variable_sco...
86bb1b205aa52e637097a0bc1ebc3482d87959a0
61,445
def showfiles(**args): """List of strings. All files modified, added, or removed by this changeset. """ return showlist('file', args['ctx'].files(), **args)
1d49591d32b7709a3704f272639dc6dca1237301
61,446
def vtk_version_ok(major, minor, build): """ Check the VTK version. :param major: Major version. :param minor: Minor version. :param build: Build version. :return: True if the requested VTK version is greater or equal to the actual VTK version. """ needed_version = 10000000000 * int(maj...
cb760ee01d143aa0be2da53210b60a433fa05320
61,447
def _parabola(data): """ Makes a parabola that fits the input data at the two endpoints. Used in the beads calculation so that ``data - _parabola(data)`` is close to 0 on the two endpoints, which gives better fits for beads. Parameters ---------- data : array-like, shape (N,) The d...
e40f42cbd79f69b33047c67d58332658ec0e643c
61,448
def get_values_cont_x_no_numba(data_vector, no_of_evalupoints): """Get cut-off points for tree splitting for continuous variables. No longer used; only kept if no_numba version would be needed Parameters ---------- sorted_data : Numpy-1D array. Sorted vector no_of_evalupoints : Int. c_dic...
2b99d5274a8a9b432b47ff1dc20db88cad0d9338
61,449
def get_population(): """Get a dummy population with minimal configuration.""" cfg = Config() cfg.game.duration = 1 # Small duration cfg.game.fps = 10 # Games of low accuracy but faster cfg.genome.rnn_prob_gru_nr = 0 cfg.genome.rnn_prob_gru_nu = 0 cfg.genome.rnn_prob_gru = 0 cfg.genome...
15604241ae2c29a0be21c781ccab53b299683c72
61,450
def adjacency_ba(tfr_dfs): """A stub transform function.""" return tfr_dfs
53212b83e590cd83358a67e5b05cc4de67474107
61,451
def run_required(func): """A wrapper to check that the simulation has been run before a method can be executed""" @wraps(func) def _run_required(*args, **kwargs): """Check that the 'tso' attribute is not None""" if args[0].tso_order1_ideal is None: print("No simulation found! Ple...
27fcfac0769e11eee34c203746e45342508fc01a
61,452
def detect_hotdog(image_bytes): """ Checks image for hotdog label using Amazon Rekoginition's object and scene detection deep learning feature. Args: image_bytes (bytes): Blob of image bytes. Returns: (boolean) True if object and scene detection finds hotdog in blob of image bytes....
1edabb803bc4bf357c97593394e590a83a4de017
61,454
import time def get_datetime(): """Return the current datetime in a database compatible format""" return time.strftime('%Y-%m-%d %H:%M:%S')
804166ac7f56899733043871ea5ec9fcce474ee7
61,455
def im_detect_keypoints_aug(model, im, boxes): """Computes keypoint predictions with test-time augmentations. Arguments: model (DetectionModelHelper): the detection model to use im (ndarray): BGR image to test boxes (ndarray): R x 4 array of bounding boxes Returns: heatmaps...
d000adb64c3b921340d1b4d9aca5407ca34ca23d
61,456
import numpy as np import scipy import torch from torch.autograd import Variable import sklearn def get_data(audio, eeg, audio_unatt=None, idx_eeg=None, num_batch=None, idx_sample=None, num_context=1, num_predict=1, dct_params=None): """Select a sequence of audio, audio_unattnd, and eeg data Reshape the ...
3d684d4e2e984b8da6662a52a7746997c9a7d224
61,457
def parse_data_loader(dataloader_cfg, dataset): """ :param dataloader_cfg: config dict :param dataset: torch.utils.data.Dataset :return: torch.utils.data.DataLoader """ data_loader = DataLoader( dataset, batch_size=dataloader_cfg.get("batch-size"), shuffle=dataloader_cfg....
e600d9361333a66d2f1b4638cd14156039dc19f3
61,458
import wget def read_first_line(file): """Gets the first line from a file. Returns ------- str the first line text of the input file """ with open(file, 'rt',encoding="utf-8") as fd: first_line = fd.readline() f = open(file, 'r',encoding="utf-8") # 開啟並讀取檔案 lines =...
20fa4bc413d22011180c02624f1edc5e7b094fbc
61,459
def sort_key(doc): """helper function - sort by 'sider.side_effect.frequency' """ # take the first element from the document default_value = -101 s = next(key_value(doc, "side_effect.frequency")) n = str(next(key_value(doc, "side_effect.name"))) # if no element then return default value, name ...
685b5d45be00c7157f507f9c43770082bdb56e69
61,460
def delete(**_): """Delete a virtual network. :param ctx: The Cloudify ctx context. :return: The status code of the REST request. :rtype: int """ utils.validate_node_property(constants.VIRTUAL_NETWORK_KEY, ctx.node.properties) utils.validate_node_property(constants.DELETABLE_KEY, ctx.node.p...
5a61deb7da3493e40455d456af769742017ded24
61,461
def bSearch(arr, target, start=0, end=-1): """ -- BINARY SEARCH -- if target is not in arr, the opposite number of the first number's index larger than target will return """ if not arr: return None if end == -1: end = len(arr) - 1 if end < start: raise Exception(...
f38413b6097df35c942faff2fa3c1850f6202f39
61,462
import inspect def expand_lambda_function(lambda_func): """ Returns a lambda function after expansion. """ lambda_function = inspect.getsource(lambda_func).split(",")[1].strip() if lambda_function.endswith(")"): return lambda_function[:-1] return lambda_function
7076ce6bdee4077f6cbf665d686cd28c2420d67e
61,463
def _softplus(x): """A nice softplus. This is a monotonous function that is equivalent to x at +inf and -1 / (3PI x^2) at -inf. To prove this, use two facts: 1. For negative x, atan(x) = -PI/2 - artan(1/x) 2. Near 0, atan(x) = x - x^3/3 + O(x^5) From these two things, you can deduce that as x -> -inf: ...
843a7b35405aa48589b3ae886ff94b632ad6d056
61,464
def utf8tounicode(arg): """Convert UTF8-encoded bytes to strings. Only in Python 2. In Python 3 the errors are returned as strings. """ if PY2 and isinstance(arg, binary_type): return arg.decode('utf-8') return arg
ab69d98b088408e57e65d6886ee27b5393f86ad2
61,466
def get_bucket_usage(namespace, workspace): """Request google bucket usage for workspace. Args: namespace (str): project to which workspace belongs workspace (str): Workspace name Swagger: https://api.firecloud.org/#!/Workspaces/getBucketUsage """ uri = "workspaces/{0}/{1}/...
ab059652e4c68f4538a6d97310eae92cf00efe73
61,467
def base2vectors(sbparams,cbparams,fbparams): """ converts dictionary of base parameters to vector of parameters and then to pygom simulation parameters""" global C_2s # scaling factor for c_2 (1000) to allow c_2 parameter to be same order of magnitude as other parameters Exposure =sbparams['Exposure'] ...
dbc277bac43bd04da09b8debb77556698e032a2f
61,468
def inter_dists(sifts_result_i, sifts_result_j, structures=None, atom_filter=None, intersect=False, output_prefix=None, model=0, raise_missing=True): """ Compute inter-chain distances (between different entities) in PDB file. Resulting distance map is typically not symmet...
e6b809d0c4afe221b9e01729edb15f2147a1f32f
61,469
def handle_400(e): """捕获abort(400)错误""" rsp = { 'msg': 'Bad Request', 'err': 10 } if isinstance(e.description, int): rsp['err'] = e.description if isinstance(e.description, dict): rsp.update(e.description) return jsonify(**rsp), 400
0e522eac390c211b1bed017631f6f62926fdcb5a
61,470
def plugin_list(parser, options, args=None): """ List github/external/built-in plugins. """ if args: print_sub_help(parser, 'list') return -1 # Requires Internet to access github. if options.github: # pragma no cover _list_github_plugins() return 0 groups =...
1c45126664d747403d172f22f641b0ca67862136
61,471
def dialog_open(starting_directory="", title="Open file", file_filter="All Files (*.*)"): """ Simple open dialog in Maya Args: starting_directory (unicode): Starting directory. (default: project root directory) title (unicode): Dialog title. (default: "Open file") file_filter (unicod...
db4f732c11e375ceebebc2f9ed546a59862e3c44
61,472
def get_messages(): """ :return: all messages stored in database """ db = DataBase() msgs = db.get_all_messages(MSG_LIMIT) messages = remove_seconds_from_messages(msgs) return jsonify(messages)
04c5f052e8954204ead96f62bf96ef81ae80d4bf
61,473
def key_matrix(rows, cols): """ first index is columns (so slightly backward from math) :param rows: :param cols: :return: """ rv = [None] * cols for i in range(0, cols): rv[i] = key_vector(rows) return rv
9331c4a029df31c076e73809ac3ca892f662a791
61,474
def next_marker(xml_node, remaining_markers): """Try to determine the marker following the current xml_node. Remaining markers is a list of other marks *within* the xml_node. May return None""" # More markers in this xml node if remaining_markers: return remaining_markers[0][0] # Ch...
4f9f28c14b24218ca46a07ffbf2cd5f292c76a2b
61,475
def renumber_nodes(G, start=1): """Renumber nodes so that NeuronLand converter does not mess up. Returns: (new_graph, node_map) node_graph: a new DiGraph with the nodes numbered by bfs sequence. node_map: dict mapping node number in G to that in node_graph """ ret = nx.DiGraph() node_map...
727d918882e398de70bdaa81517ac7b7dbad1915
61,476
def get_dict_from_params_str(params_str): """Get the dictionary of kv pairs in a string separated by semi-colon.""" if params_str: kvs = params_str.split(";") params_dict = {} for kv in kvs: k, v = kv.strip().split("=") params_dict[k] = eval(v) return ...
611f80b55c090ff5aa6afa78ee4b1b5db074cab0
61,477
def get_item_keyphrase_freq(keyphrase_freq,item): """ Get item's keyphrase frequency """ try: count = keyphrase_freq[item].todense() except: count = keyphrase_freq[item] return np.ravel(count/(np.sum(count)+0.001))
ed91d3df2f4b112bd8e02d6f7bde245176639da3
61,478
def admin(func): """Require admin rights.""" def wrap(self, message, *args, **kwargs): if message.source in self.session.admins: return func(self, message, *args, **kwargs) return message.dispatch("Sorry, you are not authorized to do that.") wrap.__doc__ = func.__doc__ wrap....
78f8d0d3dab4b2c100ae51a4fd776f70b6fd3eda
61,479
from datetime import datetime def parse_timedelta( delta, min=None, max=None, min_included=True, max_included=True, ): """ Parse time delta """ if isinstance(delta, str) and len(delta) > 0: unit = delta[-1] if unit in '0123456789': unit = 's' ...
cb641166cb45eac781de13a20123c22990955edb
61,480
def normalize(x_i): """ Normalize the vector """ min_i = tf.math.reduce_min(x_i) max_i = tf.math.reduce_max(x_i) x_i_normalized = (x_i - min_i) / (max_i - min_i) return x_i_normalized
2a3f9c98a5ae12b065259f67f5b7f1273f97ec84
61,481
def hmerge(dataset_left, dataset_right, on=None, left_on=None, right_on=None, overwrite_text=False, from_set=None, merge_existing=None, verbose=True): """ Merge Quantipy datasets together using an index-wise identifer. This function merges two Quantipy datasets (meta and data) together, upda...
34449f825742a6d84eefe1bfa25bfc55e6df4d20
61,482
def train_test_folds(features, labels_binary, cv_iterator, model_factory): """ Creates and trains an XGBoost model instance per fold from the feature matrix. Train and test metrics are printed per fold. The mean and std of the ROC AUC is printed at the end. Returns all the trained models. Argum...
29fcd87eb1e36dbe81bdfba0e7d8d2e7a3df62ed
61,483
def getSimScenarioFile(simId): """ Returns the path to sim's copy of the scenarios.xml file. """ return getSimXmlFile(simId, ScenarioFileName)
4749ba1d4fde365d7be11b58c037b05342df5000
61,484
def bunchify(dict_tree): """ Traverses a dictionary tree and converts all sub-dictionaries to Bunch() objects. """ for k,v in dict_tree.iteritems(): if type(v) == type({}): dict_tree[k] = bunchify(dict_tree[k]) return Bunch(dict_tree)
3f7997f7b707ba0cf8099d06189b09f5b55df3c6
61,485
def bot(message): """Mocked instance of the bot""" class Bot: send_message = MagicMock() return Bot()
d74c459bcbdc757017fb9ce34192875fc8d9721c
61,486
from typing import Callable from typing import Any from typing import Optional from typing import List def run_simulation( process: iterative_process.IterativeProcess, client_selection_fn: Callable[[int], Any], total_rounds: int, file_checkpoint_manager: Optional[FileCheckpointManager] = None, met...
1913504613bda298cb099c9048b1a24ef63f5e51
61,487
import torch def unique_first(x): """ Torch function to get the first appearance unique items""" unique, inverse = torch.unique(x, sorted=True, return_inverse=True) perm = torch.arange(inverse.size(0), dtype=inverse.dtype, device=inverse.device) inverse, perm = inverse.flip([0]), perm.flip([0]) pe...
f38fd73fddeec9a4ad220a40ae6c27cdc58097e3
61,488
def make_generator(): """Creates a generator model that takes a 100-dimensional noise vector as a "seed", and outputs images of size 28x28x1.""" model = Sequential() model.add(Dense(1024, input_dim=100)) model.add(LeakyReLU()) model.add(Dense(128 * 7 * 7)) model.add(BatchNormalization()) ...
6cd56499c02500981a62f1ecb27f21506358488d
61,489
from typing import List def delete_policies(system_id: str, subject_type: str, subject_id: str, policy_ids: List[int]) -> None: """ 删除权限 """ url_path = "/api/v1/web/policies" data = {"system_id": system_id, "subject_type": subject_type, "subject_id": subject_id, "ids": policy_ids} permission_l...
a4827db7a4ebbd0470395c7d0240c333cd62d334
61,490
def WENOReconstruct( u_stencil, eps, p ): """WENO reconstruction. This reconstructs u_{i+1/2} given cell averages \\bar{u}_i at each neighboring location. See `High Order Weighted Essentially Nonoscillatory Schemes for Convection Dominated Problems'. Input ----- u_stencil : ...
aa49be7b069f09c90c9b350d86575376eb5c9fbb
61,491
def import_airfoil_polars(airfoil_polar_files): """This imports airfoil polars from a text file output from XFOIL or Airfoiltools.com Assumptions: Input airfoil polars file is obtained from XFOIL or from Airfoiltools.com Source: http://airfoiltools.com/ Inputs: airfoil polar files ...
1be5432bc5bbde5767c5591cbb06146f09547d90
61,492
from typing import List def _get_representative_years(df_temp: pd.DataFrame, FS: pd.DataFrame) -> List[int]: """ Args: df_temp(pd.DataFrame): FS: Returns: List[int]: 月別の代表的な年 """ df_threshold = pd.merge(df_temp, FS, on=['y', 'm'], suffixes=['_mean', '_fs']).sort_values(["m", ...
b0fb063fae3455dba28872575a87a8980f09b260
61,493
from toil.batchSystems.mesos.batchSystem import MesosBatchSystem def loadBatchSystemClass(config): """ Returns a pair containing the concrete batch system class and a dictionary of keyword arguments to be passed to the constructor of that class. :param config: the current configuration :param key...
c0e449fa0275b74559cf9a0bb8fa5b83fc034382
61,494
import warnings def convert_feature_vector_to_time_series(feature_vector, sample_data): """ Parse the feature name and reconstruct a time series object holding the equivalent data In a feature vector object, a feature is determined by the feature name and the feature value. When dealing with time do...
1fd02054fb1d94bb2cf8fe38283b3bf0167dbbcd
61,495
import inspect def generate_cache_key(namespace, f, *args, **kwargs): """Generates a string key, based on a given function as well as arguments to the returned function itself. """ argspec = inspect.getargspec(f) has_self = bool(argspec[0]) and argspec[0][0] in ('self', 'cls') if has_self: ...
b9f69980784560989d9c40426f091332f032eba9
61,497
def total_error(y_true, y_pred): """ I think this is simply the variance, but as a sum... """ return K.sum(K.square(y_true - K.mean(y_true)))
5364239bf16be7603149d45f09663fd9a651f454
61,499
def hill_climbing(data_frame, et0=None, u=5, metric='bic', metric_params=None, chc=False, tw_bound_type='b', tw_bound=5, optimization_type='size', k_complex=0.1, cores=multiprocessing.cpu_count(), forbidden_parent=None): """Gets the adjacency matrix of the Bayesian network encoded by the elimination tree et Ar...
531f867d74982db34802daf39f82cea81219fc49
61,500
def get_dataloader(batch_size, image_size, data_dir='processed_celeba_small/'): """ Batch the neural network data using DataLoader :param batch_size: The size of each batch; the number of images in a batch :param img_size: The square size of the image data (x, y) :param data_dir: Directory where ima...
ff4328fe649575850c79e3d84e98ddb8310dcb0b
61,501
def get_sample_list(obj, args): """ Try to get an attribute from an object. Example: {% if block|getattr:"editable,True" %} Beware that the default is always a string, if you want this to return False, pass an empty second argument: {% if block|getattr:"editable," %} """ args = args.split(...
9f218a4b3bd306a796edbe7393fc8c1baa9bd29b
61,502
def get_energy(vv, tt, chemical_potential, gbar=2.0, *args, **kwargs): # type: (np.ndarray, np.ndarray, np.ndarray, float, list, dict) -> np.ndarray """Get IFG energy E in atomic units. :param vv: Matrix of specific volumes in atomic units. :param tt: Matrix of temperatures in atomic units. :param ...
78cfbb098f159be4b803a7aa33c94f92eb442229
61,503
def load_idx_cmds(): """Load the cmds.h5 file, trying up to 3 times It seems that one can occasionally get: File "tables/hdf5extension.pyx", line 492, in tables.hdf5extension.File._g_new tables.exceptions.HDF5ExtError: HDF5 error back trace ... File "H5FDsec2.c", line 941, in H5FD_sec2_lock u...
0f1044e699d6eaf310663e3429c023634a436576
61,505
def objective_to_coeffs(objective_func, variables, objective_type='minimize'): """Extracts variable coefficients from symbolic minimization objective funtion. Parameters ---------- objective_func: symbolic linear expression variables: list of symbols objective_type: ...
0302f4a7789f9569340f70c33113cd26f7e42a20
61,506
def _stateless_uniform_orthogonal(shape, seed, gain=1.0, dtype=tf.dtypes.float32): """Samples an orthogonal matrix from the uniform/Haar distribution.""" # The implementation of this function is essentially copied from # tf.initializers.Orthogonal. # Check the shape if len(...
31019a8c2cad11317d680898920efe2d86fe2704
61,509
def read_ssm_params(params, ssm): """Build dictionary from SSM keys in the form `ssm://{key}` to value in the paramater store. """ result = ssm.get_parameters(Names=[s[len('ssm://'):] for s in params], WithDecryption=True) if result['InvalidParameters']: raise...
dc4aa3272b8b371621074230bc2ce2b3cad1dd72
61,510
from typing import Tuple def _split_resource(context: Context) -> Tuple[str, str, str]: """Splits a background event's resource into a CloudEvent service, resource, and subject.""" service = "" resource = "" if isinstance(context.resource, dict): service = context.resource.get("service", "") ...
5196f07516df20f1303745b70be77232e06d5c9a
61,511
def packages_by_price(inf, sup, packages): """ Retrieves all avaiable packages that are within a specified price threshold :param: lowest value of price :param: highest value of price :param: list of packages """ lista = [] if inf: inf = str_to_float(inf) else: inf = float(0) if s...
d26ddd4f3a513b0cf9fc69cfbbc620195b95f13e
61,512
def convert_example(example, tokenizer, is_test=False): """ Builds model inputs from a sequence for sequence classification tasks. It use `jieba.cut` to tokenize text. Args: example(obj:`list[str]`): List of input data, containing text and label if it have label. tokenizer(obj: paddlen...
e9c84c3a28bd6c03d4fb5deb82f012ecef5aae0e
61,513
def aten_type_as(mapper, graph, node): """ 构造转换Tensor类型的PaddleLayer。 TorchScript示例: %57 : Tensor = aten::type_as(%56, %mask.1) 参数含义: %57 (Tensor): 输出,改变类型后的Tensor。 %56 (Tensor): 需要改变类型的Tensor。 %mask.1 (Tensor): 转换成与该Tensor相一致的类型。 """ scope_name = mapper.normalize...
92c42927438d982f27aae1ec2173aa41d3912aff
61,514
import re def is_stable_version(version): """ A stable version has no letters in the final component, but only numbers. Stable version example: 1.2, 1.3.4, 1.0.5 Not stable version: 1.2alpha, 1.3.4beta, 0.1.0rc1, 3.0.0dev """ if not isinstance(version, tuple): version = version.split(...
995dff30ff81908e0d5a00d88816d874e9bfd626
61,515
def generate_color_array(colors, opacities): """Generate RGB arrays each with opacity values that corresponds to the frequency of the mutation present in each sample""" co = np.zeros((len(colors), 4)) for i, (c, o) in enumerate(zip(colors, opacities)): co[i, :3] = matplotlib.colors.to_rgb(c) ...
f5d13f148cf63f1599328c018d81d4be496bcc54
61,516
import click def runner() -> click.testing.CliRunner: """Return a CLI console for testing""" return click.testing.CliRunner()
098c0fdf232eb57913459d446b5b36d582ce5737
61,517
import json def login(): """ Log in the user """ errors = None try: request_data = json.loads(request.data) validate_dict_with_schema(request_data, "user/register/request") user = User.check_user( email=request_data["email"], password=request_data["p...
df97c182c13faca2e48d4af0faa0fb3e164ed76c
61,518
def mnx(): """Path to xref reduced xref file.""" return join(dirname(__file__), "data", "chem_xref_seedset.tsv")
46e49ce7df6cf285cc1f13336a72e3c78f9b733e
61,519
def get_preferred_ca_repository(): """Returns a singleton Secret repository instance.""" global _PREFERRED_CA_REPOSITORY return _get_repository(_PREFERRED_CA_REPOSITORY, PreferredCertificateAuthorityRepo)
c3bc5d5c1637b17bf859d3ba326f8aa35c9aac14
61,520
from datetime import datetime def chart_grouping_as_date(value): """Transforms a string YYYYMM or YYYY in a date object""" value = str(value) for format in ('%Y', '%Y%m'): try: return datetime.strptime(str(value), format).date() except ValueError: pass
92f80be0baea30944ebd90e1377dfa953f5fb7fa
61,521
def _ncvar_to_dict(ncvar, lazydict=False): """ Convert a NetCDF Dataset variable to a dictionary. """ # copy all attribute except for scaling parameters d = dict((k, getattr(ncvar, k)) for k in ncvar.ncattrs() if k not in ['scale_factor', 'add_offset']) data_extractor = _NetCDFVariableDataE...
2db5ac12bf06bf2f95cda89b2f6206f8b1813b06
61,523
def get_stream_credentials(username, password): """ Uses the `/user/uuid` endpoint. takes a valid username and password as parameter. It will return all the necessary credentials to use the API and the upload endpoints. e.g. username="bej48snvvthy", password="" """ endpoint = KICKFLIP_...
17a98632f71fdeb502e14db3cc37c68069ae7621
61,524
import re def desc( operation: str = 'None' ): """ 函数描述装饰器 自动添加请求属性配对 :return: """ def inner_method(f): # 获取方法的参数名集合 # FullArgSpec(args=['test_arg1'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={}) full_arg_spec = g...
644ab2db06c9d9028be54cab2b03054db56aa919
61,525
import requests def run_ticket_validation(user_id, access_token, nonce): """ Validates Oculus session ticket. Returns a unique ID for this player. """ token_check_url = 'https://graph.oculus.com/user_nonce_validate?access_token={access_token}&nonce={nonce}&user_id={user_id}' url = token_check...
d8f5ca9d92681fe1f7ccd91fde08cada3a788f4d
61,526
def impartial(f, *args, **kwargs): """ Acts just like Python's functools.partial, except that any arguments to the returned function are ignored (making it 'impartial', get it?) """ def func(*_a, **_k): return f(*args, **kwargs) return func
ef512146057ae09546b6e7fac64c2496ac8f7d53
61,528
def convert_15_to_18(the15Id): """ Convert Salesforce 15 Id to 18 Id Arguments: * the15Id - to be converted 15 Id Return: * 18 Id - converted 18 Id """ if not the15Id or len(the15Id) != 15: return the15Id cmap = { "00000": "A", "00001": "B", "00010": "C", "00011": "D", ...
7a9ae31da7a5a84977ca1f4a1d02307d4be1e5fa
61,529
def obs_seq(truth, obs_dim, obs_un, obs_op, seed): """This function takes the true state trajectory, and parameters, and returns an associated sequence of observations """ np.random.seed(seed) [sys_dim, nanl] = np.shape(truth) obs = np.zeros([obs_dim, nanl]) zero = np.zeros(obs_dim) R = np....
fc64bd73b2bfb519eadb1601271d8c76497b4bb0
61,530
import torch import asyncio async def webenv_slice(lock, state, indices, obs, act_len): """ Turns two PyTorch state tensors (pre-step and pre-output) (and what WebEnv received: observations and action lengths) into post-step state and lists of predictions and actions, asynchronously. """ # `obs` and `act_len`...
ffded703fbed40bf43713d62a798cbb6f5518c1e
61,531
def bpow_const(a, f): """Broken power law with constant. This model assumes that there is a break in the power spectrum at some given frequency. At high frequencies the power spectrum is dominated by the constant background. Parameters ---------- a : ndarray(5) * a[0] : the natura...
a57c36c7965d1fe8ebfe8db937741ad6557ba911
61,532
def basic_encoding(x: pd.DataFrame, is_classification: bool): """ Perform 'basic' encoding of categorical features. Specifically, perform: - Ordinal encoding for features with 2 or fewer unique values. - One hot encoding for features with at most 10 unique values. - Ordinal encoding for feat...
1567d8a0170a32d4353cc777c90cdd1ccef69d86
61,533
def liked_products_view(request, **kwargs): """Return all the products liked by a given user""" user_list = get_object_or_404(Like, user=request.user) serializer = LikeSerializer(instance=user_list) return Response(data=serializer.data)
7024a91bf66980148a26976f1696a10bbe4a0726
61,535
def generate_header(build_type): """Return a C/C++ header for the given build type. Args: build_type: The build type definition to use. Returns: A string containing the C/C++ header file. """ return BUILD_TYPE_TEMPLATE.format(build_type=build_type)
02fe6427fcfd23536c09d908593d0148e1a843cc
61,536
def grid_dist(self,bmu_ind): """ som and bmu_ind depending on the lattice "hexa" or "rect" we have different grid distance functions. bmu_ind is a number between 0 and number of nodes-1. depending on the map size bmu_coord will be calculated and then distance matrix in the map will be returned ...
60d3a1865bd750fe6c44aa16eedb4ecde504e855
61,537