content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
async def subnet_present( hub, ctx, name, address_prefix, virtual_network, resource_group, security_group=None, route_table=None, connection_auth=None, **kwargs, ): """ .. versionadded:: 1.0.0 Ensure a subnet exists. :param name: Name of the subnet. ...
66ab96df63a1a4e0d6ba0e5380360d06afe079d4
73,400
from typing import Dict def get_files_modified_since_fork(repo_dir, base_sha, head_sha, log, project_dir) -> Dict: """Get changed files and their status in head tree compared to base tree. Skip submodule changes. They require further processing to find out which files have actually been changed under the...
99e625833c58aff79af7ec8f5913bbfdc8d49269
73,401
from typing import Type def loadenv_into_dataclass(dataklass: Type[DataClass]) -> DataClass: """Return dataklass, instantiated with values from the environment""" dataklass_envfields = {} for var_in_env, var_in_dataklass in dataklass.__dataclass_fields__.items(): if not isinstance(var_in_dataklass...
8036af916da73250d4eb7a897438845b5029ab35
73,402
def random_sign(shape, dtype=tf.float32, seed=None): """Draw values from {-1, 1} uniformly, i.e., Rademacher distribution.""" random_bernoulli = tf.random_uniform(shape, minval=0, maxval=2, dtype=tf.int32, seed=seed) return tf.cast(2 * ...
db4b3b4fabede101186ba7f3500bf5b87fb39aba
73,403
def _lucas_test_sequence(n, a, b): """ Return x_0, x_1, x_m, x_{m+1} of Lucas sequence of parameter a, b, where m = (n - (a**2 - 4*b / n)) >> 1. """ d = a**2 - 4*b if (d >= 0 and arith1.floorsqrt(d) ** 2 == d) \ or not(gcd.coprime(n, 2*a*b*d)): raise ValueError("Choose another parame...
e412efcc088ea2a3ed8d548c873f234d62d5d24e
73,404
def _timestamp_date(arg: ir.TimestampValue) -> ir.DateValue: """Return the date component of `arg`. Parameters ---------- arg A timestamp expression Returns ------- DateValue The date component of `arg` """ return ops.Date(arg).to_expr()
6ba110d0d076253d22d34ec2dc11bd5c3ac7e582
73,405
def is_func_ptr(dis: Disassembler, address: int) -> bool: """Returns true if the given offset is a function pointer.""" # As a first check, simply see if the offset is the start of a function. try: func = dis.get_function(address) if func.start == address: return True except ...
42be0b05e7f2724b8610a5afc6ce80757fe3a78b
73,406
import torch import tqdm def train_one_epoch(model,train_loader:DataLoader,optimizer:AdamW,scheduler:torch.optim.lr_scheduler.LambdaLR,epoch:int,max_epoch:int): """Loops through the dataloader and trains the model and optimizer Args: model ([BertForSequenceClassification]): [description] data...
f05fe3a2fb5d392a8cf5f3e0abecb9956e42a23b
73,407
def generate_2D_reflection(angle): """ Given an angle generate a 2D rotation matrix""" angle_rad = angle/180.*np.pi return np.array([[np.cos(2.*angle_rad),np.sin(2.*angle_rad)],[np.sin(2.*angle_rad),-np.cos(2.*angle_rad)]])
80aa26eb16e9146e8f6b4f192c6be9afcf389106
73,408
from operator import index def compute_expected_obs_counts_jax(gamma, obs, n_states, n_obs): """ Computes the expected observation count for each observation o by summing the probability of being at any of the states for each time t. Parameters ---------- gamma : array A matrix of shap...
3cbe9625ad16c14a743382ba5a54b111082dedfe
73,409
def STOCH(data: xr.DataArray, fastk_period: int = 5, slowk_period: int = 3, slowk_matype: int = 0, slowd_period: int = 3, slowd_matype: int = 0) -> xr.DataArray: """ Stochastic (Momentum Indicators) Input: data: [high, low, close] Parameters: fastk_period: 5...
bb497649d36008b3cbd3df34caed13e0a1aa964a
73,410
from ecommerce.models import Product from hubspot.serializers import ProductSerializer def make_product_sync_message(product_id): """ Create the body of a sync message for a product. Args: product_id (int): Product id Returns: list: dict containing serializable sync-message data for ...
ed9f5512fd3f15169b829f57fee3334bb3e7a5fe
73,411
def generate_xy(number_pixels, center=0.0 * u.arcsec, pixel_size=1.0 * u.arcsec): """ Generate the x or y coordinates given the number of pixels, center and pixel size. Parameters ---------- number_pixels : `int` Number of pixels center : `float`, optional Center coordinates ...
e43d9fe3d0601453472c335db29ab240ee8c7652
73,412
def matched_modifiers(g, n, modifiers): """ returns the set of predecessors of node 'n' that are of a category contained in 'modifiers' """ pred = g.predecessors(n) if not pred: return False pcats = [] for p in pred: pcats.extend(p.getCategory()) return set(pcats).in...
d58453fa40271cad95ba9845026c17c2cc1025af
73,413
def new_matrix_input(): """Логика генерации новой матрицы""" n = int(input("Введите кол-во строк в матрице -> ")) m = int(input("Введите кол-во столбцов в матрице -> ")) # Генерируем matrix1 = matrix_gen(n, m) matrix2 = matrix_gen(m, n) # Пишем в файлы matrix_writer(matrix1, MATRIX1_FI...
0a3bc38edd90eb104e5a53252e1caeb2c1f53499
73,414
def _layout_to_matrix(layout): """Create the adjacency matrix for the tree specified by the given layout (level sequence).""" result = [[0] * len(layout) for i in range(len(layout))] stack = [] for i in range(len(layout)): i_level = layout[i] if stack: j = stack[-1] ...
cd27cad3a7ab6f34ea2be13e5617a34dbbba834f
73,415
from typing import Type def get_alg_dataset(alg_cls: Type[Algorithm]) -> Dataset: """Return an instance of the dataset for an algorithm.""" settings = _get_alg_settings(alg_cls)['dataset'] if isinstance(settings, tuple): (cls, kwargs) = settings else: (cls, kwargs) = (settings, {}) ...
1e4814f59abb85bb3918ae63a5562a20fad78a10
73,416
import click def email_arg(required, email="email", metavar="[EMAIL]", nargs=1): """ Email positional argument standard definition. Use as decorator for commands. """ return click.argument(email, metavar=metavar, nargs=nargs, type=str, required=required)
26e51c44f1109c0f690f243ee9d40de959570b08
73,417
def simplify_dataset_name(dataset_name): """In a couple of cases (BraTS and MURA) the dataset name is not quite correct because of a mistake made earlier in the pipeline. This function transforms the dataset names into a more readable format. Args: dataset_name (string): name of dataset to sim...
af0e504df0af2f250c716fb4f797970f31cbb1e1
73,418
import click from pathlib import Path import os def edit_inputs(client, workflow): """Edit workflow inputs.""" for input_ in workflow.inputs: new_path = click.prompt( '{0._id}'.format(input_), default=input_.consumes.path, ) input_.consumes.path = str( ...
e9668f717b50786ddd3fe6375f56d17bad5ada05
73,419
def read_graph(filepath, format='edgelist') -> Graph: """Reads a graph from an edge list file and returns an igraph Graph object. Parameters ---------- filepath : str Path to the edge list file. format : str Format of the input file, e.g. 'edgelist', 'pajek',... Returns ---...
2db0a5d6af99eb76aeec84a2085f88e54084879e
73,420
def read_img(components): """ Loads image from meta.img_path. Assigns the image to the field img of the same meta instance. :param components: components :return: updated components """ img_buf = open(components[0], 'rb').read() if not img_buf: raise Exception('image not read,...
016628a0f167cac7a4efa6da20e8e6d8c0504523
73,421
import requests from bs4 import BeautifulSoup def get_problems() -> list: """Get the list of problems Returns: list: Problems """ problems = [] website = requests.get(view_url) soup = BeautifulSoup(website.text, 'lxml') for i in soup.find_all('span'): try: ...
3a2ceb643edb22d09dee76a62e7c23269986af01
73,422
import logging def NN_aggregate_model_updates(clients_model_updates, global_model_parameters, update_rate, verbose, aggregation_type): """ For each layer average the gradient and add it to the global model layer with some update_rate """ agg_weights = [] clients_model_updates_copy = list(clients_m...
9fdcdc0ccd539345708a41f0c6f170c7bb2ee86c
73,423
from datetime import datetime def report_top_month(request): """ TOP 30 users-downloaders """ today = datetime.datetime.combine(datetime.date.today(), datetime.time()) last_mon = today - datetime.timedelta(days=today.weekday(), weeks=1) last_mon = int(datetime.datetime.timestamp(last_mon)) ...
35201f0a0509bc1d78d58cf5d90407b16dbb0720
73,424
import json def api_products_delete(barcode): """ API method : Deletes an item from the products table. Outputs JSON. Returns the latest version of the grocery list. JSON format : - {"status": ...} Possible return status : - OK (200) - DELETE ERROR (400) """ # AJAX Auth che...
5a32d5e203e7d4a76c6a12d6bb2375d030bf6022
73,425
import argparse def get_parser(): """ Returns the CLI parser to get the YAML file for the EC2 instance configuration. Retrieve the YAML configuration file using the 'file' argument. """ parser = argparse.ArgumentParser(description='Creates EC2 instances from a basic YAML configuration file') ...
2f57a88db79529e89d685a84dcdcf8101f38a833
73,426
def cpu_mandel(x, y, max_iters): """ Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. """ c = complex(x, y) z = 0.0j for i in range(max_iters): z = z * z + c if ...
30d0b637a924670e4038ba9f68c20c943de0e009
73,427
def get_model(model_class): """This functio nis for building the model for mlp and lstm""" model = Sequential() if model_class == 'mlp' or model_class == 'mlp_angle' : # Add a hidden layer with ReLU activation model.add(Dense(1024, input_dim=input_dim, activation='rel...
5a2b568ea1f02d9b007bc92d59e8535bf478b275
73,428
def get_test_data_path(): """ Returns the path to test datasets, terminated with separator. Test-related data are kept in tests folder in "data". Based on function by Yaroslav Halchenko used in Neurosynth Python package. """ return abspath(join(dirname(__file__), "data") + sep)
22325d16fd6eafb6acfa7564918cf3941dec803d
73,429
from typing import Tuple def load_dataset(dataset_path: str, mode: str) -> Tuple[list, list, list, list]: """ Divide all audio paths and transcripts into train and validate Args: dataset_path (str): path with audio and transcript mode (str): flag indication train or eval Returns: tra...
af18885c5cf9bc7b6831fae7574b520e5a55046f
73,430
def single_recurrence_goal(target, z_next, within, players, ij, aut): """Development harness for parameterized assumption construction.""" assert 'scheduler' not in players print('single recurrence goal: {ij}'.format(ij=ij)) i, j = ij assert i >= 0, i assert j >= 0, j phase = '{i}_{j}'.forma...
5082ee4c4e07be296e7bd15d03e3930ebc0c6b20
73,431
def upload_file(project_id): """Upload file (POST) - Upload a data file to the project's filestore. """ # The upload request may contain a file object or an Url from where to # download the data. if request.files and 'file' in request.files: file = request.files['file'] # A browser m...
a9ab038b9e65e8abc0a71904a9c75a282bc13df6
73,432
def colormap_to_rgb(raster): """" The function is designed to work with single band image service that has internal colormap. It will convert the image into a three-band 8-bit RGB raster. This function takes no arguments except an input raster. For qualified image service, there are two situations ...
6174c519a854ff15cf5bc8cc17cafee6ebacb4df
73,433
import numpy def filled_circle(shape, radius, center=None): """ creates a circle mask of defined radius and center in an array of the provided shape with value of 0 inside the circle and 1 outside the circle """ r2 = radius*radius if center is None: ### set to center of array center = (shape[0]-1)/2.0,(sh...
ad7f252d5b225ccd4496843ee8ebbd71ab2196da
73,434
def binary_labelisation_from_markers(tree, object_marker, background_marker, leaf_graph=None): """ Given two binary markers :math:`o` (object) and :math:`b` (background) (given by their indicator functions) on the leaves of a tree :math:`T`, the corresponding binary labelization of the leaves of :math:`T` i...
6861b2411f99f5accc02726eb132afde3c3ce442
73,435
def get_pointcloud_bbox(pointcloud: np.ndarray) -> AABB: """ Create a mitsuba bounding box by using min and max on the input ndarray :param pointcloud: The pointcloud (Nx3) to calculate the bounding box from :return: The bounding box around the given pointcloud """ min_values = np.min(pointcloud...
f0070a2ff339a7bd72052f7933ac29cca05bd949
73,436
def arange(start, stop=None, step=1, dtype=None, ctx=None): """Return evenly spaced values within a given interval. Values are generated within the half-open interval ``[start, stop)`` (in other words, the interval including `start` but excluding `stop`). For integer arguments the function is equivalen...
93c2698032b9f0864bcf3b3537cbba2914a02c61
73,437
def U_np(angle1, angle2, angle3, invert): """Return numpy array with U gate (IBM).""" gate = np.zeros(4, dtype=complex).reshape(2, 2) cosan = np.cos(angle1/2) sinan = np.sin(angle1/2) mult = 1 if invert: mult = -1 gate[0, 0] = cosan if not invert: gate[0, 1] = -sinan * np...
eaf81ac490d9cdb8d97410737bae2caa4ff370cc
73,438
def log_log(xarr, yarr, *args): """Given x and y, returns log(x) and log(y) arrays. """ x = np.array(list(map(lambda xi: np.log(abs(xi)), xarr))) y = np.array(list(map(lambda yi: np.log(abs(yi)), yarr))) return (x, y) + args
5a3dcc7340468cfed5bbfb06c300769ac5eb2460
73,439
import google def get_local_user(network, site_id): """Get the local user_instance from the social details.""" network_check = models.User.oauth_site == network id_check = models.User.social_id == site_id existing_user = (models.User.query .filter(network_check) ...
56b8b0851f27d12b73948fb7bc9f72405a71ce65
73,440
def insertTensor(tree, graph, dims=[2, 2, 2], dtype='VX_TYPE_UINT8', fpp="0"): """ Insert a tensor """ tensor = etree.Element(etree.QName(tree, stensor)) ref = getNewRef() updateAttributes(tensor, dict(reference=ref, number_of_dims=len(dims), data_type=dtype, fi...
deb628d797d26714bd5e11602e3b1695268b8a10
73,441
import random def seq_aleatoire(l_ascii): """Mélange une liste. Cette fonction permet de générer une séquence alétoire de même composition que celle passée en argument. Parameters ---------- l_ascii : list `l_ascii` est une liste d'entiers. Returns ------- l_ascii : list...
eb9c3e1d5182c4a359566e8efd1174934f415c4b
73,442
def pos_wise_FFN_module(x, n_inner=2048, keep_prob=0.9, is_training=False, scope='PW_FNN_module'): """ postion wise Feed forward networks sublayer module """ with tf.variable_scope(scope): n_hidds = x.get_sh...
b4cd7173337c3bb3a4ebf8ae49a3a58f87cd8e95
73,443
def maketrans(fromstr, tostr): """maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length. """ if len(fromstr) != len(tostr): raise ValueError, "maketrans arguments mus...
38be4d42c1e671fb04b693055b355b501490422d
73,444
from typing import Tuple def _load_feature_metadata(feature_file: str, format_type: str, sep: str = "\t") -> Tuple[pd.DataFrame, str]: """ Load feature information """ feature_metadata = pd.read_csv(feature_file, sep=sep, header=None) if format_type == "HCA DCP": # HCA DCP format genes.tsv.gz ...
c02599e0bac9fca6cadfafdd6835ce578b10dcb3
73,445
import warnings def compute_err_score(true_positives, n_ref, n_est): """Compute error score metrics. Parameters ---------- true_positives : np.ndarray Array containing the number of true positives at each time point. n_ref : np.ndarray Array containing the number of reference freq...
b215fc28609bc6584912dc5d87172eb3b9c909cd
73,446
def fibonacci_recursive(nth_nmb: int) -> int: """An recursive approach to find Fibonacci sequence value. YOU MAY NOT MODIFY ANYTHING IN THIS FUNCTION!!""" cache = {0: 0, 1: 1} def fib(_n): return _n if _n in cache else fib(_n - 1) + fib(_n - 2) return fib(nth_nmb)
a6efe2a984e743d580d04a106a04463fa5d329c3
73,447
def api_core_myself(): """自身のCcInfoのCRUD.""" if request.method == 'GET': return _get_core_myself() abort(405)
4c983a5a2c27b7bc11c3ef16b21b1dce50a45252
73,448
import os import numpy as np import h5py def psf_maker(file_name, wl_endpoints=(350, 1100), f=1, size=101, res=(100, 100)): """ Creates a new file containing the full-color PSF, without interpolating as with psf_maker Parameters ---------- file_name : str Desired name of the file. wl_...
aaa24f6145e6796d4d4fb2267350c524b42d7554
73,449
def AC(obs, mod, axis=None): """ Anomaly Correlation """ obs_bar = obs.mean(axis=axis) if not axis is None: obs_bar = np.expand_dims(obs_bar, axis=axis) p1 = ((mod - obs_bar) * (obs - obs_bar)).sum(axis=axis) p2 = (((mod - obs_bar) ** 2).sum(axis=axis) * ((obs - obs_bar) ** 2).sum(axis=axis)...
07c6891769793729eafa6b72cfed281153a9c46e
73,450
def table_to_data_frame(table): """Converts a vtkTable to a pandas DataFrame""" if not isinstance(table, vtk.vtkTable): raise _helpers.PVGeoError('Input is not a vtkTable') if not isinstance(table, pv.Table): table = pv.Table(table) return table.to_pandas()
0219cb28d766ea7ae3aaee27f83b672c4d2eae01
73,451
def ode_solutions(t,tsteps,M,S,gamma): """ Solve the differentials with an array of initial conditions and returns lists of positions and velocities. Parameters ---------- t: float The current time t[i]. tsteps: int The number of times between [0,t] the solution is calculate...
aeb10534620852042f9dae0492976e358d444c2b
73,452
import time def test_main2(): """Tests buckets containing multiple matches for traffic.""" b = [] # counting buckets for i in range(0,2): b.append(QueryTest()) time.sleep(0.2) pol1 = match(srcip=ip1) >> b[0] pol2 = match(srcip=ip2) >> b[1] pol3 = match(srcip=ip3) >> b[0] ...
61a43a7586aaa4ad548b97a0e6cbaa342aec37ea
73,453
def recall_from_cfg(cfg): """ Runs MCQ from julia based on the passed configuration Params cfg: Configuration (ConfigSpace.ConfigurationSpace.Configuration) Configuration containing the parameters. Configurations are indexable! Returns: scores: A crossvalidated mean score for the ...
27ab71d4486d5bc084e2419546c6e64c03b22f46
73,454
import keyword def is_valid_implicit_namespace_package_name(s): """ Checks whether provided string could represent implicit namespace package name. :param s: string to check :return: True if provided string could represent implicit namespace package name and False otherwise """ return isidenti...
2ded9b0c20913d5a440169532d064b2691671a35
73,455
import logging from datetime import datetime def _load_listing_from_file(dir: WindowsPath = project_dir / 'data/raw', **kwargs) -> pd.DataFrame: """ Loads the data from file, drops some null rows, add `execution_date` and then upload to Postgres. :param dir: The directory t...
ccfb91e733e7db887907962e02b33d220e89b2f9
73,456
def get_maps_nested(models, cases, varList, from_time, to_time, avg_over_lev=False, pmin=None, p_level=None, pressure_adjust=True, raw_data_path=get_input_datapath(), recalculate=False, ...
f7f8960a6a455c5fa33ffd0555fef4c66a2fb5e8
73,457
async def login_post(request: Request, user: str = Form(...), db: Session = Depends(get_db)): """ POST route handler for the login page of the webapp :param user: The form data for the user name to use to login. :param db: Dependency for the db session. :return: The response to the user based on the...
df97fffb0e9cc25fc681400edef29b19e0d7e6df
73,458
import numpy def _raw_fftnd(x, s, axes, direction, overwrite_x, work_function): """ Internal auxiliary function for fftnd, ifftnd.""" if s is None: if axes is None: s = x.shape else: s = numpy.take(x.shape, axes) s = tuple(s) if axes is None: noaxes = T...
6341f5f49ef23fd773e285a845b39cf74332498f
73,459
def check_apikey(name, query_type): """Verifies API Key.""" if not config.get(f"{name}", "api_key"): print(f"Please add {name} api key to the '{settings.name}' file") else: api_key = config.get(f"{name}", "api_key") name = query_type(api_key) return name return None
38716627628b31094660b70b3da3e655f1150219
73,460
def delete(): """ Deletes a system settings from list. :return: 200 on successful delete, 404 if not found """ user = security.get_valid_user_from_token(dbsession=db.session) logger.debug(f"Logged in user {user}") if not (user and user.isLZAdmin): return abort(401, "JWT not valid...
4c4661b91d6574adcb395f5fd661dfc1b9e4f4e8
73,461
from typing import List def motion_annotation(ephemerides: List[Ephemeris], wcs: WCS) -> GroupAnnotation: """Return an annotation showing the motion of an object on the sky. If the motion is sufficiently large, it is shown as an arrow from the initial to the final position. Labels for the initial and fin...
39dcf46898b6c730ec1a1e452321c8f63c5620cf
73,462
def select_k_best(points, scores, k, H=None, shape=None, margin=0): """ Select the k best scoring points. If H and shape are defined, additionally keep only the keypoints that once warped by H are still inside shape within a given margin to the border. """ if H is None: mask = np.ze...
5072e9542acea5cdd65f9df29ef6e3e24d970243
73,463
def predict_linear_regression_labaled_features(fitted_model, dict_features): """ Calculates y ~ const + sum( parameter*value ) essentially the inner product { 'feature name' : value } Does not assume you have all features present, so prediction may be off. Assumes const parameter is not p...
b86fa00ff80e528080e473f849721a16e6f9f2a8
73,464
import json def get_store_username(): """ 如果存储了用户名,就获取它 """ filename = 'username.json' try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return username
68197999c12d0fdc5574dde45e92ef09f4a37d58
73,465
def group_documents_by_owner(documents): """Groups documents by owner.""" grouped = defaultdict(lambda: []) for doc in documents: grouped[doc.evergreen_owner].append(doc) return grouped
e1b7bc9c571d3d376dea7811923f0e665120a37c
73,466
def parse_time(text): """ parse time of slurm output """ # check for days tokens = text.split('-', 1) if len(tokens) > 1: days = int(tokens[0]) rest = tokens[1] else: days = 0 rest = tokens[0] # check for time tokens = rest.split(':') return days*24*60 + ...
91a07479f02a6d428a2c45fe6b701e009a9675cf
73,467
def sigmaclip_inf(a, sigma_lower=3., sigma_upper=3., cenfunc='median', ddof=1, outfunc='median'): """ Infinite loop sigma-clip. copy from `scipy`_. .. _scipy: https://github.com/scipy/scipy/blob/4c0fd79391e3b2ec2738bf85bb5dab366dcd12e4/scipy/stats/stats.py#L3159-L3225 """ # bn.me...
7ac94c1857f69c55c294e41f6a5a92c8b9fd94e3
73,468
import gzip import json import hashlib def labeled(token, feature, frame): """ """ project = Project.get(token) if not project: return jsonify({'error': f'project {token} not found'}), 404 labeled_array = project.get_labeled_array(feature, frame).astype(np.int32) content = gzip.compress(js...
800604821c15055cf9440e7e914d97744cf5fe14
73,469
def get_video_name(image_name): """ Extracts the video name from an image filename. Args: image_name: The name of the image file. Returns: The name of the video that the image belongs to. """ video_name = image_name.split("_")[0:3] video_name = "%s_%s_%s" % (video_name[0], video_name[1], video_name[2]...
d2e5254dfaa650455b346cec43273cd50004b335
73,470
def pretrain_model(albert_config, seq_length, max_predictions_per_seq, initializer=None): """Returns model to be used for pre-training. Args: albert_config: Configuration that defines the core ALBERT model. seq_length: Maximum sequence length of t...
070e2b57487d130be823cee5924f522e2c48217a
73,471
import keyword def is_identifier(string): """Check if string could be a valid python identifier :param string: string to be tested :returns: True if string can be a python identifier, False otherwise :rtype: bool """ val = PYTHON_IDENTIFIER_RE.match(string) and not keyword.iskeyword(string) ...
e0a2360909fb14a851711780051319c77cd27d22
73,472
def create_tf1_call_model_function(graph, session, y, x, conv_layer=None): """Creates a call_model_function which calls the TF1 model specified. Args: graph: The TensorFlo...
041db914ece83ae0f58162bc625ebf213207d62a
73,473
def check_orthogonality(modes, num_modes): """ Check orthogonality of modes. :param np.ndarray modes: modes. :param int num_modes: number of modes. :return: True if orthogonality check passes. :rtype: bool """ for m1 in range(num_modes): for m2 in range(num_modes): if m1 == m2: s_ = np.sum(modes[:,m1...
07c2fadf7ead843aee0a1e2f5048b84dd345a207
73,474
def Mce3(m, q, ξ, *, p=0): """ v = Mce3(m, q, ξ, *, p=0) Compute the value of the even Radial Mathieu function of the third kind Mce⁽³⁾ₘ(q, ξ). Parameters ---------- m : array_like interger order of the Mathieu function q : array_like positive parameter in the Mathieu d...
349a3de477bb9c7913e18b3848db9ded040b776b
73,475
import os import tempfile import shutil def _get_metrics( datadriftdetector, start_time, end_time, run_id, daily_latest_only=True, with_adhoc=False, logger=None, ): """ :param datadriftdetector: :param start_time: :param end_time: :param run_id: :param daily_latest...
c3584637ebad2e6142c22db35118083abe17f925
73,476
from loopy.isl_helpers import static_max_of_pw_aff from loopy.symbolic import pw_aff_to_expr from loopy.kernel.data import VectorizeTag from pymbolic import var import six def privatize_temporaries_with_inames( kernel, privatizing_inames, only_var_names=None): """This function provides each loop iteration...
ef83a9b3fa00bfebcbeaf1c4dc2004e2e4ab5b60
73,477
def task(func): """A decorator for a task function The k2phot model is that you write wrapper code around your pipeline functions that extract values from a clipboard to pass as input arguments, and store the return values back in the clipboard. This wrapper code is called a "task". This decor...
6a2ce615585ca1af8418e7d674c2ddae15946448
73,478
import argparse import os def parse_args(): """Parse the command-line arguments and canonicalize file path arguments""" parser = argparse.ArgumentParser(description="Script to incrementally " + "upload an Illumina run directory (HiSeq 2500, HiSeq X, NextSeq, " + "MiSeq). This script c...
2575228903983b7d36e8dddc33d0f318a9013161
73,479
def estimate_reasonable_max(df, x): """Estimate a reasonable maximum value for the plot y axis.""" # Use 1.5 IQR of the largest group. group = df.groupby(x) q1 = group.Time.quantile(0.25) q3 = group.Time.quantile(0.75) iqr = (q3 - q1).max() return q3.max() + 1.5*iqr
a5fd4be194ca938c7cebd1ad31128ccffcfd44bd
73,480
def multilabel_precision(y_true, y_pred): """ Macro-precision, with thresholds defined by by argmax F1 """ values = list() for i in range(y_true.get_shape()[1]): pr, rec, thresholds = precision_recall_curve(y_true[:, i], y_pred[:, i]) f1 = 2.0 * pr * rec / (pr + rec) values.a...
25895da1a32085aa1f737d9afd13be3cbc6c06c6
73,481
def _add_members_to_obj(obj, data, columns): """Add members to obj.members """ i = 0 for member in obj.members: name = 'member_' + str(i + 1) data += ('\n'.join((f'{a}={v}' for a, v in member[i])),) columns = columns + (name, ) i += 1 return data, columns
6fd03824f3a17bb92fd7a42e16d3951222451cc2
73,482
def Compounds2Scaffolds(db,cids): """ Return list of ScafIDs for selected compounds. """ cur=db.cursor() sql='''\ SELECT DISTINCT scaffold.id AS scafid FROM scaffold JOIN scafid2cid ON (scafid2cid.scaffold_id=scaffold.id) JOIN compound ON (compound.id=scafid2cid.compound_id) WHERE compound.id IN ( %(CIDS)s...
7001628b0e9c4bc0ef569ae94857bafd02cfc430
73,483
def toggle_values_by_name(username=None, domain=None): """ Loads all toggles into a dictionary for use in JS all toggles (including those not enabled) are included """ return {toggle_name: (toggle.enabled(username, NAMESPACE_USER) or toggle.enabled(domain, NAMESPACE_DOMAIN...
a81efbccc5c0305a9d9bcd5b59bce9ac948cb151
73,484
import math def get_exp(quantizer): """get max/min exp value for relu_po2 or quantized_po2.""" if quantizer.is_signed: non_sign_bits = quantizer.bits - 1 else: non_sign_bits = quantizer.bits min_exp = -2 ** (non_sign_bits - 1) max_exp_orig = 2 ** (non_sign_bits - 1) - 1 max_exp = max_exp_orig ...
b8a6e0f090c065e34350ee064f9b37bd09064b4b
73,485
def scale_df_X_to_range(df_X, a, b): """ Given df_X (a pd.DataFrame containing just X values where each row is a time series and each column is a voltage), scale each row to the range [a, b]. Take the min and max values for the sequence to be -40 and 40 (found by inspecting all time series individu...
abe59ed3a7f17d4f74a5d74ab948e3abb2a77044
73,486
from typing import Type def count_field(instance: Type[Model], field: str) -> int: """ Returns count of a related field. if `{field}_count` exists in instance, then it's value will be returned """ count = getattr(instance, f'{field}_count', None) if count is None: count = getattr(insta...
8c6723f725f37c27d3df9d604671244eebd7f16f
73,487
def parse_number(value, locale=None): """Take localized number string and return a long integer. Throws ValueError if bad format. """ return long(value.replace(get_group_format(locale), ""))
b30ee5ec347710a5a81e2ff78eb1885deef98294
73,488
import gzip def load(filename): """Loads a compressed object from disk """ file = gzip.GzipFile(filename, 'rb') object = cPickle.load(file) file.close() return object
c381d24517a73fc2aac08d29a340718bb442680c
73,489
def _correct_background(v_raw_score, mat_ctrl_raw_score, v_var_ratio_c2t): """Cell-wise and gene-wise background correction Args ---- v_raw_score (n_cell,n_ctrl) : np.ndarray Trait raw score mat_ctrl_raw_score (n_cell,n_ctrl) : np.ndarray Control raw scores ...
0ab76890f69bf6db1f8b05c6e462f82405330817
73,490
def get_points(file,img_shape,mirror=False): """ Read wp from a YOLO style file: each wp are the upper-left and the lower-right points of the bounding box """ points = [] img_shape = img_shape[:-1][::-1] file = open(file).read().split('\n')[:-1] for r in file: r = r.split() ...
9648edc2aa065aceadf2128c28b5ff71ded2cb92
73,491
import os import traceback def delete_recpie(): """Remove recipe from data base.""" try: recipe_id = request.args.get("id") recipe = recipemodel.Recipe.get(recipemodel.Recipe.id == recipe_id) if recipe.image: utils.remove_file(os.path.join(current_app.config.get("IMAGE_PATH...
619f04220ed2a86928aabc6dba55bf9b2d578532
73,492
import os import sys import json def load_alias(path="alias.json"): """Load alias, return empty dict if file not found Keyword Arguments: path {str} -- path or filename of Alias JSON (default: {"alias.json"}) Returns: dict -- loaded dictionary of alias Raises: UnknownPythonE...
e3c5cc730388757d8c20d6be4e1f736d22b54cc0
73,493
def orjson_dumps(v, *, default): """ orjson.dumps returns bytes, to match standard json.dumps we need to decode. orjson.dumps option arguments provide many options such as `option=orjson.OPT_SERIALIZE_UUID` to natively encode UUID instances. """ return orjson.dumps(v, default=default).decode()
450473c8a4af546114aa453dcdead5530d7e6534
73,494
def definition(): """ Cost information, for use in TT administration. Seperate to v_c_cost for performance reasons - the other is used for the curriculum model interface. """ acad_week_list = text_concat( "acad_week", "x.acad_week FROM c_cost_week x WHERE x.cost_id = c.cost_id", ", ") ...
3ae36d32a066b8280a409d44c7e51f62ddfc7e4f
73,495
from typing import Optional from typing import Union from typing import Sequence from typing import Dict from pathlib import Path def prepare_mtedx( corpus_dir: Pathlike, output_dir: Optional[Pathlike] = None, languages: Optional[Union[str, Sequence[str]]] = "all", num_jobs: int = 1, ) -> Dict[str, Di...
0cc2790354ac008685061539de448468662eeb3d
73,496
import json import os def build_feature_dict(args, examples): """Index features (one hot) from fields in examples and options.""" # if not args.create_vocab: return json.load(open(os.path.join(args.vocab_dir, 'feat_dict.json'))) def _insert(feature): if feature not in feature_dict: ...
7be12c092f369587429e7ff0af9c05b2e6200c55
73,497
def get_label_mask(labelPath, params, mode): """ Loads the ground truth image (semantic or depth) :param labelPath: Path to the ground truth file (CLS or AGL file) :param params: input parameters from params.py :param mode: either SEMANTIC_MODE or SINGLEVIEW_MODE from params (0 or 1) :return: nu...
049e9c0195f840c3a62e2db9e31eae75c67e02cd
73,498
def _is_url(filename): """Check if the file is a url link. Args: filename (str): the file name or url link. Returns: bool: is url or not. """ prefixes = ['http://', 'https://'] for p in prefixes: if filename.startswith(p): return True return False
cfffb3db75de4f613097c081f950d3feff079f63
73,499