content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def tgamma ( x ) : """'tgamma' function taking into account the uncertainties """ fun = getattr ( x , '__tgamma__' , None ) if fun : return fun() return math.gamma ( x )
35c73e2e0a9945cb38beffb6376dd7b7bc6443e9
3,637,150
def detect_peaks_by_channel(traces, peak_sign, abs_threholds, n_shifts): """Detect peaks using the 'by channel' method.""" traces_center = traces[n_shifts:-n_shifts, :] length = traces_center.shape[0] if peak_sign in ('pos', 'both'): peak_mask = traces_center > abs_threholds[None, :] f...
c5024e73e103ba50c6d011067849eafb519d7ca7
3,637,151
def multi_gauss_psf_kernel(psf_parameters, BINSZ=0.02, NEW_BINSZ=0.02, **kwargs): """Create multi-Gauss PSF kernel. The Gaussian PSF components are specified via the amplitude at the center and the FWHM. See the example for the exact format. Parameters ---------- psf_parameters : dict ...
07705bcebb02c622c8f1a4cddcad8781ebfa08fa
3,637,152
from typing import List from typing import Optional from typing import Union def Wavefunction( # type: ignore # pylint: disable=function-redefined param: List[List[int]], broken: Optional[Union[List[str], str]] = None) -> 'Wavefunction': """Initialize a wavefunction through the fqe namespace ...
d5646e26c908c2c824095f20e82cf9418c6115a6
3,637,153
def extractFiles(comment): """Find all files in a comment. @param comment: The C{unicode} comment text. @return: A C{list} of about values from the comment, with no duplicates, in the order they appear in the comment. """ return uniqueList(findall(FILE_REGEX, comment))
af795598e9f5be973d0e7df771d11d064590881f
3,637,154
def rint_compute(input_x): """rint compute implementation""" res = akg.lang.cce.round(input_x) res = akg.lang.cce.cast_to(res, input_x.dtype) return res
f1797518d6b4a7d117ee894c5c0ff26bb4eb09f9
3,637,156
def _solequal(sol1, sol2, prec): """ Compare two different solutions with a given precision. Return True if they equal. """ res = True for sol_1, sol_2 in zip(sol1, sol2): if np.ndim(sol_1) != 0 and np.ndim(sol_2) != 0: res &= _dist(sol_1, sol_2) < prec elif np.ndim...
29361d34cf1d1703fa60c8df77132d15e4e1e849
3,637,157
def clip_rows(data, ord=2, L=1): """ Scale clip rows according the same factor to ensure that the maximum value of the norm of any row is L """ max_norm = get_max_norm(data, ord=ord) print("For order {0}, max norm is {1}".format(ord, max_norm)) normalized_data = data.copy() modified = ...
64ed166a88eee193f5b6c157bb2d0f37f02af150
3,637,159
from typing import Pattern def extrapolate_to_zero_linear(pattern): """ Extrapolates a pattern to (0, 0) using a linear function from the most left point in the pattern :param pattern: input Pattern :return: extrapolated Pattern (includes the original one) """ x, y = pattern.data step = x[...
ca148be4a104a0eaff5b765de3a847bdf9c052be
3,637,160
import random def findKthSmallest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def partition(left, right, pivot_index): pivot = nums[pivot_index] # 1. move pivot to end nums[pivot_index], nums[right] = nums[right], nums[pivot_index] ...
d82176bd9539cf36416c5dc3c7da53a99f2a8f62
3,637,161
def racetrack_AP_RR_TF( wavelength, sw_angle=90, radius=12, couplerLength=4.5, gap=0.2, width=0.5, thickness=0.2, widthCoupler=0.5, loss=[0.99], coupling=[0], ): """This particular transfer function assumes that the coupling sides of the ring resonator are straight, and t...
e6bc912970333b901bf70e573a8b9194f6255de5
3,637,162
from typing import Union from typing import Iterator import tqdm def consume_chunks(generator: Union[PandasTextFileReader, Iterator], progress: bool = True, total: int = None): """Transform the result of chained filters into a pandas DataFrame :param generator: iterator to be transformed into a dataframe ...
60198262341e9bd6dd5170cb98439c5b9975a238
3,637,164
def lang_not_found(s): """Is called when the language files aren't found""" return s + "⚙"
064d73e10d6e2aa9436557b38941ed2eb020d7bb
3,637,165
def _get_corr_matrix(corr, rho): """Preprocessing of correlation matrix ``corr`` or correlation values ``rho``. Given either ``corr`` or ``rho`` (each may be an array, callable or process instance), returns the corresponding, possibly time-dependent correlation matrix, with a ``shape`` attribut...
8241c0245cbd4b8554c31deb28179556c9da8cd1
3,637,166
def sequence_exact_match(true_seq, pred_seq): """ Boolean return value indicates whether or not seqs are exact match """ true_seq = strip_whitespace(true_seq) pred_seq = strip_whitespace(pred_seq) return pred_seq["start"] == true_seq["start"] and pred_seq["end"] == true_seq["end"]
574ad0a7ad0a31875c298824fc1230bdf662f356
3,637,168
def same_variable(a, b): """ Cette fonction dit si les deux objets sont en fait le même objet (True) ou non (False) s'ils sont différents (même s'ils contiennent la même information). @param a n'importe quel objet @param b n'importe quel objet @return ``True`` ...
0c33a33e01e5457c7216982df580abc90db47d2f
3,637,169
def format_level_2_memory(memory, header=None): """Format an experiment result memory object for measurement level 2. Args: memory (list): Memory from experiment with `meas_level==2` and `memory==True`. header (dict): the experiment header dictionary containing useful information fo...
ebb8b0ca2e34ac93aaec01efe05a8a4d5de785d5
3,637,170
from .objectbased.conversion import to_polar def convert_objects_to_polar(rendering_items): """Apply conversion to turn all Objects block formats into polar.""" return list(apply_to_object_blocks(rendering_items, to_polar))
df7206530e60d3765b1eaf7a3d6b45a41efc50c0
3,637,171
from typing import Tuple import ast def find_in_module(var_name: str, module, i: int = 0) -> Tuple[str, ast.AST]: """Find the piece of code that assigned a value to the variable with name *var_name* in the module *module*. :param var_name: Name of the variable to look for. :param module: Module to se...
7cb6e6bd17018e72953273e53c2fe5f9ac73f2c2
3,637,172
def empty(shape, dtype="f8", order="C", device=None, usm_type="device", sycl_queue=None): """Creates `dpnp_array` from uninitialized USM allocation.""" array_obj = dpt.empty(shape, dtype=dtype, order=order, ...
3229a4a99a1073c9bee636d630a818d5c91a3c97
3,637,173
def solve2(input_data): """use scipy.ndimage""" data_array = np.array(parse(input_data)) # boundaries of objects must be 0 for scipy label # convert 0 in data to -1 and 9 to 0 data_array[data_array == 0] = -1 data_array[data_array == 9] = 0 labels, _ = label(data_array) _, counts = n...
0ba8767020388c33a068b10f89b9cacd51f9e85d
3,637,174
import math def yolox_semi_warm_cos_lr( lr, min_lr_ratio, warmup_lr_start, total_iters, normal_iters, no_aug_iters, warmup_total_iters, semi_iters, iters_per_epoch, iters_per_epoch_semi, iters, ): """Cosine learning rate with warm up.""" min_lr = lr * min_lr_ratio ...
ac6b1850031a5c36f8de2c7597c374bc401aaee3
3,637,175
def builder(obj, dep, denominator=None): """ A func that modifies its obj without explicit return. """ def decorate(func): tasks.append(Builder(func, obj, dep, denominator)) return func return decorate
8b9d9887324c6aa931efcf905db56ded606c6d84
3,637,176
def on_segment(p, r, q, epsilon): """ Given three colinear points p, q, r, and a threshold epsilone, determine if determine if point q lies on line segment pr """ # Taken from http://stackoverflow.com/questions/328107/how-can-you-determine-a-point-is-between-two-other-points-on-a-line-segment cr...
b8517fc9d3c6d916cac698913c35ba4e5d873697
3,637,178
def groupby_times(df, kind, unit=None): """Groupby specific times Parameters ---------- df : pandas.DataFrame DataFrame with `pandas.TimedeltaIndex` as index. kind : {'monthly', 'weekly', 'daily', 'hourly', 'minutely', 'all'} How to group `df`. unit : str (optional) What...
81d5a17e3f89b36a0ce88867ce6d04cd1602a0b4
3,637,179
def pid_to_path(pid): """Returns the full path of the executable of a process given its pid.""" ps_command = "ps -o command " + pid ps_output = execute(ps_command) command = get_command(ps_output) whereis_command = "whereis " + command whereis_output = execute(whereis_command) path = get_path(whe...
942a5756f9b4aecb51472efce558f86d0b9c8d67
3,637,180
def get_script_histogram(utext): """Return a map from script to character count + chars, excluding some common whitespace, and inherited characters. utext is a unicode string.""" exclusions = {0x00, 0x0A, 0x0D, 0x20, 0xA0, 0xFEFF} result = {} for cp in utext: if ord(cp) in exclusions: ...
657e60bc1a8d6c7b436cf4f8700041abe41721ea
3,637,181
def ja_nein_vielleicht(*args): """ Ohne Argumente erstellt diese Funktion eine Ja-Nein-Vielleicht Auswahl. Mit einem Argument gibt es den Wert der entsprechenden Auswahl zurück. """ values = { True: "Vermutlich ja", False: "Vermutlich nein", None: "Kann ich noch nicht sagen" ...
a4e58ab3f2dc9662e1c054ddfd32ff1ae988b438
3,637,182
def ebic(covariance, precision, n_samples, n_features, gamma=0): """ Extended Bayesian Information Criteria for model selection. When using path mode, use this as an alternative to cross-validation for finding lambda. See: "Extended Bayesian Information Criteria for Gaussian Graphical Mode...
e5183ee7a4b0f4edc7509afb7217e4203a73919a
3,637,183
def _process_cli_plugin(bases, attrdict) -> dict: """Process a CLI plugin, generate its hook functions, and return a new attrdict with all attributes set correctly. """ attrdict_copy = dict(attrdict) # copy to avoid mutating original if cli.Command in bases and cli.CommandExtension in bases: ...
999f5011532ae67626ff5a7f416efcfad447c127
3,637,184
def get_group(yaml_dict): """ Return the attributes of the light group :param yaml_dict: :return: """ group_name = list(yaml_dict["groups"].keys())[0] group_dict = yaml_dict["groups"][group_name] # Check group_dict has an id attribute if 'id' not in group_dict.keys(): prin...
db9e027594d3a9a9e0a1838da62316cfe6e0c380
3,637,185
def plot_time( monitors, labels, savefile, title="Average computation time per epoch", ylabel="Seconds", log=False, directory=DEFAULT_DIRECTORY, ): """Plots the computation time required for each step as a horizontal bar plot :param monitors: a list of monitor sets: [(training,...
7723be1933bd9f2dd84e1ebec7364b4cbe942601
3,637,186
def average_gradients(tower_grads): """Calculate the average gradient for each shared variable across all towers. Note that this function provides a synchronization point across all towers. Args: tower_grads: List of lists of (gradient, variable) tuples. The outer list is over individual gradi...
fc2a8692046fe32884cb75d405d21fce6301a88d
3,637,187
def recommend(model): """ Generate n recommendations. :param model: recommendation model :return: tuple(recommendations made by model, recommendations made by primitive model, recall, coverage) """ n = 10 hit = 0 # used for recall calculation total_recommendations = 0 all_recommend...
07d5e538cbfafd60bee7030fd31e6c9b5d178cfa
3,637,188
def drop_nondominant_term(latex_dict: dict) -> str: """ given x = \\langle\\psi_{\\alpha}| \\hat{A} |\\psi_{\\beta}\\rangle return x = \\langle\\psi_{\\alpha}| a_{\\beta} |\psi_{\\beta} \\rangle >>> latex_dict = {} >>> latex_dict['input'] = [{'LHS': parse_latex(''), 'RHS': parse_latex('')}]...
6f53dcce5e17761d6ab9f7f0a772dcd81d91b33e
3,637,190
def template_introduce(): """ This function constructs three image carousels for self introduction. Check also: faq_bot/model/data.py reference - `Common Message Property <https://developers.worksmobile.com/kr/document/100500805?lang=en>`_ :return: image carousels type message content....
f0b6585512b8419932c1be38831057508a4454eb
3,637,191
def assign_distance_to_mesh_vertex(vkey, weight, target_LOW, target_HIGH): """ Fills in the 'get_distance' attribute for a single vertex with vkey. Parameters ---------- vkey: int The vertex key. weight: float, The weighting of the distances from the lower and the upper target, ...
5859ef6535d394d098a92603b2a3e6ac7c619e51
3,637,192
import hashlib def _get_user_by_email_or_username(request): """ Finds a user object in the database based on the given request, ignores all fields except for email and username. """ if 'email_or_username' not in request.POST or 'password' not in request.POST: raise AuthFailedError(_('There was...
7bf8ced15acd226b647f0b2e272699c41c3432bc
3,637,193
def get_minsize_assignment(N, min_comm_size): """Create membership vector where each community contains at least as a certain number of nodes. Parameters ---------- N : int Desired length of membership vector min_comm_size : int Minimum number of nodes each community should have...
e708b81a2b16d9885a0625d275fedcf001308c00
3,637,195
def _combine_plots( p1, p2, combine_rules=None, sort_plot=False, sort_key=lambda x_y: x_y[0] ): """Combine two plots into one, following the given combine_rules to determine how to merge the constants :param p1: 1st plot to combine :param p2: 2nd plot to combine :param combine_rules:...
93665498ba30af51020300f774ba5f0cfc2684ce
3,637,196
def shape_of(array, *, strict=False): """ Return the shape of array. (sizes of each dimension) """ shape = [] layer = array while True: if not isinstance(layer, (tuple, list)): break size = len(layer) shape.append(size) if not size: break ...
c6e889338761897c1e036bef29cd73bd430608aa
3,637,197
def return_state_dict(network): """ save model to state_dict """ feat_model = {k: v.cpu() for k, v in network["feat_model"].state_dict().items()} classifier = {k: v.cpu() for k, v in network["classifier"].state_dict().items()} return {"feat_model": feat_model, "classifier": classifier}
c0bcd9bd84f7c722c7de5f52d12cf6762a86e1e0
3,637,198
def get_elevation_data(lonlat, dem_path): """ Get elevation data for a scene. :param lon_lat: The latitude, longitude of the scene center. :type lon_lat: float (2-tuple) :dem_dir: The directory in which the DEM can be found. :type dem_dir: str """ datafi...
b7876bbae41bb6fbadbeff414485a2edff2646bf
3,637,199
from datetime import datetime def iso8601(dt=None, aware=False): """ Returns string datetime stamp in iso 8601 format from datetime object dt If dt is missing and aware then use now(timezone.utc) else utcnow() naive YYYY-MM-DDTHH:MM:SS.mmmmmm which is strftime '%Y-%m-%dT%H:%M:%S.%f' Only TZ aware ...
181d2f38b39792cc0331ee7bd9a34f76691b5128
3,637,200
import re import string def parse_text(infile, xpath=None, filter_words=None, attributes=None): """Filter text using XPath, regex keywords, and tag attributes. Keyword arguments: infile -- HTML or text content to parse (list) xpath -- an XPath expression (str) filter_words -- regex keywords (list...
7d2b04c477624db322721b785d95bffa16af1576
3,637,201
def _check_blacklist_members(rule_members=None, policy_members=None): """Blacklist: Check that policy members ARE NOT in rule members. If a policy member is found in the rule members, add it to the violating members. Args: rule_members (list): IamPolicyMembers allowed in the rule. poli...
2fc41f4ff6c401de0976b04dd6a8cb858cef96e7
3,637,202
def create_variable_weather(weather_data, original_epw_file, columns: list = ['drybulb'], variation: tuple = None): """ Create a new weather file adding gaussian noise to the original one. Parameters ---------- weather_data : opyplus.WeatherData Opyplus object with the weather for the simul...
13674db675cb5c03c77047e78d0cf57b3bfab1ac
3,637,203
def transform(func, geom): """Applies `func` to all coordinates of `geom` and returns a new geometry of the same type from the transformed coordinates. `func` maps x, y, and optionally z to output xp, yp, zp. The input parameters may iterable types like lists or arrays or single values. The output ...
71bde1500ec8370a7718542ee26181d2aad6591f
3,637,204
def get_jit(policy_name, asc_location, resource_group_name): """Building query Args: policy_name: Policy name asc_location: Machine location resource_group_name: Resource name group Returns: dict: response body """ cmd_url = ( "/resourceGroups/{}/providers/M...
9e50eaf91fb2b2318f6b5334b848a6dce70ddf61
3,637,205
def rank_by_yield(df): """ Rank phenotypes by yield only. Parameters ---------- df : pd.DataFrame MAIZSIM yield output dataframe. df_sims or df_mature """ # Prep data groups = ['cvar', 'site'] how = 'mean' sim = 'dm_ear' mx_mean = agg_sims(df, groups, how, ...
10dd1c9a8e3ffc94cf4580bc789d7cc19353d748
3,637,206
def k2lc(epic): """ load k2 light curve """ prefix = epic[:4] id = epic[4:] c = "01" path = "data/c01/{0}00000/{1}".format(prefix, id) end = "kepler_v1.0_lc.fits" file = "{0}/hlsp_everest_k2_llc_{1}-c{2}_{3}".format(path, epic, c, end) x, y = process_data(file) return x, y
6cd5ffa387fa3d666c2f6561c06b458c7556509f
3,637,207
def multi_leave_topics(multileaver, user_id, time): """Multileaves a number of suggested topics for a user and returns the results.""" topics = get_user_suggested_topics(user_id) if not topics: return None ranking, credit = multileaver.team_draft_multileave(topics) topic_recommendations...
0b845a7a16419e4592ffd4f75d988728cef70727
3,637,208
def generate_age(sex): """Generate the age of a person depending on its sex Parameters ---------- sex : int Sex should be either 0 (men) or 1 (women). Raises ------ ValueError If sex is not 0 or 1. Returns ------- age : int Generated age of a perso...
8f0ba4f215417035760fd1bbe1db5cc0974ed629
3,637,209
def _extract_text_Wikilink(node: mwparserfromhell.nodes.wikilink.Wikilink) -> str: """ Wikilinks come in 2 formats, thumbnails and actual links. In the case of thumbnails, if posible pull out the nested caption. """ if node.title.startswith('File:') or node.title.startswith('Image:'): if nod...
bc6c16aff602cfeac9756d0c357e054731dc7ff8
3,637,210
def dict_zip(*dicts): """ Take a series of dicts that share the same keys, and reduce the values for each key as if folding an iterator. """ keyset = set(dicts[0]) for d in dicts: if set(d) != keyset: raise KeyError(f"Mismatched keysets in fold_dicts: {sorted(keyset)}, {sorte...
47416641a6451828b78ae6dfd81a48676fcea71f
3,637,211
def Ustagger_to_mass(U): """ U are the data on the left and right of a grid box A simple conversion of the U stagger grid to the mass points. Calculates the average of the left and right value of a grid box. Looping over all columns it reduces the staggered grid to the same dimensions as the mas...
d3dbae52d74aff40b83b0437eed9f0aafb5e37ee
3,637,213
def _linear(args, output_size, bias, bias_initializer=tf.zeros_initializer(), kernel_initializer=initializer(), scope=None, reuse=None): """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. Args: args: a 2D Tensor or a l...
3d11e74e4e28aeb737f63046fc4e53b4e68aeb9b
3,637,214
def build_fpn_mask_graph(rois, feature_maps, image_size, num_classes, pool_size, train_bn=True): """Builds the computation graph of the mask head of Feature Pyramid Network. rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized coordinates. feature_maps: L...
c6286955fb07d3feb20801a409d44e20382133ef
3,637,215
def calculate_perf_counter_counter(previous, current, property_name): """ PERF_COUNTER_COUNTER https://technet.microsoft.com/en-us/library/cc740048(v=ws.10).aspx """ n0 = previous[property_name] n1 = current[property_name] d0 = previous["Timestamp_Sys100NS"] d1 = current["Timestamp_Sys1...
f517f39ef20af5a4d23f1fd74a14fab93be4037b
3,637,216
import http from datetime import datetime def event_edit(request, id): """Edit form for a particular event.""" event = get_object_or_404(Event, id=id) result = can_edit_event(event, request.user) if isinstance(result, http.HttpResponse): return result if request.user.has_perm('main.change_...
0ea47e7b1772c3fa0529f6cc7675a83108ad0018
3,637,217
from typing import Callable def migrator(from_: str, to_: str) -> Callable[[MigratorF], MigratorF]: """Decorate function as migrating settings from v `from_` to v `to_`. A migrator should mutate a `NapariSettings` model from schema version `from_` to schema version `to_` (in place). Parameters -...
20bf5c7c8e693fc880ed9d31e610b2d939f8c020
3,637,218
import json def rawChipByLocation_query(): """ Get chips images by parcel id. Generates a series of extracted Sentinel-2 LEVEL2A segments of 128x128 (10m resolution bands) or 64x64 (20 m) pixels as list of full resolution GeoTIFFs --- tags: - rawChipByLocation responses: 200: ...
bfb2b32a17d5b1b8a05efcf710d70fc4179996c5
3,637,219
from pathlib import Path from typing import Optional from typing import List import json def build_settings( tmp_path: Path, template: str, *, oidc_clients: Optional[List[OIDCClient]] = None, **settings: str, ) -> Path: """Generate a test Gafaelfawr settings file with secrets. Parameters ...
aaba1048c96cd07b42492d11ca34a87365350a20
3,637,221
def get_actions_matching_arn(arn): """ Given a user-supplied ARN, get a list of all actions that correspond to that ARN. Arguments: arn: A user-supplied arn Returns: List: A list of all actions that can match it. """ raw_arns = get_matching_raw_arns(arn) results = [] for...
595e985829df5035c81928a4441c64b136818e8d
3,637,223
import time def api_retry(func, task_id): """ 添加api重试机制 :param func: 调用的api函数 :param task_id: 任务id :return: 重试结果 """ retry_flag, status_result = False, "" for i in range(TRANSPORT_RETRY_TIMES): time.sleep(TRANSPORT_RETRY_INTERVAL) retry_flag, status_result = func(task_...
8f3ad5d6c9865ec8405c7504e9a6af851f5e4916
3,637,226
def test_bound_callables(): """Test that we can use a callable as a bound value.""" @magicgui(x={"bind": lambda x: 10}) def f(x: int = 5): return x assert f() == 10 f.x.unbind() assert f() == 5
baf0cafcef7160e23c1b66be9734245adbe9d219
3,637,227
def delete_role(user_id: str, role_id: str): """ Removes a role from a user """ print(user_id) print(role_id) return jsonify(), HTTPStatus.NO_CONTENT
aa97868d54f0f3b887d80a7f4f8ef258fb050001
3,637,228
import multiprocessing as mp from functools import partial from jinfo.utils.percentage_identity import percentage_identity def remove_degenerate_seqs( alignment_obj: BaseAlignment, identity_limit: int, show_id_array: bool = False ) -> BaseAlignment: """ Filter high similarity sequences from a list of Seq ...
fcada477a01290fb54a83d074c31de31c9be17e1
3,637,229
def get_domain(url): """ Get the domain from a URL. Parameters ---------- url : string HTTP URL Returns ------- domain : string domain of the URL """ o = urlparse(url) scheme = o.scheme if not o.scheme: scheme = "http" link = scheme + "://" + o...
e47d2fdedab66d356887a94db5c22770f5e21823
3,637,230
def push_activations(activations, from_layer, to_layer): """Push activations from one model to another using prerecorded correlations""" inverse_covariance_matrix = layer_inverse_covariance(from_layer) activations_decorrelated = np.dot(inverse_covariance_matrix, activations.T).T covariance_matrix = laye...
ddbacdbbfb30156204df27b00c79a28a4895810e
3,637,231
def cross_val_score(estimator, X, y=None, groups=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs'): """Evaluate a score using cross-validation Parameters ---------- estimator : estimator object implementing 'fit' The object to use to...
8c4fe69cb2043adf5541b188d99da23beb4d9874
3,637,232
def load_graph(N, M): """ Builds an adjacency list representation of a graph with N vertices. Each graph[i][j] is the minimum length of an edge between vertice i and j. :rtype List[int, Dict[int, int]] """ graph = [dict() for i in range(0, N)] for i in range(0, M): (x, y, r) = read...
acee5cb79eb5bbc04eada9d54344700bff3ffaa4
3,637,233
def quartile_range(arr): """ Find out the Interquartile Range """ #if it is odd if len(arr)%2 != 0: left=median(arr[:len(arr)/2]) right=median(arr[len(arr)/2 + 1:]) else: #if array is even left = median(arr[:len(arr)/2]) right = median(arr[len(arr)/2:]) ...
c6fafd63e3e64b893a4632bfb2027e330e8a3c32
3,637,234
def check_syntax(filename, raise_error=False): """Return True if syntax is okay.""" with autopep8.open_with_encoding(filename) as input_file: try: compile(input_file.read(), '<string>', 'exec', dont_inherit=True) return True except (SyntaxError, TypeError, UnicodeDecodeEr...
d401e292ddb20d66c65a7ffa8988ddab4a7962ec
3,637,235
from astropy.convolution import convolve as astropy_convolve from ..utils import process_image_pixels def test_process_image_pixels(): """Check the example how to implement convolution given in the docstring""" def convolve(image, kernel): '''Convolve image with kernel''' images = dict(image=...
439e45a7fd403de4df8dd9dfc662be6405d69dc0
3,637,236
import math def im2vec(im, bsize, padsize=0): """ Converts image to vector. Args: im: Input image to be converted to a vector. bsize: Size of block of im to be converted to vec. Must be 1x2 non-negative int array. padsize (optional, default=0): Must be non-negative integers in a 1...
0a88cf02e37fdaeb24103cc0a7027067ea703c82
3,637,237
def mobilenetV2_block( input_layer, filters: int = 32, dropout_ratio: float = DEFAULT_DROPOUT_RATIO, use_batchnorm: bool = False, prefix: str = "mobilenetV2_", initializer=DEFAULT_KERNEL_INITIALIZER, regularizer=DEFAULT_KERNEL_REGULARIZER, channels_index: ...
0fd2e38d32d192412de4928c7ef92b577235581f
3,637,238
def _grid_archive(): """Deterministically created GridArchive.""" # The archive must be low-res enough that we can tell if the number of cells # is correct, yet high-res enough that we can see different colors. archive = GridArchive([10, 10], [(-1, 1), (-1, 1)], seed=42) archive.initialize(solution_...
540ea0270bbe06830ab096c79590c6ffcad487a2
3,637,239
def check_flush(hand): """Check whether the hand has a flush; returns a boolean.""" if len(hand) == len(hand.by_suit(hand[0].suit)): return True return False
de11f50f11b477e61f284063c7f0da0dda2dd87e
3,637,240
import torch def binary_accuracy(preds, y): """ Returns accuracy per batch :param preds: prediction logits :param y: target labels :return: accuracy = percentage of correct predictions """ # round predictions to the closest integer rounded_predictions = torch.round(torch.sigmoid(preds...
2a321bb9e60a937a879619c2fa3baf1cbe968a33
3,637,241
import csv def load_taxondump(idpath): """Importing the Acidobacteria taxon IDs""" taxons = {} with open(idpath) as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: taxons[row[1]] = row[0] return taxons
b20c973f97d609b646e5c15be7cc320019f21236
3,637,242
import re def _to_numeric_range(cell): """ Translate an Excel cell (eg 'A1') into a (col, row) tuple indexed from zero. e.g. 'A1' returns (0, 0) """ match = re.match("^\$?([A-Z]+)\$?(\d+)$", cell.upper()) if not match: raise RuntimeError("'%s' is not a valid excel cell address" % cell)...
468f452a7e4d4b045ecbb1a1fc261712fb25f3fc
3,637,243
def protocol(recarr, design_type, *hrfs): """ Create an object that can evaluate the FIAC Subclass of formulae.Formula, but not necessary. Parameters ---------- recarr : (N,) structured array with fields 'time' and 'event' design_type : str one of ['event', 'block']. Handles how...
d2ce4b35614ca692226133ec72b4f1d46baf065c
3,637,245
def iter_children(param,childlist=[]): """ | Iterator over all sub children of a given parameters. | Returns all childrens names. =============== ================================= ==================================== **Parameters** **Type** **Description*...
2edbdccc5957cbe6131da70d6dfc24ea67a19e69
3,637,246
def depth_first_graph_search(problem): """ [Figure 3.7] Search the deepest nodes in the search tree first. Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. Does not get trapped by loops. If two paths reach a state, only use the first ...
d610752a99a8c4e7f1b5eee2d520d88f868279eb
3,637,248
def check_matrix_equality(A, B, tol=None): """ Checks the equality of two matrices. :param A: The first matrix :param B: The second matrix :param tol: The decimal place tolerance of the check :return: The boolean result of the equality check """ if len(A) != len(B) or len...
afc89de848597c6325b6eceb109f7f2311c9be7d
3,637,249
def about(topic): """Return a select function that returns whether a paragraph contains one of the words in TOPIC. Arguments: topic: a list of words related to a subject >>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy']) >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_d...
b73512058675ac9a17a8d5cd36ab544080a2acbe
3,637,250
def calcBarycentricCoords(pt, verts): """calculate the Barycentric coordinates""" verts = np.array(verts) # vertices formed by N+1 nearest voxels pt = np.array(pt) # voxel of interest A = np.transpose(np.column_stack((verts, np.ones(verts.shape[0])))) b = np.append(pt, 1) retur...
5869c40d9b95280d3db77dd7eb3a42fab46c45a8
3,637,251
import re def parse_regex(ctx, param, values): """Compile a regex if given. :param click.Context ctx: click command context. :param click.Parameter param: click command parameter (in this case, ``ignore_regex`` from ``-r|--ignore-regiex``). :param list(str) values: list of regular expressions...
b920d5a406ac3b7a8f28bb9125313c90eec5e212
3,637,253
def get_query_string(**kwargs): """ Concatenates the non-None keyword arguments to create a query string for ElasticSearch. :return: concatenated query string or None if not arguments were given """ q = ['%s:%s' % (key, value) for key, value in kwargs.items() if value not in (None, '')] return ...
cc73c157a8975e5df9c98efcd5b10396e5175486
3,637,256
def check_bin(img): """Checks whether image has been properly binarized. NB: works on the assumption that there should be more background pixels than element pixels. Parameters ---------- img : np.ndarray Description of parameter `img`. Returns ------- np.ndarray A bina...
808e4635befa5848d7683e6e12ead5b5ee297339
3,637,257
def add_quotes(path): """Return quotes if needed for spaces on path.""" quotes = '"' if ' ' in path and '"' not in path else '' return '{quotes}{path}{quotes}'.format(quotes=quotes, path=path)
6e65da4512183ef62a0ac22b4c3c74f9e5273fbd
3,637,258
def terminal(board): """ Returns True if game is over, False otherwise. """ if len(actions(board)) == 0: return True if winner(board) is not None: return True return False #raise NotImplementedError
6776ad6a261dd8dd90abbb6abb5fa428f8149bba
3,637,259
def login(): """LogIn Page""" if request.method == "GET": return render_template("login.html") email = request.form.get("email") password = request.form.get("password") remember = bool(request.form.get("remember")) user = User.query.filter_by(email=email).first() if not user or not...
3db9447298ca149037cdac89e850e893d5f9ac37
3,637,260
from typing import List from operator import not_ def apply_modifiers(membership: npt.ArrayLike, modifiers: List[str]) -> npt.ArrayLike: """ Apply a list of modifiers or hedges to a numpy array. :param membership: Membership values to be modified. :param modifiers: List of modifiers or hedges. ...
6140646bc5943ba7c7b6ce597e033c9797ba5ab4
3,637,261
def unitY(m=1.0): """Return an unit vector on Y""" return np.array((0, m, 0))
fda046e085e9ab00d263ec7f5569bcd719113c5d
3,637,262
def create_suction_model(radius): """Create a suction model""" hm = np.zeros((2 * radius + 1, 2 * radius + 1)) hm1 = np.tile(np.arange(-radius, radius + 1), (2 * radius + 1, 1)) hm2 = hm1.T d = np.sqrt(hm1**2 + hm2**2) return np.where(d < radius, 1, 0).astype(np.float64)
df8e34b0b8957169099740dc74d07c813056dfc4
3,637,263
def model_entrypoint(model_name): """Fetch a model entrypoint for specified model name """ return _model_entrypoints[model_name]
8c1658f07db87e99ffbde428bc55281b6b185639
3,637,264
def encrypt(data, password): """Enrcrypt data and return content in binary""" try: cipher = AES.new(password.encode(), AES.MODE_CBC) cypher_text_bytes = cipher.encrypt(pad(data.encode(), AES.block_size)) return b'' + cipher.iv + b':' + cypher_text_bytes except ValueError: p...
2e4719cc48ded4f8c5400bfb5ab583a229034261
3,637,265
from datetime import datetime def change_datetime_to_str(input_time=None, str_format="%Y-%m-%d"): """ :param input_time: 指定需要转换的时间, 默认当前时间 :param str_format: 字符时间的格式, 默认%Y-%m-%d :return: """ spec_time = input_time or datetime.datetime.now() return spec_time.strftime(str_format)
f0f3a72ee05b41dbeec12b05a89a26542fcefb21
3,637,266