content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def filter_sides(segmentation): """Remove hedges on left and right hand side. Also remove anything from the edge of the hedge to the closest edge of the image. """ ydim, xdim = segmentation.shape mid_point = xdim // 2 for i in segmentation.identifiers: region = segmentation.region_b...
4d02903b4cadc39fb3461fdc13916cc7233ad39d
3,610,219
from datetime import datetime def log_file_name(extension): """ Create a file name in the logfiles directory, based on current data and time Requires the computer to have an RTC or synched clock """ now = datetime.now() # Linux file_name = '%0.4d%0.2d%0.2d-%0.2d%0.2d%0.2d' % (now.year, now...
795ab0623ee6a563cfc4e2531cd8745f0ff2fac3
3,610,220
def arc(data: bytes) -> int: """ Compute a CRC-16 checksum of data with the arc algorithm. :param bytes data: The data to be computed :return: The checksum :rtype: int :raises TypeError: if the data is not a bytes-like object """ _ensure_bytes(data) return _crc_16_arc(data)
1ce9de456d04b1a8b060a1cb83ffd1b457bdae86
3,610,221
def check_replication(master_vals, slave_vals, options): """Check replication among a master and a slave. master_vals[in] Master connection in form: user:passwd@host:port:socket or login-path:port:socket slave_vals[in] Slave connection in form user:passwd@host:port:socket ...
dde3878a9afde2bd12209da20da5681fd64ba77c
3,610,222
def _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count): """ Note. Most of this script is taken from scikit-learn, except for the last line. --- Original doc --- Calculate mean update and a Youngs and Cramer variance update. last_mean and last_variance are statistics compute...
55eacfc7905eae1b2608314a651c25f2707a3ac7
3,610,223
def _calculate_expected_result( dist_per_cell, numeric_values, numeric_values_scale, input_mask_float, logits_aggregation, config ): """ Calculates the expected result given cell and aggregation probabilities. Args: dist_per_cell (`tfp.distributions.Bernoulli`): Cell selection distr...
b282c538b495989b6c4066b8f99d72fc4810845e
3,610,224
def fit_unbinned(f_likelihood, data, start_guess, min_method=None, bounds=None): """ unbinned max likelihood fit to data with given likelihood func """ if method is None: method="L-BFGS-B" # minimization method, see docs result = minimize( neg_log_like, # function to minimize ...
ac20d2fe30aae1922190fee7a38d204a1612a2ad
3,610,225
def load_data(n_pca=3): """Data Loader :param n_pca: number of pca components, defaults to 3 :type n_pca: int, optional """ path = f'../dataRBC/RBC_r28L_T100R100_pca{n_pca}_enc_data.txt.gz' traj_data = pd.read_csv(path, header=None).values traj_data = traj_data.reshape(-1, 200, n_pca) ...
e7e7c454da1aebb2af83f800e488cfab3296b110
3,610,226
def delete_attachment(self, request, form): """ Delete a notice attachment. """ layout = Layout(self, request) notice = self.linked_official_notices[0] if notice.state == 'accepted' or notice.state == 'published': if not request.is_secret(self): request.message( _("...
6715c1079dfabd4e43e97a88ff4b5c75c563b00c
3,610,228
def geoloc(ip_address: str) -> dict: """ Return {'lat':, 'lon':} values for {ip_address} """ ip_details = method_ipinfo(ip_address) return {'lat': ip_details['latitude'], 'lon': ip_details['longitude']}
1f98d69dd9d239f27c85e490cc69d5a27aac9184
3,610,229
def TreeImportanceArray(reg): """Get important array if `reg` is tree regression.""" return reg.feature_importances_
59f3b0bcc9a4c60af71b62163e3e087137c64f49
3,610,230
def _get_test_stats_with_mi(feature_names): """Get stats proto for MI test.""" result = statistics_pb2.DatasetFeatureStatistics() for feature_name in feature_names: feature_proto = text_format.Parse( """ custom_stats { name: "max_sklearn_adjusted_mutual_information" ...
d5ebdd6a55ca0af03b1076ecc5fd4741f296ec19
3,610,231
def ride(self: Client, riders_or_rides: str) -> RideProxy: """Delegates to a :py:class:`mcipc.rcon.be.commands.ride.RideProxy` """ return RideProxy(self, 'ride', riders_or_rides)
209f5804eaf7a6e566fd13acc484abf73802d47c
3,610,232
def process_data(event_id, st, sampling_rate, pre_filt=(1.2, 2, 8, 10), water_level=100, folder_name="default_folder", save_processed=True): """ Function to process the raw data stream Args: event_id (str): Event ID -> Ideally should be time stamp YYYY-MM-DDTHH:MM:SS.000 st ...
bf2b1f829bb0211d9d1729d8feb4534cb01b236e
3,610,233
from typing import Any from typing import Dict def _check_headers(headers: Any) -> Dict: """Check headers format an validate content type. :param headers: configured headers :return Dict: request headers """ if headers is None: headers = {} if 'Content-Type' not in headers.keys(): ...
f7dc965ffd740ea94ca3485f455cf6427ebc16d8
3,610,234
def average_test_disorder(data, test_classifier, target_classifier): """Given a list of points, a feature-test Classifier, and a Classifier for determining the true classification of each point, computes and returns the disorder of the feature-test stump.""" test_disorder = 0 test_classifications = ...
555b55c58cfa956642d6b4f53afca07a999a33b1
3,610,235
import signal def seed_initial_offsets_peaks(y, noise, rect_area=500, prominence_knockdown_factor=0.03): """ Generate the locations of the seeds for the initial fit. Place a seed at each of the peaks. Determine peak location from smoothed version of signal. Smooth signal by cross correlating it with rect....
e7b4f572cedf5ef37e5bc0c3a6f724704c212f16
3,610,237
def ReadNetString(fp): """Reads a net string from the File object fp, returning the string in unicode. A net string has the format <len>:<str>, where <len> is decimal of the length of <str>, and comma ends the string. Returns: The unicode string contained in the netstring, or '' if...
9805367388fea261df94209482f3d496ef6e749b
3,610,238
def to_str(obj): """Attempts to convert given object to a string object """ if not isinstance(obj, str) and PY3 and isinstance(obj, bytes): obj = obj.decode('utf-8') return obj if isinstance(obj, string_types) else str(obj)
1123f73fff9b0eebe3a6d29f2768f0459e0d83f2
3,610,239
def get_middle_value(my_list): """Return the middle value from a list after sorting. :param list my_list: List of sortable values""" return sorted(my_list)[len(my_list) // 2] """Convert an integer resolution in base-pairs to a nicely formatted string. :param int window_size: Integer resolution ...
53e8724f1709429707766db45c34ebd0db62a686
3,610,240
import math def ll2m(lat, lon): """Lat/lon to meters""" x = lon * 20037508.34 / 180.0 y = math.log(math.tan((90.0 + lat) * math.pi / 360.0)) / (math.pi / 180.0) y = y * 20037508.34 / 180 return (x, y)
f998cb7af707d56c9dd6e7a26b8d165f392e07f3
3,610,241
def bilinterp(x, y, nx_tuple, ny_tuple, x_tuple, y_tuple, fxy): """ Bilinear interpolation: Given nx-tuple + 1 x-points, ny-tuple + 1 y-points, x_tuple and y_tuple, routine finds f(x, y) = fxy at (x, y) in (x_tuple, y_tuple). Assumes x_tuple and y_tuple are increasing arrays. """...
ee6ffb312cb0a7af3cff524aa366e71f176158f8
3,610,242
def get_version(): """Return version of the dynamic link library. Wraps: int DWGetVersion();""" return _get_version()
a99b2c66124f14b04c476b888663ffd7b38a61ff
3,610,243
def edu_plotter(func): """Decorator to apply to all plotting functions in OGGM-Edu. Parameters ---------- func : function the function or method to decorate Returns ------- the decorated function """ @wraps(func) def context_wrapper( *args, sns_context=...
d44a63d1c62f5107eb9cbedd89b3c3634bc60a00
3,610,244
def load_sample_data(name): """ Load an example dataset from the GMT server. The data are downloaded to a cache directory (usually ``~/.gmt/cache``) the first time you invoke this function. Afterwards, it will load the data from the cache. So you'll need an internet connection the first time around...
73ffa2caa4106f97d88766214756fbf6347f4787
3,610,245
def rip_svgi(content: str, embed_styles: bool = False) -> str: """ Rips SVG content (single diagram) and scripts for interaction out of HTML :param content: HTML page content in text format :param embed_styles: If specified as True then mentioned styles would be downloaded and embedded into SVG ...
d5472b86be70e138128ff527f388a9b1ffa2602d
3,610,246
def get_info(request): """ Obtiene """ info = "Backend" if UserToken.get_headquar_id(request.session): try: sede = Headquar.objects.get( id=UserToken.get_headquar_id(request.session)) info = "%s-%s" % (sede.enterprise.name, sede.name) except:...
fbfdf8ce2a802af374b0004bb0e6029849c38b9d
3,610,247
from typing import Sequence def prune_by_lbh(seq_list: list, seq_length: int, q: Sequence, kim_reduction: float = 0.75, keogh_reduction: float = 0.25): """ Prune the sequences based on LB_Kim and LB_Keogh lower bound. First the sequences are pruned using LB_Kim reduction factor and then u...
c2ed7e88f9597e9f27ed1902fca858a35e028ff3
3,610,248
def keyDataIdsInit(): """ Initializes the key data klasses. This function is called from the init function and the application should not call it directly. Returns : 0 on success or a negative value if an error occurs. """ return xmlsecmod.keyDataIdsInit()
a2f254c8b0655cea68f6a91092ac0b7697f99df2
3,610,249
import numpy def _image_to_ground_plane_perform(r_tgt_coa, r_dot_tgt_coa, arp_coa, varp_coa, gref, uZ): """ Parameters ---------- r_tgt_coa : numpy.ndarray r_dot_tgt_coa : numpy.ndarray arp_coa : numpy.ndarray varp_coa : numpy.ndarray gref : numpy.ndarray uZ : numpy.ndarray R...
d325471ce2f21562dfd38e536ce77eb215069349
3,610,251
def encode_string_text(text): """Replace special symbols with corresponding entities or magicwords.""" text = text.replace("<", "&lt;") text = text.replace(">", "&gt;") text = text.replace("[", "&#91;") text = text.replace("]", "&#93;") text = text.replace("{", "&#123;") text = text.replace(...
c7887934983efda3a0d1e06451ccd85cab529a30
3,610,252
def compute_input_planes(input_channels, merging_strategy, inputs, abs_nodes): """Compute the number of input planes.""" if len(inputs) == 0: # this is an input node return input_channels inplanes = 0 for i in inputs: if merging_strategy == EdgeMerge.CAT: inplanes += abs_nod...
a6f163a9891f77ba58e06905d3ed03fe9e7259eb
3,610,253
def test_01_setup(): """ sample init init attr, state, action space :return: """ names = ['gender', 'age'] vals = {'gender': ['M', 'F', 'U'], 'age': ['0-19', '20-29', '30-39', '40-49', '50-59', '60-69', '70-*']} attr_set = AttrSet(names, vals) state_set = StateSet(['date', '...
ce487a5287859ea1502aea0090df90f5a0769036
3,610,254
def make_aware(value, timezone=None): """ Make a naive datetime.datetime in a given time zone aware. :param value: datetime :param timezone: timezone :return: localized datetime in settings.TIMEZONE or timezone """ if timezone is None: timezone = TIMEZONE # Check that we won't...
8012d14a84bf44f14454f5bf02f4ec93d31668cf
3,610,255
from typing import Tuple def parse_reflections_array(array: np.array) -> Tuple: """ Helper method for parsing reflections without exporting to ".CSV" Parse an reflection array of GSASII defined as: index explanation 0,1,2 h,k,l (float) 3 (int) multiplicity 4 (float) d-space, Å 5 (floa...
a20e11499b6baba9c6c6631441cd457a88bac5b9
3,610,256
def get_dbconn(db_dsn): """Connects to the MongoDB server and returns a database handler.""" def _ensure_indexes(db): """ Ensures that an index exists on specified collections. Definitions: index_by_collection = { 'collection_name': [ ('field_name_1'...
f4b074547ce539865f17cee302feae0ca4bbd0d2
3,610,257
def _params_to_ints(qs): """Convert a (string) list of string ids to a list of integers""" return [int(str_id) for str_id in qs.split(',')]
7568eeb6cf28f1c8e696e2fab6e7a89dcbbc07fc
3,610,258
import typing import json def _prepare_hyperparams(free_hyperparams: typing.Sequence, hyperparameter_values: typing.Dict) -> typing.Tuple[typing.Sequence, typing.Set[str]]: """ Values in ``hyperparameter_values`` should be serialized as JSON, as obtained by JSON-serializing the output of hyper-parameter's...
90a42428d33c6931622258691d92e82642dfa49e
3,610,259
from typing import List def est_croissante2(l : List[float]) -> bool: """ ... cf. ci-dessus ... """ # Résultat b : bool = True # Indice courant i : int = 0 while (i < len(l) - 1) and b: b = l[i] < l[i + 1] i = i + 1 return b
74357fe91d42b3cb0d95e09346504b0701ab7164
3,610,260
def compose(f, g): """ Compose two filter f and g. :param f: Outer filter function. :type f: filter function. :param g: Inner filter function. :type g: filter function. :return: lambda x: f(g(x)) :rtype: filter function. """ def filter_fn(df): df = g(df) if len...
d90cda63eb365219ce5f454265036c7d977da216
3,610,261
def Device(device_name): """Returns the taurus device for the given device name It is a shortcut to:: import taurus.core.taurusmanager manager = taurus.core.taurusmanager.TaurusManager() factory = manager.getFactory() device = factory.getDevice(device_name) :param device_...
834baf071ab408e9150cc803a317f151554950cb
3,610,262
def load_data(self, name): """Load data given a data path. This is a low level method that will search through the various search paths until it's able to load a value. This is typically only needed to load *non* model files (such as _endpoints and _retry). If you need to load model files, you sho...
94e75787fa72b91ea5e27e8cd076b36037044962
3,610,263
def stop_list_to_link_list(stop_list): """ [a, b, c, d] -> [(a,b), (b,c), (c,d)] """ return list(zip(stop_list[:-1], stop_list[1:]))
49046e60664cd9c19ab55c1254684932d937531a
3,610,264
from typing import Union def compare(A: Mv, B: Mv) -> Union[Expr, int]: """ Determine if ``B = c*A`` where c is a scalar. If true return c otherwise return 0. """ if isinstance(A, Mv) and isinstance(B, Mv): Acoefs, Abases = metric.linear_expand(A.obj) Bcoefs, Bbases = metric.linea...
830dfaa97cf042278278b5c1aff8da77d5ee8f5a
3,610,265
def get_enum_size(*args): """get_enum_size(enum_t id) -> size_t""" return _idaapi.get_enum_size(*args)
58024506d567e6d07d420233a16c1bd1e2f7750e
3,610,266
def _martin_luther_king_holiday(year): """Martin Luther King's birthday (third Monday in January)""" if year < 1983: return None for day in range(15, 22): d = dt.date(year, 1, day) if d.weekday()==0: return d raise Exception('Should never get there')
06cfb37660a8b7034bad3cadc329bca84694acb6
3,610,267
def random_bivariate_anisotropic_Gaussian(kernel_size, sigma_x_range, sigma_y_range, rotation_range, noise_range=None, ...
add17263e4bc7c1b99bf55bf032e40cc093d7079
3,610,268
def validate_guess(number) -> str or None: """ :param number: the number to guess :return: the valid guessed number or None if user gives up """ number_size = len(number) while True: guess = easygui.enterbox(f"Please guess the {number_size}-digit number: ") if guess is None: ...
41cfc02f97f33365389bd27dcd42d65c31ccdb57
3,610,269
def excel_radiosonde(request, form): """ Reads the radiosonde form and converts the data into a excel file """ start = form.cleaned_data['start_date_radiosonde'] end = form.cleaned_data['end_date_radiosonde'] time = form.cleaned_data['time_radiosonde'] fields = form.cleaned_data['fields...
371736b8f6c0eb0b84a46bc4aa36060bf85b3db4
3,610,270
def compare_metrics(best_eval_result, current_eval_result): """Compares two evaluation results.""" return best_eval_result["exact_match"] < current_eval_result["exact_match"]
ce3880c2cc271d9c8c766a2dfbd95d31f5fb651c
3,610,271
import importlib def import_module(filename): """Import a module given a full path to the file.""" spec = importlib.util.spec_from_file_location("doc_filter", filename) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
924f19b96d98290dabfda1aef70cb7f67455f553
3,610,272
def set_target_bits(targs, sourcemask): """Apply bright source mask to targets, return desi_target array. Parameters ---------- targs : :class:`recarray` A recarray of targets as made by, e.g., :mod:`desitarget.cuts.select_targets`. sourcemask : :class:`recarray` A recarray containi...
156a45e5c79a02321a3de05081ec429f5a4c325d
3,610,273
def get_checksum_value(checksum): """ Return the checksum value. The given checksum might either be a standard ad32 or md5 string, or a dictionary with the format { checksum_type: value } as defined in the `FileSpec` class. This function extracts the checksum value from this dictionary (or immediate...
bc5a3a506a53970217a32fc0be79378e85787c18
3,610,274
def construct_bibfile_data(*paths): """ List of data corresponding to individual bib files :param pathlib.Path *paths: Path to file possibly containing BibTeX data. :rtype: list """ bibs = [reffile_factory(path) for path in paths] return bibs
7b0ddfd615e8cb54ce905d52a756e689824454a1
3,610,275
def check_shell_pipes(cmd): """ Determine whether a command appears to contain shell pipes. :param str cmd: Command to investigate. :return bool: Whether the command appears to contain shell pipes. """ return "|" in strip_braced_txt(cmd)
ad91661727e42fef6c95428b524c0178e23642ec
3,610,276
from typing import Dict import requests from bs4 import BeautifulSoup import re def scrap_allrecipes_recipe(url: str) -> Dict: """This function scraps a recipe of Allrecipes, given its URL, and prepare a JSON file to index in Elasticsearch. :param url: the URL of the recipe :return: the recipe as a J...
0c060ba40e784b7dad6ab2af40dd6f0aa4600173
3,610,277
def waitTargetUpdate(omni_robot, timeout): """ Wait for target updating :param omni_robot: (OmniRobot) :param timeout: (time to wait for updating) """ omni_robot.target_pos_changed = True time = 0.0 # second while time < timeout and not rospy.is_shutdown(): if not omni_robot.tar...
c9be8516640667a758ef1a3fc62b881fc4bedec3
3,610,278
def known_references(request): """ List all known references witht he option of removing the contact date """ user = request.user if 'remove_known_ref' in request.POST and \ request.POST['remove_known_ref'].isdigit(): try: application = CredentialApplication.objects.get( ...
e22424641306f0020006f233cfea2b169a4c17c6
3,610,279
def get_plugin(): """Return the filter.""" return IpynbFilter
991dead0a95e97526736e3cf06bd76138be46cf2
3,610,280
def __ensure_paragraphs(text): """ Checks if paragraph break in text else adds it and returns """ if "\n\n" in text: # Paragraph break detected just return it return text # If not detected add it ourselves new_text = "\n\n".join(__cut_text(text, length=500)) return new_text
5b79021021c4a89bc12901ac12c29257e16d3409
3,610,283
def main(path, task, representation): """ :param path: str specifying path to dataset. :param task: str specifying the task. Always e_iso_pi in the case of the human performance comparison :param representation: str specifying the molecular representation. One of ['fingerprints, 'fragments', 'fragprints...
732f96bc4697ce11f3665584799c608b8c0096ae
3,610,284
def region_of_interest(img, vertices): """ 区域选择 Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. """ # defining a blank mask to start with mask = np.zeros_like(img) # defining a 3 channel or 1 channel color to fill...
a0b3741b135a9a9c2356b6b63061ee784c0a6b98
3,610,286
def segformer_b5(pretrained=False, progress=True, num_classes=150): """Create a SegFormer-B5 model. Args: pretrained: Download backbone weights pretrained on ImageNet data if true. progress: Display the download progress of pretrained weights if true. num_classes: Number of output class...
39bc9c36fd26a49856848d8ba08076a0a9205334
3,610,287
def expand_codes(df=None, codes=None, cols=None, sep=None, codebook=None, hyphen=True, star=True, colon=True, regex=None, del_dot=False, case_sensitiv...
e2e6132cf94a6b19c9d6294c36ffc8fa412401a0
3,610,288
import math def compute_roce(fpr, preds, real): """ Calculate the ROC enrichment (ROCE) score - i.e., the y value divided by the x value on an ROC curve, at a fixed predetermined x value (i.e. a fixed false positive rate). Args: fpr (float): pre-set false positive rate preds (np.ar...
89190c89b4faa0d2025da578b06ba94906e7bfe8
3,610,289
def segmentPlaneIntersection(s0 = "const Dim<3>::Vector&", s1 = "const Dim<3>::Vector&", point = "const Dim<3>::Vector&", normal = "const Dim<3>::Vector&", tol = ("const double", "1.0e-8")): """Inters...
eb68974937de575702069565fc3ee34dfadf89cc
3,610,291
def get_host_data(root): """Traverses the xml tree and build lists of scan information and returns a list of lists. """ host_data = [] hosts = root.findall('host') for host in hosts: addr_info = [] # Ignore hosts that are not 'up' if not host.findall('status')[0].attrib[...
6f4967da12edd496df613b210083745c5c137578
3,610,293
import concurrent def with_progress_bar(target): """ Adapted from ipywidgets progress bar example :param target: Function to run. Function must take progress bar as argument. :return: None Try it out with:: a = [] def work(progress): total = 3 for i in ran...
0d814c035363c14cff98de798781129b42a2858a
3,610,294
def incident_beam(*, source_chopper: sc.Variable, sample_position: sc.Variable) -> sc.Variable: """ Compute the incident beam vector from the source chopper position vector, instead of the source_position vector. """ return sample_position - source_chopper.value['position'].data
2f6b5502e336ed02b4c733808bb446f5e0310689
3,610,295
import math def arrhenius (A: float, E: float, T: float, R: float = R) -> float: """ Args: A: Pre-exponential (frequency) factor. ValueError raised if not > 0. E: Activation energy. T: Temperature in Kelvins. ValueError raised if not >= 0. R: Universal g...
8f5d43bb659070fed34274db36fb9e5ec79343d1
3,610,296
def xoai_contributor(source, *args, **kwargs): """ CZ: EN: """ value = [] for person_role in source: role = person_role["@name"] field = person_role["element"]["field"] if isinstance(field, list): for person in field: value.append( ...
a17ab90aee1326c66cdc546b726666b86039cc3f
3,610,297
def http_endpoint( flask_entity, flask_rule, method: HttpMethod = HttpMethod.GET, returns_json_response: bool = True, ): """ Decorator factory used to easily register a Transiter HTTP endpoint. :param flask_entity: either the Flask app or a Flask blueprint :param flask_rule: the URL rel...
a33c4a24466ce8ebaa96e243714ae045ce1f22fa
3,610,298
from typing import Any from typing import List import torch def all_gather_cuda(data: Any) -> List[bytes]: """ Run all_gather on arbitrary picklable data (not necessarily tensors) Args: data: any picklable object Returns: list[data]: list of data gathered from each rank """ world_size = global_world_size() ...
763c64ee2f5efe129be1a292acb81461ba395bf5
3,610,299
def from_array(array, copy=True): """Convert a NumPy array to a tensor. Initializes a taco tensor from a NumPy array and copies the array by default. This always creates a dense tensor. Parameters ------------ array: numpy.array A NumPy array to convert to a taco tensor copy: boo...
189e5be32db3f411e0a649357a9f8a4e164093ac
3,610,300
def maybeName(obj): """ Returns an object's __name__ attribute or it's string representation. @param obj any object @return obj name or string representation """ try: return obj.__name__ except (AttributeError, ): return str(obj)
2b83918c49fc6cd19a027c1d2db07fcb0d57166a
3,610,301
def compare(attr_a, attr_b=0, operation=0): """Create math_Compare-node to get boolean of logical comparison between given attrs. Args: attr_a (NcNode or NcAttrs or string): Maya node attribute. attr_b (NcNode or NcAttrs or float): Maya node attribute. operation (NcNode or NcAttrs or in...
54d94c30984c52daf250e9bed83fba3d56844938
3,610,303
import inspect def gc_nc_60_79(mqc): """ Analogous to gc_nc_0_19. """ k = inspect.currentframe().f_code.co_name try: d = next(iter(mqc["multiqc_picard_gcbias"].values())) v = d["GC_NC_60_79"] v = np.round(v, DECIMALS) except KeyError: v = "NA" return k, v
cb3febae5450c3662e8ce91175b5e8ecc42f52b1
3,610,305
import math import random def generate_random_pose(): """ generate a random rod pose in the room with center at (0, 0), width 10 meters and depth 10 meters. The robot has 0.2 meters as radius Returns: random_pose """ def angleRange(x, y, room, L): """ Compute rod an...
81c26bbabb6b4386b4086b20a09fe8691add2fed
3,610,306
import logging def version_description(project_arn: str, version_name: str = None): """[Describes a Project on Rekognition in AWS] Args: project_arn (str): [Unique Identifier for a Project on Rekognition in AWS] version_name (str, optional): [Display Name]. Defaults to None. Raises: ...
3af2244c502a2599ad5c283b3e9147d785ef3a51
3,610,307
def feature_importance(residuals, analysis_type="collective", date_from=None, date_till=None, weigh=True): """Feature importance calculation Parameters ---------- residuals : pandas.DataFrame() analysis_type : str, "single"/"collective", "single" by default date_from : str in format 'yyyy-mm-...
45c66fa9ddae1b8e81e68c055de94a72a311c83f
3,610,308
def utest(a, b): """ MannWhitney U statistic scipy.stats.mannwhitneyu tests for a != b Use only when the number of observation in each sample is > 20 and yo have 2 independent samples of ranks. Mann-Whitney U is significant if the u-obtained is LESS THAN or equal to the critical value of U....
4628ef64e3a3aaf60dc88f750976b7f0147852bd
3,610,309
from typing import Callable from typing import Any import asyncio import time async def run_async(func: Callable[..., Any], *args, **kwargs) -> Any: """ Runs a callable on the database thread pool executor using the current thread's I/O loop instance. Usage: def blocking_task(arg1, arg2, ar...
69f7bf02daa77bff85baa34139c8771b20660f1e
3,610,310
def constant_schedule_with_warmup(epoch, warmup_epochs=0, lr_start=1e-4, lr_max=1e-3): """ Create a schedule with a constant learning rate preceded by a warmup period during which the learning rate increases linearly between {lr_start} and {lr_max}. """ if epoch < warmup_epochs: lr = (lr_max - ...
e780c3946f0207f94065c3ce8333896c3513f25a
3,610,311
def gen_lc(x,p0,struct,pmax=85.): """ From gen_lc.pro """ #p0 = m0i, m0v, m0b, period, phase shift, tbreak1, tbreak2 p = np.array(p0).copy() if len(p) < 11: # use the poly fits to fill in the pca1-pca4 coeffs c_need = 11 - len(p0) poly_fits = struct["POLY_FITS"][0] new_coeffs = [...
6a211bad9280dd2d78cc70ee95bd57e6c2d0439b
3,610,312
def create_embed(author, level, ascendency_name, class_name, main_skill: Skill, is_support): """ Create the basic embed we add information to :param author: of the parsed message - str :param level: of the build :param ascendency_name: to display :param class_name: to display if no ascendency ha...
4a116384d1507909addce61b51151c12f0d2a24b
3,610,313
def get_cluster_name(): """ Retrieves the current cluster name from the CLUSTERNAME environment variable This should probably be in conf.py, but it creates dependency issues with ZMQ :return: str cluster name """ return environ.get('CLUSTERNAME')
25ce09ffce1654c5d316ee06b70187ed7d4dd9c0
3,610,315
def ml_ssl(stft, sv, compression=0, eps=1e-8, norm=False, mask=None): """ Maximum likelihood SSL Arguments: stft: STFT transform result, M x T x F sv: steer vector in each directions, A x M x F norm: normalze STFT or not mask: TF-mask for source, T x F x (N) Return: ...
aef6117f45de1f64b15449ae872e9ddc96455578
3,610,316
def vonMisesStressUtilization(axial_stress, hoop_stress, shear_stress, gamma, sigma_y): """combine stress for von Mises""" # von mises stress a = ((axial_stress + hoop_stress)/2.0)**2 b = ((axial_stress - hoop_stress)/2.0)**2 c = shear_stress**2 von_mises = np.sqrt(a + 3.0*(b+c)) # stress ...
3b62b0c6e91eb6f244a70b60ab8b74fb712fac82
3,610,317
def bar_chart(data2): """ A bar chart, like the one above but with small custom alterations title and size """ Chart2 = alt.Chart(data2).mark_bar().encode( alt.X ('movies', title="My Favorite Movies"), alt.Y ('num_oscars', title="# of Academy Awards"), color='movies', )....
aca1fd668a529b82b9293d54f99fa662a8da72b4
3,610,319
def nSpecies(): """ Returns the total number of species in the model. """ return 62
b9e77841cb46bba4faa1fab3c1ea00875753aaf1
3,610,320
def plot_convergence(*args, **kwargs): """Plot one or several convergence traces. Parameters ---------- * `args[i]` [`OptimizeResult`, list of `OptimizeResult`, or tuple]: The result(s) for which to plot the convergence trace. - if `OptimizeResult`, then draw the corresponding single t...
81ad36bd5e1efeddee70e5899aed547a63909e7d
3,610,321
def server_player_id(player_id): """Serve player ID endpoint. This endpoint is used to indicate a buzzer has been triggered, or register a buzzer. Args: player_id: Player identifier. """ gameshow = flask.current_app gameshow.state_machine.process( state_machine.Events.TRIGG...
39220e2c66aeafbeb52d5176adcba8ead7faf91b
3,610,322
import math def crt(cong): """Use the Chinese Remainder THeorem to solve the given system of congruences, cong = [(mod1, rem1), (mod2, rem2), ...] where val = rem1 mod mod1 val = rem2 mod mod2 ... The val satisfying the congruences is returned. """ result = 0 nprod = math.prod([v[0...
1b63975b769c8d8cf9e5dcf65b102a6a03a7e3c5
3,610,323
import base64 def compose_message(body, subject, contacts): """ composes message using message text, subject, contacts and returns it encoded """ message = MIMEMultipart() message['subject'] = subject message['from'] = me message['to'] = contacts plaintext_body = html_to_text(...
77926afa9ac8d95f83b47a9d1a978008d2a5100d
3,610,324
def getFileList(dbid, fnr, printi=0, type='A'): """ Get list of Sdicfile objects from Predict file :param dbid: dbid of Predic file :param fnr: file number of Predic file :param printi: print file list if True :param type: select by file type ('A' is Adabas file) :returns: list of Sdicfile na...
09aba2798337b337981fcf8885e774b87ea00409
3,610,325
def insertWarnings(lines, badCommand): """Insert warnings after a command that is probably to be checked. The text is to be given as a list of lines. A command in this sense can be any text that is not to be followed by an asciiletter """ lineNumber = 0 while lineNumber < len(lines): ...
0b8dfb35f818cd74dea54846d9aca9abb9c42efe
3,610,326
def rho_p(rank_vector): """Compares each element in the vector to its corresponding value in the null distribution vector, using the probability mass function of the binomial distribution. Assigns a p-value to each element in the vector, creating the betaScore vector. Uses minimum betaScore as rho ...
ba35368b14c2ee0635ffd70e0a243b634698dda2
3,610,327
import copy def occupy_seats(data, seat_tolerance, only_adjacent): """ Occupies seats according to rules. :param data: seat map (2d array) :param seat_tolerance: number of discovered seats that can be occupied to still make the person occupy the seat :param only_adjacent: boolean, if True only check ...
ab86082b0e6c0b4f453c7af2e6dfe383ed6b3054
3,610,328
def get_orthogonal_grid_edges(pix_x, pix_y, scale_aspect=True): """calculate the bin edges of the slanted, orthogonal pixel grid to resample the pixel signals with np.histogramdd right after. Parameters ---------- pix_x, pix_y : 1D numpy arrays the list of x and y coordinates of the slanted...
11f79e53b021c8744f047f47fb4699c277a3f3ab
3,610,329
def rom(a, b,f, eps = 1e-8): """Approximate the definite integral of f from a to b by Romberg's method. eps is the desired accuracy.""" R = [[0.5 * (b - a) * (f(a) + f(b))]] # R[0][0] #print_row(R[0]) n = 1 while True: h = float(b-a)/2**n R.append((n+1)*[None]) # Add an empty r...
3dfd00652837b999187a30ace3c3143fa381cb2a
3,610,330