content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def list_service_offering(api_client, **kwargs): """Lists all available service offerings.""" cmd = {} cmd.update(kwargs) # [setattr(cmd, k, v) for k, v in kwargs.items()] if 'account' in kwargs.keys() and 'domainid' in kwargs.keys(): cmd['listall'] = True return Response.list(api_clien...
da2102df4fe198972efb0def69739ed684fdfaef
72,167
def read_fileset_vols(file): """ Read in the fileset volumes from the given file and returns the paths :param file: :return: [list] of paths """ with open(file) as r: filesets = r.readlines() paths = [] for fs in filesets: fs_parts = fs.strip().split(' ') #print...
6a704097a58f83c8b3eb7c20b81a866353df5ca5
72,168
def get_scene_nodes(): """ Returns al nodes in current scene as GamEX nodes :return: list<gx.dcc.DCCNode> """ node_list = list() _append_children(MaxPlus.Core.GetRootNode(), node_list) return node_list, len(node_list)
67da9ae796211f40fc784d44d2e2e4ce8416e022
72,169
def parse(r): """ Parse and return a pandas TimeSeries object """ # Create TimeSeries try: d = {} for tup in r.json(): d[dt.datetime.fromtimestamp(tup[0])] = tup[1] except: print("-------> Problem with Flukso data parsing <-------") ...
8fcb07f4e6795cf6a64550e547a6c10049f373b0
72,170
def shake_shake_skip_connection(x, output_filters, stride, is_training): """Adds a residual connection to the filter x for the shake-shake model.""" curr_filters = common_layers.shape_list(x)[-1] if curr_filters == output_filters: return x stride_spec = [1, stride, stride, 1] # Skip path 1. path1 = tf.n...
55c43fc838c7520ecbe8c33a1680854cf9ee7335
72,171
def rename_genome(genome, assembly_summary): """Rename FASTAs based on info in the assembly summary """ genome_id = parse_genome_id(genome) infraspecific_name = assembly_summary.at[genome_id, "infraspecific_name"] organism_name = assembly_summary.at[genome_id, "organism_name"] if type(infraspeci...
8f5f0a296ae0eeff008d1493d3ea9d6d063d25bb
72,172
from typing import Union from typing import List from typing import Optional def op_add_listing_details_at_aoi(id_shape: Union[int, List[int]]) -> Optional[str]: """ Fetch and store into the database LISTING DETAILS for the LISTING_IDs found in the quad-grids intersecting with AOI ID_SHAPEs. This is an i...
7b057cf7908a34c46f93a63afff1645e31325f8d
72,173
import json def autocomplete_autor(): """ route for retrieving autocomplete entries for field autor :return: list of entries for autocomplete """ return json.dumps(Publication.get_autocomplete_entries("autor", request.args['term']))
9b4a9d12d36940cad4d438aae73e46d685f59db7
72,174
def generate_data(): """ """ np.random.seed(2046) d1 = np.random.normal(5, 5, 10) d2 = np.random.normal(5, 5, 10) groups = ["d1"] * 10 + ["d2"] * 10 d = {"A": np.concatenate((d1, d2)), "B": groups} data = pd.DataFrame(d) return data
ee4e34b7de82f9ad039b42203d810471c14b92b2
72,176
def show_about(): """关于本站""" site_desc = SiteDesc.query_by_id(1) return render_template("main/about.html", site_desc=site_desc, channel_id=3)
5c83c5013df3eed695043016b5cd5c84bcc561dd
72,177
import math def correlation(x,y,n): """ computes pearson correlation coefficient """ a=covariance(x,y,n)/math.sqrt(variance(x,n)*variance(y,n)) return a
f30178037f415a96df8eb4bf31d8a33c4d66a423
72,178
def partition(n, g): """ Returns the number of ways to partitions set of n elements with a partition of size g """ if n == 1: return 1 elif n == g: return 1 elif g>n or g<=0: return 0 else: sum = 0 for i in range(g, n-g+1, 1): sum += pa...
e0af35b413963c6ff600e87e5a55e8f4dbcc4b84
72,179
from typing import Union def _get_tol_from_less_precise(check_less_precise: Union[bool, int]) -> float: """ Return the tolerance equivalent to the deprecated `check_less_precise` parameter. Parameters ---------- check_less_precise : bool or int Returns ------- float Toler...
375f7918a04fafb4a79f77abd3f0282cdc74e992
72,180
def benchmark(scale=1): """ Benchmark and return information regarding the relative performance of a protocol which does not use the buffering mixin and a protocol which does. @type scale: C{int} @param scale: A multiplier to the amount of work to perform @return: A Deferred which will fir...
61303746bc600926d9f64433ac1bb77c91957e06
72,181
def answer_card_api(state: State) -> flask.Response: """Verify A User's Answer This route is intended for use by xhr/ajax POST Parameters: a: The answer to test against Returns: JSON with the fields: correct (bool): indicates whether the answer was correct scor...
78deca17279e739d02158fc765eb530d89cc6c2f
72,182
def _check_data_params(obj, X, y, conf_score): """Extracted out of BaseHandler for WeightedBag & Costing""" # Reproducibility rns = check_random_state(obj.random_state) for k, v in obj.get_params().items(): if isinstance(v, BaseEstimator) and 'random_state' in v.get_params(): v.set_...
a09f0db52a467ce22518a8464321c9429bca2ec6
72,184
def plot_photostim_effect(session_key, photostim_key, axs=None, title='', plot=True): """ For all trials in this "session_key", split to 4 groups: + control left-lick + control right-lick + photostim left-lick (specified by "photostim_key") + photostim right-lick (specified by "photostim_key") ...
18ecb8532658241636d479013710e3d6bf8b09dd
72,185
def calculate_mean_spectrum(msi): """ reduce this image to only its mean spectrum. If the msi.get_image() is a masked array these values will be ignored when calculating the mean spectrum """ # reshape to collapse all but last dimension (which contains reflectances) collapsedImage = collapse_image(m...
acda0a1df1f32bd765f971d184fb4a4b70ed422a
72,186
def P_s_next(A, i, j, C, shape): """ Calculate the next probability at position i,j """ temp = Q_s(A, i, j, 1, C, shape) * A[i, j] return temp / ((temp + (1.0 - A[i, j]) * Q_s(A, i, j, 0, C, shape)) + 0.000000001)
5bbc35e4c190eeb9859b87f16a110c9a7bb87c68
72,187
import dask.dataframe as dd def create_statistical_metrics(df_var, percentiles=None, iqr=True, diffs=True, num_workers=1, verbosity=0): """Calculate statistial metrics from a dataframe with pd.DateTimeIndex and a instance (e.g. pixels) dimension. Parameters ---------- df_var : [type] [de...
ff7ed4e4c507681757b51e09d07448efa793c082
72,188
def extract_nodegraph_info(filename): """Open the given nodegraph file and return a tuple of information. Returns: the k-mer size, the table size, the number of tables, the version of the table format, and the type of table flag. Keyword argument: filename -- the name of the nodegraph file to insp...
026a3788fa7fdd180b6c7090e07aebdeec3ee997
72,189
def name(): """Return the precise name for the software.""" return 'Python'
d3aa60120be2ef6eb90844aa9396c347d486cf62
72,190
def get_cold_start_rating(user_id, movie_id): """ Given user_id and movie_id, return a predicted rating parameters ---------- user_id, movie_id returns ------- movie rating (float) If current user, current movie = average rating of movie by cluster If current user, NOT ...
7f33ca28c778f9f94c15beaff28d44e858238299
72,191
def continuous_blocking( radius: float, source: _typing.Sequence[_typing.Sequence[float]] ) -> _typechecking.BlockingFunction[_typechecking.Record]: """Block on continuous variables. Split the real number line into overlapping blocks. A quantity is in exactly two blocks. Two quantities within `radi...
ad3a649af7ee17aea2eedc8f1a842425502896bd
72,193
import numpy def point(pose,px,py,pz): """ Project a 3D point into the camera. Input: pose -- camera pose px,py,pz -- point in global frame Output: u,v -- pixel coordinates """ p = pose.dot(numpy.matrix([[px],[py],[pz],[1]])) X = p[0,0] Y = p[1,0] Z = p[2...
3393311323b285eaa973cbfb52fbbe301d3f78f0
72,194
def install(name, clean=True): """ Install a port from the ports tree. Installs using ``BATCH=yes`` for non-interactive building. To set config options for a given port, use :mod:`ports.config <salt.modules.freebsdports.config>`. clean : True If ``True``, cleans after installation. Equivale...
f4b3f3fdfd4f3a3b2e99541e26a118f6e13e33da
72,195
from typing import Callable def flip(f: Callable) -> Callable: """ Reverse the order of positional arguments of `f` Example: >>> f = lambda a, b, c: (a, b, c) >>> flip(f)('a', 'b', 'c') ('c', 'b', 'a') Args: f: Function to flip positional arguments of Returns: ...
7f483f762b2a1c2cc7ac0643e037b6326a08377e
72,196
def _accumulate(data_list, no_concat=()): """Concatenate a list of dicts `(name, array)`. You can specify some names which arrays should not be concatenated. This is necessary with lists of plots with different sizes. """ acc = Accumulator() for data in data_list: for name, val in data...
a16e1a60c0921866a5e5c0ced14bcbc7c4d62140
72,197
def blck_if(preprocessor: Preprocessor, args: str, contents: str) -> str: """the if block usage: {% if <condition> %} ... [{% elif <condition> %} ...] [{% else %}...] {% endif %} """ value = condition_eval(preprocessor, args) pos_0 = 0 desc = "in if block" while True: else_info = find_e...
1713d67bd45efbc0c5bdeb8f3d00d2a733ee2d75
72,199
def scale(data, scale_feats): """ Just scales feats """ # Create scaler scaler = StandardScaler() scaler.fit(data[scale_feats]) scaled = data[scale_feats].copy() # Convert numeric features to standard units scaled = scaler.transform(scaled) data[scale_feats] = scaled ...
49c4c94e057824e6fe40eafd635317a21eab1d85
72,200
from typing import Optional def str_(): """ Return an optional str serde. """ return Optional(StrSerde())
f85a218b70aaff1f46caded15d0f719e3a922b9b
72,201
def get_slice_miss(self, dimspins, x): """ Convenience method to get list of missing values (get_miss), choose slice of array (get_slice), and set missing values to NaN or np.datetime64('NaT') in slice (set_miss). Parameters ---------- self : class ncvue class dimspins : list ...
049eae51ca1ec1d72ddb1e6db14c0b0e02e777b8
72,202
def getLandmarksFromVTKFile(file): """ Extract each landmark point line by line from a VTK file, and return vector containing all landmarks. For cardiac data landmark indexes: 0-2 RV insert points 1 -> RV lateral wall turning point 3 -> LV lateral wall mid-point 4 -> apex ...
7c09876c6db6d7f6314a641944a76a570216d2ae
72,203
def get_arg(cmds): """Accepts a split string command and validates its size. Args: cmds: A split command line as a list of strings. Returns: The string argument to the command. Raises: ValueError: If there is no argument. """ if len(cmds) != 2: raise ValueError('%s needs an argument.' % c...
a12b9402cb824748127c9a925850a10f6a9fe022
72,205
from pathlib import Path def _resolve_ros_workspace(ros_workspace_input: str) -> Path: """Allow for relative paths to be passed in as a ros workspace dir.""" ros_workspace_dir = Path(ros_workspace_input).resolve() if not (ros_workspace_dir / 'src').is_dir(): raise ValueError( 'specifie...
45c5843a2e34a79f077ae595b100f2d58f903bae
72,206
def rnd(n, s): """ returns positive int, within normal distribution n = mean, s = std """ return int(abs(np.ceil(r.normal(n, s))))
09abbf79644521253785ff6eb91996cfc13a515d
72,207
def distorted_bounding_box_crop(image, bbox, min_object_covered=0.1, aspect_ratio_range=(0.75, 1.33), area_range=(0.05, 1.0), max_attempts=100, ...
ba93d39242508ea0a2d0774618f4aec8011b5f8e
72,208
from typing import Dict from typing import List def get_blob_services(credentials: Credentials, subscription_id: str, storage_account: Dict) -> List[Dict]: """ Gets the list of blob services. """ try: client = get_client(credentials, subscription_id) blob_service_list = list( ...
491b32d3592a31658618ad985cb08f74b243b80f
72,209
def ordering_list(attr, count_from=None, **kw): """Prepares an OrderingList factory for use in mapper definitions. Returns an object suitable for use as an argument to a Mapper relation's ``collection_class`` option. Arguments are: attr Name of the mapped attribute to use for storage and retrie...
3084ce0e336f7a45832b69d58f5f659aa3516fa7
72,210
def unscale_daily_temp(mean_temp, scaled_daily_temp, scale_params): """scale back the daily temp""" daily_temp = scaled_daily_temp*\ (scale_params[0] - scale_params[1]*mean_temp) + mean_temp return daily_temp
bbb66eabbfc929d1a9099a07e31ad1bd606d20e7
72,212
import math def transform(img, origin1, origin2, target1, target2): """ :param img: image parameter of 4288*2848 image :param origin1: OD Center of the image being processed, 2d array like [1260.60227367 826.91868854] :param origin2: Fovea Center of the image being processed, 2d array :param tar...
1f4613fc37625a87dd26c690ece7857da9efdb38
72,213
from typing import Union def BM2(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]: """ J. Wojdyła, Z. Szkutnik, "Nonparamteric confidence bands in Wicksell's problem", Statistica Sinica28(2018), 93-113 """ return 0.45 * 111384 * (1 - x) ** 12 * x ** 5 + 0.55 * 2558160 * (1 - x) ** 7 * x ** 14
ccfa52952042be1bb8f58354e1051ea3663be140
72,214
from typing import List def xlsx_export(features: List[LayerResponse]): """ packages features into an excel workbook. Returns an HTTP response object that has the saved workbook ready to be returned to the client (e.g. the calling http handler can return this object directly) """ wb = openpyxl.W...
75020b4cc71bfaae3c5cdc9613dbf73e1fc1c9ed
72,215
def _partial_dependence_num(vals, df, model, feature_column, assembler, model_type, n_samples): """Compute PD values for numerical feature""" vals_df = spark.createDataFrame(list(map(lambda x: (float(x),), vals)), schema=StructType([StructField(feature_column, DoubleType())])...
f76c75c1520db0317a963d3d6b7dd719a5b132b6
72,216
def str2date(datestring): """Converts a string in the format YYYY-MM-DD into a date object.""" return date(*strptime(datestring, '%Y-%m-%d')[0:3])
58756011b4e21a699c914cd8b2f22fca2a94c157
72,217
def transform_args(dflt_trans_func=None, /, **trans_func_for_arg): """ Make a decorator that transforms function arguments before calling the function. Works with plain functions and bounded methods. For example: * original argument: a relative path --> used argument: a full path * origi...
31303a902565ea8beae86e9ea6145c07b4af730a
72,218
def api_get_project_webhook_token(repo, username=None, namespace=None): """ Get project webhook token ------------------------- Allow project collaborators to retrieve the project webhook token. :: GET /api/0/<repo>/webhook/token GET /api/0/<namespace>/<repo>/webhook/token :: ...
4d1749c3171186120d76766fdf0417b24cf904e6
72,219
from typing import Union import torch def clip_encoder( device: Union[torch.device, str] = None, name: str = "clip", ) -> nn.Module: """ Loads clip's image encoder module, discarding the lm component. If the variant is a resnet model, we also remove the attention pooling. """ if name in ["cli...
34e0f91d21382adeb220240b7e5a2052fdd44010
72,220
def div_roundup(a, b): """ Return a/b rounded up to nearest integer, equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only without possible floating point accuracy errors. """ return (int(a) + int(b) - 1) / int(b)
7fa4d18f1fb54d7641906d38f9e6ced0a88394ac
72,223
from pathlib import Path def readlines_(file, remove_blank_lines=False): """Reading txt file (similar to builtin ``readlines``). In addition to the standard implementation of ``readlines`` for ``_io.TextIOWrapper``, this version provides the possibility to remove empty text lines. Args: ...
793add397510b52e655449d4d4e0fad7138c9358
72,224
def find_data_dims(ndvar, dims, extra_dim=None): """Find dimensions in data. Raise a ValueError if the dimensions don't match, except when the ``case`` dimension is omitted in ``dims``. Parameters ---------- ndvar : NDVar NDVar instance to query. dims : int | tuple of str T...
20142305a39ca7308867f6a83598af24ae42480a
72,225
def build_model(): """ Builds sequential model for repetitive calls :return: model """ model = models.Sequential() model.add(layers.Dense(64, activation="relu", input_shape=(train_data.shape[1],))) model.add(layers.Dense(64, activation="relu")) model.add(layers.Dense(1)) model.compi...
22e8e7e9074b3b56bc73f2eaa91b0ced5f79a5ca
72,226
def get_connection(retry=False): """ Retrieve the connection to the configured database. Makes a connection if none already exists. Returns: (Connection): Database connection """ global context if "db" not in context: context.db = make_connection(retry) return context.d...
3ca477f48b4ae9b8faee78e6105a3a81fdcc3841
72,227
import re def case_preserving_replace(string, old, new): """Replace string while preserving the case""" def repl(match): current = match.group() result = "" all_upper = True for i, c in enumerate(current): if i >= len(new): break if c.is...
bfa051c7bfb4a54241e5e10cfb37d4293babad5c
72,228
def addProjectToDatabase( projectData ): """Adds the project to the database Input is a dict containing: projectName, projectMISOID, projectPROID, owner,description """ #print "Adding project %s to the database." % projectData["projectName"] try: thisProject, created = Project.objec...
289bb246ee53a2eaf338ef04f650f4c936199836
72,230
def train_input_fn(filepath, example_parser, batch_size, num_epochs, shuffle_buffer_size): """ deepfm模型的input_fn Args: filepath (str): 训练集/验证集的路径 example_parser (function): 解析example的函数 batch_size (int): 每个batch样本大小 num_epochs (int): 训练轮数 shuffle_buffer_size (inr)...
a920af891d05bb5d41a950086ff33bf0e1d29c32
72,231
def calculate_partners(data): """ Function to parse data, and geather all result :param data: input data in json format :return result: all result according to all countries """ countries = set() for partner in data["partners"]: countries.add(partner["country"]) ""...
c7dfdc6d5e87f776132df91a7f00529eb126bafe
72,232
def get_result_error_from_openmc_sp(filename, m): """ Convert the openmc flux into result, rel_err, res_tot, rel_err_tot. Parameters: ----------- filename : str The OpenMC state point file name. m : MeshTally MeshTally for the tally. Returns: -------- result : numpy...
6659b1b66c82c80ae2fff1f26f387384da2f4c40
72,233
def ball_shape(img, min_radius=30, max_radius=50): """ This function requires images in an array and returns the coordinates of centre and radius of the circle detected. It is used to calculate (Cx,Cy) and radius r of the metal ball used for light calibration. It uses Hough Transform to detect the circl...
71975e89613033929d1ac4408ecc76834398ebcd
72,234
def _magnitude_to_marker_size(v_mag): """Calculate the size of a matplotlib plot marker representing an object with a given visual megnitude. A third-degree polynomial was fit to a few hand-curated examples of marker sizes for magnitudes, as follows: >>> x = np.array([-1.44, -0.5, 0., 1., 2., 3., ...
cb030993c5799da9f84e9bbadb9fe30680d74944
72,235
import scipy def train_model(X, y, X_valid, config): """ train_model uses the following config keys: - learner - use_bbsc - undersample_to_proportion """ if config.undersample_to_proportion: undersample_to_proportion = config.undersample_to_proportion pos_count = np.sum(...
72da26730b470d1d2a2b256261f73de281c47d90
72,236
def matmul_AT_B(a, b): """ Computes A.T * B, dealing automatically with sparsity and data modes. :param a: Tensor or SparseTensor with rank 2 or 3. :param b: Tensor or SparseTensor with rank 2 or 3. :return: Tensor or SparseTensor with rank = max(rank(a), rank(b)). """ mode = modes.autodetec...
bb63ab1030f31bd542f5e99480f71ac1a166b297
72,237
def upto(limit: str, text: str) -> str: """ return all the text up to the limit string """ return text[0 : text.find(limit)]
0fbe1732954c225fe8d8714badb9126c8ab72a4d
72,238
import torch def generate_part_labels( vertices, faces, cam_t, neural_renderer, part_texture, K, R, part_bins ): """ :param vertices: (torch tensor NVx3) mesh vertices :param faces: (torch tensor NFx3) mesh faces :param cam_t: (Nx3) camera translation :param neural_renderer: renderer :para...
189adf5939bab026c197c84ac07bf8272abc5ca9
72,239
def check_occuring_variables(formula,variables_to_consider,allowed_variables) : """ Checks if the intersection of the variables in <formula> with the variables in <variables_to_consider> is contained in <allowed_variables> Parameters ---------- formula : list of list of integers The formula to cons...
16faf544cc6f4993afb1cad356037820d54225ba
72,240
def tableau(y): """Yamanouchi word --> Young tableau""" elist = [j+1 for _, j in sorted(list(zip(y, range(len(y)))))] tbl = np.array(elist).reshape(max(y), len(y)//max(y)) return tbl
1bc649e0ebe6062ca66f764f3be5c54e9b04c5e3
72,241
import warnings def make_figure(width, height, nrows, ncols, interactive=None, **kwargs): """ Make a :class:`matplotlib.figure.Figure` and its axes. :param width: Width of the figure. :type width: int :param height: Height of the figure. :type height: int :param interactive: If ``True``...
0a4e99b695f16701ca7a8b3de08d28ee88c4119e
72,242
def calculate_loss_logistic_regression(y, tx, w): """compute the cost by negative log likelihood.""" # Note: this function takes y with values either 0 or 1 return - np.squeeze((y.T @ np.log(sigmoid(tx @ w)) + (1 - y).T @ np.log(1 - sigmoid(tx @ w))))
bb24ca552c16ab997ee9e107678b4ec05edffa86
72,243
from typing import Tuple def _make_ui_window( window: console_config.WindowType, switchboard_inst: switchboard_base.SwitchboardBase ) -> Tuple[widgets.TextArea, widgets.Frame]: """Creates a text area and an enclosing frame. Args: window: Console window description. switchboard_inst: Switchboard c...
6546274ce28c1e4ef05d24018615cfc10bf83ac8
72,244
def mvn_rvs(mean, cov): """ Function to sample from multiple Gaussian distributions Parameters ---------- mean : numpy.array N_samples x N_dim cov : numpy.array or list (N_samples x N_dim x N_dim) or list[numpy.array(N_dim x N_dim)] return : numpy.array N_samples x N_...
e3bb8cb8fad7a4a30b69eaf41267c758f68cbe19
72,246
def DynFlow(con, tau, sigma, tmax=20, timestep=0.1, normed=True): """Returns the extrinsinc flow on a network over time for a given input. Parameters ---------- con : ndarray of rank-2 The adjacency matrix of the network. tau : real valued number, or ndarray of rank-1 The decay rate...
4ea117c0f3a427fc86ca332589785e93a9e5d90f
72,247
import pathlib def _fspath(path): """Return the path representation of a path-like object. If str or bytes is passed in, it is returned unchanged. Otherwise the os.PathLike interface is used to get the path representation. If the path representation is not str or bytes, TypeError is raised. If the ...
39b0841ce68f698b7952eb457ac407a7fa3261e9
72,248
def generate_dataset(num_of_samples, num_of_class): """ The function generated a linearly separated 2D Dataset with two classes. num_of_samples: number of samples in each classes mean: Mean values for the distribution cov: Covariable for the normal distribution Functions used: np.random...
170fa27ee441f91d1208473ac3f2808fed5e594d
72,249
import logging import tqdm def get_responses(responses_file: str, histories: pd.DataFrame) -> pd.DataFrame: """ :param responses_file: The original survey CSV file (as exported by Typeform) see https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey :param histories: DataFrame for the users' histor...
cc82afbc4b45216800ffc2db450e402f22c46068
72,250
def generate_metadata(bwt, ranks=None, counts=None, alphabet=None): """Return ranks, counts and alphabet given or deduced from given bwt""" if alphabet is None: alphabet = tuple(sorted(tuple(set(bwt)))) if ranks is None or counts is None: *ranks, counts = tuple(generate_ranks(bwt)) # pri...
abf6322ec7e5bbf68c835d552a71b7359fac5509
72,251
import torch def SOS_KNN_MOD_HOR(xa, xp, knn): """ Second Order Similarity KNN Modified Horizontal :param xa: x anchor, nxd :param xp: x positive, nxd :param knn: int, like: 8 :return: """ if xa.shape[0] <= knn: raise EmptyTensorError assert xa.shape[0] == xp.shape[0] n...
3e23c3d7a8eccb3a278d095fabd110f11f2cf2e8
72,252
def classproperty(f): """decorator that registers a function as a read-only property of the class.""" class _ClassProperty: def __get__(self, _, cls): # python will call the __get__ magic function whenever the property is # read from the class. return f(cls) return _ClassProperty()
de5586548b77e8c1c72176690b64df603edacf78
72,253
import time def execute_search( search: Search, *, search_terms: str = "", user: AbstractBaseUser | None = None, reference: str | None = "", save: bool = True, ) -> SearchQuery: """ Create a new SearchQuery instance and execute a search against ES. Args: search: elasticsea...
2a00a73ee74b6703e89676cecf18601dd87d59e7
72,254
import json def prepare(dp: frictionless.package.Package, name: str): """ Prepare data in EnerMaps format. Parameters ---------- dp : frictionless.package.Package Valid datapackage name : str Name of the dataset (used for constructing the FID) Returns ------- Dat...
b34e992de80d48daafb373bd6e300be2c28b6ffb
72,255
def _merge_config_dicts(dct1, dct2): """ Return new dict created by merging two dicts, giving dct1 priority over dct2, but giving truthy values in dct2 priority over falsey values in dct1. """ return {str(key): dct1.get(key) or dct2.get(key) for key in set(dct1) | set(dct2)}
9d66c10438027254fbac7d8cc91185a07dd9da65
72,256
def streetgenerator(specs, CELLSIZE, grid, skipx, skipy): """Generate a road network. Input: size of each cell for buildings, size of the grid, the number of streets to skip in each direction (so not every building is bounded by four streets, looks to dense).""" width = 5.0 separation = 1.0 ro...
e7db683433fdc441147a350020ff07daf480de19
72,257
def beatiful_font(text): """ Função que estiliza certas partes de um texto, de acordo com as cores e estilos definidos pelo programador """ father = [] ansi = [] scala = -1 for word in text.split(">"): start = word.find("<") + 1 color = word[start:] tag = "" ...
30de00ea57ec2981b898a17fac637e8545f3b7ad
72,258
def is_number(number): """ Returns true if number is a valid number value False otherwise """ try: float(number) return True except (ValueError, TypeError): return False
f5b67ba24bc30611153612f1ba73a376f533485d
72,259
import warnings def check_duplicate_cfs(data, biosphere): """Check that multiple substances in input data are not matched to same ecoinvent flow""" bd = {obj.key: obj for obj in biosphere} for ds in data: seen = {} for cf in ds["exchanges"]: if not cf.get("input"): ...
2afcd35df8d6fd891ce83988d9fcb32c72edb11d
72,261
def from_list(*args): """ Input: args - variable number of integers represented as lists, e.g. from_list([1,0,2], [5]) Output: new_lst - a Python array of integers represented as strings, e.g. ['102','5'] """ new_lst = [] for lst in args: new_string = '' for digi...
c3c0a2224433104a00ffabdadf612127d1b0ed3c
72,262
def conv2d(x, W, b, strides=1): """ Add a convolution layer using ReLu as the activation function. Args: x: input data W: weights b: bias strides: stride size (assume square stride) Returns: A TensorFlow convolution layer. """ x = tf.nn.conv2d(x, W, stri...
30004142f9eee93d573e64cab4d0bb4a8ecbc21f
72,263
async def canSend(): """ Returns True if a command can be sent """ return not commandSent
9cb1de5cf9d905b41a760133f42e749bb307ea17
72,264
def ROI(loc, dim, center=False): """ Slicing operator for extracting a region of interest (ROI) from a 2D array. Eg: Accumulate src into dst at (10, 10) dst = np.zeors(HW(100, 100)) src = np.zeors(HW(50, 50)) roi = ROI(YX(10, 10), HW(src.shape)) dst[roi] += src """ lo...
b21900ab74f069a06ada037b333cc487551de309
72,265
def compute_homography(src, dst): """computes the homography from src, to dst using inversion method.""" if src.shape[1] == 2 : p1 = np.ones((len(src),3),'float64') p1[:,:2] = src elif src.shape[1] == 3 : p1 = src if dst.shape[1] == 2 : p2 = np.ones((len(dst),3),'...
622da34e9a99590155582a79764fd1014a48e097
72,266
def make_embed(title, description, idx, pages): """Make an embed with page number footer.""" e = discord.Embed(title=title, description=description) e.set_footer(text="Page {} of {}".format( idx + 1, pages)) return e
4cd6b35a020f86991739b19e0930dbe9b83142d5
72,267
def interp_shifts(coords, shifts, n=None): """ Interpolate shifts for all frames not in coords and create dask array Parameters ---------- coords : (N,) coordinates for shifts shifts : (d, N) list of arrays to be interpolated n : int or None, defaults=None final leng...
63a4b7a79620124a390f700c8ed7479c3edc0827
72,268
import numpy def lip2dens( perc_lipid, dens_lipid=0.9007, dens_prot=1.34, dens_water=0.994, dens_ash=2.3 ): """Derive tissue density from lipids The equation calculating animal density is from Biuw et al. (2003), and default values for component densities are from human studies collected in the b...
f64796816713196bef104536aa88ec2de54a2b21
72,269
def get_currentID(isamAppliance, check_mode=False, force=False): """ Retrieve the current point of contact profile information """ return isamAppliance.invoke_get("Retrieve the current point of contact profile information", uri, requires_modules=requires_modules, ...
0269edba2692157e9fbae059ee796903c9ac566b
72,270
from datetime import datetime def create_article_id(created=None): """根据created参数,创建一个数字id,有可能重复,需要自己判断下""" if not created: created = datetime.now() # 计算与2013-2-10相差天数 # print(created,type(created)) date_now = created.date() date_start = date(2013, 2, 10) days = (date_now - date_s...
3a5535ce5d162170de972cb138658d62a5246df5
72,271
def random_crop(input_image, target_image): """Crop random matching portion from image and target. Args: input_image (tf.Tensor, dtype 'uint8', dimensions m x n x 3): Tensor (photo) to be cropped. target_image (tf.Tensor, dtype 'uint8', dimensions m x n x 3): Tensor (lin...
29a45079ce65774abd2d8fc13524f385d3381cf3
72,272
def attribute(sxpr, key, val=None): """Get an attribute of an sxpr. sxpr sxpr key attribute key val default value (default None) returns attribute value """ for x in attributes(sxpr): if x[0] == key: val = x[1] break return val
2474e499df87a5d0c4d327a118b66d0de450abe9
72,273
def serial_corr(wave, lag=1): """Computes serial correlation with given lag. wave: Wave lag: integer, how much to shift the wave returns: float correlation coefficient """ n = len(wave) y1 = wave.ys[lag:] y2 = wave.ys[:n-lag] corr = corrcoef(y1, y2) return corr
30c49e0e2dbe49b1fbe60831966c895458d19a94
72,274
import pynvml def mem_utilization_for(device_handle): """ Percent of time over the past sample period during which global (device) memory was being read or written. """ try: return pynvml.nvmlDeviceGetUtilizationRates(device_handle).memory except pynvml.NVMLError: return None
60f688439b991c51fb7556abf6990003d8995035
72,275
from typing import Optional def find_short_phrase(head_word: Token, uses_exact_spacy_noun_chunk: bool = False) -> Optional[Span]: """This is based on scanning for a limit set of dependency edges. This is essentially motivated by StuffIE's original algorithm, but also relies on the `noun_chunks` function o...
dcfc90f5c133e33200b6fae7a00f73b224739f86
72,276
def jewish_dusk(date, location): """Return standard time of Jewish dusk on fixed date, date, at location, location, (as per Vilna Gaon).""" return dusk(date, location, angle(4, 40, 0))
2dc2c558f229cbca2970842c99932c3e0bf31f1e
72,277