content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def horiLine(lineLength, lineWidth=None, lineCharacter=None, printOut=None): """Generate a horizontal line. Args: lineLength (int): The length of the line or how many characters the line will have. lineWidth (int, optional): The width of the line or how many lines of text the line will take spa...
64a4e9e22b480cbe3e038464fe6e0061e023d2c2
33,200
import struct import functools def decrypt(content, salt=None, key=None, private_key=None, dh=None, auth_secret=None, keyid=None, keylabel="P-256", rs=4096, version="aes128gcm"): """ Decrypt a data block :param content: Data to be decrypted :type content: str :...
e9a993f1a94bac294d14f21b993b9e59d26ae9e7
33,201
import math def _rescale_read_counts_if_necessary(n_ref_reads, n_total_reads, max_allowed_reads): """Ensures that n_total_reads <= max_allowed_reads, rescaling if necessary. This function ensures that n_total_reads <= max_allowed_reads. If n_total_reads is <= max_allowed_r...
d09b343cee12f77fa06ab467335a194cf69cccb4
33,202
def encode_log_entry_to_json(logEntry): """ Transform the log entry to jason format dict to store into MongoDB """ if logEntry.action == "Query_Success" or "Commit_Success": # Common fileds for query and commit log entry json_dict= {"date": logEntry.utcTimestamp, ...
4185074194459bb9ba78677a9383d29f92b2b12f
33,203
import os from pathlib import Path def getFilesFromPath(path): """returns all files corresponding to path parameter""" raw = os.listdir(Path(path)) files_to_return = list() for i in raw: if i != ".DS_Store": files_to_return.append(i) return files_to_return
a2248b0a57a722fd9412bb80f49d3d8e8b5b6b69
33,204
def run_backward_rnn(sess, test_idx, test_feat, num_lstm_units): """ Run backward RNN given a query.""" res_set = [] lstm_state = np.zeros([1, 2 * num_lstm_units]) for test_id in reversed(test_idx): input_feed = np.reshape(test_feat[test_id], [1, -1]) [lstm_state, lstm_output] = rnn_one_step( ...
f6c113aed718b23778b75d592ccdcee9210a46bd
33,205
import functools def preprocess_xarray(func): """Decorate a function to convert all DataArray arguments to pint.Quantities. This uses the metpy xarray accessors to do the actual conversion. """ @functools.wraps(func) def wrapper(*args, **kwargs): args = tuple(a.metpy.unit_array if isinsta...
dc59d7c4b84cff76584c859354c25a77df6ab9b2
33,206
def _get_verticalalignment(angle, location, side, is_vertical, is_flipped_x, is_flipped_y): """Return vertical alignment along the y axis. Parameters ---------- angle : {0, 90, -90} location : {'first', 'last', 'inner', 'outer'} side : {'first', 'last'} is_vertica...
6dfceb74bea740f70f0958192b316c43eb9a2ef7
33,207
import os def get_work_dir() -> str: """Retrieve the ambianic working directory""" env_work_dir = os.environ.get('AMBIANIC_DIR', os.getcwd()) if not env_work_dir: env_work_dir = DEFAULT_WORK_DIR return env_work_dir
932aaa1b8e63a58edcd2096d34d5e6b000edc925
33,208
import logging import os def get_pages(root_path): """ Reads the content folder structure and returns a list of dicts, one per page. Each page dict has these keys: path: list of logical uri path elements uri: URI of the final rendered page as string file_path: physical path of the...
acc6887638e2d6f6950d4e38556b155e22a6999f
33,209
def load_dict(path): """ Load a dictionary and a corresponding reverse dictionary from the given file where line number (0-indexed) is key and line string is value. """ retdict = list() rev_retdict = dict() with open(path) as fin: for idx, line in enumerate(fin): text = line.stri...
31a67c2a28518a3632a47ced2889150c2ce98a78
33,210
import numpy def hsplit(ary, indices_or_sections): """ Split an array into multiple sub-arrays horizontally (column-wise). Please refer to the `split` documentation. `hsplit` is equivalent to `split` with ``axis=1``, the array is always split along the second axis regardless of the array dimensi...
cd04cbeb3ac89910289d6f1ddc1809373f896ac6
33,211
def is_valid_ipv6_addr(input=""): """Check if this is a valid IPv6 string. Returns ------- bool A boolean indicating whether this is a valid IPv6 string """ assert input != "" if _RGX_IPV6ADDR.search(input): return True return False
f866aa5e8e005823ec78edcc9c7dedd923c28c4f
33,212
import sys def might_need_auth(f): """Decorate a CLI function that might require authentication. Catches any UnauthorizedException raised, prints a helpful message and then exits. """ @wraps(f) def wrapper(cli_args): try: return_value = f(cli_args) except Unauthori...
15bc2f1291c4c0f0484ea6788d3da7bae80a360d
33,213
def intersection_k(is_k_acceptable_func, *lists_of_interesting_parts): """ Segments, where intersects k parts, where is_k_acceptable_func(k) is True. For example for is_k_acceptable_func = lamda k: k >= 1 this function returns segments where there is at laest on part i.e. union of segments. This fun...
90cf497969095f9511e72f79cef796fe5aaf3751
33,214
def calc_TEC( maindir, window=4096, incoh_int=100, sfactor=4, offset=0.0, timewin=[0, 0], snrmin=0.0, ): """ Estimation of phase curve using coherent and incoherent integration. Args: maindir (:obj:`str`): Path for data. window (:obj:'int'): Window length in samp...
f2af0a58d866b79de320e076e3ecc5ae3e704cad
33,215
def solve(A, b): """solve a sparse system Ax = b Args: A (torch.sparse.Tensor[b, m, m]): the sparse matrix defining the system. b (torch.Tensor[b, m, n]): the target matrix b Returns: x (torch.Tensor[b, m, n]): the initially unknown matrix x Note: 'A' should be 'dense'...
64a51eb8b1bd52ea3c47b80363b68ec346260ac9
33,216
import os def paths(alembic_files): """ 获取文件路径交集 :rtype: list """ #get texture sets def _get_set(path): # 获取文件路径集合 _list = [] def _get_path(_path, _list): _path_new = os.path.dirname(_path) if _path_new != _path: _list.append(_path_n...
fa33fdc65e0032f1aa116251a583247f1275eb5c
33,217
def smiles_to_fp(smiles): """ Convert smiles to Daylight FP and MACCSkeys. Parameters ---------- smiles : str, smiles representation of a molecule Returns ------- fp : np.ndarray zero and one representation of the fingerprints """ try: mol = Chem.MolFromSmiles(smiles) ...
e64b3b94ccf950af41473800e992720b7dd6b155
33,218
import re def _networkinfo(interface): """Given an interface name, returns dict containing network and broadcast address as IPv4Interface objects If an interface has no IP, returns None """ ipcmds = "ip -o -4 address show dev {}".format(interface).split() out = check_output(ipcmds).decode('ut...
51ab39e2f05f1dad8d02272c425a357750781414
33,219
import functools def handle_view_errors(func): """ view error handler wrapper # TODO - raise user related errors here """ @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ValueError as e: message: str ...
90f6ceb9562277faafa3c84ae2d1f12364e3352d
33,220
from typing import Union from typing import List from typing import Optional from typing import Dict import os from typing import TYPE_CHECKING import functools def eztrim( clip: vs.VideoNode, /, trims: Union[List[Trim], Trim], audio_file: str, outfile: Optional[str] = None, *, ffmpeg_path...
31f13be00aa67fd2c2a27c0e312310c00895ece1
33,221
def score_decorator(f): """Decorator for sklearn's _score function. Special `hack` for sklearn.model_selection._validation._score in order to score pipelines that drop samples during transforming. """ def wrapper(*args, **kwargs): args = list(args) # Convert to list for item assignment ...
ee3464cb596846f3047fa04a6d40f5bec9634077
33,222
def trait(name, notify=True, optional=False): """ Create a new expression for observing a trait with the exact name given. Events emitted (if any) will be instances of :class:`~traits.observation.events.TraitChangeEvent`. Parameters ---------- name : str Name of the trait to match....
ecd6b0525efadea6e0a7bc2b57ebaf99f2463cca
33,223
def get_splits(space, data, props, max_specs=None, seed=None, fp_type="morgan"): """ Get representations and values of the data given a certain set of Morgan hyperparameters. Args: space (dict): hyperopt` space of hyperpara...
9ff20a62b7615d3f7b1b3a8ede1c1d4f6ff5bccf
33,224
import hashlib from sys import path import logging def download(url, *paths): """Download a file if it isn't already present""" chunkSize = 4096 h = hashlib.sha256() if path.isfile(path.isfile(wspath(*paths))): logging.info( '"{}" already exists. Will not download.'.format(wspath...
d7b1696791960097e79a72e7a1ef21792a7432dc
33,225
def amortized_loan(principal, apr, periods, m=12): """ """ return principal / pvifa(apr, periods, m)
f7d67683cd625179012a24e6cd62c0c552009a48
33,226
import binascii import struct def _icc_to_dict(field_data): """ Get de55 fields from message :param field_data: the field containing de55 :return: dictionary of de55 key values key is tag+tagid """ TWO_BYTE_TAG_PREFIXES = [b'\x9f', b'\x5f'] field_pointer = 0 return_value...
b72915e59f5c1f10289533ae7d363dd510fbe6d4
33,227
from typing import Optional from typing import Iterable def horizontal_legend( fig: Figure, handles: Optional[Iterable[Artist]] = None, labels: Optional[Iterable[str]] = None, *, ncol: int = 1, **kwargs, ) -> Legend: """ Place a legend on the figure, with the items arranged to read right to left rathe...
ea229c4deee241c37b3c26a5ab2fab4d2233b8dd
33,228
def _create_lock_inventory(session, rp_uuid, inventories): """Return a function that will lock inventory for this rp.""" def _lock_inventory(): rp_url = '/resource_providers/%s' % rp_uuid inv_url = rp_url + '/' + 'inventories' resp = session.get(rp_url) if resp: data ...
e9988b989cc22f82110923466906aa64a515c41f
33,229
def strip(string, p=" \t\n\r"): """ strip(string, p=" \t\n\r") """ return string.strip(p)
1be2a256394455ea235b675d51d2023e8142415d
33,230
def deepvariant_header(contigs, sample_names, add_info_candidates=False, include_med_dp=True): """Returns a VcfHeader used for writing VCF output. This function fills out the FILTER, INFO, FORMAT, and extra header information created by the Dee...
8589817386bca02f8fe56d736f40defb7c626a23
33,231
def correlation_matrix_plot( df, function=pearsonr, significance_level=0.05, cbar_levels=8, figsize=(6, 6) ): """Plot corrmat considering p-vals.""" corr, pvals = correlation_matrix(df, function=function) # create triangular mask for heatmap mask = np.zeros_like(corr) mask[np.triu_indices_from(...
343aa7c0240be34da037ea45bd0020d6eed83770
33,232
def _unvec(vecA, m=None): """inverse of _vec() operator""" N = vecA.shape[0] if m is None: m = np.sqrt(vecA.shape[1] + 0.25).astype(np.int64) return vecA.reshape((N, m, -1), order='F')
766dd244016691cc2f29d0af383034116e067401
33,233
import logging def one_hot_encode(sequences): """One hot encoding of a list of DNA sequences Args: sequences (list):: python list of strings of equal length Returns: numpy.ndarray: 3-dimension numpy array with shape (len(sequences), len(list_i...
3ccb69c433872968510065e2ce86b69558767cf8
33,234
def binary_cross_entropy(labels, logits, linear_input=True, eps=1.e-5, name='binary_cross_entropy_loss'): """ Same as cross_entropy_loss for the binary classification problem. the model should have a one dimensional output, the targets should be given in form of a matrix of dimensions batch_size x 1 with va...
60c29e67144e91ac384016642322eafe34d70984
33,235
def get_number_from_user(): """ None -> (int) Get a symbol by index from the user's input. """ movers = ApiWrapper.get_movers() while True: print("To choose a company, enter a responding integer from the list below") print_movers(movers) y = input("Enter the number of compan...
f04d312ba115bd601e9d0d6bfde7f614359ba13d
33,236
from sys import path def handle_templates(url, domain, _method, **kwargs): """ Handle Templates :param url: Incoming URL dictionary :type url: dict :param domain: Incoming domain :type domain: str :param _method: Incoming request method (but not used here) :type _method: str :param...
d5360ee0293eca98af28a98c87731eca49258f10
33,237
def read_refseqscan_results(fn): """Read RefSeqScan output file""" ret = dict() for line in open(fn): line = line.strip() if line == '' or line.startswith('#'): continue cols = line.split() ret[cols[0]] = cols[2] return ret
4450e4113d47e72c5332dd1ca79b37a6847a296f
33,238
import array def discretize_categories(iterable): """ :param iterable: :return: """ uniques = sorted(set(iterable)) discretize = False for v in uniques: if isinstance(v, str): discretize = True if discretize: # Discretize and return an array str_to_int_...
a55bb0cc8632274d15f00478783e3def3f4ebd49
33,239
def multhist(hists, asone=1): """Takes a set of histograms and combines them. If asone is true, then returns one histogram of key->[val1, val2, ...]. Otherwise, returns one histogram per input""" ret = {} num = len(hists) for i, h in enumerate(hists): for k in sorted(h): if k...
0bb6b0af90e75fcfb4c2bee698a123c897bcb64c
33,240
def to_dict(obj, table=None, scrub=None, fields=None): """ Takes a single or list of sqlalchemy objects and serializes to JSON-compatible base python objects. If scrub is set to True, then this function will also remove all keys that match the specified list """ data = None serialize_obj = ...
270c22f8a096d65024f0ddc5699ba21155b7c2ef
33,241
import torch def CWLoss(output, target, confidence=0): """ CW loss (Marging loss). """ num_classes = output.shape[-1] target = target.data target_onehot = torch.zeros(target.size() + (num_classes,)) target_onehot = target_onehot.cuda() target_onehot.scatter_(1, target.unsqueeze(1), 1.)...
6f9a61dcb1b2377e4e76fa71d0de86ee12647f17
33,242
def get_square(array, size, y, x, position=False, force=False, verbose=True): """ Return an square subframe from a 2d array or image. Parameters ---------- array : 2d array_like Input frame. size : int Size of the subframe. y : int Y coordinate of the center of the s...
8d83d4d16241e118bbb65593c14f9f9d5ae0834c
33,243
def iou_with_anchors(anchors_min, anchors_max, box_min, box_max): """Compute jaccard score between a box and the anchors. """ len_anchors = anchors_max - anchors_min int_xmin = np.maximum(anchors_min, box_min) int_xmax = np.minimum(anchors_max, box_max) inter_len = np.maximum(int_xmax - int_xmi...
f3c3a10b8d86bb25ca851998de275a7c5fb8fbec
33,244
def load_from_np(filename, arr_idx_der): """ arr_idx_der 1 for rho and 2 for p """ # load npy data of 3D tube arr = np.load(filename) arr_t = arr[:, 0] arr_der = arr[:, arr_idx_der] return arr_t, arr_der
77b64fdf067cf70a6861d75b60c7ca63bbf21de0
33,245
def rxzero_vel_amp_eval(parm, t_idx): """ siglognormal velocity amplitude evaluation """ if len(parm) == 6: D, t0, mu, sigma, theta_s, theta_e = parm elif len(parm) == 4: D, t0, mu, sigma = parm else: print 'Invalid length of parm...' return None #argument for...
acc1c102723d276db6603104ad8ad3848f72b7f8
33,246
import base64 import io def get_image_from_request(request, type): """ Based on the content type, get the image data from the request. """ logger.info(prepend_ip("get_image_from_request method=%s content_type=%s" %(request.method, request.content_type), request)) logger.debug("first 32 bytes of body: %s" ...
bcdf0942885a48999f3e19f9407f5c47bc08cf3f
33,247
import json def read_json(json_file): """ Read input JSON file and return the dict. """ json_data = None with open(json_file, 'rt') as json_fh: json_data = json.load(json_fh) return json_data
4e1ea153d040ec0c3478c2d1d3136eb3c48bfe1c
33,248
def mixnet_xl(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Creates a MixNet Extra-Large model. Not a paper spec, experimental def by RW w/ depth scaling. """ default_cfg = default_cfgs['mixnet_xl'] #kwargs['drop_connect_rate'] = 0.2 model = _gen_mixnet_m( channel_multipl...
e03c12abb4bb2cb43553cecd6b175cf6724cc8c0
33,249
def accuracy(results): """ Evaluate the accuracy of results, considering victories and defeats. Args: results: List of 2 elements representing the number of victories and defeats Returns: results accuracy """ return results[1] / (results[0] + results[1]) * 100
911e38741b7c02772c23dd6a347db36b96a0e7e0
33,250
def sub_sellos_agregar(): """ Agregar nuevo registro a 'sub_sellos' """ form = SQLFORM(db.sub_sellos, submit_button='Aceptar') if form.accepts(request.vars, session): response.flash = 'Registro ingresado' return dict(form=form)
8c9ad3c3648bda12f5259b164886a0e6ce822d11
33,251
async def ensure_valid_path(current_path: str) -> bool: """ ensures the path is configured to allow auto refresh """ paths_to_check = settings.NO_AUTO_REFRESH for path in paths_to_check: if path in current_path: return False return True
a39c46e0df1db2ac93afbb063e16a3c52cb378eb
33,252
def lookup_series(name=None, tvdb_id=None, only_cached=False, session=None, language=None): """ Look up information on a series. Will be returned from cache if available, and looked up online and cached if not. Either `name` or `tvdb_id` parameter are needed to specify the series. :param unicode name: ...
5a9c788b2a0b9b17a4f0983d78b20795d50806f5
33,253
from typing import List def part_1_original_approach(lines: List[str]) -> int: """ This was my original approach. I missed a few critical details that really bit me in the ass. 1. Operator precedence for modulo. """ ans = 0 seq = [[int(c) for c in x] for x in lines] for _ in range(10...
b8fbf734c0a476244cb8f999afa961c8ec0ff737
33,254
import subprocess def pacman_packages_to_update(): """ Return the packages to update from the pacman's database. """ pacman_proc = subprocess.Popen(["/bin/pacman -Qu"], stdout=subprocess.PIPE, shell=True) (pacman_out, pacman_err) = pacman_proc.communicate() if pacman_proc.returncode == 0: ...
8ed265a3590d946464fba410d516d1e5f1fe1842
33,255
def get_distances(username,location,dist): """ The purpose of this function is the calculation of distances between user and created rooms """ distances=[] keys = ['_id','dist'] base=list(nego.find({},{'location':0})) ## Retrieves every user in the base except location for d in base: ...
41c3caf26c46d227367da813fb8e2a0d059e6500
33,256
import pickle def AcProgEgrep(context, grep, selection=None): """Corresponds to AC_PROG_EGREP_ autoconf macro :Parameters: context SCons configuration context. grep Path to ``grep`` program as found by `AcProgGrep`. selection If ``None`` (default), ...
d8f8ed373950ef4a9b6aaa2790a988f5aacd9730
33,257
def is_number(s): """Is string a number.""" try: float(s) return True except ValueError: return False
22eb560c2723f6551d1a445ba777208a75139a7c
33,258
import numpy def calc_motif_dist(motifList): """Given a list of motifs, returns a dictionary of the distances for each motif pair, e.g. {Motif1:Motif2:(dist, offset, sense/antisense)} """ ret = {} for m1 in motifList: for m2 in motifList: if m1.id != m2.id: #che...
1610d2213afc28a810077949c4a763e742f364ab
33,259
def step(name=None): """ Decorates functions that will register a step. """ def decorator(func): add_step(get_name(name, func), func) return func return decorator
64a69b5c0f31bef4e5126c869417a9215adc9221
33,260
def prepare_subimg(image5d, size, offset): """Extracts a subimage from a larger image. Args: image5d: Image array as a 5D array (t, z, y, x, c), or 4D if no separate channel dimension exists as with most one channel images. size: Size of the region of interest as ...
c8c14333ed862fc3acec4347d0462e5dcb644ab8
33,261
def filter_plants_by_region_id(region_id, year, host='switch-db2.erg.berkeley.edu', area=0.5): """ Filters generation plant data by NERC Region, according to the provided id. Generation plants w/o Region get assigned to the NERC Region with which more than a certain percentage of its County area interse...
e9eaa363a4ec2293b97a7a7ffacf82bc0ae49702
33,262
def _get_image_blob(roidb, scale_ind): """Builds an input blob from the images in the roidb at the specified scales. """ num_images = len(roidb) processed_ims = [] # processed_ims_depth = [] # processed_ims_normal = [] im_scales = [] for i in xrange(num_images): # rgba ...
69200c535818d159b10f80d9c967546cbbd33a75
33,263
def translate_month(month): """ Translates the month string into an integer value Args: month (unicode): month string parsed from the website listings. Returns: int: month index starting from 1 Examples: >>> translate_month('jan') 1 """ for key, values ...
5ff0e3506e37e4b9b5cdd2cd3bf5b322622172ab
33,264
def gencpppxd(desc, exception_type='+'): """Generates a cpp_*.pxd Cython header file for exposing C/C++ data from to other Cython wrappers based off of a dictionary description. Parameters ---------- desc : dict Class description dictonary. exception_type : str, optional Cython...
a2e7cc486589ee301483b8a76b65313eb754221d
33,265
import os def read_files(filepath, **kwargs): """Reads a ``.dbf``/``.shp`` pair, squashing geometries into a 'geometry' column. Parameters ---------- filepath : str The file path. **kwargs : dict Optional keyword arguments for ``dbf2df()``. Returns ------- df ...
0ca28bccb6dbd9e5ef8b75b77c64fa2fecf9813a
33,266
def no_results_to_show(): """Produce an error message when there are no results to show.""" return format_html('<p class="expenses-empty">{}</p>', _("No results to show."))
492c1c19d4daf159a495c001bfc6671fdf6ed593
33,267
import inspect import os def getExecDirectory(_file_=None): """ Get the directory of the root execution file Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing For eclipse user with unittest or debugger, the function search for the...
80a2d6e08c549b0bb33369e5022d2fc80a922e53
33,268
def enhance_shadows(Shw, method, **kwargs): """ Given a specific method, employ shadow transform Parameters ---------- Shw : np.array, size=(m,n), dtype={float,integer} array with intensities of shading and shadowing method : {‘mean’,’kuwahara’,’median’,’otsu’,'anistropic'} method n...
daddde00889be9eb6a1bb57fc140363d85ede32a
33,269
from typing import Optional from typing import Set import collections def _to_real_set( number_or_sequence: Optional[ScalarOrSequence] ) -> Set[chex.Scalar]: """Converts the optional number or sequence to a set.""" if number_or_sequence is None: return set() elif isinstance(number_or_sequence, (float, i...
c0f380a9a179634da04447198ad6553c3c684f7c
33,270
def alt_or_ref(record, samples: list): """ takes in a single record in a vcf file and returns the sample names divided into two lists: ones that have the reference snp state and ones that have the alternative snp state Parameters ---------- record the record supplied by the vcf reader ...
abaccfeef02ee625d103da88b23fce82a40bc04c
33,271
def plot_loss(ctx, tests, rulers=[], sfx="", **kwargs): """Loss plot (1 row per test, val on left, train on right).""" vh = len(tests) fig, axs = plt.subplots(vh, 2, figsize=(16, 4 * vh)) for base, row in zip(tests, axs.reshape(vh, 2)): ctx.plot_loss( base, row[0], baselines=["adam"]...
d215ec0bc20520380bf0625f27abbad383981cd3
33,272
def mpi_rank(): """ Returns the rank of the calling process. """ comm = mpi4py.MPI.COMM_WORLD rank = comm.Get_rank() return rank
63fba63118edbced080b5077931c0d63d2c672b2
33,273
def db(app): """ Setup our database, this only gets executed once per session. :param app: Pytest fixture :return: SQLAlchemy database session """ _db.drop_all() _db.create_all() # Create a single user because a lot of tests do not mutate this user. # It will result in faster tests...
0176de576b1f217ce56e61cdba5b2deb287d7430
33,274
def is_const_component(record_component): """Determines whether a group or dataset in the HDF5 file is constant. Parameters ---------- record_component : h5py.Group or h5py.Dataset Returns ------- bool True if constant, False otherwise References ---------- .. https://...
4adb2ff7f6fb04086b70186a32a4589ae9161bb5
33,275
def centernet_resnet101b_voc(pretrained_backbone=False, classes=20, **kwargs): """ CenterNet model on the base of ResNet-101b for VOC Detection from 'Objects as Points,' https://arxiv.org/abs/1904.07850. Parameters: ---------- pretrained_backbone : bool, default False Whether to load th...
39b6ed4aa1d5c1143ef3b35f12f6be71160ec5cf
33,276
from re import T from datetime import datetime from re import A def req(): """ REST Controller """ load("req_req") default_type = 3 request.vars["default_type"] = 3 if "skill_id" in request.get_vars: # Look up the Request from the Skill component # (since that is what is availabl...
d39566d7d0a47206d16b0f23eb09efe774393d98
33,277
import pytz def isodate(dt): """Formats a datetime to ISO format.""" tz = pytz.timezone('Europe/Zagreb') return dt.astimezone(tz).isoformat()
d07118e188772ec6a87d554c6883530164eeb550
33,278
def _ncells_after_subdiv(ms_inf, divisor): """Calculates total number of vtu cells in partition after subdivision :param ms_inf: Mesh/solninformation. ('ele_type', [npts, nele, ndims]) :type ms_inf: tuple: (str, list) :rtype: integer """ # Catch all for cases where cell subdivision is not perf...
981db31a7729c0cac88575b1cb12505a30cf0abb
33,279
def match_santa_pairs(participants: list): """ This function returns a list of tuples of (Santa, Target) pairings """ shuffle(participants) return list(make_circular_pairs(participants))
dc002f82d25df89ee70392ff48fdd401a960ccc5
33,280
def conv_relu_forward(x, w, b, conv_param): """ A convenience layer that performs a convolution followed by a ReLU. Inputs: - x: Input to the convolutional layer - w, b, conv_param: Weights and parameters for the convolutional layer Returns a tuple of: - out: Output from the ReLU - cache: Object to give to t...
52ee4941c7cf48179652a0f0e26a4d271579047f
33,281
def top_rank(df, target, n=None, ascending=False, method='spearman'): """ Calculate first / last N correlation with target This method is measuring single-feature relevance importance and works well for independent features But suffers in the presence of codependent features. pearson : standard corr...
f8e2b0b9888af00c6c75acac4f5063580bbada07
33,282
def sample_points_on_sphere(center, distance_from_center, hemisphere=False): """just use the polar coordinates to do this, this can be sped up do that """ EPS = 1e-6 thetas = np.linspace(0+EPS, 2*np.pi, 64) phis = np.linspace(0+EPS, np.pi/2, 64) if hemisphere else np.linspace(0+EPS, np.pi, 64) p...
0441a58da5e9bd6cccd8aeae29c022ffd6e6eae8
33,283
from pathlib import Path def get_package_path() -> Path: """ Get local install path of the package. """ return to_path(__file__).parent.absolute()
7976606ad2731b408dd6a44d72e27f6307c2fa8b
33,284
import inspect import types def parameterized_class(cls): """A class decorator for running parameterized test cases. Mark your class with @parameterized_class. Mark your test cases with @parameterized. """ test_functions = inspect.getmembers(cls, predicate=inspect.ismethod) for (name, f) in t...
084ec02b2c9427ffb9ddd41ef9857390477d9d6f
33,285
def isStringLike(s): """ Returns True if s acts "like" a string, i.e. is str or unicode. Args: s (string): instance to inspect Returns: True if s acts like a string """ try: s + '' except: return False else: return True
73fc002843735536c159eed91cf54886f52e78e7
33,286
def velocity_to_wavelength(velocities, input_units, center_wavelength=None, center_wavelength_units=None, wavelength_units='meters', convention='optical'): """ Conventions defined here: http://www.gb.nrao.edu/~fghigo/gbtdoc/doppler.html * Radio V = c (c/l0 - c/l)/(c/l0) f(V) = (c/l0)...
aff040967297848253e49272eb6b5ba4e687433b
33,287
def get_social_profile_provider_list(profile): """ """ sp = None sp = SocialProfileProvider.objects.filter(user=profile.user).order_by('provider', 'website',) return sp
9e157c97dfd0d7daa1a2d0ad80bd84add3dcc281
33,288
import os def load_tomogram(path_to_dataset: str, dtype=None) -> np.array: """ Verified that they open according to same coordinate system """ _, data_file_extension = os.path.splitext(path_to_dataset) print("file in {} format".format(data_file_extension)) assert data_file_extension in [".em",...
2eb5877b7abe147e051bcabb092f917848048697
33,289
import socket import struct def ip2long(ip): """ Convert an IP string to long """ packedIP = socket.inet_aton(ip) return struct.unpack("!L", packedIP)[0]
fbcd7e6255590fa5f67c90bb077d2aa9858abf0a
33,290
def item_link_copy(request, op): """ Objekt zum Einblenden markieren """ if request.GET.has_key('id'): item_container = get_item_container_by_id(request.GET['id']) else: item_container = get_my_item_container(request, op) if item_container.parent_item_id != -1: #request.session['dms_link_copy_id'] =...
1696eaa219193f80d4f61a9b573d00c4a06f077b
33,291
def get_aggregation_fn_cls(rng): """Sample aggregation function for feature""" return rng.choice(AGGREGATION_OPERATORS)
843fc97c7216148e2bdfb40009da5a56f77b7008
33,292
def resnet_mvgcnn(depth, pretrained=False, **kwargs): """Constructs a MVGCNN based on ResNet-18 model.""" model = ResNetMVGCNN(BasicBlock, resnet_layers[depth], **kwargs) if pretrained: pretrained_dict = model_zoo.load_url( model_urls['re...
433b028c8af6c99a17b4cb35fc217bffaeee1439
33,293
def _smooth_samples_by_weight(values, samples): """Add Gaussian noise to each bootstrap replicate. The result is used to compute a "smoothed bootstrap," where the added noise ensures that for small samples (e.g. number of bins in the segment) the bootstrapped CI is close to the standard error of the me...
470c2263f81212daf56450e43f64b56d32b654a0
33,294
def lpc_ref(signal, order): """Compute the Linear Prediction Coefficients. Return the order + 1 LPC coefficients for the signal. c = lpc(x, k) will find the k+1 coefficients of a k order linear filter: xp[n] = -c[1] * x[n-2] - ... - c[k-1] * x[n-k-1] Such as the sum of the squared-error e[i] = ...
bd148dd367fa179933b7f318e071e1017fd707ce
33,295
def make_mpo_networks( action_spec, policy_layer_sizes = (300, 200), critic_layer_sizes = (400, 300), ): """Creates networks used by the agent.""" num_dimensions = np.prod(action_spec.shape, dtype=int) critic_layer_sizes = list(critic_layer_sizes) + [1] policy_network = snt.Sequential([ netw...
c52cb76f96390ab633ca05f33e1e40b20d78ae93
33,296
from typing import Callable from typing import Any def numgrad_x(f: Callable[[Any], Any], x: Tensor, eps: float = 1e-6) -> Tensor: """get numgrad with the same shape of x Args: f (Callable[[Any], Any]): the original function x (Tensor): the source x eps (float, optional): default error. Default...
fd8b680e122de3adaa3a3246f8d7f786bffd24a2
33,297
def throw_darts_serial(n_darts): """Throw darts at a square. Execute serially! Count how many end up in an inscribed circle. Approximate pi. Parameters ---------- n_darts : int Number of darts to throw Returns ------- pi_approx : float Approximation of pi ...
1aee3692af97eb2ac6d68ccfd573fa55e9e98a6c
33,298
def sample_category(user, name='Movie', slug='film'): """Create and return a sample ingredient""" return Category.objects.create(user=user, name=name, slug=slug)
c7291808b63244a74e97700819584d3630fd2f04
33,299