content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import signal def notch(waves, calcs, f_notch, Q, wfin="wf_blsub", wfout="wf_notch", test=False): """ apply notch filter with some quality factor Q TODO: apply multiple notches (f_notch, Q could be lists) """ wfs = waves[wfin] clk = waves["settings"]["clk"] # Hz f_nyquist = 0.5 * clk ...
814787cf714f0f6a96ec57491611cddd1754090a
42,800
def hdu_records(hdu_list: fits.BinTableHDU) -> fits.FITS_rec: """ Generator function to yield each record in hdu_list :param hdu_list: HDUList object (containing data) :return: List of HDU records """ return hdu_list.data
9054a6724dcab5096580f17b3543d82c6f32d568
42,801
def format_italic(value): """ Wrap the input value in the ANSI escape sequence for italic. """ return _format_code(value, 3)
eec1b505505206a5da0b4730db9aafe3689885b7
42,802
import json import base64 import hashlib import time def publish_jsonl_to_s3(key, row, target_bucket, max_retries=5, validate_payload_checksum=False): """ Publishes individual rows to S3 as minified JSON. This assumes that the entire 'row' element is written as a single JSON object to the target file. ...
39ea3c835313f059d0d174f6384ffe5d7ffbddf7
42,803
from typing import Union def generate_target_points(subject_paths) -> \ Union[np.ndarray, list[np.ndarray]]: """ This function generates the coordinates for a target point or list of target points. It calls upon a GUI implemented in `gui.targetSelection` """ target_points = gui.target...
6ca1d567dc95f8eed14d08ebc5eb8a1aa16bf34a
42,804
def roc_auc(y_true, y_score): """ Returns are under the ROC curve """ notnull = ~np.isnan(y_true) fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true[notnull], y_score[notnull]) return sklearn.metrics.auc(fpr, tpr)
3fc34285b4e73440f194c495230831673d8c0d3b
42,805
def config_stp_vlan_param(dut, cfgdictionary={}): """ config spanning_tree vlan <enable/disable> <vlanid> cfgdictionary={'' : ['enable', 'vlanid']} cfgdictionary={'' : ['disable', 'vlanid']} config spanning_tree vlan forward_delay <vlanid> <forward_delay> cfgdictionary={'forward_delay' : ['vid'...
12b526e878e6ea928bc90f0807ae38a3fd9dff69
42,806
def Events_detail(request, query): """ Retrieve, update or delete a serie. """ try: map_columns=names_to_representation(Cleanevent) map_columns={i[1]:i[0] for i in map_columns} parameters=query.split("-") dict_params={} for i in parameters: spli...
6b99f8c7c7867b7289bbb3c1dc646d102779be21
42,807
def splice_in_preproc_name(base_env_name, preproc_name): """Splice the name of a preprocessor into a magical benchmark name. e.g. you might start with "MoveToCorner-Demo-v0" and insert "LoResStack" to end up with "MoveToCorner-Demo-LoResStack-v0". Will do a sanity check to ensure that the preprocessor a...
61262abd54d0f3c9be5ee59fdc36c8d2a6cd10eb
42,808
def load(thing=None, working_directory=None): """ Loads site files (customization files) from various locations. Without an argument, loads all default site customization options. With a specific argument, load that argument as a customization file (real file or URL). """ if thing is None: ...
bd6a06340f64b462d5e1a80bca48f085004cbd3e
42,809
def invert_node_predicate(node_predicate): """Build a node predicate that is the inverse of the given node predicate. :param node_predicate: An edge predicate :type node_predicate: (pybel.BELGraph, BaseEntity) -> bool :rtype: (pybel.BELGraph, BaseEntity) -> bool """ def inverse_predicate(graph...
b6132728d17d520fd9ee22f228c45b364704d5ef
42,810
from typing import List from typing import Dict from typing import Any def from_protos_v2( proto_list: List[fra.ForwardRateAgreement], config: "ForwardRateAgreementConfig" = None ) -> Dict[str, Any]: """Creates a dictionary of preprocessed swap data.""" prepare_fras = {} for fra_proto in proto_list:...
8d1ad55d3e5253f18991139f9011038c79c9864b
42,811
def query(q): """Run query exacly as provided.""" con = get_db() c = con.cursor() c.execute(q) con.commit() return c.fetchall()
28f75670b24f3e4da08fbfdc410d21a76e1fb02e
42,812
def adjacent_moves(self): """Returns all moves for adjacent tiles.""" moves = [] if world.tile_exists(self.x + 1, self.y): moves.append(actions.MoveEast()) if world.tile_exists(self.x - 1, self.y): moves.append(actions.MoveWest()) if world.tile_exists(self.x, self.y - 1): mov...
ad91a7727fb4c3990c597458bf215f57c049df34
42,813
import random def get_number_by_pro(number_list, pro_list): """ :param number_list:数字列表 :param pro_list:数字对应的概率列表 :return:按概率从数字列表中抽取的数字 """ # 用均匀分布中的样本值来模拟概率 x = random.uniform(0, 1) # 累积概率 cum_pro = 0.0 # 将可迭代对象打包成元组列表 for number, number_pro in zip(number_list, pro_list):...
34e367cb0e29df59ddf1e15deec1837d71a922f9
42,814
def _pauli2circuit(pauli_ansatz): """Transform a pauli ansatz to parameterized quantum circuit.""" circuit = Circuit() for k, v in pauli_ansatz.items(): circuit += decompose_single_term_time_evolution(k, v) return circuit
afc82c4a121e087b275d52f9db02a8510ba04eaf
42,815
def is_valid_source_state(value): """This function makes exeptions for special source states. E.g. It explicitly allows '*' (for any state) and `None` (as this is default value for sqlalchemy colums) """ return (value == '*') or (value is None) or is_valid_fsm_state(value)
f71bac70eb8c8420ae3ec8ff7dcf77606918bceb
42,816
import logging import sys def configure_logging(args): """ Creates logging configuration and sets logging level based on cli argument Args: args: all arguments parsed from cli Returns: logging: logging configuration """ if args.debug: logging.basicConfig(stream=sys.st...
a45f308f2908e16f890598e1a481c0401d2eee90
42,817
def is_valid_ip_whitelist_name(name): """True if string looks like a valid IP whitelist name.""" return bool(IP_WHITELIST_NAME_RE.match(name))
953ba7bd5c9afd3a546f65bba4da85b51a8860dc
42,818
def gcd_fast(a: int, b: int) -> tuple: """ GCD using Euler's Extended Algorithm generalized for all integers of the set Z. Including negative values. :param a: The first number. :param b: The second number. :return: gcd,x,y. Where x and y are bezout's coeffecients. """ gcd=0 x=0 y=0 x=0 """ if a < 0: s...
d29cf59b310a7035555a04aaa358410319c3d1b3
42,819
def get_option_name(flags): """ Function to get option names from the user defined arguments. Parameters ---------- flags : list List of user defined arguments Returns ------- flags : list List of option names """ for individualFla...
359ab05c563aac217d8f275bb946fbafc37f3af2
42,820
def write_ros_handshake_header(sock, header): """ Write ROS handshake header header to socket sock @param sock: socket to write to (must be in blocking mode) @type sock: socket.socket @param header: header field keys/values @type header: {str : str} @return: Number of bytes sent (for stati...
d115af5aa095cc8c5a99b7cd89c11943bdb5fbad
42,821
def _rrv_add_ ( s , o ) : """Addition of RooRealVar and ``number'' >>> var = ... >>> num = ... >>> res = var + num """ if isinstance ( o , _RRV_ ) and not o.isConstant() : o = o.ve () elif hasattr ( o , 'getVal' ) : o = o.getVal () # v = s.ge...
6b7070ece98cd25afb7f5cff7ae245440383f2e4
42,822
import os import struct import re def find_lib_path(name): """ Find full path of a shared library. Parameter --------- name : str Link name of library, e.g., cublas for libcublas.so.*. Returns ------- path : str Full path to library. Notes ----- Code adap...
08dc10b5b4e7cec84e7f9eabbfa6f76b5f00b002
42,823
def NarrowToOctaveBand(freq, dat, n): """ Convert dat from narrowband freq to 1/n octave band """ df = np.mean(np.diff(freq)) lowf = 1000 # Start at 1000 Hz prevf = lowf*(2**(1.0/n)) while (prevf-lowf)>df: prevf = lowf lowf = lowf/(2**(1.0/n)) # Calculate center freque...
296f73b1b1d3e319e1fe4d90dbd7c619e061ce91
42,824
def acq_max(f_acq, gp, y_max, bounds, space, num_warmup, num_starting_points): """ 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 ``num_warmup`` points at random, and then running ...
49e88b9156fce77b888b4217766e7b87094576db
42,825
def openthread_suppress_error_flags(): """Suppress errors for openthread""" return [ '-Wno-error=embedded-directive', '-Wno-error=gnu-zero-variadic-macro-arguments', '-Wno-error=overlength-strings', '-Wno-error=c++11-long-long', '-Wno-error=c++11-extensions', '-Wno-error=variadic...
a6379b1b6133ca24226ca996d9275e4ada8dc3eb
42,826
import tempfile import os def _get_object_detector_cache_filenames(cache_dir, image_dir, annotations_dir, annotations_list, num_shards, ...
78e4312a1710cc7c2826606fc17434883fc748d9
42,827
from typing import Callable def signal_rshift(shift: int) -> Callable[[int], int]: """A circuit element performing a fixed RSHIFT on a signal.""" return lambda x: limit_signal(x >> shift)
54cb582a22a18c73147302be969b48a33d709218
42,828
def es_indices(prefix="", conn=None): """ es_indices gets a potentially filtered list of index names. :type prefix: str :param prefix: the prefix to filter for :type conn: Elasticsearch :param conn: an ES connection object :return: _all or list of index names """ if prefix is not "": ...
1d7831b5b5aa0b8caf16108e33d307e2a16c6128
42,829
import random def wakeup(): """Determine whether the afflicted should wake up.""" return random.randint(0, 99) < WAKEUP_RATE
43af55085c98fbb40165362a9d1ace7bbaf348e0
42,830
from typing import List from typing import Dict from typing import Any import os def check_raster_file(src_path: str) -> ValidationInfo: # pragma: no cover """ Implementation from https://github.com/cogeotiff/rio-cogeo/blob/0f00a6ee1eff602014fbc88178a069bd9f4a10da/rio_cogeo/cogeo.py This function is...
ff1e6b1dfe818e110141d09b8457baa993ddfa76
42,831
def validate(val_loader, model, p_model, criterion): """ Run evaluation """ losses = AverageMeter() top1 = AverageMeter() # switch to evaluate mode _set_fix_method_eval_ori(model) model.eval() with torch.no_grad(): for i, (input, target) in enumerate(val_loader): ...
ad6599b37efbee6cf436da70e5ec05f6bacac638
42,832
def ServiceRequest(opener, host, method, request_dict): """Makes service request to '/service/' + "method" API method.""" req = _MakeRequest(host, '/service/%s' % method, request_dict) return _HandleResponse(method, opener.open(req))
697a032a0f726f5df23631e9b36ee3a2be5dc309
42,833
def test_catch_failure(): """Test case for when the function called with catch raises an exception.""" def f_fail(): return 1 / 0 assert catch(f_fail) is None
211cfe2428610c509dd3ae5ddefa5baa3838b230
42,834
import copy def get_content_node_args(node_data): """ Returns (source_id, title, license) from node_data dictionary. """ node_data = copy.deepcopy(node_data) source_id = node_data.pop('source_id') title = node_data.pop('title') license = node_data.pop('license') return source_id, title...
69aa006fa5b2475f59d52bebb5b5b2424d804eb7
42,835
def get_alt(ref, var_size, var_type): """ Generate alternative allele from SNV and INS but not DEL. :param var_type: SNV or INS :return: A string of nucleotides """ if var_type == 'SNV': nucleotides = [x for x in dna if x != ref] return choice(nucleotides) elif var_type == '...
34a1316a2fe6fcea55faefb3d2debe530b19d0c5
42,836
import click import yaml import os def minify_js( js_files, root, js_comments, js_encoding, git_repo, verbose, quiet, test_run, continue_on_error, compilation_errors, file_map, ): """sass compilation.""" changed_files = False for input_str, output_str in js_fil...
fc74232a89096497a8e3304ae03ef307d2f7f0e9
42,837
def interpolate_volume(ref, resize): """Intperolate a 3D volume """ assert len(ref.shape) == 3, "3D data only" (sx, sy, sz) = ref.shape assert sx == sy, "Only cubic data allowed" assert sx == sz, "Only cubic data allowed" # 2D interpolation along first two axes twodintp = np.zeros((sx, ...
6052c33eb7d4bc34b2e548815fc6540b01493559
42,838
def mock_run_controller(decoy: Decoy) -> RunController: """Get a fake RunController dependency.""" return decoy.mock(cls=RunController)
d33174c6d1a1bf543632a6d0c4dd7584e746adc5
42,839
def detectorEff(E): """Function to describe the detector efficiency. It is based on a fit of Serpent2 results. Parameters ---------- E : float or list Energy in MeV Returns ------- Eps : float or list Detector efficiency at energy/energies E """ E=E*100...
e52a4f398782396ed2922f7d949528935d704fc1
42,840
def getenv(): """Get a mapping of current options.""" global _env if not _env: raise EnvError("No environment exists") else: log.debug("Got a copy of environment %r options", _env) return _env.options.copy()
a63fbb69782d7d498c9d453e439722ef1e947515
42,841
def hilbert(x, N=None, axis=-1): """ Compute the analytic signal, using the Hilbert transform. The transformation is done along the last axis by default. Parameters ---------- x : array_like Signal data. Must be real. N : int, optional Number of Fourier components. Defaul...
37c441a08b2baf23bfec5245b858dc3d7df1b8d3
42,842
import logging def setup_logging(logger=None, console=False, console_level='INFO', filename=None, file_level='DEBUG', queue=None, file_kwargs=None): """Setup logging for console and/or file logging. Returns a scribe thread object. Defaults to no logging.""" if queue is None: queu...
1ecc7ca66d2124fa273b6302652d47839e117884
42,843
from typing import Dict def retrieve_monthly_average_scores(database_connection: mysql.connector.connect ) -> Dict: """Retrieve average panelist scores grouped by month for every available year""" cursor = database_connection.cursor(dictionary=True) query = ("SELECT...
0a4ec2471e3129d64f2dfefd0b59b007e501e4a0
42,844
def Float(*args, **kwargs): """Create a validator that checks that the value is a valid float according to the `spec` :param spec: The specification to check the float against. Can be either None Anything that is a float passes. e.g. 1.2 and "1.2" ar...
29ecd23e7b5ee407fc037afa706524fd2cf19798
42,845
def CV_IS_SEQ_POLYGON(*args): """CV_IS_SEQ_POLYGON(CvSeq seq) -> int""" return _cv.CV_IS_SEQ_POLYGON(*args)
46548bebfb9881c0cfb04d730165efec75e05a8d
42,846
import itertools import six import os def eval_instance_segmentation_coco( pred_masks, pred_labels, pred_scores, gt_masks, gt_labels, gt_areas=None, gt_crowdeds=None): """Evaluate instance segmentations based on evaluation code of MS COCO. This function evaluates predicted instance segmentati...
4d0d5f938588eb3905bde0a4448d5085128b0203
42,847
def fetch_fork_result_list(pipe_ids): """ Read the output pipe of the children, used after forking to perform work and after forking to entry.writeStats() @type pipe_ids: dict @param pipe_ids: Dictinary of pipe and pid @rtype: dict @return: Dictionary of fork_results """ out = {} ...
71f5249463cdb6797f13cbbc524ce406300156f6
42,848
from typing import Mapping from typing import Iterable def is_drf_friendly_errors_dict(val) -> bool: """Check if val is in format drf-friendly-errors.""" try: return ( isinstance(val, Mapping) and val.get('code', None) is not None and is_integer_value(val.get('code'...
68201684822c502b2311737ce8e8dfa079bccd3a
42,849
def home(): """Will render React once compiled.""" return render_template("index.html")
7fecae256d71773be739faf9d13c4b6a3cbffc08
42,850
def del_flowspec_local(flowspec_family, route_dist, rules): """Deletes/withdraws Flow Specification route from VRF identified by *route_dist*. """ try: tm = CORE_MANAGER.get_core_service().table_manager tm.update_flowspec_vrf_table( flowspec_family=flowspec_family, route_dist...
1139bd366dfdef51f757b8737d82dac9d2b28de2
42,851
from typing import Sequence from typing import Tuple def logical_slice_assign_op(x, update, slice_tup_list: Sequence[Tuple[int, int, int]]): """Update a slice of tensor `x`(in-place). Like `x[start:stop:step] = update`. Args: x: A `Tensor`, whose slice will be updated. update: A `Tensor`, in...
f87dd0691bb8df1d498fc713de5e40b47722726f
42,852
def standardize(X, scale_dict = None, reverse = False): """Facilitates standardizing data by subtracting the mean and dividing by the standard deviation. Set reverse to True to perform the inverse operation. Parameters ---------- X : numpy ndarray, or pandas.DataFrame Data for whic...
f10afa7f1bd64ba1d4b223c99fb81dbef1b9c204
42,853
def draw_landmarks_edges(image, keypoint_locs, keypoint_edges, edge_colors, keypoint_color=(0, 255, 0)): """Draw landmarks and edges on the input image and return it.""" for landmark in keypoint_locs: landmark_x ...
991b60c7d833afdb85b5cca7fcda982425bdc5a5
42,854
import torch def psnr(img_batch, ref_batch, batched=False, factor=1.0): """Standard PSNR.""" def get_psnr(img_in, img_ref): mse = ((img_in - img_ref)**2).mean() # if mse > 0 and torch.isfinite(mse): # return (10 * torch.log10(factor**2 / mse)) # elif not torch.isfinite(mse)...
aff37f49ea558ac97bb6e2197a0a58d37ad5b73d
42,855
def current_loss(model_loss): """ Returns the minimum validation loss from the trained model """ losses_list = [] [losses_list.append(x) for x in model_loss] return np.min(np.array(losses_list))
278090761133cb01610ce53965c1d6c0f51da0dd
42,856
def explicit_impute( adata: AnnData, replacement: (str | int) | (dict[str, str | int]), impute_empty_strings: bool = True, copy: bool = False, ) -> AnnData: """Replaces all missing values in all or the specified columns with the passed value There are two scenarios to cover: 1. Replace all ...
23af91ee58852e34105145f35a82706a4baafc12
42,857
def get_nodes_and_edges(schema): """Creates lists of nodes and edges, through references and relations. Parameters: schema (dict): contains information on all nodes and edges in a schema. Returns: nodes (dict): dictionary of nodes edges (list): list of edges """ nodes = {} edges ...
9b328163e48b7617af5adf064d5eb0ae57ddbbba
42,858
def jacobi_solver(L,dp_dx,mu,u_i,tol): """ simple jacobi solver for testing purposes """ Ny = np.size(u_i) u_even = np.copy(u_i) u_odd = np.copy(u_i) h = L/(float(Ny) - 1.) rhs = (h**2)*(1./mu)*dp_dx maxIter = 1000000 KEEP_GOING = True nIter = 0 exit_code = 0 wh...
97815c9f231cee4a710c1b828a881d62c9f7b773
42,859
import ast def default_for_unknown(word): """Provide a default definition for words that are not in the lexicon.""" proper_noun = ast.SentenceNode(word, ast.Var(word.lower()), ast.TYPE_ENTITY) single_place = ast.SentenceNode( word, ast.Lambda("x", ast.Call(ast.Var(word.title()), ast.Var("x...
4a81b696c0531a1fec6dfb0e841afacde838191b
42,860
def add_basic_head(model, blob_in, dim_in, pool_stride, out_spatial_dim, suffix, lfb_infer_only, test_mode): """Add an output head for models predicting "clip-level outputs".""" # -> (B, 2048, 1, 1, 1) pooled = model.AveragePool( blob_in, blob_in + '_pooled', kernels=[pool_stri...
7771d33c3a8fbb839f1901dcc19d45bc723bd38d
42,861
def connect(app: Application) -> NetworkState: """ Estabilish a connection to the server. """ client = nm.get_client() assert app.current_network_uuid is not None nm.activate_connection( client, app.current_network_uuid, partial(on_any_update_callback, app), ) ret...
2ab2fae74941de765c6244dee636b08cd445b1f6
42,862
import random from datetime import datetime def gen_malicious(num_per_dga=10000): """Generates num_per_dga of each DGA""" domains = [] labels = [] # We use some arbitrary seeds to create domains with banjori banjori_seeds = ['somestring', 'firetruck', 'bulldozer', 'airplane', 'racecar', ...
05ce47c5ec739f14b81c1efc4c2c05f4d5087a34
42,863
def rnd_date_array(size, start=date(1970, 1, 1), end=date.today()): """ Array or Matrix of random date generator. """ start = parser.parse_date(start) end = parser.parse_date(end) _assert_correct_start_end(start, end) return _randn(size, _rnd_date, start, end)
c1495729f9ef03f5a1c5c9164eba4295e51e1aaa
42,864
import builtins def createResolutionCallbackFromClosure(fn): """ Create a resolutionCallback by introspecting the function instead of looking up the stack for the enclosing scope """ closure = get_closure(fn) def env(key): if key in closure: return closure[key] eli...
7ab59b1d38919005e096b65865fd7be47dbdafcc
42,865
def move(locations): """ Provide an interface to the user facilitating their movement between locations. Arguments --------- locations : list A list of locations they can move to. Returns ------- str The location the user enters to move to. """ move...
9792bc56b7b0961619864df6d582a71dd14f37ce
42,866
import os import tempfile import tarfile def run_wasm_tests(work_dir, target, desired_config, config_name, options): """Runs wasm via blaze/v8, or returns 0 if skipped.""" if desired_config is not None and desired_config != config_name: return 0 args = [options.v8, "--no-liftoff", "--experimental-wasm-simd"...
5942c5cb86dff88face3a2a1c5f6d222a34ec09f
42,867
def split_loops_into_anchors(file_name): """ Split loops into anchors. """ left = [] right = [] run = file_name.split('.')[0] i = -1 with open(file_name, 'r') as f: for line in f: if '#' in line: # Skip header continue ...
c5040b4c2a675d7250d0658a4e60fddd064d933a
42,868
from pathlib import Path import tqdm def read_challenge17_data(db_dir, verbose=False): """ Read the PhysioNet Challenge 2017 data set. @param db_dir: Database directory. @param verbose: Whether to show a progress bar. @return: Tuple of: (array of wfdb records, DataFrame with record ids as index ...
8a4c51fd7c6728d98a88d42c0ce3abd118d5804c
42,869
def create_population(number_of_individual, data_file_name, intervals_min, intervals_max): """ -> Create a population of random initialized individuals """ pack = dichotomization.extract_matrix_from(data_file_name) variable_to_position = pack[1] population = [] for x in range(0, number_of_individual): individ...
e424842172f4dafb5d4d8a9c3cd3012e9768221c
42,870
def AdjointOperator(model, geometry, space_order=4, **kwargs): """ Construct an adjoint modelling operator in an tti media. Parameters ---------- model : Model Object containing the physical parameters. geometry : AcquisitionGeometry Geometry object that cont...
6b6362110e0da85460b16cca29c2d6460dadf981
42,871
def get_vdi_url(request, compute_id, vname): """ :param request: :param vname: :return: """ compute = get_object_or_404(Compute, pk=compute_id) try: conn = wvmInstance(compute.hostname, compute.login, compute.password, compute.type, vname) fqdn = get_hostname_by_ip(compute....
02af96867090b9703b99a19c52275f843aea8c9a
42,872
def munsell_colour_to_xyY(munsell_colour: StrOrArrayLike) -> NDArray: """ Convert given *Munsell* colour to *CIE xyY* colourspace. Parameters ---------- munsell_colour *Munsell* colour. Returns ------- :class:`numpy.ndarray` *CIE xyY* colourspace array. Notes -...
a2c7d4df68a1c9f9e6cdc79fafd4f06501ea60e5
42,873
def get_filter_meta_table(): """Generate a table with meta information about HELP filters This function generates an astropy.table.Table containing the information about the filters used in HELP, except their transmission profile. Returns ------- astropy.table.Table """ # List of fil...
d81f0d848651c6f52bba1f9f556c86027d3740b5
42,874
def corner_subpix(image, corners, window_size=11, alpha=0.99): """Determine subpixel position of corners. Parameters ---------- image : ndarray Input image. corners : (N, 2) ndarray Corner coordinates `(row, col)`. window_size : int, optional Search window size for subpi...
a0e93691833e4d66aeb0f2cbbd9302972cd511c3
42,875
import torch def adaptive_attack_pgd(model, X, y, c_head_model, scripted_transforms, criterion, epsilon, alpha, attack_iters, restarts, norm, early_stop=False, mixup=False, y_a=None, y_b=None, lam=None, n_views=2, lambda_S=1): """Defense Aware Attack, where the attacker optimizes to ...
3cf61686d42dde18dff7fee614b4d4a5424a1cff
42,876
def login_view(request): """ View that allow us to login a user """ context = {} user = request.user if user.is_authenticated: return redirect("mainpage") if request.method == "POST": form = AccountAuthenticationForm(request.POST) if form.is_valid(): email...
0100394ec069ad9f82648b6f31b61dbe3b6b3903
42,877
def rearrange(da, out_dims, in_dims=None, **kwargs): """Wrap `einops.rearrange <https://einops.rocks/api/rearrange/>`_. Parameters ---------- da : xarray.DataArray Input DataArray to be rearranged out_dims : list of str, list or dict The output pattern for the dimensions. Th...
198bd91b132ff08d0432e5086ee2bcd879f7b161
42,878
def first(*objects): """ Return the first non-None object in objects. """ for obj in objects: if obj is not None: return obj
4d33225eb0348aa9b7fefa875070eb5527e67135
42,879
def example_interaction_with_policy(policy="random"): """Example usage of Interaction that uses a random policy or user interaction to decide which candidate to expand. """ assert policy in ("random", "user") def random_policy(state): """Choose a random candidate to expand""" from h...
0a6a964878b0f70d50026390bfd54883f03b913a
42,880
def add_gallery_media_pic(): """ POST endpoint that adds a new gallery picture to the club with an image upload and a caption. """ user = get_current_user() json = g.clean_json gallery_pic_file = request.files.get('photo', None) if gallery_pic_file is not None: gallery_pic_url, pi...
20114a3fffef909a38d1dce1235a3ec01af5dd3e
42,881
from typing import Optional import torch import functools from typing import OrderedDict import tqdm def volume_render( rays_o, rays_d, model: NeuS, obj_bounding_radius=1.0, batched = False, batched_info = {}, # render algorithm config calc_normal = False, use_view_dirs...
e63ed820080e25f2debfe67baec60230ae40598b
42,882
def ball_tree(dataset, profondeur): """ Compartimente dataset selon l'algorithme BallTree. Parameters ---------- dataset : list Liste de points à séparer. profondeur : int Nombre de fois que la liste de départ est séparé. Returns ------- listes : list liste ...
2ad96667834c8eec63a95d65c8cbf5f26bfe2c06
42,883
import os def find_all_items(data_type, root_path, debug=False): """ extract all the items in the dir with their label params: root_path <str> output: output_x <list> date_paths iutput: output_y <list> data's label """ output_x = [] output_y = [] _walk_instance = os.walk(root_pat...
cbd6be40d010a37b3e3f1ae1fdef6025e06db5a6
42,884
def init_list_with_values(list_length: int, init_value): """Return a pre-initialized list. Returns a list of length list_length with each element equal to init_value. init_value must be immutable (e.g. an int is okay; a dictionary is not), or the resulting list will be a list of references to same object (e.g. re...
85d5aa5f575b6aec54658ca6d398ded5f48f7188
42,885
import math def get_ab_test_ci( conversions_control: int, conversions_treatment: int, total_users_control: int, total_users_treatment: int, confidence_level: float = 0.05, ) -> str: """ Conducts an A/B test on the two sided hypothesis: - H_0: Probability of conversion in treatment ...
a3cdc23941c1eec956a0d9eb631300c62f07a402
42,886
def euler_to_quaternion(euler_angles, rotation_order=DEFAULT_ROTATION_ORDER,filter_values=True): """Convert euler angles to quaternion vector [qw, qx, qy, qz] Parameters ---------- * euler_angles: list of floats \tA list of ordered euler angles in degress * rotation_order: Iteratable \t a li...
4259e96658f46a99d8c056e5b98aa3a63cd9aed2
42,887
from tqdm import tqdm as t def tqdm(iterable=None, desc=None, total=None, leave=True, **kwargs): """ascii=Trueでncols=100なtqdm。""" return t(iterable, desc, total, leave, ascii=True, ncols=100, **kwargs)
7e4bd94ac0a94318b16b3f16d920665106c62361
42,888
def get_largest_mol(mol_list): """ Given a list of rdkit mol objects, returns mol object containing the largest num of atoms. If multiple containing largest num of atoms, picks the first one. Args: mol_list(list): a list of rdkit mol object. Returns: the largest mol. """ ...
c30b2bb55af911f72fa29b800ef0081ad7c1830b
42,889
import re def decode_sigma(ds,sigma_v): """ ds: Dataset sigma_v: sigma coordinate variable. return DataArray of z coordinate implied by sigma_v """ formula_terms=sigma_v.attrs['formula_terms'] terms={} for hit in re.findall(r'\s*(\w+)\s*:\s*(\w+)', formula_terms): terms[hit[0]]...
3ea233f2b3acb0012166e8e002d6824845a7c043
42,890
def is_territory(element: inkex.BaseElement) -> bool: """ Checks if the given element is a territory :param element: :return: """ return Warzone.TERRITORY_IDENTIFIER in element.get_id()
e2a00e223884f0704a8b03524079e6aecf302d19
42,891
def lowfirst(string): """ Make the first letter of a string lowercase (counterpart of :func:`~django.utils.text.capfirst`, see also :templatefilter:`capfirst`). :param string: The input text :type string: str :return: The lowercase text :rtype: str """ return string and str(string)...
f877129f9225e84989fc70d096b01715a2287373
42,892
import requests def get_snapchat_access_token(snap_credentials): """Generate short-lived snapchat access token""" access_url = 'https://accounts.snapchat.com/login/oauth2/access_token' access_params = { 'client_id': snap_credentials['client_id'], 'client_secret': snap_credentials['client_s...
3681afbc82fabef6d34e5b671bd51d1bae1eb591
42,893
def FindSat(ephem, times, gpsweek): # Satloc contains both positions and velocities. """ # Original in ECE456_orbitutils.py. #NOTE: Ask Ashwin for original source # Function to coarse calculate satellite positions given the GPS almanac. # The calculation can be performed for multiple satellites with...
254ad7af7895024d07adda590746c64e9d9a10f1
42,894
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" xml = dumps(data) # simplexml lacks ability to insert encoding and standalone, # so this is a hack xml_with_headers = "%s%s%s" % (xml[0:20], 'encoding="utf-8" standalone=...
40a26b0f23aea40a95ff6d940c84155afeff29d3
42,895
def plot_box(points_horizon, img_obj): """ Based on the crosspoints to extract the grids :param points_horizon: horizon crosspoints :param img_obj: the class of img :return: """ #################################################################################################################...
90a18f9a14ecb30b7c38b580152d201ba12654c7
42,896
def priority(profile): """ function : to set priority level based on certain age group input : id, age, infection_status (0 means not infected , 1 means infected) , coordinates, residency output : priority level : local_high(6), local_medium(5) , local_low (4), foreign(3), foreign(2) ,foreign(1)...
dae951efb11f8988cb32910e708bb4f69d8a3ed0
42,897
from typing import Sequence def _compile1_next_statement_with_mods(statements: Sequence[Statement]) -> (IFElement, int): """Returns the IFElements and the number of statements read""" main_statement = statements[0] if main_statement.matches_pattern(TEXT_PATTERN): ifelement = IFText(main_statement...
01aaebeecd3b305f3ac4c26ebeb9a06427ccd67b
42,898
def build_selection(stage_name, config, weights=[]): """Creates event selectors based on the configuration. Parameters: stage_name: Used to help in error messages. config: The event selection configuration. weights: How to weight events, used to produce the resulting cut eff...
300f88c2544da9cf0313ec431b8944f062d1e91c
42,899