content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import uuid from datetime import datetime def new_issue( session, repo, title, content, user, issue_id=None, issue_uid=None, private=False, related_prs=[], status=None, close_status=None, notify=True, date_created=None, milestone=None, priority=None, ass...
cf8c05819ca5dc48cfa826cb1f3f9d2995bee722
38,200
import argparse def options(): """Parse command line options. Args: Returns: argparse object Raises: """ parser = argparse.ArgumentParser(description="Share Clowder Datasets by associating them with a Clowder Space.", formatter_class=argparse.A...
6f22870c115ec2442e0f935228cca89bd9be21bc
38,201
import sys def memory_usage(obj): """Returns the memory usage in a human readable format.""" def get_size(obj, seen=None): """Recursively finds size of objects""" size = sys.getsizeof(obj) if seen is None: seen = set() obj_id = id(obj) if obj_id in seen: ...
a3dd735797c875e03f1800ae9857da5005cc9800
38,202
import os def read(path_to_image): """ Read MCCD image from file. Parameters ---------- path_to_image : str Path to MCCD image to read Returns ------- (image, metadata, mccdheader) : tuple Returns tuple containing the ndarray of the image, experimental metada...
0aa1052eb9a2221c054ee003b4a53afb203d5c19
38,203
def fit_circle_to_data(in_data, verbose=False): """ Wrapper around _fit_circle_impl that takes care of unwrapping shapes and so on... Returns ------- """ slope, intercept, r_value, p_value, std_err = linregress(in_data[0], in_data[1]) if verbose: print("R-square of linear fit : {}"...
223b349c37e6d04f8a3b7823ed70dd335d48d19a
38,204
def dilated_components(output, dil_param, cc_thresh): """ Performs a version of connected components with dilation Expands the voxels over threshold by dil_param in 2D Runs connected components on the dilated mask Removes the voxels which weren't originally above threshold """ if dil_param...
d5e9444db2fcbafcad7cf7e3b5a14e2e5f0de7ee
38,205
def get_model(sess, image_shape=(80, 160, 3), gf_dim=64, df_dim=64, batch_size=64, name="autoencoder", gpu=0): """ Compiles and outputs models and functions for training and running models. """ K.set_session(sess) checkpoint_dir = './outputs/results_' + name with tf.variable_scope(...
eaca2291266b865a69fc617a5b09479d1fdad134
38,206
from typing import Tuple def define_model() -> Tuple[Model, Model]: """Defines the architecture of the model.""" i = Input([None, None, 3], dtype=tf.uint8) x = tf.cast(i, tf.float32) x = preprocess_input(x) # base_model = MobileNetV2(include_top=False, weights='imagenet', input_shape=(192, 192, 3...
60d5e5da86d1379360a1de7fa6877578e0f39fe5
38,207
import os def get_pid(pidfile, default=None): """ Get the PID (Process ID) by trying to access an PID file. Args: pidfile (str): The path of the pid file. default (int, optional): What to return if file does not exist. Returns: pid (str): The process id or `default`. """...
5f6c94e38bf7e1c788a5861a79455b31696c4259
38,208
def get_case_forms(case_id): """ Get all forms that have submitted against a case (including archived and deleted forms) wrapped by the appropriate form type. """ form_ids = get_case_xform_ids(case_id) return [fetch_and_wrap_form(id) for id in form_ids]
1d7afb1c08ec69a8f8f9d57456ecdd4c7dff08f2
38,209
def get_generic_data(): """ Get generic variables. Parameters ---------- gendata: str path to generic data directory. Returns ------- dict: the generic variables. """ gen_data = { 'instance_display_name': _get_display_name(), 'auth': _get_authenticat...
ad862aa030eb255a89a0b56204918ec2474bf3a1
38,210
import torch def generate_embeddings_of_one_image(model, dataloader, repeats=50): """Generates representations for all images in the dataloader with the given model """ embeddings = [] filenames = [] with torch.no_grad(): for _ in range(repeats): for (img1, img2), _, _ in ...
00099996cae6449c9e138fbbd4334a9317098fb8
38,211
import requests def get_status_code(url, opts): """ Open connection to the given url and check status code. :param url: URL of the website to be checked :return: (availibility, success, HTTP code) """ availibility, success, code = (False, False, None) timeout_duration_seconds = get_opt(op...
5799152a6e040d273b8720572330abf5a1ff17fc
38,212
def get_default_kubernetes_metadata_config( ) -> metadata_store_pb2.ConnectionConfig: """Returns the default metadata connection config for a kubernetes cluster. Returns: A config proto that will be serialized as JSON and passed to the running container so the TFX component driver is able to communicate wi...
ae6fe0a73bd9453f81223b2602a32f95d7fea31c
38,213
def camb_fisher_derivs(p): """ Get derivatives (as a function of ell) for the full set of CAMB Fisher parameters. Includes TT, EE, TE derivatives. """ # Get derivatives for various parameters # {n_s, w0, wa, w_b, omega_k, w_cdm, h} d_ns = camb_deriv("scalar_spectral_index__1___", 0.004, p) ...
37b4a5d7b193c8f63085dcd611cf61f672772d0f
38,214
def compute_hard_volumes(labels, voxel_volume=1., label_list=None, skip_background=True): """Compute hard volumes in a label map. :param labels: a label map :param voxel_volume: (optional) volume of voxel. Default is 1 (i.e. returned volumes are voxel counts). :param label_list: (optional) list of label...
c107e1ef2b69de4dca2564fbf2f35b6ff15e8277
38,215
def pairwise(iterable, pairs=2): """ a generator to return n consecutive values from an iterable, e.g.: pairs = 2 s -> (s0,s1), (s1,s2), (s2, s3), ... pairs = 3 s -> (s0, s1, s2), (s1, s2, s3), (s2, s3, s4), ... adapted from https://docs.python.org/3.7/library/itertools.ht...
afa62818854ea7bf175efded7307aa1f74435711
38,216
def logical_intervals(vals, x=None): """ Determine contiguous intervals during which ``vals`` is True. Returns an Astropy Table with a row for each interval. Columns are: * idx_start: index of interval start * idx_stop: index of interval stop * x_start: x value at idx_start (if ``x`` is supplie...
2c692b412004096c0ad6314ddcc7bf705abb1598
38,217
def coords2uv(coords, width, height): """ Image coordinates (xy) to uv """ middleX = width / 2 + 0.5 middleY = height / 2 + 0.5 uv = np.hstack([ (coords[:, [0]] - middleX) / width * 2 * np.pi, -(coords[:, [1]] - middleY) / height * np.pi]) return uv
4264bca17713835da8ce7ce3063d00796c5a9c0d
38,218
def _compute_teleport_distribution_from_ratings(user_rating, all_movies): """ returns the teleporting distribution as explained in the homework if a movie M has been rated, its probability is: RATE_M / SUM_OF_ALL_RATINGS else, its probability is: 0 :param user_rating: a dict of (movie_id, rating) :param all_movie...
7a88cf8a69c9fafc70e14d9337f0af25829bfb20
38,219
def extract_subdomain(url): """Uses teldextract to retrieve the subdomain of the url""" return tldextract.extract(url).subdomain
368fe66d84c6e4b2380b60089be99b6d8a8fe205
38,220
from typing import Optional from typing import Any def check_empty(value: Optional[Any]): """Validate whether the value provided is of class `Empty`.""" if isinstance(value, Empty): return True return False
e9cb5ff4685599bfd6f680a72931017f220fc0cd
38,221
def get_env_config(env_name=None, config_file=None): """Fetch an environment name and config object from the config.json file. If the name is None and there's only one environment, we'll select the first, otherwise we'll die to avoid ambiguity. :param config_file: a `file`-like object that contains the...
e2188cd912ca78274fd111bdc2951c267f5de575
38,222
import ntpath def path_base_and_leaf(path): """ Splits path to a base part and a file or directory name, as in the following example: path: '/a/b'; base: '/a'; leaf: 'b' """ head, tail = ntpath.split(path) if not tail: # in case there is trailing slash at the end of path return {'base...
956daa06f87cc60c8e304fa129fb86e49c4776ce
38,223
import torch def mutate_input(model, input_list, input_of_interest=0, output_extract_fn=lambda x: x, mutate_val=0, return_diff=True, max_batch_size=128, **kwargs): """ Switches each value in input_list[input_of_interest].size(1) to mutate_val one-by-one and collects output_extract_fn(mode...
c7f845ba279d97c9f8ac0e4caa0e794bd69ef543
38,224
def UnsignedShortCast(value): """Explicitly cast a value to type 'usigned short'.""" return UnsignedCast(And(value, ConstInt(0xFFFF)))
8f7e3780df17b23054d38843792e503447c17ce8
38,225
def Normalize_C3V(vec): """Scales the argument by its Euclidean length, assuming its a 3d vector (indexable object of length 3).""" length = Hypot_C3V(vec); vec[0] /= length vec[1] /= length vec[2] /= length return None;
d5ba177c1350728a63e4225f3f04e28fd68458fb
38,226
import sympy def extract_coefficients(equation: sympy.Expr, local_map: dict, global_coords: list) -> tuple: """ Args: equation: The equation in local coordinates. local_map: The mapping from local coordinates to the index of a glob...
39905209860464d17c7bb73e96f9b62ef78cb2bc
38,227
from typing import TextIO from typing import Dict import csv import re import unicodedata def read_variables(fh: TextIO) -> Dict[str, str]: """Read variables from file""" reader = csv.reader(fh, delimiter=',') headers = filter_map(normalize, next(reader)) assert all(f in headers for f...
b188fde84862b11223c3fd49c067067985192e6d
38,228
def _is_dunder(name): """Returns True if a __dunder__ name, False otherwise.""" return (name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2] != '_' and len(name) > 4)
507ce31674c8e6307ac3f76230c88886b6f1a79c
38,229
def get_oidc_fxa_setting(attr): """Helper method to return the appropriate setting for Firefox Accounts authentication.""" FXA_CONFIGURATION = { 'OIDC_OP_TOKEN_ENDPOINT': settings.FXA_OP_TOKEN_ENDPOINT, 'OIDC_OP_AUTHORIZATION_ENDPOINT': settings.FXA_OP_AUTHORIZATION_ENDPOINT, 'OIDC_OP_US...
87d59ff0bbd5cdf08b5832e830ac18acff5eebb6
38,230
import io def detect_nb_doctype(path): """Dectect what sort of document we are dealing with.""" # This is inefficient because we end up opening the file twice? with io.open(fp, encoding="utf-8") as f: txt = f.read() typ = jupytext.formats.divine_format(txt) return typ
c43b9a1944b7ac53508cf890f469206af612d776
38,231
import tqdm def from_cell_to_heatmap(slide, trans, cell_table, filter_out="LBP", level=7, n_comp=2): """ Parameters ---------- slide : wsi object, openslide object from which we extract. trans : function, infers the new coordinates of a given point. It is or: - the...
918e63262ec9ec5af1b7c7f506e3e171c011a8e8
38,232
def get_genome_subsequence(gseq=None, start=None, end=None): """ The letters of nucleotides in the reference are shown in upper case. """ subseq = gseq[start-1:end] return subseq.upper()
6bcdacad1e5714b6e5d04434adc7c36b292e9d11
38,233
def mvee(atoms, tol = 0.00001): """ Find the minimum volume ellipse around a set of atom objects. Return A, c where the equation for the ellipse given in "center form" is (x-c).T * A * (x-c) = 1 [U Q V] = svd(A); where r = 1/sqrt(Q) V is rotation matrix U is ??? """ points_asar...
60d2b5d03a0c0ce185133b33d1daac09e8dcd0c4
38,234
async def list_credentials(hub, ctx, name, resource_group, **kwargs): """ .. versionadded:: 3.0.0 Lists the login credentials for the specified container registry. :param name: The name of the container registry. :param resource_group: The name of the resource group to which the container registr...
5ca069fe456dd7366220c095da431b6b0a1661da
38,235
from collections import defaultdict def analyze_hash_miss(hashchain, htask, hcomp, taskname, skipcache): """ Function that analyzes and gives out a printout of possible hass miss reasons. The importance of a candidate is calculated as Ic = Nm/Nc where: - Ic is an imporance coefficient; ...
7a1728c7c47f400c9164acb409afe738271c40a9
38,236
def set_cv_folds(dataset_name, k): """ Split data into different folds. The resulting split names have the form cv_<k>-<i>, where i is the current folds used for testing. param dataset_name: name of dataset without .csv param k: number of folds """ return sd.cross_validation_folds(dataset_name, k, return_...
248f52c1f6d8adfa0f743f940ebbf800ff0bfd54
38,237
def fetch_test_names(app, host_app, release, enabled_tests_only=True): """Determine the list of (TestCase, testMethod) for the app. Args: app: (string) path to app host_app: (string) path to host app. None or "NO_PATH" for EG1. release: (bool) whether this is a release build. enab...
1bd592d69bf72350eea259154296030079791a37
38,238
def augment_data(X_train, Y_train): """ Augments the data 8-fold by 90 degree rotations and flipping. Parameters ---------- X_train : array(float) Array of source images. Y_train : float Array of label images. Returns ------- X_train_aug : array(float) Augmen...
8167f19d13f44ed83e645da7fa65463ee68ed09a
38,239
import json def load_config(run_name): """ Load configuration json """ with open(get_config_loc(run_name)) as data_file: data = json.load(data_file) return data
1545f1387c0ec2588d61cd1ab201451618a11333
38,240
import collections import os def generate_graphs(data_frames, hardware_info, steps, outdir, verbose=False): """Generate all graphs for a bcbio run.""" _setup_matplotlib() # Hash of hosts containing (data, hardware, steps) tuple collectl_info = collections.defaultdict(dict) for...
495fbf26f59a91528586c748ddb32ab167743978
38,241
def get_nmdc_jsonschema_string() -> str: """Retruns the nmdc.schema.json file as a string. Returns ------- str A string containing the contents of nmdc.schema.json file. """ nmdc_json = get_nmdc_jsonschema_bytes() return nmdc_json.decode("utf-8")
340b7e0e4eac708366c247b3496b094955e7ce09
38,242
def stackmean(array): """Cacluate the mean of a stack This function calculates the mean of a stack of images (or any array). It ignores values that are np.NAN and does not include them in the mean calculation. It assumes an array of shape (.. i, j, x, y) where x and y are the size of the returned a...
132f012a00c2a49eadab54f1cfb4cff3f5192dc4
38,243
from pathlib import Path import logging def nfs_remap(path, depth, autofs=None): """Remap filesystems that are exported over NFS to their path on GPFS. Eg: radonc-ljungman-dataden.dataden.arc-ts.umich.edu:/gpfs/locker0/ces/dataden/g/radonc-ljungman-dataden /nfs/dataden/radonc-ljungman-dataden umms-bl...
f35c0c591474b40770bd1e860058ff29038d72b8
38,244
def cvSetReal3D(*args): """cvSetReal3D(CvArr arr, int idx0, int idx1, int idx2, double value)""" return _cv.cvSetReal3D(*args)
2a86cb6448d289b81e297a12bc784e7a049c0525
38,245
def api_settings(_request): """Repond with user prefs in JSON.""" account = models.Account.current_user_account return { 'xsrf_token': account.get_xsrf_token(), 'email': account.email, 'nickname': account.nickname, 'deprecated_ui': account.deprecated_ui, 'default_context': account.default_cont...
1245b253e975aba825d9199b1265457c653cb7f9
38,246
import argparse def get_config(parse=True, **optional_kwargs): """ Get configurations as attributes of class 1. Parse configurations with argparse. 2. Create Config class initialized with parsed kwargs. 3. Return Config class. """ parser = argparse.ArgumentParser(formatter_class=argparse.A...
a566934f30b01c20e9dbbba52a88a224f6309f41
38,247
from scipy.spatial.qhull import Delaunay from typing import Union def create_mesh_from_trace(linestring, zmax: Union[float, int], zmin: Union[float, int], ): """ Args: linestring (shapely.geometry.LineString): zm...
e2998e1cd82d2d74d36392af56dc401891a6ef79
38,248
import math def find_nearest(array,value): """ Find nearest value in array """ idx = np.searchsorted(array, value, side="left") if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])): return array[idx-1] else: return array[idx]
a48f8f29fab539993f80af7d31ae9efef5a5d08a
38,249
def handle_context_opt(ctx, param, value): """Handle eager CLI options to configure context. The eager options are evaluated directly during parsing phase, and can affect other options parsing (like required/not). The only side effect of consuming these options are setting attributes of the global...
846008bac7a8ed67fea0e31da9a8ed69223b2ccc
38,250
from typing import OrderedDict def make_minimal_feature_set(feature_definitions, features): """Reduce feature_definitions to the minimum necessary features Parameters ---------- feature_definitions : list of dict Feature definitions from the elasticsearch LTR plugin features : list of str...
3759acdba258c54cec2669cc7a32beecdbe0c04a
38,251
def nonroster_player_attr_by_id(player_id, attribute): """Returns the attribute of a non-roster player via the NHL People API. Args: player_id (str): Player unique identifier (IDXXXXXXX) attribute (str): Attribute from roster dictionary. Returns: string: Attribute of the person req...
016a06bb59249b18537fc9f467e7e1a050d959a3
38,252
import torch def merge_aug_bboxes(aug_bboxes, aug_scores, img_metas, rcnn_test_cfg): """Merge augmented detection bboxes and scores. Args: aug_bboxes (list[Tensor]): shape (n, 4*#class) aug_scores (list[Tensor] or None): shape (n, #class) img_shapes (list[Tensor]): shape (3, ). ...
b887f9f279664823104f435d63bd0fc2a49b3dd4
38,253
import os def local_helper_exists(production=False): """This function checks to see if a helper file is present in the ``local/`` directory. .. versionadded:: 4.1.0 :param production: Defines whether or not the helper file is associated with a Production environment :type production: bool, None ...
cb300e8a488f8001e2f22d36185f9054ab7b3c30
38,254
def is_provided_and_is_date_less_than_a_year_ago(value): """Returns True if the date value is provided and within the last year.""" if not value: return False return _is_provided_and_is_date_in_the_past( value, ) and ( value > date.today() - relativedelta(years=1) )
28e87fac14161e9c1772288a58e13747786cc906
38,255
def load_data(train_data, valid_data, test_data, user_review, item_review, user_rid, item_rid, stopwords): """ Loads and preprocessed data for the MR dataset. Returns input vectors, labels, vocabulary, and inverse vocabulary. """ # Load and preprocess data u_text, i_text, u_text_old, i_text_old,...
e02cce3f208046e805851aced54ee74e22e9de0c
38,256
def filter_records(records, key, operator, test_value): """Removes all records from a list of records, which do not fulfill the specified criteria. """ filtered_records = [] for record in records: # @shoeffner: missing , and : if isinstance(record[key] int) test_value = i...
c2bac026ba3d048898bb147263b937ce81db37bd
38,257
from typing import FrozenSet def _numeric_range_is_disjoint( bin_ranges: FrozenSet[Range], numeric_accuracy: float ) -> bool: """ A method that checks if the numeric range bins are disjoint and don't contain gaps. :param bin_ranges: the set of ranges we want to check :param numeric_ac...
e291451d612332c2ceb0e615a239448613250c95
38,258
import torch def large_state_termination(state, action, next_state=None): """Termination condition for environment.""" if not isinstance(state, torch.Tensor): state = torch.tensor(state) if not isinstance(action, torch.Tensor): action = torch.tensor(action) done = torch.any(torch.abs(...
99491952d0f57a24de112c686d3a13436c7b3a50
38,259
def get_filtered_properties_df(prefix: str, prop: str, **kwargs) -> pd.DataFrame: """Extract a single property for each term.""" path = prefix_directory_join(prefix, 'cache', 'properties', f"{prop}.tsv") @cached_df(path=path, dtype=str) def _df_getter() -> pd.DataFrame: obo = get(prefix, **kwar...
ea8866733f7476bd5d1eae0510cbda4a08352eb7
38,260
def to_1d(arg, raw=False): """Reshape argument to one dimension. If `raw` is `True`, returns NumPy array. If 2-dim, will collapse along axis 1 (i.e., DataFrame with one column to Series).""" if raw or not checks.is_array(arg): arg = np.asarray(arg) if arg.ndim == 2: if arg.shape[1]...
02973e0fe29a9b5b54f34ac82f322c1ecc572d12
38,261
import cloudpickle import pickle def _load_model_from_local_file(path, serialization_format): """Load a scikit-learn model saved as an MLflow artifact on the local file system. :param path: Local filesystem path to the MLflow Model saved with the ``sklearn`` flavor :param serialization_format: The format...
d183a1d92e683507611d827469f14344b6f78b8b
38,262
def sum_sq_diff(img_0, img_1, u, x, y, x_len, y_len): """ Returns the summed square difference between two image patches, using even weighting across the patch. Parameters : img_0, img_1 : two images being compared u : displacement vector between patches x, y ...
85e2f7095d766948058e6ce3ed0b0632026217cc
38,263
import re import zipfile def instance_name_from_zip(path): """Determines the instance filename within a SEC EDGAR zip archive.""" re_instance_name = re.compile(r'.+-\d{8}\.xml') for name in zipfile.ZipFile(path).namelist(): if re_instance_name.fullmatch(name): return name raise Run...
59b2154d433e500e9b0cdf39ee70d4c058da1d06
38,264
def delete_load_blanacer(ilb_name): """ Delete a deployed Internal Load Balancer :param ilb_name: :return: None or str """ response = describe_load_balancers(ilb_name) for i in response['LoadBalancerDescriptions']: if 'LoadBalancerName' in i: elb.delete_load_balancer(Loa...
32448835674a60766c395917301659ae42041f6e
38,265
import argparse def get_arguments(): """Obtains command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( '--inputs', required=True, nargs='+', metavar='INPUT', help='read Q2 inputs from Feather files %(metavar)ss') parser.add_argumen...
118e76d633bf5ea37b85a53dcd5ba07cf7e46e04
38,266
from scipy.stats import pearsonr def crosscorrelation(a, b): """ Calculates a normalized cross-correlation between two vectors. Returns the Pearson correlation coefficient. """ return (pearsonr(a, b))[0]
155f46ec9ed7e71b7fc26afaf3fd470ebca58705
38,267
def hypothesis_test_v1(unknown_agent_actions, known_agent_dists, update_times, num_actions, num_samples=50, score_funcs_list = [z1_score_function, z2_score_function, z3_score_function], weight_value=(1.0/3)): """ Calculate p-values for various timesteps of an i...
9e5fc69a8e638fac7e094c57def4c70ad454af0b
38,268
def area_hexagon(r): """Return the area of a regular hexagon with side length R.""" return r * r * 3 * sqrt(3) / 2
aacb70f57bf3b7e202a085b9ce5cdd694688468a
38,269
def index2state(Is, n, Juv, Jdv=None): """ Returns state with a given index Parameters ---------- Is : ndarray list of indices n : int number of sites Juv : ndarray Lin table of spin-up states Jdv : ndarray Lin table for spin-down states """ Nu = ...
dba20dad94332d8bcea64c7ed1f43d96e692ed31
38,270
import re def headers_ok(meta): """check that headers are 'name' or end with c/d/ll""" meta_fh = open(meta) headers = meta_fh.readline().rstrip().split('\t') return headers[0] == 'name' and \ all(map(lambda s: re.search(r'\.(c|d|ll)$', s), headers[1:]))
408975c795de8bf22529cf917ca881ca98ede4f9
38,271
import os import errno def rasterizeSSURGOFeatures(config, outputDir, featureFilename, featureLayername, featureAttrList, \ getResolutionFromRasterFileNamed=None, rasterResolutionX=None, rasterResolutionY=None): """ Create raster maps, in GeoTIFF format, for SSURGO attributes associate...
27ecefc55dea2b6a91b224d99793ee75fb081071
38,272
import urllib def get_fontawesome_panel_express() -> str: """Converts the official css file at FONTAWESOME_CSS_URL into it's panel representation Returns: str -- [description] """ with urllib.request.urlopen(FONTAWESOME_CSS_URL) as file: fontawesome_css = file.read().decode("utf-...
e71acbe7dcef7a8f57a511c5945ebdba7fabd979
38,273
def search_index_for_variable(index,parent_tag,variable_expression,resolve=False): """ :param str parent_tag: tag created of colon-separated identifiers, e.g. "mymodule" or "mymodule:mysubroutine". %param str variable_expression% a simple identifier such as 'a' or 'A_d' or a more complicated tag representin...
1b427243dbb4b8c9a14a2ef60e76aa51b56ad470
38,274
import re def has_number(name): """判断名name内是否出现了数字(包括中文的数字)""" if bool(re.search(r'\d',name)): return True num_str = ['一','二','三','四','五','六','七','八','九','十'] for s in num_str: if s in name: return True return False
56dec9664e945d852cbfee4791f386aaab15f215
38,275
import re def validate_entity_arn(entity_arn): """Validate entity ARN""" # account_number = SESSION.client('sts').get_caller_identity()["Account"] # Roles are valid: arn:aws:iam::842337631775:role/1S-Admins # arn:aws:sts::281782457076:assumed-role/1S-Admins/alex # Users are inval...
601e2d7ef8f214b4b9882b599eb4fbd74edcbb76
38,276
import random def seed_student_proposal(request, i): """Returns the properties of a new student proposal. """ ensureUser() org = Organization.get_by_key_name('google/gsoc2009/org_%d' % i) mentor = Mentor.get_by_key_name('google/gsoc2009/org_%d/mentor' % i) user = User.get_by_key_name('user_%d' % i) stu...
22aca19e5b901a236e9a49a3b47c284496ec8f56
38,277
def get_data_f2(x, a, b, c, d, noise): """ return function y = a*exp(-(x-b/c)^2) + d + noise """ y = a * np.exp(-( (x - b) / c)**2) + d + noise * np.random.rand(x.shape[0], x.shape[1]) return y
58cc76971b21d970ad08d55c61168849e3ed9f2f
38,278
def subpixel_contours(da, z_values=[0.0], crs=None, affine=None, attribute_df=None, output_path=None, min_vertices=2, dim='time', errors='ignore...
c9dedeb7f3f911dc32f940936aed7e9f3f349018
38,279
def collect_hosts(hosts): """Collect a set of hosts and an optional chroot from a string.""" host_ports, chroot = hosts.partition("/")[::2] chroot = "/" + chroot if chroot else None result = [] for host_port in host_ports.split(","): # put all complexity of dealing with # IPv4 & IPv...
6749f893337505d66b7eab12c9699934b90afea7
38,280
def process_frame(img, frame, face_cascade): """ Determine whether the current frame contains the faces of people from our database """ global ready_to_detect_identity gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) # Loop through all the f...
a05d9939e2c0383c513fda791af9029b821bb060
38,281
def GetMtdDevForNameOrNone(partname): """Find the mtd# for a named partition. In /proc/mtd we have: dev: size erasesize name mtd0: 00200000 00010000 "cfe" mtd1: 00200000 00010000 "reserve0" mtd2: 10000000 00100000 "kernel0" mtd3: 10000000 00100000 "kernel1" Args: partname: the partition to ...
9bc0be382c428935c0ee53576fd2a90cb103867d
38,282
def PIoN2SolNTableConvert (inUV, outSNVer, NITable, pos, err): """ Evaluate Ionospheric model table at pos and convert to SN table Returns resultant SN table * inUV = UV data for output SN table. Control parameters on inUV info member: ========== ================ =================...
b817f9383ffd617f0d25c131b0f3fbe1a812c1d4
38,283
def hasp( revisions: pd.DataFrame, window: int = 12, ) -> pd.DataFrame: """Apply the half window splice revision extension method. Parameters ---------- revisions : pandas DataFrame A DataFrame of the rolling revisions. The values only need to be correct for the size of the ...
cfaddfa509fb1e596caf19fd298154fd47c7f3a5
38,284
import numpy def get_vignette_mask(image, percent_vignetted=5): """Convert a well-exposed image (ideally a brightfield image with ~uniform intensity) into a mask delimiting the image region from the dark, vignetted borders of the image. percent_vignetted: percent (0-100) of pixels estimated to be in ...
ac41f9b7f80b76ac948a4e7815dd84296063469a
38,285
def cohort_to_int(year, season, base=16): """cohort_to_int(year, season[, base]) Converts cohort tuple to a unique sequential ID. Positional arguments: year (int) - 2-digit year season (int) - season ID Keyword arguments: base (int) - base year to treat as 0 Returns: ...
1f1981eb6c43ab6f77abf6d04ba3b92d9053953d
38,286
import re import time def delete_project(project_ids: list) -> bool: """ Deletes project, groups, tasks and results from Firebase and Postgres. """ for project_id in project_ids: logger.info( f"Delete project, groups, tasks and results of project: {project_id}" ) f...
a039882efaf269ece21866eff0a0665c47d874b0
38,287
def set_data_format(array_values): """ Check and set the corresponding format for each value :param list[list[str]] array_values: list of values :return: list[list[str]]: array formatted """ formatted_data = [] for d in array_values: values = [] for v in d: # Try...
7546f0dd5c661790d384f2f8063abed1701a3e8c
38,288
def dict_of_transition_matrix(mat): """ Convert a transition matrix (list of list or numpy array) to a dictionary mapping (state, state) to probabilities (as used by :class:`pykov.Chain`).""" if isinstance(mat, list): return {(i, j): mat[i][j] for i in range(len(mat)) for j in range(len(mat[i]))} el...
b823ff496a751f4ffe305a31f1c1d019f7a25d33
38,289
def taxii2_collection_by_id(api_root: str, collection_id: str) -> Response: """ Defines TAXII API - Collections: Get Collection section (5.2) `here for v.2.0 <http://docs.oasis-open.org/cti/taxii/v2.0/cs01/taxii-v2.0-cs01.html#_Toc496542736>`__ and `here for v.2.1 <https://docs.oasis-open.org/cti/ta...
f0932d93e0843747b56dc50ee7019814fa3e0a6e
38,290
def argmaxn(value_list, n, order='desc'): """ Return the index of top n elements in the list if order is set to 'desc', otherwise return the index of n smallest elements :param value_list: a list containing all values :type value_list: list, array :param n: the number of the elements to select ...
423c16e1c7bd83ef547a2ac6cd7e51498b18bab5
38,291
import math def nms(args, classes, offsets, anchors): """Perform NMS (Algorithm 11.12.1). Arguments: args : User-defined configurations classes (tensor): Predicted classes offsets (tensor): Predicted offsets Returns: objects (tensor): class predictions per anchor ...
f5cfef75972a4d8416161398199185e704f88db2
38,292
def extract_features(data_frame: pd.DataFrame) -> pd.DataFrame: """Obtains training features from the data frame containing subreddit data. Params: - data_frame (pd.DataFrame): data frame containing subreddit data Returns: - features (pd.DataFrame): the training features returned by the data frame...
59d2407ba758c8f2e6937d2ffb03d9648b792b37
38,293
def get_bugzilla_bug(bugzilla_url, bug_id): """ Read bug XML, return all fields and values in a dictionary. """ bug_xml = _fetch_bug_content(bugzilla_url, bug_id) return parse_bug_fields(bug_xml)
3ac255f5135ab639b9e7137d5d52e0c5eed61b51
38,294
def _funded_by(record, extra_data): """Check if publication has "Funded by SCOAP3" marking *in pdf(a) file* """ patterns = ['funded.?by.?scoap3?', ] return __find_regexp_in_pdf(extra_data, patterns)
c3c60103f117512e6553478c828f95715f81511c
38,295
def profile(request, profile_slug): """ Display profile details. """ speaker_profile = get_object_or_404(AttendeeProfile, slug=profile_slug) if not profile_page_visible(profile=speaker_profile, for_user=request.user): return TemplateResponse(request, "conference/profiles/profile_unavailable...
a03d10a9c9641f1fdf04810e915e8a483cb4a01b
38,296
def save_file(filename, contents): """Save a file from the editor""" if not filename: return 0, 0 with open(filename, 'w') as f: f.write(contents) return len(contents), hash(contents)
8e973f67a22a2e7b0836f8db25090c65238492e3
38,297
def GetDockerImageFromTagOrDigest(image_name): """Gets an image object given either a tag or a digest. Args: image_name: Either a fully qualified tag or a fully qualified digest. Defaults to latest if no tag specified. Returns: Either a docker_name.Tag or a docker_name.Digest object. """ if no...
7e61f8a3dde64ec5efa833fc72e909e9140f77f9
38,298
def line_label(ax, pos, label, dir='v', loc='top', xx=None, yy=None, ha=None, va=None, line_kwargs={}, text_kwargs={}, dashes=None, rot=None): """Plot a vertical line, and give it a label outside the axes. Arguments --------- ax : `matplotlib.axes.Axes` object Axes on which to pl...
9612f2218ce6559f7deffc0f148c4d205b3608b1
38,299