content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def make_word(parts, sub, i): """Replace a syllable in a list of words, and return the joined word.""" j = 0 for part in parts: for k in range(len(part)): if i == j: part[k] = sub return ' '.join(''.join(p for p in part) for part in parts) j +=...
869aa94f60b819b38ad7ddc315b65d862cf525e0
40,971
def calc_anchors_pillar_center(proposals, l=7, h=7, w=7, anchor_offset=[0.5, 0.5, 0.5]): """ calc the proposals' center location of each grid proposals: [bs, 6]: [xmin, xmax, ymin, ymax, zmin, zmax] return: anchors_pillars: [batch_size, l, h, w, 3] """ proposal_unstack = tf.unstack(pro...
bee9c4c64acd87bb28109ad379d8eb612154288e
40,972
def acq_max(ac, gp, y_max, bounds, random_state, n_warmup=10000, n_iter=10): """ A function to find the maximum of the acquisition function It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method. First by sampling `n_warmup` (1e5) points at random, and then running ...
5e0a4dc4f6c9ffa6fc102c360e8d1c7fb91de782
40,973
def number_negatives(seq): """Number of negative residues a protein sequence""" # Convert sequence to upper case seq = seq.upper() for aa in seq: if aa not in bootcamp_utils.aa.keys(): raise RuntimeError(aa + ' is not a valid amino acid.') # Count E's and D's, since these are t...
19bf9498732fb73914f892944fbf525397742dc0
40,974
def dcmread_scale(fn): """Transform from path of raw pixel data to scaled one and inversing (if the case)""" dcm = dcmread(fn) return dcm_scale(dcm)
7e76f5b9e8b0935d9859a42db917002ab45c80ea
40,975
import re def parse(lines): """ Parse a list of lines from nose output. :param lines: list of nose error output lines. :returns: nose output augmented with specially formatted lines adapted to this plugin errorformat which will populate Vim clist. """ results = [] lines = iter(li...
59f2a89fd16b4bfcaa020dfc6bccde62b1ea1511
40,976
import attr def attr_lt(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr_gt(attrname, 54) Only true if access_obj's attribute < the value given. """ return attr(accessing_obj, accessed_obj, *args, **{'compare':'lt'})
88903d0921e5d4efaa25561dbf93e12403896256
40,978
import locale import math def format_col(df, col_name, rounding=0, currency=False, percent=False): """Function to format numerical Pandas Dataframe columns (one at a time). WARNING: This function will convert the column to strings. Apply this function as the last step in your script. Output is the formatted ...
a049c3a5f0ce28c3ec54ad0988e2679d512c6135
40,979
def slice_signal(signal, window_size, stride=0.5): """ Return windows of the given signal by sweeping in stride fractions of window """ assert signal.ndim == 1, signal.ndim n_samples = signal.shape[0] offset = int(window_size * stride) slices = [] for beg_i, end_i in zip(range(0, n_s...
b99202008858cd610aaf4a7969a897e88a2ba5fa
40,980
def create_mysql_oursql(username, password, host, port, database, **kwargs): # pragma: no cover """ create an engine connected to a mysql database using oursql. """ return create_engine( _create_mysql_oursql(username, password, host, port, database), **kwargs )
d1fac26b36f4045fe1bfe797b2929b888867531e
40,981
def does_nothing(profile): """ evaluate if the profile is just doing nothing to the loss. this allows to save some memory and compulation time and memory during the calculation :param profile: np.array of fm_profile_dtype or fm_profile_step_dtype profile :return: boolean : True i...
cfd7db22cc206bce85d677f6d0e2186c7b65a0f0
40,983
def pis_pasep(formatting: bool=True, data_only: bool=True) -> str: """Gere o código do PIS/PASEP aleatório.""" r = fordev_request( content_length=26, referer='gerador_de_pis_pasep', payload={ 'acao': 'gerar_pis', 'pontuacao': 'S' if formatting else 'N' } ...
cb0d9944b00210e3f278b74e7858c601a01e8e82
40,984
def tab_clickable_evt() -> str: """Adds javascript code within HTML at the bottom that allows the interactivity with tabs. Returns ------- str javascript code in HTML to process interactive tabs """ return """ <script> function menu(evt, menu_name) { var i, tab...
bc15f819ef615200d09a356e250bc2d41710b36a
40,985
def urban_patches(built_up, transform): """Identify urban patches.""" built_up = binary_closing(built_up, iterations=int( 100 / transform.a), border_value=1) patch_geoms = [] for geom, value in shapes(built_up.astype('uint8'), connectivity=4, transform=transform): if value == 1: ...
41e1eca80a45a54d3f96db8f7b849e793d3307bc
40,986
def add_new_comp(mol, option=None, comp_id=None): """Function to add a new compound to the database given an RDKit molecule Takes an RDKit molecule. Option of LIG to return original smiles with the Compound object Returns a compound object for the RDKit molecule.""" # Neutralise and desalt compound the ...
10fec0a63daa328d31ab82cd315358c1371a3e9a
40,987
def get_resource_tokens(source, data_only=False, tokenize_variables=False): """Parses the given source to resource file tokens. Otherwise same as :func:`get_tokens` but the source is considered to be a resource file. This affects, for example, what settings are valid. """ lexer = Lexer(ResourceFile...
922d07a83310fb58d3be07d1de0e4065bace2409
40,988
from typing import Dict def aggregate_author_stance_preds(preds: np.ndarray) -> Dict[int, float]: """ describe what's going on """ max_pred_indices = np.argmax(preds, axis=1) max_pred_values = np.max(preds, axis=1) max_index_value_pairs = zip(max_pred_indices, max_pred_values) max_index_va...
37e1e7bc894ad3cc712047c1fed31266ebb80e51
40,989
def data_mnist(datadir='/tmp/', train_start=0, train_end=60000, test_start=0, test_end=10000): """ Load and preprocess MNIST dataset :param datadir: path to folder where data should be stored :param train_start: index of first training set example :param train_end: index of last train...
49924f5ecaefb7fcc122e178001cbf704c961741
40,992
def validate_input_config(config): """Validate that the input source is valid""" input_manifest_s3_uri = config.get("inputManifestS3Uri") chain_from_job_name = config.get("chainFromJobName") if input_manifest_s3_uri and not chain_from_job_name: return None if not input_manifest_s3_uri and ...
4a2788c421225b7c38ec9414285e38d3323ac1ab
40,993
def create_app(config=None, testing=False, cli=False): """Application factory, used to create application """ app = Flask('insta_pic') configure_app(app, testing) configure_extensions(app, cli) register_blueprints(app) @app.errorhandler(Exception) def error_handler(e): return j...
0ddf25cc0dbc0c9073e977bc5b1a2b4ed700614f
40,994
def get_cast_table(paths, player_data, blocklist): """ Create an aggregated CastTable from GamParse output file(s) :param paths: a list of paths to GamParse output :param player_data: a PlayerData object :param blocklist: a list of spells to be ignored :return: a CastTable object """ re...
b4e99b0231687982c5d62083f63be9d9cdd9440e
40,995
def polygon_area(polygon): """ Get the area of a polygon which is represented by a 2D array of points. Area is computed using the Shoelace Algorithm. Args: polygon: 2D array of points. """ x = polygon[:, 0] y = polygon[:, 1] area = (np.dot(x, np.roll(y, -1)) - np.dot...
90431d15f0a0cf57b7983daf2510f2c4493fb48d
40,996
def isValidAutoIp(ip): """Checks an IPv4 or IPv6 address where "auto" is a valid value""" if ip != "auto": try: isValidIpv4(ip) except TypeError: isValidIpv6(ip) return True
0385c5153fc333c03925ec3eb8e4a3269f3d3341
40,997
def addScaleBar(ax, *args, **kwargs): """ Utility function to add a scalebar to a plot. Args: ax (`matplotlib.axes.Axes`): axes object to which to add the scale bar *args: arguments passed on to `.ScaleBar` **kwargs: key-word arguments passed on to `.ScaleBar` Returns: ...
340d0eefe86081742e383f8e64e932974e06231e
40,998
def containsAny(seq, aset): """ Check whether sequence seq contains ANY of the items in aset. """ for c in seq: if c in aset: return True return False
a83040058110dc773da3e694418c4711f0e7dc61
40,999
def reverse_complement(string): """Returns the reverse complement strand for a given DNA sequence""" return(string[::-1].translate(str.maketrans('ATGC','TACG')))
bd033b9be51a92fdf111b6c63ef6441c91b638a3
41,000
def normal2color(normal, mask, dtype=np.uint8): """Conversion from 3D (x, y, z) surface normals to a color image representing surface normals. Args: normal (ndarray): Surface normals. The shape is H x W x 3. mask (ndarray): Mask with shape of H x W. The value must be 0 or 1. dtype (type...
4ffbdd036d26c9f2beca8abe88697c83a82b888f
41,001
def sample( rng: chex.PRNGKey, mean: chex.Array, C: chex.Array, sigma: float, popsize: int, ) -> chex.Array: """Jittable Gaussian Sample Helper.""" S = C + sigma ** 2 * jnp.eye(C.shape[0]) candidates = jax.random.multivariate_normal( rng, mean, S, (popsize,) ) # ~ N(m, S) - ...
fa99e09c357203b94ce5351ccba4fa1201109dfe
41,002
import tokenize def build_model(): """ build a MultiOutputClassifier model using GridSearch Input: None Output: cv_model (GridSearchCV): ML model """ pipeline = Pipeline([ ('features', FeatureUnion([ ('text_pipeline', Pipeline([ ('vect'...
70c596cc9d0ea1cd1048a3ccb6e128979c38bb0d
41,003
import copy def stackImages(_imgList, cols, scale): """ Stack Images together to display in a single window :param _imgList: list of images to stack :param cols: the num of img in a row :param scale: bigger~1+ ans smaller~1- :return: Stacked Image """ imgList = copy.deepcopy(_imgList) ...
5829ff5f43dea414c31a86e6c07a50aaf1b59e26
41,004
def ellipsoid_fit(X): """fits an arbitrary ellipsoid to a set of points """ x = X[:, 0] y = X[:, 1] z = X[:, 2] D = np.array([ x * x + y * y - 2 * z * z, x * x + z * z - 2 * y * y, 2 * x * y, 2 * x * z, 2 * y * z, 2 * x, 2 * y, 2 * z, 1 - 0 * x ]) d2 = np.array(x * x + y ...
bb335ef8cbec0fd8bf98f53ee13cdc8c9ab64157
41,005
def same_genes(dictionary, sample_ids): """ update main AnnData object for list of samples so all contain the same list of genes Parameters ---------- dictionary : dict dictionary containing AnnData objects sample_ids : list list of sample IDs to compare against one ano...
00391be20cdbd58a2d367fc11693949ef450fe22
41,006
from typing import Dict from typing import Any def async_engine_from_config( configuration: Dict[str, Any], prefix: str = "sqlalchemy.", **kwargs: Any ) -> AsyncEngine: """Create a new AsyncEngine instance using a configuration dictionary. This function is analogous to the :func:`_sa.engine_from_config` ...
4f2044c9035ea9570d210bea51f8fbac6694690f
41,007
def mity_qual(AO, DP, p=0.002): """ Compute variant quality :param AO: (int) number of alternative reads :param DP: (int) total read depth :param p: (float) noise parameter. default=0.002 :return: (float) phred-scaled quality score >>> [mity_qual(x,10) for x in [1,2,3,4,5,6,7,8,9,10]] '...
a154aa770fb9a876b291129fe817fa1b5867368e
41,008
def get_prompt_from_code(code_str): """Split ``code_str`` to a <prompt, completion> based on indents. Args: code_str (str): code str. Returns: <before, after> """ splits = list( split_before( code_str.splitlines(), lambda x: x and x[0].isspace(), max...
916c081a08a267a9fc6deb60d13374bc9a1bb04d
41,009
def mix_chroma(mixmap,chroma_list,illum_count): """ Mix illuminant chroma according to mixture map coefficient mixmap : (w,h,c) - c is the number of valid illuminant chroma_list : (3 (RGB), 3 (Illum_idx)) contains R,G,B value or 0,0,0 illum_count : contains valid illuminant nu...
245fc1c46dca89e14e27bd9ad6515e4863e9dc4c
41,010
def create_worker_dmatrix(*args, **kwargs): """ Creates a DMatrix object local to a given worker. Simply forwards arguments onto the standard DMatrix constructor, if one of the arguments is a dask dataframe, unpack the data frame to get the local components. All dask dataframe arguments must use th...
096c99a7d3e975a4857abf8b5234280fd871d5e7
41,011
def compute_melspec(y, params): """ Computes a mel-spectrogram and puts it at decibel scale Arguments: y {np array} -- signal params {AudioParams} -- Parameters to use for the spectrogram. Expected to have the attributes sr, n_mels, f_min, f_max Returns: np array -- Mel-spectrogr...
068c5e9ae445010d297a99b2836e13cf7088b609
41,012
def _parse_seq(seq): """Get a primary sequence and its length (without gaps)""" return seq, len(seq.replace('-', ''))
f02c6f316e3bc56d3d77b6ca6363aa1e0a6b4780
41,013
import urllib import json def get_pkg_json(pkg): """ recieve json from pypi.org """ url = url_template.format(pkg_name=pkg) u = urllib.request.urlopen(url) resp = json.loads(u.read().decode('utf-8')) return resp
7093f2476d00a695620869ef05db8ffd233018d1
41,014
from typing import Tuple def train_step(vae_apply, vae_params, opt_state: OptState, opt_update: UpdateFn, batch: Batch, random_key: RandomKey) -> Tuple[Params, OptState, Array]: """A single step of training for the VAE.""" def params_loss(...
73bf3302cbf170a33c584f109ee2a1b262508c4b
41,015
def schedule_conv3d_winograd_weight_transform(attrs, outs, target): """Schedule conv3d_winograd_weight_transform""" with target: return topi.generic.schedule_conv3d_winograd_weight_transform(outs)
77145d10a1e781b12e4bbdb8d6175385df9269c7
41,016
def i_(indxs_old, indxs, k): """ Returns indexes of elements that were not enlarged in new enlarged array. :param indxs_old: Indexes (in original 1D array) of elements that won't be substituted in new enlarged 1D array. :param indxs: Indexes of elements in original 1D array that ...
27af69a35b506cfde1892182a8ff149aa32b896e
41,017
def gsl_coerce_float(*args, **kwargs): """gsl_coerce_float(float x) -> float""" return _gslwrap.gsl_coerce_float(*args, **kwargs)
d67aa847d19bc29931bd6622a6da849ef05336df
41,018
def get_one_user(id): """ USERS GET ONE """ cursor = mysql.connection.cursor() cursor.execute("SELECT * FROM users WHERE id = %s", (id)) data = cursor.fetchall() cursor.close() print(data) data_res = {"id": data[0][0], "name": data[0][1], "teamId": data[0][2]} message = {"mes...
1768d4f4eaca488b9d1ac9e6d0e13ba4b7859beb
41,019
def get_phi(row): """Helper function for rotating data. row: 2D-entry in matrix with shape (?, 2) """ return np.arctan2(row[0], row[1])
89a8ea48eca99083a087d951211f1e8a1e4bcb65
41,020
def verifyProxy(ip, type): """ 验证代理的有效性 """ request_header = { 'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36" } url = "http://www.baidu.com" # 填写代理地址 proxy = {type: ip} # 创建proxyHandler proxy_ha...
5462d8cba61ac181c2dcf7ca9ab8c334dbdd0e43
41,022
def str_aula(value): # Only one argument. """Converts a string into all lowercase""" if(value == True): return "Sim" else: return "Nao"
f90dc7ab8e76ab254b6306131d2c3921453889e9
41,024
def unions_buffered(contig, buffer, lower_bound='start', upper_bound='stop'): """ Calculate interval unions among loci of a contig and extend them with a non-overlapping buffer. The new cluster intervals will contain only fields of the upper and lower bounds of clusters which may be named with the ...
8319075508147904a5a85c5b96bdd2bea836e469
41,025
def coll_exc_xsec(eng, species=None): """ e-e collisional excitation cross section in cm\ :sup:`2`\ . See 0906.1197. Parameters ---------- eng : float or ndarray Abscissa of *kinetic* energies. species : {'HI', 'HeI', 'HeII'} Species of interest. Returns ------- f...
65c6fb83ccab3c43b64b69a977eff18575f7b54d
41,026
def mirror_tree(root: TreeNode): """ Offer 27 二叉树的镜像 :param root: :return: """ if not root: return [] nodes = [root] while nodes: node = nodes.pop(0) node.left, node.right = node.right, node.left if node.left: nodes.append(node.left) i...
07b1c0d32c212b3d886665847c2b164a2b967501
41,027
def reverse_digit(x): """ Reverses the digits of an integer. Parameters ---------- x : int Digit to be reversed. Returns ------- rev_x : int `x` with it's digits reversed. """ # Initialisations if x < 0: neg = True else: neg ...
d7358f5778897262b8d57c6dd3e2eb4acb05a2d1
41,028
def yyyymmdd(d, separator=''): """ :param d: datetime instance separator: string :return: string: yyyymmdd """ month = d.month if month < 10: month = '0' + str(month) else: month = str(month) day = d.day if day < 10: day = '0' + str(day) else: ...
a5b765ea9b740ac26b03fd16def62c7d84389e8e
41,029
def recurrent_layers( value, layer_sizes, bidirectional=True, dropout=0.0, rnn_type="lstm", return_sequences=False): """ Make one or more RNN layers """ if rnn_type == "lstm": rnn_class = LSTM elif rnn_type == "gru": rnn_class = GRU ...
3eb0adf75e3dd9089c4ba1cb4f3049ce430c0c60
41,030
def _applicable_weight_based_methods(weight, qs): """Return weight based shipping methods that are applicable for the total weight.""" qs = qs.weight_based() min_weight_matched = Q(minimum_order_weight__lte=weight) | Q( minimum_order_weight__isnull=True ) max_weight_matched = Q(maximum_order...
3fbe44950e6738995f865b3cba97967344219b22
41,032
import json import time def index_phenomenon(es, index_l, type_l, phenomenon = None, threshold=0): """ Indexes a phenomenon of a file. Returns the id that the phenomenon will have in the database. """ if phenomenon is None: return pid = None pid = abs(hash(str(phenomenon))) ph...
321a82c247ecc7c98aab0904b71aebbcdf3471d7
41,033
def _imwread(imgName): """ Reads a *.imw file. imgName should come with no extension. """ w, h = _readDim(imgName + '.dim') return _readImage(imgName + '.imw', w, h, '>H', 2)
05b5b11e935262f10e8be30d25eb8b6ec7639290
41,035
import requests def train(**kwargs): """ Train network https://docs.deep-hybrid-datacloud.eu/projects/deepaas/en/latest/user/v2-api.html#deepaas.model.v2.base.BaseModel.train :param kwargs: :return: """ message = { "status": "ok", "training": [], } # ...
d01e0b5ee5dc623ae11180ede6bff9dec7c95ef8
41,036
import ray def sync_ensemble(workers: WorkerSet) -> None: """Syncs dynamics ensemble weights from driver (main) to workers. Args: workers (WorkerSet): Set of workers, including driver (main). """ def get_ensemble_weights(worker): policy_map = worker.policy_map policies = poli...
bac6b306ff890f1b002389806a112ad7000cd75f
41,037
def last_days_quotations(request): """Return last days quotations of a currency. Keyword arguments: request -- parameters [ days, currency ] """ args = request.GET days = int(args.get('days', None)) currency = args.get('currency', None) quotations = Quotation() quotations_list = qu...
e57e8e10ec1c70a82b37798e58b53c910fec42b7
41,038
from operator import add def cksum(buf): """Return computed CRC-32c checksum.""" return done(add(0xffffffff, buf))
f3c9d110d6f364e669e5d15c718a3497c470df74
41,039
import torch def yuv420_to_rgb(image_y: Tensor, image_uv: Tensor) -> Tensor: """Convert an YUV420 image to RGB. Image data is assumed to be in the range of [0.0, 1.0] for luma and [-0.5, 0.5] for chroma. Input need to be padded to be evenly divisible by 2 horizontal and vertical. This function assumed...
c3d53d721ae905eac9cdf1021b2096d22dfc19d8
41,040
import csv def read_sensor_types_file(csv_file: str) -> []: """ Read in a csv file :param csv_file: path to file :type: csv_file: str :return: sensor_types :rtype: dict """ sensor_types = {} with open(csv_file, mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) ...
8d3897de83de18a5d1188d3564af55747ace1277
41,041
def ping(value=0): """Return given value + 1, must be an integer.""" return {'value': value + 1}
487902e19decd04f2d1b7a75da6a9ca6bb2714d7
41,042
import math import random def Lf(lo, hi): """Log-uniform distributed floatint point number.""" return math.exp(random.uniform(math.log(lo), math.log(hi)))
3eb756c65f20ca60f62ef87187476452f30168c7
41,043
def test_default_args(): """ Verify that default arguments are properly passed to the isolated function call. """ def isolated_function(arg1='default1', arg2='default2', arg3='default3'): return arg1, arg2, arg3 # Sanity check assert isolated_function.__defaults__ == ('default1', 'defau...
208293af69b957ce7cefc9b11e159ccf9dfc520f
41,044
def partition_data(array, partition_size=500, seed=None): """Partition the into multiple groups with given size It will partition the data with same schema if seed is consistent for each partitioning Args: array (array) partition_size(int): size of each partition group, default=500 ...
2b1ee3eb37c6a8d393d4b5b0c99fe144f1075f9d
41,045
def add_character(story, name='"Merquivest Monogarymbalid"', role="stranger"): """ Adds a new character to the story with the given name and role. Returns the id Predicate for the added character. """ character = next_id_prs(story, "chr", 1)[0] story.add(character) story.add( intrinsic_pr(story, character...
d8a3aa13e29e85748df58829a28516fb3fb4ac6d
41,046
def resize_image_and_boxes(image, boxes, new_size): """ Resizes image and boxes. :param image: Image to resize. :param boxes: Boxes to resize. :param new_size: New size of the image. :return: Resized image and boxes. """ resized_image = image.resize(new_size) scale = np.zeros(2) sca...
d1bb68cb60a077f0ae2d9b0963657256e9285158
41,047
def _standard_frame_length(header): """Calculates the length of a standard ciphertext frame, given a complete header. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :rtype: int """ frame_length = 4 # Sequence Number frame_length += h...
2e455e536de649ed3e4c9faa7b31ab3abafe19a1
41,048
def f(x): """ Quadratic function. It's easy to see the minimum value of the function is 5 when is x=0. """ return x**2 + 5
7469225fd7d864c96ca957caa51bec924a81d599
41,049
import numbers def coerce_retention_period(value): """ Coerce a retention period to a Python value. :param value: A string containing the text 'always', a number or an expression that can be evaluated to a number. :returns: A number or the string 'always'. :raises: :exc:`~except...
a7a53f84b037a7d48898573a0268aab1eecb0790
41,050
def daily_log_return(close, fillna=False): """Daily Log Return (DLR) https://stackoverflow.com/questions/31287552/logarithmic-returns-in-pandas-dataframe Args: close(pandas.Series): dataset 'Close' column. fillna(bool): if True, fill nan values. Returns: pandas.Series: New fea...
1745ffd47133821ca99beeb907758682cc10ca37
41,051
import logging def find_links_fast(communities_grouped, max_parent_combinations, offsets, min_forward_containment=0, min_backward_containment=0, reverse_mappings=None): """find_links_fast Under development. """ n_largest_combos = 0 edge_list = [] for i, communities in en...
b0cff4f97b2a014fe2c8062e5a1de14e9fe4b1e8
41,052
def read(path): """Return dict-like object of config parameters from file path.""" return ConfigObj(path, unrepr=True)
e85b5d260bb9789acd8c2da118152b5e2bf3775e
41,053
from typing import Dict import ast def builds_file(file: str, do_clean: bool = False) -> Dict[str, PyssectGraph]: """Takes a python file and returns the corresponding PyssectGraph""" with open(file, 'r') as f: return ASTtoCFG().build(ast.parse(f.read()), do_clean)
67c05dd46370e5b73d980e32fec5665c236aca78
41,054
def dropLabels(events, minPct=.05): """ # apply weights, drop labels with insufficient examples """ while True: df0 = events['bin'].value_counts(normalize=True) if df0.min() > minPct or df0.shape[0] < 3: break print('dropped label: ', df0.argmin(), df0.min()) ...
cbfc6de91be685d6e5309a490c455badd7596093
41,055
def get_partitions(raw_data_id): """ 获取rt_id对应的kafka topic的partition数量 @:param rt_id: result_table表的id :return: kafka上rt_id对应的topic的分区数量 """ rawdata = model_manager.get_raw_data_by_id(raw_data_id) if rawdata: kafka_bs = _get_rawdata_kafka_bootstrap_server(rawdata) if kafka_bs...
b8fec4945a973340ef600fb4441623ad7a624894
41,056
def latest(history_secs=600, max_data_points=200): """ Retrieve latest data, with sampling to indicated number of data points NOTE: all speedtests are always returned """ return { 'ip_local': ip.local(), 'speedtest': DATA['speedtest'], ** { k: _sample_buffer(...
32de7247bdefa1b0528437e70f393cc8cdebca45
41,057
def calc_chi2_stats(df_popl, df_cust, attributes, alpha=0.05, exclude_na=True, use_perc=True): """ Calculates the chi-sq stays for the attribute to compare the similarities between population and customer ref: https://machinelearningmastery.com/chi-squared-test-for-machine-learning/ :params df_popl:...
80a335f1ca45d1529c4b0ebbb2719b8afcca2d07
41,059
def hammingDistance(str1, str2): """ Returns the number of `i`th characters in `str1` that don't match the `i`th character in `str2`. Args --- `str1 : string` The first string `str2 : string` The second string Returns --- `differences : int` The differences between `str1` and `str2` ...
ad35cc79f89171c75a16a13ec6862a2a4abdbd61
41,060
def prepare_data(df, n_cell_x, n_cell_y): """ Feature engineering and computation of the grid. """ # Creating the grid size_x = 10. / n_cell_x size_y = 10. / n_cell_y eps = 0.00001 xs = np.where(df.x.values < eps, 0, df.x.values - eps) ys = np.where(df.y.values < eps, 0, df.y.values ...
f55fd655920daee8deaa8d85dceb6b8922542478
41,061
def powerstat_ucsc(sg, wanted_servers): """ Get the power status of the UCS Central servers. """ try: handle = UCSCUtil.ucsc_login(sg) except KubamError as e: return jsonify({"error": str(e)}), Const.HTTP_UNAUTHORIZED try: powerstat = UCSCServer.list_servers(handle) ...
4c6f78e2deaa722c0d84e1cc8d9b9178c32ff232
41,062
import logging def _from_pretrained(cls, *args, **kw): """Load a transformers model in TF2, with fallback to PyTorch weights.""" try: return cls.from_pretrained(*args, **kw) except OSError as e: logging.warning("Caught OSError loading model: %s", e) logging.warning( "Re-trying to convert fro...
4459aba28e7e30ca63cb328aba84487af6bbe8a7
41,063
def get_frame_durations(file): """ Return an array of each frame duration in the given file. Durations are in milliseconds. """ pos = file.tell() frame_durations = [] last_frame_timestamp = None def collect_timestamps(frame, timestamp): timestamp = round(timestamp*1000) ...
12f22fc489289e7d601699c0b469c8d79cecc86a
41,064
def pedirOpcion(): """Pide y devuelve un entero en el rango de opciones validas""" correcto = False num = 0 while not correcto: try: num = int(input("Elige una opcion -> ")) if num < 0 or num > 3: raise ValueError correcto = True excep...
a758254110e0d39fc8b1b4cab91b95799311fdcf
41,065
import tqdm import glob import json def extract_preprocessing_json(root: str): """ :param root: :return: """ vols_xymin, vols_ccords = dict(), dict() for path in tqdm(sorted(glob(root))): volume_name = "_".join(path[:-5].split("/")[-2:]) with open(path, 'rb') as file: ...
f5335ffd78ebc8f6f45bfac26cdb2510440ccb5d
41,067
def slugurl(context, slug): """Returns the URL for the page that has the given slug.""" page = Page.objects.filter(slug=slug).first() if page: return pageurl(context, page) else: return None
b0ddf5347e1aa8a5342d4563d431950e87473b57
41,068
from typing import OrderedDict def _order_dict(d): """Convert dict to sorted OrderedDict""" if isinstance(d, dict): d = [(k, v) for k, v in d.items()] d = sorted(d, key=lambda x: x[0]) return OrderedDict(d) elif isinstance(d, OrderedDict): return d else: raise E...
94b3e9e0c5b34e466c913c46683c752ca9560a12
41,069
def _sampling_probabilities(indices): """ Compute marginal sampling probabilities for each training point so that the classes will be balanced. """ N, k = indices.shape probs = np.zeros(N) for i in range(k): not_missing = indices[:,i] != -1 probs[not_missing] += 1./(np.s...
9568c0661443bfb7c3b46478042b9062750fa6f7
41,070
def plot_proj_error(traj_top, traj_left, X, Y, Z, cam_top, cam_left, time, savedir='data_treat/Reproj_error.png', plot=True): """Plot the reprojected trajectory for each camera to check for the trajectory errors :param traj_top,traj_left: screen trajectory for the top and left cameras :param X,Y,Z:...
4ae6e4f2a758878fe58cfbb4009d7610eee0c77a
41,071
def temp_monthly(): """Returns temperature obs from the database""" session = Session(bind=engine) year_ago = dt.date(my_date.year, my_date.month, my_date.day) - dt.timedelta(days=365) # In the function (logic should be the same from the starter_climate_analysis.ipynb notebook): # Calculate the date 1 y...
5b3c18b4ab9913856e4009362e88c4f4ec497936
41,072
def get_comment_app(): """ Get the comment app (i.e. "commentary") as defined in the settings """ # Make sure the app's in INSTALLED_APPS comments_app = _get_setting('APP', DEFAULT_COMMENTS_APP) if not apps.is_installed(comments_app): raise ImproperlyConfigured( 'The COMMENTS...
b023de39ed1eafc3b13f8ed2cca2ba1652776a83
41,073
def get_report_types(): """Get the types of reports that are available :rtype: list """ return [{"type": key, "name": val["name"]} for key, val in REPORTS.items()]
a0857b35bb79ac3cdcb7da1ca7e85fc646c64a06
41,074
def read_fasta(fasta_file): """ read a fasta file and retrieve its sequences """ sequences = AlignIO.read(fasta_file, "fasta") return sequences
605907eba45d32c9b734428e71726e4166bfa72e
41,075
def display_get_rule_name(): """display function to prompt for the name of the rule to add""" return input("Name of the rule to add: ")
e6df6b4df7aecb289d56d65c35de78eb1a8ab591
41,076
def _get_stack_status(stack_name, region): """ Returns the stack status which will be one of: 'CREATE_IN_PROGRESS' 'CREATE_FAILED' 'CREATE_COMPLETE' 'ROLLBACK_IN_PROGRESS' 'ROLLBACK_FAILED' 'ROLLBACK_COMPLETE' 'DELETE_IN_PROGRESS' 'DELETE_FAILED' ...
7256d34570eada00ce4838d84957d6a974aa1b62
41,077
def parse_varint(stream): """ Parses SQLite's "varint" (short for variable-length integer) as mentioned here: https://www.sqlite.org/fileformat2.html#varint """ usable_bytes = read_usable_bytes(stream) value = 0 for index, usable_byte in enumerate(usable_bytes): # For all bytes except ...
c2349149fca0d362a3e29beea26a2d34cbfa891b
41,079
from pathlib import Path def _latest_input() -> Path: """Since the exports are complete exports, can just use the most recent export""" return last(sorted(get_files(config.export_path), key=lambda p: p.stat().st_mtime))
1b714d549eec243971d6fb358670b7f9844b13b5
41,080
from typing import Callable def jacobian(func: Callable, delta: float): """Finite differences approximation to the Jacobian.""" def jacfn(z): num_dims = len(z) Jac = np.zeros((num_dims, num_dims)) for j in range(num_dims): pert = np.zeros(num_dims) pert[j] = 0.5...
1b29c5d7845197e577f017f9fb0407b5cae26338
41,081