content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def scorer(func): """This function is a decorator for a scoring function. This is hack a to get around self being passed as the first argument to the scoring function.""" def wrapped(a, b=None): if b is not None: return func(b) return func(a) return wrapped
39ec390982d26d10a6ce827800df654ff6c4ab42
3,654,700
def print_stats(yards): """ This function prints the final stats after a skier has crashed. """ print print "You skied a total of", yards, "yards!" #print "Want to take another shot?" print return 0
72b56bf8cfb0691636e41ccfcfe9b3893ab870eb
3,654,701
def _calculate_risk_reduction(module): """ Function to calculate the risk reduction due to testing. The algorithms used are based on the methodology presented in RL-TR-92-52, "SOFTWARE RELIABILITY, MEASUREMENT, AND TESTING Guidebook for Software Reliability Measurement and Testing." Rather than at...
c8876bc247243f13572d49c07063a063ba4eb42a
3,654,702
def run_metarl(env, test_env, seed, log_dir): """Create metarl model and training.""" deterministic.set_seed(seed) snapshot_config = SnapshotConfig(snapshot_dir=log_dir, snapshot_mode='gap', snapshot_gap=10) runner = LocalRunner(...
adc4041539d55d9cddba69a44a0d0fcfbbc1c16e
3,654,703
from ..nn.nn_modifiers import get_single_nn_mutation_op def get_default_mutation_op(dom): """ Returns the default mutation operator for the domain. """ if dom.get_type() == 'euclidean': return lambda x: euclidean_gauss_mutation(x, dom.bounds) elif dom.get_type() == 'integral': return lambda x: integral_...
8e9455ca96dac89b11bebcc3e4f779f62111a010
3,654,704
import itertools def chunked(src, size, count=None, **kw): """Returns a list of *count* chunks, each with *size* elements, generated from iterable *src*. If *src* is not evenly divisible by *size*, the final chunk will have fewer than *size* elements. Provide the *fill* keyword argument to provide a p...
6f35735d9294f4c245643609641fb86b0f988fb1
3,654,705
def doc_to_schema_fields(doc, schema_file_name='_schema.yaml'): """Parse a doc to retrieve the schema file.""" return doc_to_schema(doc, schema_file_name=schema_file_name)[ 'schema_fields']
b9d88f52ff49e43cae0ad5373a8d841f0236bb50
3,654,706
from typing import Tuple from typing import OrderedDict from typing import Counter import tqdm def cluster(df: pd.DataFrame, k: int, knn: int = 10, m: int = 30, alpha: float = 2.0, verbose0: bool = False, verbose1: bool = False, verbose2: bool = True, plot: bool = True) -> Tuple[pd.DataFrame, OrderedDict]...
2363df84104da1f182c63faaac21006033e23083
3,654,707
def get_CIFAR10_data(num_training=49000, num_validation=1000, num_test=1000): """ Load the CIFAR-10 dataset from disk and perform preprocessing to prepare it for the two-layer neural net classifier. These are the same steps as we used for the SVM, but condensed to a single function. """ # Load...
515777ca498ae9a234a1503660f2cde40f0b0244
3,654,708
def timeframe_int_to_str(timeframe: int) -> str: """ Convert timeframe from integer to string :param timeframe: minutes per candle (240) :return: string representation for API (4h) """ if timeframe < 60: return f"{timeframe}m" elif timeframe < 1440: return f"{int(timeframe / ...
75778742dea8204c74a47bfe92c25aef43ebbad8
3,654,709
def FIT(individual): """Sphere test objective function. F(x) = sum_{i=1}^d xi^2 d=1,2,3,... Range: [-100,100] Minima: 0 """ y=sum(x**2 for x in individual) return y
d6aadf620f85bd9cb27cef661e2ec664a4eb43b1
3,654,710
def update_range(value): """ For user selections, return the relevant range """ global df min, max = df.timestamp.iloc[value[0]], df.timestamp.iloc[value[-1]] return 'timestamp slider: {} | {}'.format(min, max)
c4819b46cdd78be3c86fc503791a7a0ff9cd96b3
3,654,711
def simplify(tile): """ :param tile: 34 tile format :return: tile: 0-8 presentation """ return tile - 9 * (tile // 9)
c8543d73e37d4fa1d665d3d28277ff99095e0635
3,654,712
def vep(dataset, config, block_size=1000, name='vep', csq=False) -> MatrixTable: """Annotate variants with VEP. .. include:: ../_templates/req_tvariant.rst :func:`.vep` runs `Variant Effect Predictor <http://www.ensembl.org/info/docs/tools/vep/index.html>`__ with the `LOFTEE plugin <https://github...
e9433db17e82d00aba275066026a301a9b97e5e0
3,654,713
def __get_ll_type__(ll_type): """ Given an lltype value, retrieve its definition. """ res = [llt for llt in __LL_TYPES__ if llt[1] == ll_type] assert len(res) < 2, 'Duplicate linklayer types.' if res: return res[0] else: return None
f2e86ddd027ec26546a4be8ff8060c1cd8c64aca
3,654,714
import os import logging def is_cloaked(path, names): """ Return True if this is likely to be a cloaked encrypted post """ fname = unicoder(os.path.split(path)[1]).lower() fname = os.path.splitext(fname)[0] for name in names: name = os.path.split(name.lower())[1] name, ext = os.path.sp...
69a6ccacd9a26adcba64fa84ede25074594a27bc
3,654,715
def slice_node(node, split): """Splits a node up into two sides. For text nodes, this will return two text nodes. For text elements, this will return two of the source nodes with children distributed on either side. Children that live on the split will be split further. Parameters -------...
5958afbb61160f7e00c42e80c4c69aa7f8644925
3,654,716
def k_radius(x,centroids): """ Maximal distance between centroids and corresponding samples in partition """ labels = partition_labels(x,centroids) radii = [] for idx in range(centroids.shape[0]): mask = labels == idx radii.append( np.max( np.linalg.n...
de010609e726ce250d72d773a9c1ffb772315b0c
3,654,717
def build_feature_df(data, default=True, custom_features={}): """ Computes the feature matrix for the dataset of components. Args: data (dataset): A mapping of {ic_id: IC}. Compatible with the dataset representaion produced by load_dataset(). default (bool, optional): Determines wether to c...
bbd2543a5043ae11305fe86449778a74f7e7ceb3
3,654,718
def update_uid_digests_cache(uid, digest): """ Updates uid_digest cache, also updates rd_digest and rd_digest_dict cache also. """ debug = False try: if debug: print '\n debug -- Entered update_uid_digests_cache...' dump_dict(digest, debug) # Get the cache; I...
841d1b2517594175867b970e0e1af4631d97d9c7
3,654,719
def decode_complex(data, complex_names=(None, None)): """ Decodes possibly complex data read from an HDF5 file. Decodes possibly complex datasets read from an HDF5 file. HDF5 doesn't have a native complex type, so they are stored as H5T_COMPOUND types with fields such as 'r' and 'i' for the real and ...
4c2fad09751ddfe4c5623d47a187f710ab62532f
3,654,720
def CLYH( directed = False, preprocess = "auto", load_nodes = True, load_node_types = True, load_edge_weights = True, auto_enable_tradeoffs = True, sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None, cache_sys_var = "GRAPH_CACHE_DIR", version = "2020-05-29", **kwargs ) -> Graph: """Re...
6dcddfff1411ea71d1743fabde782066c41ace9f
3,654,721
def tif_to_array( filename, image_descriptions=False, verbose=False, ): """Load a tif into memory and return it as a numpy array. This is primarily a tool we use to interact with ImageJ, so that's the only case it's really been debugged for. I bet somebody made nice python bindings for ...
db81009b9a3ccc6238bf605a56247e38586fc134
3,654,722
def lineParPlot(parDict, FigAx=None, **kwargs): """ Plot the results of lineParameters(). Parameters ---------- parDict : dict The relevant parameters: xPerc : tuple, (xPerc1, xPerc2) Left and right x-axis values of the line profile at perc% of the peak flux. Xc ...
4767446fb983902ea0a3ce631420c61f032970f9
3,654,723
def prepare_data_arrays(tr_df, te_df, target): """ tr_df: train dataset made by "prepare_dataset" function te_df: test dataset made by "prepare_dataset" function target: name of target y return: (numpy array of train dataset), (numpy array of test dataset: y will be filled with NaN), ...
097f376263dfeecffaf201f4ea1cd29980d88746
3,654,724
import tempfile import os def download_git_repo(repo: str): """ Download remote git repo """ local_filename = repo.split('/')[-1] class CloneProgress(RemoteProgress): def update(self, op_code, cur_count, max_count=None, message=''): if message: print(message) ...
7d2b6b1bcadb9d0a8ed8baae9ec4576c67b9099a
3,654,725
def plot(model_set, actual_mdot=True, qnuc=0.0, verbose=True, ls='-', offset=True, bprops=('rate', 'fluence', 'peak'), display=True, grid_version=0): """Plot predefined set of mesa model comparisons model_set : int ID for set of models (defined below) """ mesa_info = get_mesa_set(model...
2ceec63d162fe07dd4a00a508657095528243421
3,654,726
import os import shutil def main(): """Main documentation builder script.""" parser = ArgumentParser( description="build GGRC documentation", ) parser.add_argument( '-c', '--clean', action='store_true', default=False, help='clean cache before build', dest='clean', ) par...
9c193e70df24c1b1431d0eea9809b3d07baf0c62
3,654,727
def preprocessing_fn(batch): """ Standardize, then normalize sound clips """ processed_batch = [] for clip in batch: signal = clip.astype(np.float64) # Signal normalization signal = signal / np.max(np.abs(signal)) # get pseudorandom chunk of fixed length (from SincNe...
d277cd95d174e1ec104a8b8a8d72e23e2dd7f991
3,654,728
def generate_random_bond_list(atom_count, bond_count, seed=0): """ Generate a random :class:`BondList`. """ np.random.seed(seed) # Create random bonds between atoms of # a potential atom array of length ATOM_COUNT bonds = np.random.randint(atom_count, size=(bond_count, 3)) # Clip bond ty...
cb7784f8561be2ea7c54d5f46c2e6e697164b1b8
3,654,729
def open_cosmos_files(): """ This function opens files related to the COSMOS field. Returns: A lot of stuff. Check the code to see what it returns """ COSMOS_mastertable = pd.read_csv('data/zfire/zfire_cosmos_master_table_dr1.1.csv',index_col='Nameobj') ZF_cat = ascii.read('d...
229aa967dce5faaf42b488ebf2768b280ced9359
3,654,730
import numpy def convert_image_points_to_points(image_positions, distances): """Convert image points to 3d points. Returns: positions """ hypotenuse_small = numpy.sqrt( image_positions[:, 0]**2 + image_positions[:, 1]**2 + 1.0) ratio = distances / hypotenuse_small n = ...
3680a02997cf1109fd08f61c6642b29ea3433f1d
3,654,731
def W(i, j): """The Wilson functions. :func:`W` corresponds to formula (2) on page 16 in `the technical paper`_ defined as: .. math:: W(t, u_j)= \\ e^{-UFR\cdot (t+u_j)}\cdot \\ \left\{ \\ \\alpha\cdot\min(t, u_j) \\ -0.5\cdot e^{-\\...
37266db68fb51a87f15290edae06eb6397796b6f
3,654,732
from scipy.interpolate import interp1d def reddening_fm(wave, ebv=None, a_v=None, r_v=3.1, model='f99'): """Determines a Fitzpatrick & Massa reddening curve. Parameters ---------- wave: ~numpy.ndarray wavelength in Angstroms ebv: float E(B-V) differential extinction; specify eithe...
1f47b360044613c9bbb18bf3446bcd7e3ad20344
3,654,733
def list_registered_stateful_ops_without_inputs(): """Returns set of registered stateful ops that do not expect inputs. This list is used to identify the ops to be included in the state-graph and that are subsequently fed into the apply-graphs. Returns: A set of strings. """ return set([ name ...
aa089bc4157c6a3c36121c6e880ffbd546723f0e
3,654,734
def load_frame_from_video(path: str, frame_index: int) -> np.ndarray: """load a full trajectory video file and return a single frame from it""" vid = load_video(path) img = vid[frame_index] return img
7b8747df38dfcf1f2244166002126d6d25170506
3,654,735
from typing import Dict from typing import List def get_settings_patterns(project_id: int) -> Dict[str, str]: """Returning project patterns settings""" track_patterns: List[Dict[str, str]] = ProjectSettings.objects.get(project_id=project_id).trackPatterns return {pattern['pattern']: pattern['regex'] for p...
d566ad5ec2fd72e2384fea90aa9cae9d99d9f441
3,654,736
def video_to_array(filepath): """Process the video into an array.""" cap = cv2.VideoCapture(filepath) num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) channel = 3 frame_buffer = np.empty((num_frames, height...
2034ce56c7ca4fe61d0e0eb443c6fa9910d8a232
3,654,737
from unittest.mock import Mock async def test_10_request(requests_mock: Mock) -> None: """Test `async request()`.""" result = {"result": "the result"} rpc = RestClient("http://test", "passkey", timeout=0.1) def response(req: PreparedRequest, ctx: object) -> bytes: # pylint: disable=W0613 ass...
fa9e03d5b3f5a4f594db29eae057607f790e158c
3,654,738
def entmax15(X, axis=-1, k=None): """1.5-entmax: normalizing sparse transform (a la softmax). Solves the optimization problem: max_p <x, p> - H_1.5(p) s.t. p >= 0, sum(p) == 1. where H_1.5(p) is the Tsallis alpha-entropy with alpha=1.5. Parameters ---------- X : paddle.Tensor ...
08887ec5aff323077ea6ea99bf6bd2b83bb4cc19
3,654,739
def get_dependency_graph(node, targets=None): """Returns the dependent nodes and the edges for the passed in node. :param str node: The node to get dependencies for. :param list targets: A list with the modules that are used as targets. :return: The dependency graph info. :rtype: GraphInfo """...
39667e034379477086062a9032f5007c12aba30e
3,654,740
from pathlib import Path def is_submodule_repo(p: Path) -> bool: """ """ if p.is_file() and '.git/modules' in p.read_text(): return True return False
26675ee25e431778325081ec80d45ff3d72c2046
3,654,741
def shift_contig(df2, remove): """ The function append shifted fragment from sort_cluster_seq function. Parameters ---------- df2 : pandas DataFrame DataFrame NRPS cluster fragment. remove : list List of cluster fragment, which should removed. Returns ------- df...
7df891785fc58d818af5b423c7fdbc3c4382951f
3,654,742
import matplotlib as mpl def get_color_cycle(n=None): """Return the matplotlib color cycle. :param Optional[int] n: if given, return a list with exactly n elements formed by repeating the color cycle as necessary. Usage:: blue, green, red = get_color_cycle(3) """ cycle...
f19393d9a5c61ab158517261c258cc46b7a9701b
3,654,743
def _bocs_consistency_mapping(x): """ This is for the comparison with BOCS implementation :param x: :return: """ horizontal_ind = [0, 2, 4, 7, 9, 11, 14, 16, 18, 21, 22, 23] vertical_ind = sorted([elm for elm in range(24) if elm not in horizontal_ind]) return x[horizontal_ind].reshape((I...
bd8fe5261e024f5d5cdf1a2d77229dd564d947bf
3,654,744
def get_document(name, key): """Get document from Database""" constructor = Constructor() inst_coll = constructor.factory(kind='Collection', name=name) inst_doc = Document(inst_coll) doc = inst_doc.get_document(key) return doc
acd4e8117c0002d323a4fad79704a33437481657
3,654,745
from datetime import datetime import json def predict() -> str: """predict the movie genres based on the request data""" cur = db_connection.cursor() try: input_params = __process_input(request.data) input_vec = vectorizer.transform(input_params) prediction = classifier.predict(inp...
0ae49a8ab05d1df1c0beb07f322262a7a7ac8ee2
3,654,746
def SignificanceWeights(serializer, decay): """Multiplies a binary mask with a symbol significance mask.""" def significance_weights(mask): # (repr,) -> (batch, length, repr) # significance = [0, 1, 2] significance = serializer.significance_map assert significance.shape[0] == mask.shape[2] # sig...
545ac45149b8653f502d2dd864f92a40ee5919cb
3,654,747
def check_fun_inter_allocation(fun_inter, data, **kwargs): """Check allocation rules for fun_inter then returns objects if check""" out = None check_allocation_fun_inter = get_allocation_object(data, kwargs['xml_fun_inter_list']) if check_allocation_fun_inter is None: check_fe = check_fun_elem_d...
61f17844953f3260a23aff35a2f090a028dd9212
3,654,748
from typing import Optional def kernel_bw_lookup( compute_device: str, compute_kernel: str, caching_ratio: Optional[float] = None, ) -> Optional[float]: """ Calculates the device bandwidth based on given compute device, compute kernel, and caching ratio. Args: compute_kernel (str)...
efd70d5c2e5fc9295bccbfb05113474ac40ff1c9
3,654,749
import ctypes def spkltc(targ, et, ref, abcorr, stobs): """ Return the state (position and velocity) of a target body relative to an observer, optionally corrected for light time, expressed relative to an inertial reference frame. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkltc_c.h...
e3c701e7e9b2c15d5b182bd4fff395a2cbf5d849
3,654,750
def create_container( container_image: str, name: str = None, volumes: t.List[str] = None, ) -> str: """Create a new working container from provided container image. Args: container_image (str): The container image to start from. name (str, optional): The container name. vol...
be50e84169e5d3df5dfd9730493d7daa9788049b
3,654,751
def single_data_path(client, node_id): """ In order for a shrink to work, it should be on a single filesystem, as shards cannot span filesystems. Return `True` if the node has a single filesystem, and `False` otherwise. :arg client: An :class:`elasticsearch.Elasticsearch` client object :rtype:...
ae0b34f82acb6d12faf525f0270250cdf471a6f8
3,654,752
def sortorder(obj): """ Trys to smartly determine the sort order for this object ``obj`` """ if hasattr(obj, 'last'): return obj.last.timestamp() if isinstance(obj, str): # First assume pure numeric try: return float(obj) except ValueError: pa...
674ee77a87ccd7a0bd89a88b88a2682926a1135e
3,654,753
import json import re def get_more_details_of_post(post_url: str) -> json: """ :param post_url: the url of an imgur post :return: Details like Virality-score, username etc in JSON format """ details = {} try: request = HTMLSession().get(post_url) # some times, request isn't pr...
dd3d622c8a7e8f61daf24c2d0cc6752323d4693e
3,654,754
import struct import hmac import hashlib def subkey_public_pair_chain_code_pair(public_pair, chain_code_bytes, i): """ Yield info for a child node for this node. public_pair: base public pair chain_code: base chain code i: the index for this node. Returns a pair (new_...
8f31eb0ae3b063964ff46bcf6c78431d39d0e2ba
3,654,755
from typing import Optional def get_registry_description(metaprefix: str) -> Optional[str]: """Get the description for the registry, if available. :param metaprefix: The metaprefix of the registry :return: The description for the registry, if available, otherwise ``None``. >>> get_registry_descripti...
12b7aac7f880d6699ca85add1065eca49a06d278
3,654,756
import tqdm def evaluate(model, valid_exe, valid_ds, valid_prog, dev_count, metric): """evaluate """ acc_loss = 0 acc_top1 = 0 cc = 0 for feed_dict in tqdm.tqdm( multi_device(valid_ds.generator(), dev_count), desc='evaluating'): if dev_count > 1: loss, top1 = valid_...
7b228e7cadd71ec1ac31436767b92c4dadb5ec53
3,654,757
def _get_rank(player): """Get the rank of a player""" cursor = _DB.cursor() try: cursor.execute("SELECT score FROM scores WHERE player = ?", (player.lower(),)) rows = cursor.fetchall() if not rows: return 0 ps = rows[0][0] cursor.execute("SELECT count(*) F...
e556b9fb75f6b40c8c1be8759255dfc5953a1e9a
3,654,758
import os def getDataFromFileList(filedir): """ Reads all data from each file to one big data set ordered as: [[info],[[residue],[data]]] """ data = [] filelist =os.listdir(filedir) print("Loading data from data dir\n") if len(filelist)>0: print("DataFiles included:\n ----------------------------------") ...
7314aee3defcd72a6b7e7edbdd8be57393de39c5
3,654,759
import pydoc def spec(func): """return a string with Python function specification""" doc = pydoc.plain(pydoc.render_doc(func)) return doc.splitlines()[2]
00b96364f77141fedd7d50396946fd4e29cc5d02
3,654,760
def brm_weights(P, r, Γ, X): """Bellman-residual minimization fixed-point weights. TODO: Need to actually go through the details to make sure this is right """ assert linalg.is_stochastic(P) assert X.ndim == 2 assert len(X) == len(P) ns = len(P) Γ = as_diag(Γ, ns) Λ = as_diag(Λ, ns)...
a4392f9d33a2cdddd2af5b0002af3a750fd64ab8
3,654,761
import os import time def file_age(file_name): """ Returns the age of a file in seconds from now. -1 if the file does not exist. :param file_name: file name .. versionadded:: 9.3.1 """ if not os.path.exists(file_name): return -1 return time.time() - os.path.getmtime(file_name)
9cefc1da2f7ab1c44fbe9dc4f63a5d51bc088ab8
3,654,762
import posixpath def IsVirus(mi, log): """Test: a virus is any message with an attached executable I've also noticed the viruses come in as wav and midi attachements so I trigger on those as well. This is a very paranoid detector, since someone might send me a binary for valid reasons. I white-...
e30e91951ad49395d87bef07926cfdff4d15b3e2
3,654,763
def to_curl(request, compressed=False, verify=True): """ Returns string with curl command by provided request object Parameters ---------- compressed : bool If `True` then `--compressed` argument will be added to result """ parts = [ ('curl', None), ('-X', request.me...
b462f62031f4fe757bb7a45b50ced9bc2ea6a9b5
3,654,764
def prox_trace_indicator(a, lamda): """Time-varying latent variable graphical lasso prox.""" es, Q = np.linalg.eigh(a) xi = np.maximum(es - lamda, 0) return np.linalg.multi_dot((Q, np.diag(xi), Q.T))
85d6cb26c7a35dbab771e0a9f9c8979fba90e680
3,654,765
def get_gamma_non_jitted(esys): """Get log gamma Returns ------- float[:] """ if isinstance(esys.species[0].logc, float): v = np.empty(len(esys.species)) else: v = np.empty(len(esys.species), dtype=object) for i, sp in enumerate(esys.species): v[i] = 10.0 ** (sp....
f3d7f4b96676a10b7065196aac247006019da31e
3,654,766
def active_matrices_from_extrinsic_euler_angles( basis1, basis2, basis3, e, out=None): """Compute active rotation matrices from extrinsic Euler angles. Parameters ---------- basis1 : int Basis vector of first rotation. 0 corresponds to x axis, 1 to y axis, and 2 to z axis. ...
50218d9ce2296e3c4952cc77fe64e30c19e03f77
3,654,767
import sys import logging import traceback def save(image, parent=None): """ Save an image with appropriate dialogs (file selector) Return the chosen save path or None parent : parent wx Window for dialogs """ dialog = ImageFileDialog(parent, style=wx.FD_SAVE|wx.FD_OVERW...
83bc917f8fe21442712b0a8979bb9e8ddfdd80a7
3,654,768
def runQuery(scenarioID): """ Run a query that aquires the data from the lrs for one specific dialoguetrainer scenario \n :param scenarioID: The id of the scenario to request the data from \t :type scenarioID: int \n :returns: The data for that scenario or error \t :rtype: [Dict<string, mixe...
0f57a4468354680b315a65263593979149bdb186
3,654,769
def is_spaceafter_yes(line): """ SpaceAfter="Yes" extracted from line """ if line[-1] == "_": return False for ddd in line[MISC].split("|"): kkk, vvv = ddd.split("=") if kkk == "SpaceAfter": return vvv == "Yes" raise ValueError
5693c8874ec9676bf19d9b1cb7ead5c1772a3f0b
3,654,770
def linear_scheduler(optimizer, warmup_steps, training_steps, last_epoch=-1): """linear_scheduler with warmup from huggingface""" def lr_lambda(current_step): if current_step < warmup_steps: return float(current_step) / float(max(1, warmup_steps)) return max( 0.0, ...
d9446ede5be0ed981ae00b0bccd494017057d834
3,654,771
from functools import reduce import operator from re import X def MajorityVoteN(qubits, nrounds, prep=[], meas_delay=1e-6, add_cals=False, calRepeats=2): """ Majority vote across multiple measurement results (same or dif...
7bc3b6161d5224ed7adf9248b32b0bd283f50c70
3,654,772
def getRatios(vect1, vect2): """Assumes: vect1 and vect2 are equal length lists of numbers Returns: a list containing the meaningful values of vect1[i]/vect2[i]""" ratios = [] for index in range(len(vect1)): try: ratios.append(vect1[index]/vect2[index]) excep...
e28f871986ab2b1b87cc3671b1c27ad14a0aadf8
3,654,773
def sampleset(): """Return list with 50 positive and 10 negative samples""" pos = [(0, i) for i in range(50)] neg = [(1, i) for i in range(10)] return pos + neg
77e5a0ca3ad8757f0ded2aec9d73312a66ac9044
3,654,774
def recognize_emotion(name, mode, dataset): """ The main program for building the system. And we support following kinds of model: 1. Convolutional Neural Network (CNN) 2. Support Vector Machine (SVM) 3. Adaboost 4. Multilayer Perceptron (MLP) Args: ...
eae092866f5190a637bbdb08c4ad7188b9cb88f3
3,654,775
def feedback(request): """ Feedback page. Here one can send feedback to improve the website further. """ return render(request, "groundfloor/common/feedback.html", context = None)
8dd9f8ae57ca49629820c58b54c7d98d705597bb
3,654,776
from typing import Tuple def fill_nodata_image(dataset: xr.Dataset) -> Tuple[np.ndarray, np.ndarray]: """ Interpolate no data values in image. If no mask was given, create all valid masks :param dataset: Dataset image :type dataset: xarray.Dataset containing : - im : 2D (row,...
c245f0cbfbb79737fb85b9b8fb8381aad6373926
3,654,777
def find(value, a_list): """ TestCase for find >>> find(26, [12,14]) True >>> find(40, [14, 15, 16, 4, 6, 5]) False >>> find(1, [1]) False >>> find(1, []) False >>> find(4, [2, 3, 2]) True """ # 现将列表变为<value, index>字典 if a_list is None or len(a_list) < 2: ...
dd466a8ffa0c760ed0af9ad109b5f4e3b85a62db
3,654,778
def transform_bbox( bbox, source_epsg_code, target_epsg_code, all_coords=False ): """ Transform bbox from source_epsg_code to target_epsg_code, if necessary :returns np.array of shape 4 which represent the two coordinates: left, bottom and right, top. When `all_coords` is set to...
cd6938b2dfcc02fe9c2a323e2b60339de216dd26
3,654,779
def distance_metric(vector1, vector2): """ Returns a score value using Jaccard distance Args: vector1 (np.array): first vector with minHash values vector2 (np.array): second vector with minHash values Returns: float: Jaccard similarity """ return distance.pdist(np.array([ve...
e1acbc9eff7ee8bc78be0307acacbca9e9d69265
3,654,780
from datetime import datetime def update_calendar(request): """ to update an entry to the academic calendar to be updated. @param: request - contains metadata about the requested page. @variables: from_date - The starting date for the academic calendar event. to_date - The en...
804f3f0443d192c0c18a501c40808f2406596491
3,654,781
def get_section(entry: LogEntry) -> str: """returns the section of the request (/twiki/bin/edit/Main -> /twiki)""" section = entry.request.split('/')[:2] return '/'.join(section)
dee463b5a662846da01fc2ef8d1c72c5b582e7e5
3,654,782
def reverse_lookup(d, v): """ Reverse lookup all corresponding keys of a given value. Return a lisy containing all the keys. Raise and exception if the list is empty. """ l = [] for k in d: if d[k] == v: l.append(k) if l == []: raise ValueError else: ...
d68f437aec47df964905779f99d58be84515fb72
3,654,783
def compile_channels_table(*, channels_meta, sources, detectors, wavelengths): """Compiles a NIRSChannelsTable given the details about the channels, sources, detectors, and wavelengths. """ table = NIRSChannelsTable() for channel_id, channel in channels_meta.items(): source_label = sources.l...
ac3099ef0440962b3fbfeec36f01ae92061b5693
3,654,784
from pathlib import Path def cpe2pkg_tool(): """Unsupported ecosystem CVE fixture.""" bin = Path(__file__).parent.parent / Path('tools/bin/cpe2pkg.jar') if bin.exists(): return str(bin) else: raise RuntimeError('`cpe2pkg.jar` is not available, please run `make build-cpe2pkg once.`')
7ad5489cd560f2820a5e77c46964514a5a34edc9
3,654,785
import threading def spawn_thread(func, *args, **kwds): """ Utility function for creating and starting a daemonic thread. """ thr = threading.Thread(target=func, args=args, kwargs=kwds) thr.setDaemon(True) thr.start() return thr
afaace7e02870390acb297106ac9d35c9a931a59
3,654,786
import sys def decision(question): """Asks user for a question returning True/False answed""" if sys.version_info[0] < 3: if raw_input("\n%s [Y/n] " % question) in ["", "y", "Y"]: return True else: if input("\n%s [Y/n] " % question) in ["", "y", "Y"]: return True ...
8d31e2f11ad9aa2d0d35f35078ffb46ca0718f09
3,654,787
import uuid def get_thread_replies(parent_id): """ Get all replies to a thread If the thread does not exist, return an empty list :param parent_id: Thread ID :return: replies to thread """ assert type(parent_id) is uuid.UUID, """parent_id is not correct type""" reply_query = Query() ...
1b167dcc4ab09d50cda9feb478c8f1a4d0399e96
3,654,788
import torch def compute_acc(pred, labels): """ Compute the accuracy of prediction given the labels. """ return (torch.argmax(pred, dim=1) == labels).float().sum() / len(pred)
1b1ad83b9b4ae06f2bc80209e4e7339a421a39f3
3,654,789
async def read_update_status() -> str: """Read update status.""" return ( await cache.get(Config.update_status_id()) if await cache.exists(Config.update_status_id()) else "ready_to_update" )
0e80f7065665dbe1a41e59fe7c65904e58bb6d8f
3,654,790
def _login_and_select_first_active_device(api): """Login Erie Connect and select first active device""" # These do i/o _LOGGER.debug(f'{DOMAIN}: erie_connect.login()') api.login() _LOGGER.debug(f'{DOMAIN}: erie_connect.select_first_active_device()') api.select_first_active_device() if ( ...
1733db73978b8a2c92400946b6c044ab3bb4ab23
3,654,791
def PCopy (inFA, err): """ Make copy an GPUFArray returns copy * inFA = input Python GPUFArray * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inFA): print("Actually ",inFA.__class_...
df1047dc143fb5f8d8f4fd88a2b1ebc0904620a2
3,654,792
def _get_statuses(policy_type_id, policy_instance_id): """ shared helper to get statuses for an instance """ _instance_is_valid(policy_type_id, policy_instance_id) prefixes_for_handler = "{0}{1}.{2}.".format(HANDLER_PREFIX, policy_type_id, policy_instance_id) return list(SDL.find_and_get(A1NS, p...
fdddc26d3c2b65834d4b047a5565894b0d965f9d
3,654,793
def phase_lines(graph): """ Determines the phase lines of a graph. :param graph: Graph :return: dictionary with node id : phase in cut. """ if has_cycles(graph): raise ValueError("a cyclic graph will not have phaselines.") phases = {n: 0 for n in graph.nodes()} q = graph.nodes(in_deg...
9f1aab9e487bd258c88b0f149bcf613341945879
3,654,794
import os import webbrowser import requests def creds() -> Account: """Load or obtain credentials for user.""" credentials = "8da780f3-5ea0-4d97-ab13-9e7976370624" protocol = MSGraphProtocol(timezone="Europe/Stockholm") scopes = protocol.get_scopes_for(SCOPES) token_backend = FileSystemTokenBacke...
d8e1e547d1db443723a58bb583584ede03fe4bd5
3,654,795
import base64 def b64decode_str(b64string): """ Decodes an arbitrary string from a base 64 ASCII string """ output = base64.b64decode(b64string).decode("UTF-8") logger.debug("Decoded %s as %s", b64string, output) return output
26475a5380e0a535a9ec12146d0f6e4236d20495
3,654,796
def BCELossConfig(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :returns: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = """Creates a criterion that measures the Binary Cross E...
d0108459bdad9b2f6fad438bff542624b482ef7d
3,654,797
def gen_cities_avg(climate, multi_cities, years): """ Compute the average annual temperature over multiple cities. Args: climate: instance of Climate multi_cities: the names of cities we want to average over (list of str) years: the range of years of the yearly averaged temperature ...
9609add6a1514d09b42e2494e56c84522d3cb364
3,654,798
def tangentVectorsOnSphere( points, northPole = np.array([0.0,0.0,1.0]) ): """ Acquire a basis for the tangent space at given points on the surface of the unit sphere. :param points: N x 3 array of N points at which to acquire basis of tangent space. :param northPole: 3 array of point correspondin...
bfa23a393ac4d1b38c6c2b19207520db1bd83e03
3,654,799