content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import types import functools def copy_func(f): """Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard).""" g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__) g = functools.up...
d661876d8568c5f33ae07682c874edd8d71dd7c9
3,641,673
from typing import List def augment(img_list: list, hflip: bool = True, rot: bool = True) -> List[np.ndarray]: """ Augments the image inorder to add robustness to the model @param img_list: The List of images @param hflip: If True, add horizontal flip @param rot: If True, add 90 degrees rotation ...
3d953ba2c9ce869ec612644d9a5370690c930e22
3,641,674
def _neurovault_collections(parts, query): """Mocks the Neurovault API behind the `/api/collections/` path. parts: the parts of the URL path after "collections" ie [], ["<somecollectionid>"], or ["<somecollectionid>", "images"] query: the parsed query string, e.g. {"offset": "15", "limit": "5"} ...
5ee1e6b9b59fb12e76c38c20cde65c18c3fd201a
3,641,675
def display_states(): """ Display the states""" storage_states = storage.all(State) return render_template('7-states_list.html', states=storage_states)
b9dc5c739546fee0abce077df1bba38587062f1a
3,641,676
def recompress_folder(folders, path, extension): """Recompress folder""" dest = runez.SYS_INFO.platform_id.composed_basename("cpython", path.name, extension=extension) dest = folders.dist / dest runez.compress(path, dest, logger=print) return dest
5cadc1a0b32509630cd3fa5af9fd758899e4bf94
3,641,677
import pathlib def guessMimetype(filename): """Return the mime-type for `filename`.""" path = pathlib.Path(filename) if not isinstance(filename, pathlib.Path) else filename with path.open("rb") as signature: # Since filetype only reads 262 of file many mp3s starting with null bytes will not find...
84f6b2f80b341f330e3f6b9e65b4863d055f8796
3,641,678
def filter_ptr_checks(props): """This function will filter out extra pointer checks. Our support to primitives and overflow pointer checks is unstable and can result in lots of spurious failures. By default, we filter them out. """ def not_extra_check(prop): return extract_property_...
e5964637c3f1a27521f5305673c9e5af3189e15d
3,641,680
import time def makeKeylistObj(keylist_fname, includePrivate=False): """Return a new unsigned keylist object for the keys described in 'mirror_fname'. """ keys = [] def Key(obj): keys.append(obj) preload = {'Key': Key} r = readConfigFile(keylist_fname, (), (), preload) klist = [] ...
13e79fbb9ac8ad207cc2533532c6be6bb0372beb
3,641,681
def getwpinfo(id,wps): """Help function to create description of WP inputs.""" try: wpmin = max([w for w in wps if 'loose' in w.lower()],key=lambda x: len(x)) # get loose WP with most 'V's wpmax = max([w for w in wps if 'tight' in w.lower()],key=lambda x: len(x)) # get tight WP with most 'V's info = f"...
0dcf6c205a1988227e23a77e169a9114f1fdf2cc
3,641,682
def build_word_dg(target_word, model, depth, model_vocab=None, boost_counter=None, topn=5): """ Accept a target_word and builds a directed graph based on the results returned by model.similar_by_word. Weights are initialized to 1. Starts from the target_word and gets similarity results for it's children ...
ffd32cef2b44fd9e9cd554cd618091dfe8e5377f
3,641,683
def sample_normal_gamma(mu, lmbd, alpha, beta): """ https://en.wikipedia.org/wiki/Normal-gamma_distribution """ tau = np.random.gamma(alpha, beta) mu = np.random.normal(mu, 1.0 / np.sqrt(lmbd * tau)) return mu, tau
0f11ce95cfb772aeb023b61300bdb03d827cab37
3,641,685
def _dice(terms): """ Returns the elements of iterable *terms* in tuples of every possible length and range, without changing the order. This is useful when parsing a list of undelimited terms, which may span multiple tokens. For example: >>> _dice(["a", "b", "c"]) [('a', 'b', 'c'), ('a', 'b'),...
bb8f567d82405864c0bf81b2ee9f3cb89b875d11
3,641,687
from datetime import datetime def parse_date(val, format): """ Attempts to parse the given string date according to the provided format, raising InvalidDateError in case of problems. @param str val (e.g. 2014-08-12) @param str format (e.g. %Y-%m-%d) @return datetime.date """ try: ...
4686bf46d12310ee7ac4aa1986df55b598909a06
3,641,688
def get_capture_dimensions(capture): """Get the dimensions of a capture""" width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) return width, height
9a13253c1ca5c44b7a1ef4440989b1af9abcb776
3,641,689
def ad_modify_user_pwd_by_mail(user_mail_addr, old_password, new_password): """ 通过mail修改某个用户的密码 :param user_mail_addr: :return: """ conn = __ad_connect() user_dn = ad_get_user_dn_by_mail(user_mail_addr) result = conn.extend.microsoft.modify_password(user="%s" % user_dn, new_password="%s"...
7cc5c654517ad3f175e06500310f0bbfec516ad1
3,641,692
def markup_record(record_text, record_nr, modifiers, targets, output_dict): """ Takes current Patient record, applies context algorithm, and appends result to output_dict """ # Is used to collect multiple sentence markups. So records can be complete context = pyConText.ConTextDocument() # Split...
2eee4560a411bcd7ef364b6ed9b37cc2870cd3b5
3,641,693
import inspect def get_file_name(file_name): """ Returns a Testsuite name """ testsuite_stack = next(iter(list(filter(lambda x: file_name in x.filename.lower(), inspect.stack()))), None) if testsuite_stack: if '/' in testsuite_stack.filename: split_character = '/' els...
97172600d785339501f5e58e8aca6581a0a690e0
3,641,694
import torch def track_edge_matrix_by_spt(batch_track_bbox, batch_track_frames, history_window_size=50): """ :param batch_track_bbox: B, M, T, 4 (x, y, w, h) :return: """ B, M, T, _ = batch_track_bbox.size() batch_track_xy = batch_track_bbox[:, :, :, :2] batch_track_wh = batch_track_bbox[:...
5303f401d925c26a1c18546ba371a2119a41ec3d
3,641,695
def _file(space, fname, flags=0, w_ctx=None): """ file - Reads entire file into an array 'FILE_USE_INCLUDE_PATH': 1, 'FILE_IGNORE_NEW_LINES': 2, 'FILE_SKIP_EMPTY_LINES': 4, 'FILE_NO_DEFAULT_CONTEXT': 16, """ if not is_in_basedir(space, 'file', fname): space.ec.warn("...
d8a04244c90f3f730c297a8dbaa1372acd61993b
3,641,696
def prepare_features(tx_nan, degree, mean_nan=None, mean=None, std=None): """Clean and prepare for learning. Mean imputing, missing value indicator, standardize.""" # Get column means, if necessary if mean_nan is None: mean_nan = np.nanmean(tx_nan,axis=0) # Replace NaNs tx_val = np.where(np.isnan(...
2f9fd73cd04b40a85556573a62a083a0ffaa725c
3,641,697
def _write_matt2(model, name, mids, nmaterials, op2, op2_ascii, endian): """writes the MATT2""" #Record - MATT2(803,8,102) #Word Name Type Description #1 MID I Material identification number #2 TID(15) I TABLEMi entry identification numbers #17 UNDEF None key = (803, 8, 102) nfields = 17...
607b94a6c1e3daf4b482acbb1df1ce967f1bce3b
3,641,698
def all_subclasses(cls): """Returns all known (imported) subclasses of a class.""" return cls.__subclasses__() + [g for s in cls.__subclasses__() for g in all_subclasses(s)]
8b9a2ecd654b997b5001820d6b85e442af9cee3b
3,641,699
def _find_popular_codon(aa): """ This function returns popular codon from a 4+ fold degenerative codon. :param aa: dictionary containing amino acid information. :return: """ codons = [c[:2] for c in aa["codons"]] counts = [] for i in range(len(codons)): pc = codons[i] cou...
a555a9d42ea4dfa0260d9d4d2040de3c6fca69a0
3,641,700
import pathlib def initialize_cluster_details(scale_version, cluster_name, username, password, scale_profile_path, scale_replica_config): """ Initialize cluster details. :args: scale_version (string), cluster_name (string), username (str...
5508733e0bfbd20fb76ecaaf0df7f41675b0c5c8
3,641,701
def load(data_home=None): """Load RWC-Genre dataset Args: data_home (str): Local path where the dataset is stored. If `None`, looks for the data in the default directory, `~/mir_datasets` Returns: (dict): {`track_id`: track data} """ if data_home is None: data_...
61d09f64ec7f36bc1dac6bfc6bea8e47fe82248b
3,641,702
import copy def collate_spectra_by_source(source_list, tolerance, unit=u.arcsec): """Given a list of spec1d files from PypeIt, group the spectra within the files by their source object. The grouping is done by comparing the position of each spectra (using either pixel or RA/DEC) using a given tolerance. ...
a82b470685ee53f3fe2de5e41a3f212e32a4d606
3,641,703
def tolist(obj): """ Convert given `obj` to list. If `obj` is not a list, return `[obj]`, else return `obj` itself. """ if not isinstance(obj, list): return [obj] return obj
f511f4ebb86977b2db8646e692abc9840c2ae2d1
3,641,704
def bip44_tree(config: dict, cls=hierarchy.Node) -> hierarchy.Node: """ Return the root node of a BIP44-compatible partially ordered hierarchy. https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki The `config` parameter is a dictionary of the following form: - the keys of the dictionary a...
bd88895932b66963aa7f63f30ad49ac009ea41f1
3,641,705
def delete_useless_vrrp_subnets(client, to_delete, project_id): """ :param 'Client' client :param dict((prefix_length, type, master_region, slave_region), (state:quantity)) to_delete :rtype: list """ result = [] vrrp_subnets = client.vrrp.list(project_id=project_id) for k...
b16019b026c32d310f9f938a7ca1fada31d02d84
3,641,706
import torch import warnings def barycenter_wbc(P, K, logweights, Kb=None, c=None, debiased=False, maxiter=1000, tol=1e-4): """Compute the Wasserstein divergence barycenter between histograms. """ n_hists, width, _ = P.shape if Kb is None: b = torch.ones_like(P)[None, :] ...
453c40ed988d4fe86dc202f816c5eb3bb6cbd452
3,641,707
def logistic_predict(weights, data): """ Compute the probabilities predicted by the logistic classifier. Note: N is the number of examples and M is the number of features per example. Inputs: weights: (M+1) x 1 vector of weights, where the last element corresp...
52c2ff3ed4b854de645b2252b4949b4a7a68bda1
3,641,709
def score_matrix(motifs, k): """returns matrix score formed from motifs""" nucleotides = {'A': [0]*k, 'T': [0]*k, 'C': [0]*k, 'G': [0]*k} for motif in motifs: for index, nucleotide in enumerate(motif): nucleotides[nucleotide][index] = nucleotides[nucleotide][index] + 1 i = 0 matr...
ce9f7b770ce75d4e872da7b3c9b4fa3fbcd1e900
3,641,710
def log_loss(y_true, dist_pred, sample=True, return_std=False): """ Log loss Parameters ---------- y_true: np.array The true labels dist_pred: ProbabilisticEstimator.Distribution The predicted distribution sample: boolean, default=True If true, loss will be averaged acro...
0f3d19111593441011cfb1e532be50a19d423390
3,641,711
import scipy def matrix_pencil_method_old(data, p, noise_level=None, verbose=1, **kwargs): """ Older impleentation of the matrix pencil method with pencil p on given data to extract energy levels. Parameters ---------- data -- lists of Obs, where the nth entry is considered to be the correlat...
4bcb435b3b16b153d0d1f1689f542df1fdc74ca8
3,641,712
def ext_sum(text, ratio=0.8): """ Generate extractive summary using BERT model INPUT: text - str. Input text ratio - float. Enter a ratio between 0.1 - 1.0 [default = 0.8] (ratio = summary length / original text length) OUTPUT: summary - str. Generated summary """ bert_...
99285d08425340f70984ce0645efdbaaa3e9072a
3,641,713
def khinalug_input_normal(field, text): """ Prepare a string from one of the query fields for subsequent processing: replace common shortcuts with valid Khinalug characters. """ if field not in ('wf', 'lex', 'lex2', 'trans_ru', 'trans_ru2'): return text text = text.replace('c1_', 'č̄') ...
b9b9413ae461b6a03aa8c0db4396658dbe242c91
3,641,714
from typing import List from typing import Dict from typing import Any def _shift_all_classes(classes_list: List[ndarray], params_dict: Dict[str, Any]): """Shift the locale of all classes. Args: classes_list: List of classes as numpy arrays. params_dict: Dict including the shift values for al...
2176e5f4da6aecc25386e978182887fb8568faaa
3,641,715
def fully_connected_layer(tensor, size=None, weight_init=None, bias_init=None, name=None): """Fully connected layer. Parameters ---------- tensor: tf.Tensor Input tensor. size: int Number of output...
605cc52e8c5262aead6cb758488940e7661286b1
3,641,716
from pathlib import Path def fetch_osborne_magnetic(version): """ Magnetic airborne survey of the Osborne Mine and surroundings, Australia This is a section of a survey acquired in 1990 by the Queensland Government, Australia. The line data have approximately 80 m terrain clearance and 200 m line...
2a0575557a18ca4442f0cf21ee51ccd94d316ffa
3,641,717
from sympy.core.symbol import Symbol from sympy.printing.pycode import MpmathPrinter as Printer from sympy.printing.pycode import SciPyPrinter as Printer from sympy.printing.pycode import NumPyPrinter as Printer from sympy.printing.lambdarepr import NumExprPrinter as Printer from sympy.printing.tensorflow import Tensor...
cf7b65c503d1a7873f0ddacfb3f6aa841340ee0e
3,641,718
def _matches(o, pattern): """Match a pattern of types in a sequence.""" if not len(o) == len(pattern): return False comps = zip(o,pattern) return all(isinstance(obj,kind) for obj,kind in comps)
e494016affa28e9018f337cb7184e96858701208
3,641,719
import csv from io import StringIO def excl_import_route(): """import exclustions from csv""" form = ExclImportForm() if form.validate_on_submit(): imported = [] try: for row in csv.DictReader(StringIO(form.data.data), EXPORT_FIELDNAMES, quoting=csv.QUOTE_MINIMAL): ...
780c5646b2a5771691c538cb71bfde390cd9b847
3,641,720
def receiver(signal, **kwargs): """ A decorator for connecting receivers to signals. Used by passing in the signal and keyword arguments to connect:: @receiver(signal_object, sender=sender) def signal_receiver(sender, **kwargs): ... """ def _decorator(func): sig...
dbbde0855b2a657adaff9fa688aa158053e46579
3,641,721
from typing import final def create_new_connected_component(dict_projections, dict_cc, dict_nodes_cc, g_list_, set_no_proj, initial_method, params, i, file_tags=None): """ If needed, create new connect component and update wanted dicts. :param dict_projections: Embedding...
18b8c046e78f17b125bf85250953c9d7a656892a
3,641,722
def laguerre(x, k, c): """Generalized Laguerre polynomials. See `help(_gmw.morsewave)`. LAGUERRE is used in the computation of the generalized Morse wavelets and uses the expression given by Olhede and Walden (2002), "Generalized Morse Wavelets", Section III D. """ x = np.atleast_1d(np.asarray(...
4eac2e1cbd9fd2097763b56129873aa6af4e8419
3,641,723
import math def find_all_combinations(participants, team_sizes): """ Finds all possible experience level combinations for specific team sizes with duplicated experience levels (e.g. (1, 1, 2)) Returns a list of tuples representing all the possible combinations """ num_teams = len(team_sizes) part...
d3f4de9911a1fc427fc2e01433634ccf815f9183
3,641,726
def normalized_copy(data): """ Normalize timeseries data, using the maximum across all regions and timesteps. Parameters ---------- data : xarray Dataset Dataset with all non-time dependent variables removed Returns ------- ds : xarray Dataset Copy of `data`, with the a...
cfcb94458deb6caa1125cfcf2904652900babc87
3,641,728
def _get_exception(ex: Exception) -> Exception: """Get exception cause/context from chained exceptions :param ex: chained exception :return: cause of chained exception if any """ if ex.__cause__: return ex.__cause__ elif ex.__context__: return ex.__context__ else: re...
3f670dc237ebd865e31c7d0fd3719e2ea929de6d
3,641,729
from typing import Any from typing import Dict def recursive_normalizer(value: Any, **kwargs: Dict[str, Any]) -> Any: """ Prepare a structure for hashing by lowercasing all values and round all floats """ digits = kwargs.get("digits", 10) lowercase = kwargs.get("lowercase", True) if isinstanc...
e274c3976405838054d7251fdca8520dc75c48fd
3,641,730
from typing import Set def rip_and_tear(context) -> Set: """Edge split geometry using specified angle or unique mesh settings. Also checks non-manifold geometry and hard edges. Returns set of colors that are used to color meshes.""" processed = set() angle_use_fixed = prefs.RenderFixedAngleUse ...
6a67e9a90b4909c1aec8f7f784b2bc41750f5f79
3,641,731
def generate_primes(d): """Generate a set of all primes with d distinct digits.""" primes = set() for i in range(10**(d-1)+1, 10**d, 2): string = str(i) unique_string = "".join(set(string)) if len(string) == len(unique_string): # Check that all digits are unique if isprim...
4edf615165144f2ab6e5d12533adc4357d904506
3,641,732
def poinv(A, UPLO='L', workers=1, **kwargs): """ Compute the (multiplicative) inverse of symmetric/hermitian positive definite matrices, with broadcasting. Given a square symmetic/hermitian positive-definite matrix `a`, return the matrix `ainv` satisfying ``matrix_multiply(a, ainv) = matrix_mul...
ccba9b0fc518e0482c6ac647d56abe0e86d3409c
3,641,733
def gen_task3() -> np.ndarray: """Task 3: centre of cross or a plus sign.""" canv = blank_canvas() r, c = np.random.randint(GRID-2, size=2, dtype=np.int8) # Do we create a cross or a plus sign? syms = rand_syms(5) # a 3x3 sign has 2 symbols, outer and centre # syms = np.array([syms[0], syms[0], syms[1], sym...
aba9e78cf4d042cacd8787a90275947ba603b37c
3,641,734
def init_susceptible_00(): """ Real Name: b'init Susceptible 00' Original Eqn: b'8e+06' Units: b'person' Limits: (None, None) Type: constant b'' """ return 8e+06
acc506bdea96b224f3627084bbee9e1a025bcff9
3,641,735
def spectrum_1D_scalar(data, dx, k_bin_num=100): """Calculates and returns the 2D spectrum for a 2D gaussian field of scalars, assuming isotropy of the turbulence Example: d=np.random.randn(101,101) dx=1 k_bins_weighted,spect3D=spectrum_2D_scalar(d, dx, k_bin_num=100) ...
88cdb3917d995fdf5d870ebfef3da90f8a4526fb
3,641,736
from operator import and_ def get_previous_cat(last_index: int) -> models.Cat: """Get previous cat. Args: last_index (int): View index of last seen cat. """ cat = models.Cat.query.filter(and_(models.Cat.disabled == False, models.Cat.index < last_index)).order_by( desc(models.Cat.index)...
bd4b6511ab7b2f004b8539e46109ce128d7af4dd
3,641,737
def encode(file, res): """Encode an image. file is the path to the image, res is the resolution to use. Smaller res means smaller but lower quality output.""" out = buildHeader(res) pixels = getPixels(file, res) for i in range(0, len(pixels)): px = encodePixel(pixels[i]) out += px return out
07f9622bc222f91cb614165e432b4584374030a3
3,641,738
def process_image(img): """Resize, reduce and expand image. # Argument: img: original image. # Returns image: ndarray(64, 64, 3), processed image. """ image = cv2.resize(img, (416, 416), interpolation=cv2.INTER_CUBIC) image = np.array(image, dtype='float32') image /= 255. ...
a139d0b82c82273de35d5e95b75cfd5f0e7635e3
3,641,739
def unnormalise_x_given_lims(x_in, lims): """ Scales the input x (assumed to be between [-1, 1] for each dim) to the lims of the problem """ # assert len(x_in) == len(lims) r = lims[:, 1] - lims[:, 0] x_orig = r * (x_in + 1) / 2 + lims[:, 0] return x_orig
1d4cd35f45ab8594e297eb64e152a481c01905cd
3,641,740
def scalar_projection(vector, onto): """ Compute the scalar projection of `vector` onto the vector `onto`. `onto` need not be normalized. """ if vector.ndim == 1: check(locals(), "vector", (3,)) check(locals(), "onto", (3,)) else: k = check(locals(), "vector", (-1, 3)) ...
d5b27d46e6d498b22adb1b081b9c7143c636307b
3,641,741
def update_table(page_current, page_size, sort_by, filter, row_count_value): """ This is the collback function to update the datatable with the required filtered, sorted, extended values :param page_current: Current page number :param page_size: Page size :param sort_by: Column selected for sort...
e2669f3b98546731974e5706b8af9f6d82b47550
3,641,742
def load_mooring_csv(csvfilename): """Loads data contained in an ONC mooring csv file :arg csvfilename: path to the csv file :type csvfilename: string :returns: data, lat, lon, depth - a pandas data frame object and the latitude, longitude and depth of the morning """ data_line, lat, lon,...
a974e8607916e8fbc1b2beb7af8768d048aca8f0
3,641,744
def ez_execute(query, engine): """ Function takes a query string and an engine object and returns a dataframe on the condition that the sql query returned any rows. Arguments: query {str} -- a Sql query string engine {sqlalchemy.engine.base.Engine} -- a database engine object ...
c350d552f89dca550e766337fd7c071e138c43e6
3,641,745
def compute_lima_image(counts, background, kernel): """Compute Li & Ma significance and flux images for known background. Parameters ---------- counts : `~gammapy.maps.WcsNDMap` Counts image background : `~gammapy.maps.WcsNDMap` Background image kernel : `astropy.convolution.Ker...
8049f5a46ecf81459a64811aec917e72ec78a208
3,641,746
def get_list_from(matrix): """ Transforms capability matrix into list. """ only_valuable = [] counter = 1 for row_number in range(matrix.shape[0]): only_valuable += matrix[row_number, counter::].tolist() counter += 1 return only_valuable
bbfa52ff6a960d91d5aece948e9d416c3dcf0667
3,641,747
def g1_constraint(x, constants, variables): """ Constraint that the initial value of tangent modulus > 0 at ep=0. :param np.ndarray x: Parameters of updated Voce-Chaboche model. :param dict constants: Defines the constants for the constraint. :param dict variables: Defines constraint values that depend...
51d55a03b608cef2c3b5d87fe5cb56bf73326ae3
3,641,749
import sqlite3 def disconnect(connection_handler): """ Closes a current database connection :param connection_handler: the Connection object :return: 0 if success and -1 if an exception arises """ try: if connection_handler is not None: connection_handler.close() ...
aaba17e38ef48fe7e0be5ba825e114b6f5148433
3,641,750
def throw_out_nn_indices(ind, dist, Xind): """Throw out near neighbor indices that are used to embed the time series. This is an attempt to get around the problem of autocorrelation. Parameters ---------- ind : 2d array Indices to be filtered. dist : 2d array Distances to be fi...
638fb43ac484ffa0e15e3c19a5b643aae5a749d9
3,641,751
import math def lead_angle(target_disp,target_speed,target_angle,bullet_speed): """ Given the displacement, speed and direction of a moving target, and the speed of a projectile, returns the angle at which to fire in order to intercept the target. If no such angle exists (for example if the projectile is slower t...
fb5dfddf8b36d4e49df2d740b18f9aa97381d08f
3,641,752
import time def acme_parser(characters): """Parse records from acme global Args: characters: characters to loop through the url Returns: 2 item tuple containing all the meds as a list and a count of all meds """ link = ( 'http://acmeglobal.com/acme/' 'wp-content/t...
8e9fe3b020e05243075351d7eedbdba7a54d5d81
3,641,754
def standard_atari_env_spec(env): """Parameters of environment specification.""" standard_wrappers = [[tf_atari_wrappers.RewardClippingWrapper, {}], [tf_atari_wrappers.StackWrapper, {"history": 4}]] env_lambda = None if isinstance(env, str): env_lambda = lambda: gym.make(env) if cal...
e9751e1b376cdee5ec0f9c27d8ab4bf2e303f35b
3,641,756
def load_bikeshare(path='data', extract=True): """ Downloads the 'bikeshare' dataset, saving it to the output path specified and returns the data. """ # name of the dataset name = 'bikeshare' data = _load_file_data(name, path, extract) return data
7cce01f22c37460800a44a85b18e6574d9d7f6fb
3,641,757
def file2bytes(filename: str) -> bytes: """ Takes a filename and returns a byte string with the content of the file. """ with open(filename, 'rb') as f: data = f.read() return data
f917a265c17895c917c3c340041586bef0c34dac
3,641,758
import json def load_session() -> dict: """ Returns available session dict """ try: return json.load(SESSION_PATH.open()) except FileNotFoundError: return {}
342c8e143c878cfc4821454cebfcc3ba47a2cd2a
3,641,759
def _preprocess_zero_mean_unit_range(inputs, dtype=tf.float32): """Map image values from [0, 255] to [-1, 1].""" preprocessed_inputs = (2.0 / 255.0) * tf.cast(inputs, tf.float32) - 1.0 return tf.cast(preprocessed_inputs, dtype=dtype)
08238566a04ed35346b8f4ff0874fff7be48bded
3,641,760
from typing import cast def fill_like(input, value, shape=None, dtype=None, name=None): """Create a uniformly filled tensor / array.""" input = as_tensor(input) dtype = dtype or input.dtype if has_tensor([input, value, shape], 'tf'): value = cast(value, dtype) return tf.fill(value, inp...
1879ac8669396dfe3fe351dae97a96cd8d6a8e5e
3,641,761
from typing import Callable import operator def transform_item(key, f: Callable) -> Callable[[dict], dict]: """transform a value of `key` in a dict. i.e given a dict `d`, return a new dictionary `e` s.t e[key] = f(d[key]). >>> my_dict = {"name": "Danny", "age": 20} >>> transform_item("name", str.upper)(m...
a202fe59b29b0a1b432df759b4600388e2d9f72e
3,641,762
def mock_dataset(mocker, mock_mart, mart_datasets_response): """Returns an example dataset, built using a cached response.""" mocker.patch.object(mock_mart, 'get', return_value=mart_datasets_response) return mock_mart.datasets['mmusculus_gene_ensembl']
bb9a8b828f0ac5bfa59b3faee0f9bcc22c7d954e
3,641,763
import torch def loss_function(recon_x, x, mu, logvar): """Loss function for varational autoencoder VAE""" BCE = F.binary_cross_entropy(recon_x, x, size_average=False) # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2) KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) return BCE + KLD
38c0d6ab7a8388e007324bdcfb8611f0a3072c35
3,641,764
import scipy def resize_img(img, size): """ Given a list of images in ndarray, resize them into target size. Args: img: Input image in ndarray size: Target image size Returns: Resized images in ndarray """ img = scipy.misc.imresize(img, (size, size)) if len(img.shape) ==...
8a3ff8bfab0c864a6c0e4701be07b9296ad23f28
3,641,765
def cloudtopheight_IR(bt, cloudmask, latitude, month, method="modis"): """Cloud Top Height (CTH) from 11 micron channel. Brightness temperatures (bt) are converted to CTHs using the IR window approach: (bt_clear - bt_cloudy) / lapse_rate. See also: :func:`skimage.measure.block_reduce` ...
b68dfb37b27d3067c2956fc3653640393491e014
3,641,766
def info2lists(info, in_place=False): """ Return info with: 1) `packages` dict replaced by a 'packages' list with indexes removed 2) `releases` dict replaced by a 'releases' list with indexes removed info2list(info2dicts(info)) == info """ if 'packages' not in info and 'releases' not in i...
313fda757d386332e16a0a91bb4408fe3cb8c070
3,641,767
def calc_wave_number(g, h, omega, relax=0.5, eps=1e-15): """ Relaxed Picard iterations to find k when omega is known """ k0 = omega ** 2 / g for _ in range(100): k1 = omega ** 2 / g / tanh(k0 * h) if abs(k1 - k0) < eps: break k0 = k1 * relax + k0 * (1 - relax) ...
7173fc9f38547864943046fed1e74d9b5cc832b5
3,641,768
def emit_live_notification_for_model(obj, user, history, *, type:str="change", channel:str="events", sessionid:str="not-existing"): """ Sends a model live notification to users. """ if obj._importing: return None content_type = get_typename_for_model_in...
94e7e91ec73537aad71ab3839fbd203552d4fec2
3,641,769
def is_chitoi(tiles): """ Returns True if the hand satisfies chitoitsu. """ unique_tiles = set(tiles) return (len(unique_tiles) == 7 and all([tiles.count(tile) == 2 for tile in unique_tiles]))
c04149174bb779cd07616d4f419fc86531ab95dd
3,641,770
import itertools def get_hpo_ancestors(hpo_db, hpo_id): """ Get HPO terms higher up in the hierarchy. """ h=hpo_db.hpo.find_one({'id':hpo_id}) #print(hpo_id,h) if 'replaced_by' in h: # not primary id, replace with primary id and try again h = hpo_db.hpo.find_one({'id':h['replac...
2ef2c968bc3001b97529ccd269884cefad7a899f
3,641,771
def mcBufAir(params: dict, states: dict) -> float: """ Growth respiration Parameters ---------- params : dict Parameters saved as model constants states : dict State variables of the model Returns ------- float Growth respiration of the plant [mg m-2 s-1] ...
d31f201384fdab6c03856def1eed7d96fe28482a
3,641,772
def space_boundaries_re(regex): """Wrap regex with space or end of string.""" return rf"(?:^|\s)({regex})(?:\s|$)"
68861da6218165318b6a446c173b4906a93ef850
3,641,774
import requests import json import dateutil def get_jobs(): """ this function will query USAJOBS api and return all open FEC jobs. if api call failed, a status error message will be displayed in the jobs.html session in the career page. it also query code list to update hirepath info. a hard-coded...
46c69348b3f964fc1c4f35391aa5c7a8d049b47e
3,641,775
def artanh(x) -> ProcessBuilder: """ Inverse hyperbolic tangent :param x: A number. :return: The computed angle in radians. """ return _process('artanh', x=x)
d93ec8e7059df02ebf7a60506d2e9896bc146b32
3,641,776
from thunder.readers import normalize_scheme, get_parallel_reader import array def fromtext(path, ext='txt', dtype='float64', skip=0, shape=None, index=None, labels=None, npartitions=None, engine=None, credentials=None): """ Loads series data from text files. Assumes data are formatted as rows, where eac...
9ab049954b23888c2d2a17786edde57dd90507c0
3,641,777
def flop_gemm(n, k): """# of + and * for matmat of nxn matrix with nxk matrix, with accumulation into the output.""" return 2*n**2*k
b217b725e2ac27a47bc717789458fd20b4aa56c1
3,641,778
def index() -> str: """Rest endpoint to test whether the server is correctly working Returns: str: The default message string """ return 'DeChainy server greets you :D'
ce0caeb9994924f8d6ea10462db2be48bbc126d0
3,641,779
from typing import AnyStr from typing import List import json def load_json_samples(path: AnyStr) -> List[str]: """ Loads samples from a json file :param path: Path to the target file :return: List of samples """ with open(path, "r", encoding="utf-8") as file: samples = json.load(file...
b735e7265a31f6bc6d19381bfe9d0cbe26dcf170
3,641,781
import struct import lzma def decompress_lzma(data: bytes) -> bytes: """decompresses lzma-compressed data :param data: compressed data :type data: bytes :raises _lzma.LZMAError: Compressed data ended before the end-of-stream marker was reached :return: uncompressed data :rtype: bytes """ ...
247c3d59d45f3f140d4f2c36a7500ff8a51e45b0
3,641,783
def validate(request): """ Validate actor name exists in database before searching. If more than one name fits the criteria, selects the first one and returns the id. Won't render. """ search_for = request.GET.get('search-for', default='') start_from = request.GET.get('start-from', def...
39b9183cd570cce0ddfd81febde0ec125f11c578
3,641,784
def merge(left, right, on=None, left_on=None, right_on=None): """Merge two DataFrames using explicit-comms. This is an explicit-comms version of Dask's Dataframe.merge() that only supports "inner" joins. Requires an activate client. Notice ------ As a side effect, this operation concatena...
847070e27007c049d0c58059ec9f7c66681f21bc
3,641,785
def estimate_fs(t): """Estimates data sampling rate""" sampling_rates = [ 2000, 1250, 1000, 600, 500, 300, 250, 240, 200, 120, 75, 60, 50, 30, 25, ] fs_est = np.median(1 / np.diff(t))...
82dbd115e3c7b656302d10339cdfe77b60ab0620
3,641,786
def get_case_number(caselist): """Get line number from file caselist.""" num = 0 with open(caselist, 'r') as casefile: for line in casefile: if line.strip().startswith('#') is False: num = num + 1 return num
b1366d8e4a0e2c08da5265502d2dd2d72bf95c19
3,641,787
from typing import Any def build_param_float_request(*, scenario: str, value: float, **kwargs: Any) -> HttpRequest: """Send a post request with header values "scenario": "positive", "value": 0.07 or "scenario": "negative", "value": -3.0. See https://aka.ms/azsdk/python/protocol/quickstart for how to inco...
3e310a92ebe5760a00abc82c5c6465e160a5881d
3,641,788