content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import OrderedDict def make_info(params, htext): """ Make a custom special argument: Whether to display recipe information :param params: ParamDict, Parameter Dictionary of constants :type params: ParamDict :return: an ordered dictionary with argument parameters :rtype: OrderedDi...
f40528817d17bdbb9921df11c70f21074eb71258
3,601,499
import warnings def _root_amplitude_brentq(counts, bkg, model, root_fn=_f_cash_root): """Fit amplitude by finding roots using Brent algorithm. See Appendix A Stewart (2009). Parameters ---------- counts : `~numpy.ndarray` Slice of count map. bkg : `~numpy.ndarray` Slice of ba...
dad242e3d17bca0bacb3a98bd8cc79ee3e7c4ed6
3,601,500
def get_valid_keypoint_mask_for_class(keypoint_coordinates, class_id, class_onehot, class_weights=None, keypoint_indices=None): """Mask keypoints by their class ids a...
b50008ce56a7885a2ae2ff188cd3ef6bb7166fa0
3,601,501
def identify_target_ligand(ligand_residues): """Attempts to guess the target ligand""" # If there is only one target ligand then that must be the target # even if there are multiple instances. That could be the case if # the compound is peptidic for example. if len(ligand_residues) == 1: ret...
50e3559b2f42aa1a60ca5270279cc2a37325f3cb
3,601,502
def cue_favourite(speaker, action, args, soco_function, use_local_speaker_list): """Shortcut to mute, play favourite, stop favourite, and unmute. Preserve the mute state """ if not speaker.is_coordinator: error_report("Action '{}' can only be applied to a coordinator".format(action)) ret...
793568f70783bde890ac331244902b768c3561ad
3,601,503
def vocab_marking_definition(instance): """Ensure that the `definition_type` property of `marking-definition` objects is one of the values in the STIX 2.0 specification. """ if (instance['type'] == 'marking-definition' and 'definition_type' in instance and not instance['definitio...
68beab22bee4d76255e8acacaf7f4fe469bc6882
3,601,504
def _header_path(header_file, module_map_file, workspace_relative): """Returns the path to a header file to be written in the module map. Args: header_file: A `File` representing the header whose path should be returned. module_map_file: A `File` representing the module map being wr...
1339e5dbbecd8773fcbe4e760cae8037c553186e
3,601,505
import requests def pega_conselho(assunto=False): """ A função acessa a API e retorna um conselho Args: assunto (bool, optional): Se tiver uma palavra como argumento será retornado um conselho que tenha o assunto relacionado com o argumento passado. Por defaults o argumento é ...
1b1c26c6b13fd287c0ec66412cc9372fadf38f45
3,601,506
def Recherche(tree, word): """Recherche le mot word dans l'arbre tree et indique s'il est dans l'arbre.""" return tree.contains(word)
f17d4024b0e5e7542fec0a502f853fdb63a21c95
3,601,507
def cov(x: to.Tensor, data_along_rows: bool = False): """ Compute the covariance matrix given data. .. note:: Only real valued matrices are supported :param x: matrix containing multiple observations of multiple variables :param data_along_rows: if `True` the variables are stacked along th...
3a848ebf8d97dfdfcbf77c025846b240c33b38cc
3,601,508
def blrPredict(W, data): """ blrObjFunction predicts the label of data given the data and parameter W of Logistic Regression Input: W: the matrix of weight of size (D + 1) x 10. Each column is the weight vector of a Logistic Regression classifier. X: the data matrix...
220f1951157aec1d37b2bff7dccd9ff2dfbeb4d7
3,601,509
def preprocess_input(frames, augment=True): """Preprocesses raw frames and optionally performs data augmentation.""" preprocessing_ranges = { preprocess_sequence.IMAGE_TO_FLOAT: (), preprocess_sequence.RESIZE: { 'new_size': [CONFIG.IMAGE_SIZE, CONFIG.IMAGE_SIZE], }, preprocess_seq...
021c22924e4ff3883d6000f23fd2880fe410b438
3,601,511
import torch def draw_parabolic_binary_spline(x0, y0, x1, y1, x2, y2, imsize=224, width=1, tstep=0.01): """Non-differentiable way to draw a spline with no fuzz :param x0: int, x coordinate of point 0 :param y0: int, y coordinate of point 0 :param x1: int, x coordinat...
b3dc1ee1223b0ecea96e94f1b39655fea485c412
3,601,512
def get_reader_extensions(): """ Returns a list of extensions for which readers are available. :return: the list of extensions :rtype: list """ result = list(get_flow_readers().keys()) result.sort() return result
99351c22b098b771389de80863b117907c0bd257
3,601,513
def to_feature_vector(img): """ Converts the given image to a feature vector containing -1s (white pixels) and 1s (black pixels). """ return np.array([1 if p == 0 else -1 for p in list(img.getdata())])
bd3d58af1e62e77148d8f8abfe5db4f4e7aabb09
3,601,514
def safe_value(name, value): """ Only show up to logger_settings['reveal_sensitive_prefix'] characters from a sensitive header. :param name: Header name :param value: Header value :return: Safe header value """ if name.lower() in LOGGER_SENSITIVE_HEADERS: prefix_length = logger_...
b34a98d1bd161ae1f20b2028212ad6a8e8176f6f
3,601,515
from pathlib import Path async def dep_version_id( version_id: str = Path(..., title="Version ID", **EntityID.META) ) -> str: """Validate and return a version id specified in an endpoint path.""" return version_id
00c73a068ad8988d394a9bcf78c61395d6fdd98e
3,601,516
import http def movedTo(request, url, encoding): """ Permanently redirect C{request} to C{url}. @param request: The L{twisted.web.server.Reqeuest} to redirect. @param url: The new URL to which to redirect the request. @type url: L{bytes} @param encoding: The encoding of the response as a by...
037d6ac418ec097242244461a2bb6f7835ac71f5
3,601,517
def fix_IE_for_attach(request, response): """ This function will prevent Django from serving a Content-Disposition header while expecting the browser to cache it (only when the browser is IE). This leads to IE not allowing the client to download. """ useragent = request.META.get('HTTP_USER_AGENT...
b8fd12ba12a2f7df918a3e0fa7c64094c0bd016d
3,601,518
async def stocks(request: Request, ticker, period="1d", interval="1d"): """ Get ticker finance information :param request: :param ticker: :param period: 1d, 5d , 7d, 1mo :param interval: 1m, 2m, 5m, 15m, 30m, 60m, 1d, 5d, 1wk, 1mo :return: result """ logger.info(F"NewApiRequest: /st...
dbf7b6147a451355970691cc69e415e6eb1bfa1d
3,601,520
def Mean_Reciprocal_Rank(RGB): """. RGB: Relevance scores (list or numpy) - first element is the first rank """ Non_Zeros = (np.asarray(RGB).nonzero()[0]) if Non_Zeros.size == 0: return 0. else: return 1. / (Non_Zeros[0] + 1)
7576b0ac2561c3eb1265ed3ed286b2ec86ead6af
3,601,521
import struct def UnpackInt(inp_stream, bitlen, huff): """ Reads an int from an input BitBucket and returns it. 'bitlen' is between 1 and 32 (inclusive), and represents the number of bits to be read and interpreted as the int. 'huff' is unused. """ raw_in_stream = inp_stream.GetBits(bitlen)[0] rshif...
d77e25085720519d880f009390af59f7844e9f54
3,601,522
def to_dict(arr): """ Convert a list to a dict with keys drawn from '0', '1', '2', ... Examples -------- >>> to_dict([2, 3, 4]) # doctest: +SKIP {'0': 2, '1': 3, '2': 4} """ return dict(zip(map(str, range(len(arr))), arr))
a51c0cbb477b4569a67fda3088a200194bb8bf67
3,601,523
def downsample2(img, f): """ Downsample image by a factor of 2 Filter with Gaussian filter then take every other row/column Args: img: image to downsample f: 2d filter kernel Returns: downsampled image as (H, W) np.array """ # # You code here # img_filtered =...
1532293f53fcebd79f97cdbe8afc311334424a9f
3,601,524
def is_power_of_two(a): """Return whether the argument, cast to int, is a power of 2.""" a = int(a) # Bit manipulations. A power of 2 has a bit represetenation like 0...010...0. # For such a number subtracting 1 from it turns it into 0...001...1, so ANDing # a-1 and a should yield 0. return a > 0 and ((a - ...
d7b0d90df8eb4287a6f56e8256aa6c40b9b46441
3,601,525
import collections def possible_parameter(nb, jsonable_parameter=True, end_cell_index=None): """ Find the possible parameters from a jupyter notebook (python3 only). The possible parameters are obtained by parsing the abstract syntax tree of the python code generated from the jupyter notebook. F...
f655b4cc24db37052c95194393a27cf61193f581
3,601,526
from typing import Callable from functools import reduce def clean(text: str, *cleaners: Callable[[str], str]) -> str: """Cleans the given text using the provided cleaning functions. Arguments: text: The text string to be cleaned. cleaners: The simple cleaner functions...
67a53637bca0b19b49bd157ccc520d8dc053a12f
3,601,527
import itertools def _stitch(sequences, th=1): """ trying to connect two different sequences """ if len(sequences) <= 1: return sequences if th == 0: return [sum(sequences, [])] for i, j in itertools.combinations(range(len(sequences)), r=2): s1, s2 = sequences[i], sequences[j...
bc7131c8415532b85f981974aa0e0abf4c4a060b
3,601,528
def process_parallel(binary, input_file, procs, logger): """ Performs parallel apbs runs of the input file """ logger.message("Splitting the input file into %d separate files using the inputgen utility\n\n" % procs) # Get the base name, and split the input file using inputgen's split_input bas...
4072b495dcde3c04c0c02ef41a7313f27b1fad3d
3,601,529
def strip_parens(text): """ strips parenthesis from a string (works with nested parentheses) note that this method will leave the extra spaces behind, but this will not affect tokenization :param text: original string :return: text stripped of parenthetical words """ left_parens = [] ...
1976636150bc6705e39ab3929e1214f0b0c09644
3,601,530
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer): """Convert a set of `InputExample`s to a list of `InputFeatures`.""" features = [] for (ex_index, example) in enumerate(examples): if ex_index % 10000 == 0: print("Writing...
8a59723ec1cc82a03096616bc79e968e1f5a1fe3
3,601,531
import nltk def easy_convert_sentence_to_values(sentence_array, input_size): """ --------------------------------------------------------------------- DESCRIPTION Converts the array of sentences to an array of word value arrays. If necessary, they might be padded. -----------------------------...
f743f923fedb4434e208ac2971004fc062dd8fad
3,601,532
def get_table_delete_stmt(cls): """Returns SQL DROP table statement for the given cls class using specified Column fields""" table_name = get_table_name(cls) exec_stmt = [f"DROP TABLE {table_name}"] return ''.join(exec_stmt)
1509e873d1f98ea165333a13ff4b7048415d56be
3,601,534
def get_sensor_parameters(sensor, set="adjustable"): """ Get a set of the CSM parameters for a CSM sensor Parameters ---------- sensor : CSM sensor The CSM sensor model set : str The CSM parameter set to get. Either valid, adjustable, or non_adjustable Returns --...
2c0f7c59c620a3a482013a0570bc5e083fc25315
3,601,535
def adaptive_avg_pool1d(input, output_size): """Applies a 1D adaptive average pooling over an input signal composed of several input planes. See :mod:`oneflow.nn.AdaptiveAvgPool1d` Args: input: input tensor output_size: the target output size (single integer) """ return AdaptiveAvg...
dbc15c7e55d31cff416c9e60cf947f3406a196f9
3,601,536
import numpy def less_equal(self, other): """ Equivalent to the <= operator. """ return _PropOpB(self, other, numpy.less_equal, numpy.uint8)
5e2c7192c81ea5142c6bbe67106f925d8e69d9cf
3,601,537
def variable_name_to_title( variable_name, latex_flag=True ): """ Translates a variable name into a title suitable for inclusion in Matplotlib title strings. Variable names are assumed to be lowercased as found in IWP datasets and titles may include LaTeX markers for mathematical typesetting. Unkno...
3f9d56a13f4aacb2ec6e9cf15ad1d2ff1c4288bc
3,601,538
import json def workerById(): """ Accède à un ouvrier par son identifiant Args: request.form doit contenir : - num : l'identifiant de l'ouvrier en BDD Returns: code 1, data : data contient l'ouvrier si on le trouve code -1, message : erreur lors de...
f0a38572f384a3194857ea242b93b000527b7428
3,601,539
def survival_cross_validation(row, phenotype_df, duration_col = 'T', event_col = 'E', other_cols = []): """ duration_col: survival time event_col: whether an event (death or other) has ocured or not. 0 for no, 1 for yes other_cols: other variables to consider in the regression """ phenotype_df =...
cd7664c5d091c770f0cab7d1952d03b048b8fb81
3,601,540
def scrub(value, scrub_text=_keep_whitespace, scrub_number=_scrub_number): """ REMOVE/REPLACE VALUES THAT CAN NOT BE JSON-IZED """ return _scrub(value, set(), [], scrub_text=scrub_text, scrub_number=scrub_number)
d72bbbd1bbfa3a75f3ccd2e3ee023874b82ecad8
3,601,541
def GetToolchainTupleForBoard(board, buildroot=constants.SOURCE_ROOT): """Gets a tuple for the default and non-default toolchains for a board. Args: board: board name in question (e.g. 'daisy'). buildroot: path to buildroot. Returns: The tuples of toolchain targets ordered default, non-default for t...
ae2fb39b7d2ef00375f07af777cdd697dece5ecb
3,601,542
def show_rule_by_num(table_name, chain_name, rule_num): """ Handler for rule request URL :param table_name: Name of table to look in :param chain_name: Name of chain to look in :param rule_num: Index of rule to return :returns: Flask Response with rule in JSON format """ if table_na...
750ac4e9428d6925a0b604a8dbb569641d105326
3,601,544
import random def welzl_circle(point_set): """ Creer le cercle minimum de l'ensemble de point passé en paramètre en utilisant l'algorithme de welzl params : - point_set = L'ensemble de points à évaluer return -> Circle = Le cercle minimum de l'ensemble de points """ # On transforme ...
3284906bf30f3a4d1ce68a6bff6f4c10343d3d7c
3,601,545
def parse_paragraphs(m, desc): """Parse Markdown-formatted paragraphs into a list of HTML paragraphs.""" def strip(s): start = s.find('>') + 1 end = len(s) - s[::-1].find('<') - 1 return s[start:end] return [strip(parse_markdown(s)) for s in m.splitlines()]
3c22b6505dc22a596d1ff8ab724a90681375d55a
3,601,546
import logging def get_filewriters(basename, subset, num_shards): """Opens and returns list of tfrecord writers.""" fh = [] logging.info('Opening %s.%s.*.tfrecord for writing.', basename, subset) for i in range(num_shards): fh.append(tf.python_io.TFRecordWriter( basename + '.%s.%s.tfrecord' % (sub...
5fc9d53a5f726876ab7a550d79009fd99571b105
3,601,548
def mean_dice(results, gt_seg_maps, num_classes, ignore_index, nan_to_num=None, label_map=dict(), reduce_zero_label=False): """Calculate Mean Dice (mDice) Args: results (list[ndarray]): List of prediction segmentation ma...
0fdcb2b5d65d03b51992aa18320d2529950c3809
3,601,550
def fix_filter_query(filter): """ fix filter query from user Args: filter: filter from users Returns: dict """ if filter: try: filter = { _.split("=")[0]: _.split("=")[1] for _ in list( set( str(filt...
11dce2c8471205118277bb396ec298de7fb7bf67
3,601,551
def index(): """ Home page :return: """ _jobs_collections = mongo.db.jobs # get the jobs collections from mongo db _users_collections = mongo.db.users # get the users collections from mongo db # coming post from user page ========================= ...
a7354bf96250aeac1fb3ec423300a5de988efca2
3,601,552
def rectangle_area(length, width): """ Calculates the area of a rectangle. :param length: The length of the rectangle. :param width: The width of the rectangle. :return: The area of the rectangle. """ return length * width
0cbe453fbd4c3c6a061f520d57f303dae55fdc25
3,601,553
def linear_assignment(cost_matrix, thresh): """ Hungarian algorithm: pair new detections with previous tracklets return matches: [idx of tracked_stracks, idx of detections] u_track: [index of undefined track] u_detection: [index of undefined detection] """ if cost_mat...
4bfea019ff033e2433a765c1295662b2340f0642
3,601,554
def inspect_bursts(xc_r, starts, ends, ang_velocities, min_dist_between_start_end=50): """ An entire time series should only have as many starts as it has ang_velocities Args: xc_r (array): cross correlation between signal and rect starts (array): list of segment start locations ...
bbb2bd82740ef80f5028cf24d1b2c5226b621443
3,601,556
def has_level_five(line): """Check if we need to explode""" count = 0 for c in line: if c == '[': count += 1 if count > 4: return True elif c == ']': count -= 1 return False
6d2e9d4aed708a9d71a9f01f90519f804e1fd3d9
3,601,557
def cal_merit_lda(spectra: np.ndarray, wavenumbers: np.ndarray, replicate: np.ndarray, label: np.ndarray): """ Benchmark of replicate EMSC correction based on LDA classification :param spectra: ndarray of shape [n_samples, n_channels] :param wavenumb...
22dbd195952dbce25dc2f3f10a13b10d716d48f2
3,601,558
def combinecrinfo(crinfo1, crinfo2): """ Combine two crinfos. First used is crinfo1, second used is crinfo2. """ crinfo1 = fix_crinfo(crinfo1) crinfo2 = fix_crinfo(crinfo2) crinfo = [ [crinfo1[0][0] + crinfo2[0][0], crinfo1[0][0] + crinfo2[0][1]], [crinfo1[1][0] + crinfo2[1][0],...
e4066909c446d7c0de8d88959eb8880fef9f928c
3,601,560
def threshold_array(arr, threshold=2e-4): """ Thresholds an array, returning a binary array Parameters --------- arr : NumpyArray Contains the data to threshold Returns --------- NumpyArray Returns arr with binary values, depending of the threshold """ return (ar...
254692de4f82dbf6c3e684b10324cb73c436ff28
3,601,561
def df_large(): """Create a large random dataframe for testing.""" # Sample the discrete sets of values (just so they are not np.arange). N = 1000 n_date = 100 n_name = 100 n_country = 100 n_team = 100 n_z = 4 DATE_set = np.random.choice(N, n_date, replace=False) NAME_set = np.ra...
1322b7fcfe54670fcb876727264cd1dc47522914
3,601,563
def get_canonical_tag(): """ Uses the Config object's CANONICAL_TAG attribute to get a tag object; that tag object is the blog's canonical tag. """ canonical_tag_record = app.config['MDB'].tags.find_one( {'name': app.config['CANONICAL_TAG_NAME']} ) if canonical_tag_record is None: ...
8f4d8697fb3f1b1f602335e4947367924abfd2e8
3,601,565
import functools def python_wrapper(func): """Epsagon's general python wrapper.""" @functools.wraps(func) def _python_wrapper(*args, **kwargs): epsagon.trace.tracer.prepare() return wrap_python_function(func, args, kwargs) return _python_wrapper
edf19d6b94be85b339a0e06cdd79b0333259b149
3,601,566
def snip1d_quad(y, w=4, numiter=2): """Return SNIP-estimated baseline-background for given spectrum y. Adds a quadratic kernel convolution in parallel with the linear kernel.""" convolve1d = ndimage.convolve1d kernels = [] for p in range(w, 1, -2): N = p * 2 + 1 # linear kernel ...
884d82614c7bca6f01dce9e6d559e3ca708819b1
3,601,567
def LONG_LINE(data): """ Long Line Candle :param pd.DataFrame data: pandas DataFrame with open, high, low, close data :return pd.Series: with indicator data calculation results """ fn = Function('CDLLONGLINE') return fn(data)
b7a7494f7fdf27acebbb943524156d5079b2a2e8
3,601,568
def __binary_search(arr, f, g): """ Perform the binary search in order to find the minimum feasible value of ``c`` inside ``arr``. :param arr: The array on which to perform the binary search. :param f: Function to be applied to ``g`` and ``arr[mid]`` (``check_th7`` or ``feas``). :param g: A Network...
415528fd46a33d1efe8d736717ac8b041d34c5d7
3,601,569
from typing import List from typing import Union def keypress_prompt(accept: List[Union[str, int]]) -> Union[str, int]: """Infinitely waits until an acceptable key is pressed Parameters: accept (list): a list with allowed keys Returns: result (str, int): The pressed key """ while...
8b7990515d896f7107cf7b41dc3b37dec3c3eda0
3,601,570
def get_onpolicy_dataset(load_dir, env_name, tabular_obs, max_trajectory_length, alpha, seed): """Get on-policy dataset.""" tf_env, tf_policy = env_policies.get_env_and_policy( load_dir, env_name, alpha, env_seed=seed, tabular_obs=tabular_obs) dataset = tf_agents_onpolicy_dataset.T...
89fab13cab99231f611f9191f98e949da1e9abda
3,601,571
import re from bs4 import BeautifulSoup import requests def sourceforge(url: str) -> str: """ SourceForge direct links generator """ try: link = re.findall(r"\bhttps?://.*sourceforge\.net\S+", url)[0] except IndexError: reply = "`No SourceForge links found`\n" return reply file...
1a8b1795b286b8e85194d99de1ba8368dce00ebd
3,601,572
def get_accounts(account_id): """ Retrieve a single Account This endpoint will return an Account based on it's id """ app.logger.info("Request for Account with id: %s", account_id) account = Account.find(account_id) if not account: abort(status.HTTP_404_NOT_FOUND, f"Account with id ...
a6e6209d31881d018409acc75701faa5566616f9
3,601,573
def summarize_tree(tree): """Summarize a pytree.""" def _describe(x): if (hasattr(x, "shape") and x.shape and not isinstance(x, jax.core.Tracer)): flat = np.asarray(x).reshape([-1]) if flat.shape[0] == 0: return f"{np.dtype(x.dtype).name}{x.shape}" info = f"{np.dtype(x.dtype).name}{x....
ec44481ea97db6a7673027b15aee85e0073ff7c9
3,601,574
def stratified_sample(df, N=1000, return_indices=False): """ Build a stratified sample from a dataset. Maps NAs in partially labeled records to -1. :df: DataFrame containing file paths (in a "filepath" column) and labels in other columns :N: number of samples :return_indices: whethe...
42d622e4df15771c403c4f3bf4aa197b15b51265
3,601,575
def slot_tokenize(tokenizer): """Tokenization and aligning labels for slot tagging task""" def tokenize(examples): # remove punct symbol in utterance, since the tokenizer not consider punct as the sub word examples["utterances"] = [ remove_punct(text) for text in examples["utteranc...
17355312679f20119219144c2bee51405add3d7a
3,601,576
from typing import Sequence import copy def createAnnulusMesh3d(nodes, mesh, nextNodeIdentifier, nextElementIdentifier, startPointsx, startPointsd1, startPointsd2, startPointsd3, startNodeId, startDerivativesMap, endPointsx, endPointsd1, endPointsd2, endPointsd3, endNod...
ca86728e6782d495a849cf5f82d63ce7e42089ba
3,601,577
def create_role(keystone, name): """ Creates an OpenStack role :param keystone: the keystone client :param name: the role name :return: a SNAPS-OO Role domain object """ role = keystone.roles.create(name) logger.info('Created role with name - %s', role.name) return Role(name=role.nam...
7388d6db89aa018ff9efff2bb9ae4f47cf2243cf
3,601,578
import random def owo_convertor(text): """ Its your OwO Convertor """ # replacing 'L', 'i', 'R' and 'r' with 'W' and 'w' respectively text = text.replace('L', 'W').replace('l', 'w') text = text.replace('R', 'W').replace('r', 'w') # deal with ending text = end(text, '!', '! {}'.format(random.choice(e...
3b873b4c061e193318c6de1e847e3c0a08c0a674
3,601,579
def _current_window_for_event(event): """ Return the `Window` for the currently focussed Buffer. """ return event.app.layout.current_window
4b9859c7bf7fc4b072362d2d5b9e896022769587
3,601,580
import re def clean_xml(xml): """Clean the given XML string of namespace definition, namespace prefixes and syntactical but otherwise meaningless differences. Parameters ---------- xml : str String representation of XML document. Returns ------- str String representat...
3f566975ab512ccc22824c45e7ef04fc861a5c03
3,601,582
def preproc_data(df, NA_fill=None, add_tags=False, tag_meta=None, verbose=False): """ * NA_fill = float, 'mean' or 'median' * If add_tags==True, must provide tag_meta """ df_out = df.copy() # add feature tags if add_tags: df_out = gen_tag_features(df_out, tag_meta,...
0d5be319d5811ea2760766f55321d03407f06574
3,601,583
def purestr(x): """ A string that follows obj = type(obj)(*obj.args) exactly """ if not isinstance(x, Basic): return str(x) if type(x) in slotClasses: args = [getattr(x, slot) for slot in x.__slots__] elif type(x) in sort_classes: args = sorted(x.args, key=default_sort_key) e...
0fa0fd1f8774ef9151c06cdc89c4e88f260b0e48
3,601,584
from textwrap import dedent def compareDocReplacer(doc): """Make replacements for comparison docstrings.""" if not doc: return "" doc = dedent(doc) for magic, replace in COMPARE_DOC_MAPPING.items(): lookF = '{' + magic + '}' if lookF in doc: doc = doc.replace(lookF,...
6f75ccf9e79168df18869c93d4b2e7060410ac0a
3,601,585
import torch def _make_orthogonal(A): """ Assume that A is a tall matrix. Compute the Q factor s.t. A = QR (A may be complex) and diag(R) is real and non-negative """ X, tau = torch.geqrf(A) Q = torch.linalg.householder_product(X, tau) # The diagonal of X is the diagonal of R (which is always ...
ad2cfaa0c041062c8628bc02faedcfdbc550f4bb
3,601,586
def prepare_train_test_data(): """ Read csv file, convert it to machine learning representation, split features and labels, and split into training and testing data. """ # Reaed data from csv file data = pd.read_csv(f'{config.data_directory}/{config.data_filename}') # Split into ...
9999a62c9299ba3af8753a3e84ee9d7d82a3b5ed
3,601,587
from traceback import extract_stack from rootpy import _ROOTPY_SOURCE_PATH def rp_module_level_in_stack(): """ Returns true if we're during a rootpy import """ modlevel_files = [filename for filename, _, func, _ in extract_stack() if func == "<module>"] return any(path.start...
02e67bbbdc8ae087a132596405cc11807a489cca
3,601,588
def run_unthrottled(task): """ Determines whether a task needs to run unthrottled. Tasks that don't specify a target throughput are only considered as unthrottled if no explicit schedule or one of the built-in schedules is specified. Custom schedules might need more flexible approaches (e.g. because the...
b7523e623f4f5109aec4f75827d7f13be376722a
3,601,590
def login_required(f): """Decorate routes to require login. http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/""" @wraps(f) def decorated_function(*args, **kwargs): if session.get("user_id") is None: return redirect("/login") return f(*args, **kwargs) return decorat...
fb7c095e1bdd30e19483dae0d620274960d608ee
3,601,592
def reduce_mem_usage(df: pd.DataFrame, verbose: bool = True) -> pd.DataFrame: """ Function to reduce memory usage of numerical columns. Args: df (pd.DataFrame): Dataframe to reduce memory usage. verbose (bool, optional): If show how the memory usage decreased or not. Defaults to True. ...
bbe1938258cee169d77577f993f18a7a7028445f
3,601,593
def do_stats(covering, covered, maxD, bin_width=1, fignum=1, num_panels=4, s_frac=0.5, nhd_size_thresh=None, nhd_max_plot_size=None, minD=None, D_estimate_method="absolute", weight_by_size=False, force_xaxis_limits=False, radius_yaxis_limits=None, save=''...
a09085b65fdd4be6ca976d8aa34b0e15861c1849
3,601,594
def getVersion(includeSubrelease=False): """Returns wxWidgets version as a tuple: (major,minor,release).""" wxVersion = None major = None minor = None release = None subrelease = None if wxVersion == None: f = open(VERSION_FILE, 'rt') lines = f.readlines() f.close() ...
2db9bd7a13d65325ba3bcbf1fe9ad9e1e319cb90
3,601,595
def join(name, args, arg_separator=None): """ Returns name( argument_1, argument_2, ..., argument_n ). """ return __THE_PARSER.join(name, args, arg_separator)
ef5a7cfbeba59defa3b2569402ec2ceef63ab938
3,601,596
from typing import Tuple def masked_accuracy_fn( targets: jnp.ndarray, preds: jnp.ndarray, mask_values: Tuple[int, ...] = (),) -> MeanMetric: """Computes accuracy after discounting masked values. Args: targets: Target values of shape [batch_size, ...] in range [0, num_classes). preds: Unnorma...
be8f8e8897c312454f0a7f778feef4f6a86c393b
3,601,597
def plot(Si_df, ax=None): """Create bar chart of results. Parameters ---------- * Si_df: pd.DataFrame, of sensitivity results Returns ---------- * ax : matplotlib axes object Examples ---------- >>> from SALib.plotting.bar import plot as barplot >>> from SALib.test_functio...
c82c493a8655281fd8e841ad079a0af9869059c1
3,601,598
def build_model(config): """ """ if config["task"] == "enc_dec": model = build_enc_dec_model(config) elif config["task"] == "lm": model = build_lm_model(config) elif config["task"] == "classify": model = build_classify_model(config) elif config["task"] == "bi_lm": ...
6837e8577f91b9607c6f45510da7031474a38b94
3,601,599
def weighted_average(gini_or_entropy_left, left_cnt, gini__or_entropy_right, right_cnt): """ calculate weighted average for Gini index or Entropy :param right_cnt: count of total records on the right side of node :param left_cnt: count of total records on left side of node :param gini_or_entropy_le...
7914a0164427de4e9cebf7637dda670694f8df59
3,601,600
import torch def concat_entities(entities): """ Concat multiple graphs via concatenation of their entities tensors. Parameters ---------- entities: a list of graph tuples. Either [(v,e,c),...] or [(v,e),...] when the graph has no global attribute. Returns v,e,c - concatenated entities...
06d0619836d4cb8c977028ee0cdccd9075136c72
3,601,601
def format_filesize(num, suffix='B'): """ See: https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size """ for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) ...
2647aad4f4e09d9253b34b4ec39f601a3a558717
3,601,602
def filter_out_installed_pkgs(event_out_pkgs, installed_pkgs): """Do not install those packages that are already installed.""" return {p for p in event_out_pkgs if (p.name, p.modulestream) not in installed_pkgs}
16fb8f68372fb070869a744b15ddce0ed6591887
3,601,603
def maxlinedev(x, y): """ Find the point of maximum deviation in the contour from a line joining two points on the contour. Input: x, numpy array of abscissas of the contour y, numpy array of ordinates of the contour Output: maxdev, maximum deviation idxmaxdev, index of the ...
37f666f17aa56a7c50dc7a55d7be567d179c8a27
3,601,605
def vcs_org_url(orgname=None): """ Returns VCS endpoint for orgs in general or the specified org """ url = VCS_URL_BASE + "/orgs" if orgname == None: return url return url + "/" + orgname
38be1c95082bbf0d61ed9039edd01043b2a99703
3,601,606
def stats_variance_2d(data, ddof=0, axis=1): """Pre compiled method to get 2d variance.""" a_a, b_b = data.shape if axis == 1: var = np.zeros(a_a) for i in range(a_a): var[i] = _stats_variance_1d_2d(data[i], ddof=ddof) return var else: var = np.zeros(b_b) ...
acca95077d43ae63f88fda26d4320cfbaa628b8f
3,601,607
def root(): """Root.""" return redirect(url_for('sender.create'))
d08d4a328d4832a7b48f75db761b2e49332e4efc
3,601,608
def add_roi_Xconv1fc_head(model, blob_in, dim_in, spatial_scale): """Add a X conv + 1fc head, as a reference if not using GroupNorm""" hidden_dim = cfg.FAST_RCNN.CONV_HEAD_DIM roi_size = cfg.FAST_RCNN.ROI_XFORM_RESOLUTION roi_feat = model.RoIFeatureTransform( blob_in, 'roi_feat', ...
560a391a189c4415da18ab01e3670ca1eb6b69f7
3,601,609
def ensure_str(s, encoding='utf-8', errors='strict'): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeErr...
9f92e636351332f5cb84677fe7555186b21779f9
3,601,610
def query_database(database, username, password, hostname, query, port=3306): """ Input: database, username, passward, hostname: str Output: pd.Dataframe with display all columns """ conn = pymysql.connect(db=database, user=username, password=password, host=hostname, port=port) cur = conn.curs...
ba602979e4d6a1addb2cfc0be44ce9ab23e62549
3,601,611
def exposed_dbus_prop(name): """Exposed a property on DBus and cache locally""" local_key = '__%s' % (name,) def _getter(self, name): return self.__dict__[local_key] def _setter(self, name, value): self.__dict__[local_key] = value self.props_iface.Set( self.DBUS_NAM...
6458decc814d9a5c055a409c13ae46501f59c7cd
3,601,614