content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def align_data(data): """Given dict with lists, creates aligned strings Args: data: (dict) data["x"] = ["I", "love", "you"] (dict) data["y"] = ["O", "O", "O"] Returns: data_aligned: (dict) data_align["x"] = "I love you" data_align["y"] = "O O O " """ spac...
6be0d9854cf73b4c44a91b2bbe6b4ac1bb76157e
35,900
def average_surface_distance(mflo, mref): """ average on points so not reliable if the sampling is unhomogeneous """ pd = polydata_distance(mflo, mref, do_signed=False) xv = pd.GetPointData().GetArray("Distance") xn = nps.vtk_to_numpy(xv) return xn.mean()
42e17183d58f05b1c4810f8d995b57e5b24a7bf8
35,901
def CleanUserUrl(user_url: str) -> str: """清理 user_url,去除其中的空格和无用参数 """ user_url = user_url.strip() return user_url.split("?")[0]
7c5c2cf5879d4ddfdbd1a60a679a747f162ebe35
35,902
def get_aqi_pb_24h(pb_24h: float) -> (int, str, str): """ Calculates Pb (24h) India AQI :param pb_24h: Pb average (24h), ppm :return: Pb India AQI, Effect message, Caution message """ cp = __round_down(pb_24h * 1000, 3) return __get_aqi_general_formula_texts(cp, IN_PB_24H, IN_AQI_EFFECTS, I...
dbd8beadaf57c5a14b1f91854cf004f877389ec4
35,903
from typing import Union def check_integrity(hdpgroup: list, verbose: bool = False, enforce: bool = False) -> Union[list, bool]: """Check integrity (comprare checksums) non-proposital data corruption Args: hdpgroup (list): [description] verbose (bool, o...
24a572fb9ec7bf19830f8edb3f505d61216ce053
35,904
def id_to_ec2_snap_id(snapshot_id): """Get or create an ec2 volume ID (vol-[base 16 number]) from uuid.""" if uuidutils.is_uuid_like(snapshot_id): ctxt = context.get_admin_context() int_id = get_int_id_from_snapshot_uuid(ctxt, snapshot_id) return id_to_ec2_id(int_id, 'snap-%08x') els...
d13a1a4c608c0baf8727a2b5c1d928b8722f71f7
35,905
def delete_nonestimator_parameters(parameters): """Delete non-estimator parameters. Delete all parameters in a parameter dictionary that are not used for the actual estimator. """ if 'Number' in parameters.keys(): del parameters['Number'] if 'UsePCA' in parameters.keys(): del p...
d84984d182a5945167b8e7880e493aa8fad832b7
35,906
from pathlib import Path def get_gene_sequence(gene_name: Path) -> str: """Okay, I don't understand how this is suppose to work. \f Parameters ---------- gene_name : Return ------ seq : `str` """ try: with open(gene_name, "r") as f: seq = f.read() ...
1ec4b9a2945b3e14dc87ce440734799c87560906
35,907
def get_service(credentials): """Get the service object corresponding to GMail.""" http = credentials.authorize(httplib2.Http()) service = discovery.build('gmail', 'v1', http=http) user = service.users().getProfile(userId="me").execute() print("Authenticated user: {0}".format(user["emailAddress"])) ...
f59eaeb46a3f922855c9adc96a10ef2797ce8cbc
35,908
from typing import Optional from typing import Sequence def get_private_application_packages(display_name: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetPrivateApplicationPackagesFilterArgs']]] = None, package_types: Opt...
3dc97aa7d3fc27cc2cf12a797d7e7d364cffe210
35,909
def load_data(): """ :return: Data frame """ # load data engine = create_engine('sqlite:///data/disaster_response.db') df = pd.read_sql_table('disaster_response', engine) return df
231a0233d65717d4b171223d1870e2ba7c2822c4
35,910
def start_child_span( operation_name: str, tracer=None, parent=None, span_tag=None ): """ Start a new span as a child of parent_span. If parent_span is None, start a new root span. :param operation_name: operation name :param tracer: Tracer or None (defaults to opentracing.tracer) :param par...
e5465d45800560e601fde1d513c204d5ca1284de
35,911
def demslv08old(): """Nonlinear complementarity problem methods Solve nonlinear complementarity problem on R^2 using semismooth and minmax methods """ ''' function to be solved''' def f(z): x, y = z fval = np.array([200 * x * (y - x ** 2) + 1 - x, 100 * (x ...
4bf4b37ca8dbf7503443292996cfaf2a1ef4d368
35,912
from re import A import math def from_mercator(x, y): """Convert x,y coordinate from Spherical Mercator to lon, lat Ported from mercantile. Parameters ---------- x : float y : float Returns ------- (longitude, latitude) """ return (x * R2D / A, ((math.pi * 0.5) - 2.0 * ...
09a6a5ae85290fc230398de5ee0cfa28e8893366
35,913
def GetMaxIndex(tree): """get maximum node number.""" return tree.id
f443a9006765dface834aa9120c3ab38cd1d4369
35,914
def audit_name_starts_with(prefixes): """ Given a list of prefixes, returns a function that takes a folder and prints the folder path if the folder name does not start with one of the prefixes. """ def action(folder): if any(folder.name.startswith(prefix) for prefix in prefixes) == False: ...
886af28239aa989bed15d8f5a4462dd94cd1363b
35,915
def error_handler(error): """ Handle errors in views. """ return render('error.html'), 500
307846d8445f03ac8acb48585ccab5ffdbab972e
35,916
def save_work(work_id): """Save a work""" if not auth.session_user().can_manage_works: return Response('User not logged in or not authorized to manage works.', 401) if int(work_id) == -1: # New work work = Work() else: # Existing work work = Work.f...
296ed0eff93ea64b4541b4a84c62f8be673b6e89
35,917
def get_feedback_expertise_levels(): # noqa: E501 """Request a list of allowable expertise levels # noqa: E501 :rtype: ExpertiseLevels """ rtxFeedback = RTXFeedback() return rtxFeedback.getExpertiseLevels()
fc76ea2daf885159f4461ae694b7b68e203befdc
35,918
def get_coord_limits(coord): """get cooordinate limits""" lower_limit = float('.'.join([str(coord).split('.')[0], str(coord).split('.')[1][:2]])) if lower_limit > 0: upper_limit = lower_limit + 0.01 else: tmp = lower_limit - 0.01 upper_limit = lower_limit lower_limit = t...
803c0804e34a97d46a9555b4566be72949f55e8d
35,919
import torch def decode(loc, priors, use_yolo_regressors:bool=False): """ Decode predicted bbox coordinates using the same scheme employed by Yolov2: https://arxiv.org/pdf/1612.08242.pdf b_x = (sigmoid(pred_x) - .5) / conv_w + prior_x b_y = (sigmoid(pred_y) - .5) / conv_h + prior_y ...
8158b29c7557f1bde0e7873a6eace78d039c6d5d
35,920
def read_relative_file(filename): """Returns contents of the given file, whose path is supposed relative to this module.""" with open(join(dirname(abspath(__file__)), filename)) as f: return f.read()
b20d61e4ddc049c4beeacf106b04d30e3d0cc966
35,921
import torch import tqdm def get_activations(data_loader, model, device=None, batch_size=32, resize=False, n_samples=None): """Computes the activation of the given images Args: imgs: Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1] cuda: whether or not to run on GPU ...
2755bd34f05c3fb72f4c1da83bdb25d3df2f7662
35,922
from pathlib import Path def write( # Basic setup input_path, # preset_nickname=None, stream_name="", stream_description="", output_directory=None, output_mode="video", stream_name_file_output=False, max_cpu_cores=0, # Stream configurat...
f9b7335b5a4fe95d9f53631d78f2b1c9708d5eea
35,923
def shell_escape(string): """ Escape double quotes, backticks and dollar signs in given ``string``. For example:: >>> _shell_escape('abc$') 'abc\\\\$' >>> _shell_escape('"') '\\\\"' """ for char in ('"', '$', '`'): string = string.replace(char, '\\{}'.format...
03fcec5cdd99685e821fea11a69a234f3123fd9b
35,924
def boundary_and_obstacles(start, goal, top_vertex, bottom_vertex, obs_number): """ :param start: start coordinate :param goal: goal coordinate :param top_vertex: top right vertex coordinate of boundary :param bottom_vertex: bottom left vertex coordinate of boundary :param obs_number: number of ...
b0203b782e7655184c60d3a9e6c277ea880a2184
35,925
import logging import time def build_uncertain_table(args, scores, timestamp_list, image_path_list): """phase 3: build table from detection prediction""" logging.info('phase 3 start.') start = time.time() uncertain_scores = build_uncertain_table_fast(scores) save_uncertain_table(timestamp_list, u...
43edf61e10718dc6156060851fed3173ab47159f
35,926
import glob import os def get_current_phase(path): """Returns the current phase of the current iteration""" files = glob.glob(path + "/phase_*.sh") phases = [0] for file in files: file = os.path.basename(file) phase = file.split(".")[0] # -> phase_x phase_num = int(phase.split...
4f8f74fa4d71551c27f7757c28990a7b00fea55b
35,927
def mvg_logpdf_fixedcov(x, mean, inv_cov): """ Log-pdf of the multivariate Gaussian where the determinant and inverse of the covariance matrix are precomputed and fixed. Note that this neglects the additive constant: -0.5 * (len(x) * log(2 * pi) + log_det_cov), because it is irrelevant when comparin...
3b2d256d58f9dce655d8aae9e04f3f4f87030981
35,928
def exec_flat_python_func(func, *args, **kwargs): """Execute a flat python function (defined with def funcname(args):...)""" # Prepare a small piece of python code which calls the requested function # To do this we need to prepare two things - a set of variables we can use to pass # the values of argume...
9c494daec2172fe59d65e625cc3a1b98656de5df
35,929
def robust_scale(df): """Return copy of `df` scaled by (df - df.median()) / MAD(df) where MAD is a function returning the median absolute deviation.""" median_subtracted = df - df.median() mad = median_subtracted.abs().median() return median_subtracted/mad
ba9ce747612c99997d890930e7ac7c582ba1af70
35,930
def generate_context_menu_mainmenu(menu_id): """Generate context menu items for a listitem""" items = [] if menu_id == 'myList': items.append(_ctx_item('force_update_mylist', None)) return items
d1cd169ec71a33c7bccf50b611d61b533ebcca54
35,931
def unroll_edges(domain, xgrid): """If necessary, "unroll" intervals that cross boundary of periodic domain. """ xA, xB = domain assert all(np.diff(xgrid) >= 0) assert xA < xB assert xA <= xgrid[0] assert xgrid[-1] <= xB if xgrid[0] == xA and xgrid[-1] == xB: return xgrid ...
274c446f60bb953e2b864bed06e23bb0153fac94
35,932
def create_correct_bias_pipe(params={}, name="correct_bias_pipe"): """ Description: Correct bias using T1 and T2 images Same as bash_regis.T1xT2BiasFieldCorrection Params: - smooth (see `MathsCommand <https://nipype.readthedocs.io/en/0.12.1/\ interfaces/generated/nipype.interfaces....
ec0be858a900f1b38ea6c61d9bcbcb8ac8535b85
35,933
def infer_gaps_in_tree(df_seq, tree, id_col='id', sequence_col='sequence'): """Adds a character matrix to DendroPy tree and infers gaps using Fitch's algorithm. Infer gaps in sequences at ancestral nodes. """ taxa = tree.taxon_namespace # Get alignment as fasta alignment = df_seq.phylo.to_...
ccd71b7b10977441a25a7d753f5a228287ed8d28
35,934
def _sklearn_booster_to_model(booster: GradientBoostingClassifier): """ Load a scikit-learn gradient boosting classifier as a Model instance. A multiclass booster gets turned into a one-vs-all representation inside the JSON. . Parameters ---------- booster : sklearn.ensemble.Grad...
0c1b0cb1eb396db707d22a1bb509f3592647ddb2
35,935
def encode_utf8_with_error_log(arg): """Return byte string encoded with UTF-8, but log and replace on error. The text is encoded, but if that fails, an error is logged, and the offending characters are replaced with "?". Parameters ---------- arg : str Text to be encoded. Returns ...
9a2ebc69f00220cfba92e0561b526ee3b5fd23d2
35,936
def gearys_c(adata, vals): """ Compute Geary's C statistics for an AnnData. Adopted from https://github.com/ivirshup/scanpy/blob/metrics/scanpy/metrics/_gearys_c.py :math:`C=\\frac{(N - 1)\\sum_{i,j} w_{i,j} (x_i - x_j)^2}{2W \\sum_i (x_i - \\bar{x})^2}` Parameters ---------- ...
ea5441619f0c893242b6d851781251b93a63b05d
35,937
def eq_kinematic_src(): """ Factory associated with EqKinSrc. """ return EqKinSrc()
be15e4169f90c28323dd881f67b325182547ad43
35,938
def generate_materials_string(materials, mtlfilename, basename): """Generate final materials string. """ if not materials: materials = { 'default': 0 } mtl = create_materials(materials, mtlfilename, basename) return generate_materials(mtl, materials)
e417a3a07576b61dd6b247251834e2c04ba0a947
35,939
def _mktyperef(obj): """Return a typeref dictionary. Used for references. >>> from jsonpickle import tags >>> _mktyperef(AssertionError)[tags.TYPE].rsplit('.', 1)[0] 'exceptions' >>> _mktyperef(AssertionError)[tags.TYPE].rsplit('.', 1)[-1] 'AssertionError' """ return {tags.TYPE: '%s.%...
0c89d3771c3531773e13475487b4466231e067e5
35,940
from typing import Tuple def colorize(img: np.ndarray, color: Tuple) -> np.ndarray: """colorize a single-channel (alpha) image into a 4-channel RGBA image""" # ensure color to RGBA if len(color) == 3: color = (color[0], color[1], color[2], 255) # created result image filled with solid "color...
88e79e7adc7785f1391db94c9a295b2a55943c7c
35,941
def prepare_template_stream(stream, base_url): """Prepares the stream to be stored in the DB""" document_tree = _get_document_tree(stream) _make_links_absolute(document_tree, base_url) return _serialize_stream(document_tree)
1072573ee0856725351a015f104e20604ef3b9c3
35,942
def _jsarr(x): """Return a string that would work for a javascript array""" return "[" + ", ".join(['"{}"'.format(i) for i in x]) + "]"
9c9b6df65bf4c01fa1c321445bbb7c86c6d28c5a
35,943
import torch def class_channels_to_rgb(input_batch, output_batch, label_batch): """ Converts multichannel tensor to RGB image -- i.e. model output to final mask. """ # colors = get_color_encoding_CamVid() colors = get_color_encoding_Elements() rgb_batch_size = list(output_batch.size()) rgb_batch_...
4aef60d85fbe1a6ed87a50409f36918d9cf7c717
35,944
def PyApp_SetMacPreferencesMenuItemId(*args, **kwargs): """PyApp_SetMacPreferencesMenuItemId(long val)""" return _core_.PyApp_SetMacPreferencesMenuItemId(*args, **kwargs)
7704e544439e27f362fe703027af7d393e1ab647
35,945
def isnum(value): """ Check if a value is a type of number (decimal or integer) value: The value to check """ try: return bool(isinstance(value, (float, int))) except BaseException: return False
6116d0d4c61f5f3afefe311b06d9b23b03ab9bfc
35,946
import httpx import json async def _async_json_object(api_call): """async function to make a request to the wiki api and return a json object with article information Args: api_call (text): link to the api call Returns: dict: json content from the api call """ asy...
a047bbf16af314bd96c5d12c03ff8c2d0a16d17b
35,947
def yices_model_set_bv_int64(model, var, val): """Assign an integer value to a bitvector uninterpreted term. """ return libyices.yices_model_set_bv_int64(model, var, val)
5575adec31c297ff685884283bce7d1d9c47e386
35,948
def generate_histograms( num_users: int, counts_iid_param: float, avg_count: float, ref_distribution: np.ndarray, hist_iid_param: float, rng=np.random.default_rng()) -> np.ndarray: """Generate histograms with different total counts and distributions. Args: num_users: An integer indicati...
0e3c00a908cfe139dd273326d63a2c18cd0b1294
35,949
import sys import array def editable_str(initial_str):# -> array """Exactly the same as array.array except that it switches types based on Python Version: Python 2: character, one byte Python 3: unicode, two to four bytes""" array_type = 'u' if sys.version_info < (3, 0): array_type = 'c' ...
e901b1a9dffd7570448421f56390c4bdb778f139
35,950
import requests def neo_create_bucket(**kwargs): """Create a bucket with headers. :param auth: Tuple, consists of auth object and endpoint string :param acl: Input for canned ACL, defaults to "private" :param policy_id: String represent `x-gmt-policyid` or determines how data in the bucket will be di...
52d5c6f3c49731c7fdfa95e85cdfc06c96a84f0a
35,951
def babi_handler(data_dir, task_number): """ Handle for bAbI task. Args: data_dir (string) : Path to bAbI data directory. task_number (int) : The task ID from the bAbI dataset (1-20). Returns: BABI : Handler for bAbI task. """ task = task_list[task_number - 1] retur...
12472b8b2430bf7d04e51e41f1b34124583935aa
35,952
def _full_ner(text_analyzer): """ Run complete NER. This includes extraction of different entity types and geotagging. :param class text_analyzer: the text_analyzer of nlp_components :return dict: json with persons, geotagged locations and metadata, readalbe by the viewer """ named...
e182e4d4bbc61ce9d7eca52b1a490d8705a81808
35,953
def frequency_impulse_response(magnitudes: tf.Tensor, window_size: int = 0) -> tf.Tensor: """Get windowed impulse responses using the frequency sampling method. Follows the approach in: https://ccrma.stanford.edu/~jos/sasp/Windowing_Desired_Impulse_Response.html Args: magnit...
9e307778511b7fb4b79caab338b016a1f7e91120
35,954
def parse_station_list_to_json(filepath_or_buffer) -> str: """ Return JSON-formatted data """ return _parse_station_list(filepath_or_buffer).to_json(orient="records")
32d3e6e122433692a1dd16bd3750cda528c70596
35,955
from typing import List from typing import Callable from typing import Set import numpy def get_minimal_intactness_ls_centralities( nodes: List[Node], definitions: Definitions, get_ill_behaved_weight: Callable[[Set[Node]], float], get_mu: Callable[[numpy.array], float] ) -> numpy.array...
ac2d01a8d5ba1842379044c77398c93292e8a4f9
35,956
def inverse_sigmoid_numpy(x): """ .. todo:: WRITEME """ return np.log(x / (1. - x))
17332beacc0a6b097dfa82c8f150981eda77a722
35,957
def join_kwargs(**kwargs) -> str: """ Joins keyword arguments and their values in parenthesis. Example: key1{value1}_key2{value2} """ return "_".join(key + "{" + value + "}" for key, value in kwargs.items())
3054573ec51676bb8d93e2fcabd4cb5097e4b897
35,958
def zipped_lambda_function(): """Return a simple test lambda function, zipped.""" func_str = """ def lambda_handler(event, context): print("testing") return event """ zip_output = BytesIO() with ZipFile(zip_output, "w", ZIP_DEFLATED) as zip_file: zip_file.writestr("lambda_function.py", f...
38f2862c4e9401a32866ec54d5db420265bda2a1
35,959
def byte_builtin(): """byte: Immutable bytes array.""" return bytes("\xd0\xd2NUT", "utf-8").decode()
62e0d556d20ece651adb0a13b11d07670e0ea4f6
35,960
import torch def predict_interaction(model, n0, n1, tensors, use_cuda): """ Predict whether a list of protein pairs will interact. :param model: Model to be trained :type model: dscript.models.interaction.ModelInteraction :param n0: First protein names :type n0: list[str] :param n1: Secon...
2c7ffecbd4435c7a5df620f895e9f3c299684494
35,961
def hessian(f, varlist, constraints=[]): """Compute Hessian matrix for a function f wrt parameters in varlist which may be given as a sequence or a row/column vector. A list of constraints may optionally be given. Examples ======== >>> from sympy import Function, hessian, pprint >>> from s...
7033abc3342d3de4efb91a3a461b8c09632bc395
35,962
def extract_column_names(row_list): """ Extract names of columns from row list obtained from table csv. The first row contains all row names :param row_list: List of all rows in csv used for table creation :return: List of names present in table csv """ return row_list[0]
2adef82a7f583c262922ad28aa0de47b8b9b5e51
35,963
def index_to_point(index, origin, spacing): """Transform voxel indices to image data point coordinates.""" x = origin[0] + index[0] * spacing[0] y = origin[1] + index[1] * spacing[1] z = origin[2] + index[2] * spacing[2] return (x, y, z)
072f1ad5d1adc1e81d4771725475f6a07f32f3ce
35,964
def MakeEmptyTable(in_table=[[]], row_count=0, column_count=0): """ 1 Read in *in_table* 2 Create an empty table of '' values, which has with the same number of rows and columns as the table, (where columns based on the first row). 3 If the user has specified *row_count* and/or ...
55b32c2914cb8e2194999e1b8ba2211373ef1bcb
35,965
import torch def choose_pseudo_gt(boxes, cls_prob, im_labels): """Get proposals with highest score. inputs are all variables""" num_images, num_classes = im_labels.size() boxes = boxes[:,1:] assert num_images == 1, 'batch size shoud be equal to 1' im_labels_tmp = im_labels[0, :] gt_b...
7565a9a72052c839cad5cf12033fdf144bfcb4b0
35,966
import argparse import os import tqdm def create_submission(args: argparse.Namespace, cfg: CfgNode) -> str: """inferece models and save prediction Args: args (argparse.Namespace): argparse namespace cfg (CfgNode): cfg for parameters Returns: str: path to the saved prediction ...
77ea2bca6620cee102dc7d50151073b494d994bf
35,967
def transform_covariance_matrix(transformation, histogram): """ Compute the covariance matrix of a new histogram given by: new_histogram = transformation * histogram """ A = transformation V = compute_numpy_covariance_matrix(histogram) return A * V * A.T
f75918f83fdc8b06ab6c4a2b973a02549cb286d5
35,968
import math, random def split_list(data, splits={'train': 8, 'test': 2}, shuffle=True, seed=0): """ Split the list according to a given ratio Args: data (list): a list of data to split splits (dict): a dictionary specifying the ratio of splits shuffle (bool): shuffle the list befo...
d9b25512e666a03ec2b589850c47a45231b279a0
35,969
def decoder_gen( original_input: tuple, decoder_config: dict ): """ Create the architecture for the VAE decoder """ decoder_inputs = keras.layers.Input(shape=[decoder_config["latent_dim"]]) print("decoder_inputs", decoder_inputs._keras_shape) # Reshape input to be an image #for ori...
fdcc683d48c795fba7e25c4ce47bf71a9459b6e4
35,970
from typing import List from typing import DefaultDict from typing import Set def get_ents_by_label( data: List[Example], case_sensitive: bool = False ) -> DefaultDict[str, List[str]]: """Get a dictionary of unique text spans by label for your data # TODO: Ok so this needs to return more than just a set ...
ed5b93ed577417fffab823a1a44bad3a7aa506e7
35,971
def root(): """ root - returns 200 OK """ return Response("It's alive!", status=200)
5fa735a9cc2242928165d4e7c58e7ac576973044
35,972
def testplugin(module): """returns True if module has nessesary parameters""" logger.write( module.title ) return True
c2e66b38735e43e16f351fde5d59a43d71a0b734
35,973
import requests def put(*args, **kwargs): """Sends an HTTP PUT Request. :param args: URL argument on the first index(args[1]). :param kwargs: Optional arguments that ``requests.put`` takes. :returns: :class:`Response` object or `None` if an error occurred. :rtype: :class:`requests.Response` or `...
dc2e01aa6f6c293264b0435eeca9adf17a95820d
35,974
async def save_transform(data): """ Calculate the transormation matrix that calibrates the gantry to the deck :param data: Information obtained from a POST request. The content type is application/json. The correct packet form should be as follows: { 'token': UUID token from current sessio...
696b92dbba0c220988129d64d14f5d1f9e2ab828
35,975
import os def data_trending_dashboard(start=default_start, end=now): """Bulilds dashboard Parameters ---------- start : time configures start time for query and visualisation end : time configures end time for query and visualisation Return ------ plot_data : list ...
4811398f7754f473bfe0c0152c3cb85f0b6aee4b
35,976
import os def dl2_to_sensitivity( dl2_dir, log_from_dl1_dl2, gamma_offset="off0.0deg", prod_id=None, source_env="", wait_jobs_dl1_dl2="", ): """ Function to run the `script_dl2_to_sensitivity` for the gamma (and the different gamma offsets) and gamma-diffuse particles. Creates ...
afade682b3e4ca99ecacf6a00bbf8ae6f02e990c
35,977
import unittest def test_with_html(): """Runs the unit tests with html.""" tests = unittest.TestLoader().discover('./app/test', pattern='test*.py') outfile = open("./Report.html", "wb") runner = HTMLTestRunner( stream=outfile, title='Unit Test Backend Report', ...
2067907861625118e4cec54d1d02638b6b41cac2
35,978
def cpm_what_channels(folder): """Helper functions to print available channels given a folder with polysomnography files""" pg = PSGcompumedics(folder) return pg.available_channel
d8b494ff93917769272036d2eac570838f8aca5d
35,979
def all_close(goal, actual, tolerance): """ Convenience method for testing if a list of values are within a tolerance of their counterparts in another list @param: goal A list of floats, a Pose or a PoseStamped @param: actual A list of floats, a Pose or a PoseStamped @param: tolerance ...
a6aa910798e8ad6516274cee49bc2c2445afc5d3
35,980
def cloud_to_clusters(cloud: np.array) -> np.array: """Converts provided cloud into a set of clusters.""" clusters = defaultdict(lambda: []) for vertex in cloud: center = tuple(vertex[6:9]) if center != (0, 0, 0): clusters[center].append(vertex) print(' * [INFO]', len(list(c...
1a7d5396e238b622e2dd3339990c6d876e689503
35,981
def split_remote_url(url): """check if the user provided a local file path or a remote. If remote, try to strip off protocol info. """ remote_url = is_remote_url(url) if not remote_url: return url for prefix in REMOTE_PREFIXES: url = url.replace(prefix, '') if '@' in ur...
e672d79a7b00f1a0c6928869efe5ca811673edaa
35,982
import json def load_json(filename, user_limit=0, badge_limit=0): """ Loads data form JSON """ with open(filename) as f: data = json.loads(f.read()) if user_limit: data['transactions'] = data['transactions'][:user_limit] if badge_limit: data['badges'] = data['badges'][:...
79890f86dcc0090f89b7c401959e3e2dfc86828c
35,983
def lon2decimal(input): """ Convert a Longitude into decimal angle. """ lng_degrees = int(input[0:3]) lng_minutes = int(input[3:5]) lng_seconds = float(input[5:-2]) lng_negative = ('W' == input[-1]) return dms2decimal(lng_degrees, lng_minutes, lng_seconds, lng_negative)
557af79e9ef4fcd773ab28fea4efa99fbeb1ed38
35,984
def get_coordinate_color(color_image, coordinate, colors: list): """ Takes a color_image, coordinate (tuple), and list of color thresholds in HSV. If the pixel is within a color threshold, return the index of the color in the list. Coordinate should be in y, x format. """ try: if coordinate == None: return...
3dade67def84f6fde70df3a7241e410c306a3806
35,985
def constraint_wrapper(fun, constraint): """ Wrap a function such that it's first argument is constrained """ def inner(x, *args, **kwargs): """the wrapped function""" return fun(constraint(x), *args, **kwargs) return inner
f9055fe2cd269e4586c545bfa951bdf2ba0677c1
35,986
import os import base64 def extract_zip(base64String, extract_to): """ 1. Decode base64String to zip 2. Extract zip to files """ # Decode base64String to zip if not os.path.exists(extract_to): os.makedirs(extract_to) zipfile_path = extract_to + "/package.zip" with open(zipfile_path, "...
9a53493c0c202dc0ef7cb3dd804dba92ebe7984f
35,987
import collections def parse(): """Parse input. Return the polymer template, its pairs, and the rules.""" with open('../data/day14.txt') as f: polymer = f.readline().strip() pairs = collections.defaultdict(int) for i in range(len(polymer) - 1): pairs[polymer[i:i+2]] += 1 ...
b1e00b1176a6e60362af47e0fda9113104ed8083
35,988
def tourney_key(proto_obj): """Build a key from a scores_messages.Tournament protobuf object.""" return tourney_key_full(proto_obj.id_str)
768a1e84b7ce95ec65450cb6775355b48704b335
35,989
import re def timedelta_from_duration_string(s): """Convert time duration string to number of seconds.""" if re.match(r'^\d+$', s): return timedelta(seconds=int(s)) td_args = {} for part in s.split(','): part = part.strip() m = re.match(r'(\d+)\s+(year|month|day|hour|minute|se...
b3c7bd937a40057518cfb19eb2af2ff3bb070602
35,990
import functools def wrapped(wrapped_function, additional_result_wrapper=None, self_index=0): """ Using these decorators will take care of unwrapping and rewrapping the target object. Thus all following code is written as if the methods live on the wrapped object Also perfect to adapt free functi...
0f5c024109ecab4103d70feb5c04a84323180d30
35,991
import os import torch import logging def train(model, optim, sche, db, opt, exp_id): """ Args: model: the model to be trained optim: pytorch optimizer to be used db : prepared torch dataset object opt: command line input from the user exp_id: experiment id """ ...
2f9d5bf71ef8be25f947445daacde18ea47712ef
35,992
def format_y_ticks_as_percents(plot): """Formats y ticks as nice-looking percents. Args: plot: matplotlib.AxesSubplot object. """ y_ticks = plot.get_yticks() plot.set_yticklabels(get_percent_strings(y_ticks)) return plot
5d45ede7fa51fbe9d18fd9cd2130714035b3e6a1
35,993
def can_cast(value, class_type): """ Check if the value can be cast to the class_type, used in the parse tcl string function for tcl expressions like [Ada inputs 0] or [Ada alias robotblur] Args: value (object): The object we're attempting to cast. class_type (class): The class we're at...
85c415d2eaadb16a532e209110c1fd0f778cb681
35,994
def conv( value, filter_size, output_dim, dropout=0.0, activation="linear", padding="valid", weight_source=None): """ Perform a single scale of convolution and optionally add spatial dropout. """ if weight_source is None: conv_layer = Conv1...
19b002b5059ff28da5cdf255fde8547e3597852c
35,995
def insert_row(dataset_name, position, validate=False): """Create instance of insert row command. Parameters ---------- dataset_name: string Name of the dataset position: int Index position where row is inserted validate: bool, optional Validate the created command speci...
bc2fed6ce8a6a50a21bb1e8c60d067518722a628
35,996
def build(argmap, data): """Builds an array of arguments from the provided map and data. The argmap must consist of a mapping of keys to argbuilder functions. keys in the argmap are indexed into data, and if they are present, the corresponding values are passed to the corresponding argmap function. Th...
d9c6c9eede6d6a9ae36fea77dceb3c70cbfbdbbd
35,997
def get_prox_dist_points_cll(ppCll1, key=[]): """ get prox and dist ends of the centerline assuming that origin is cranial, right, anterior """ # Get prox and dist point for ppCll1 pends1 = np.array([ppCll1[0], ppCll1[-1]]) # pp centerline is in order of centerline points if 'vLRA' in key: ...
418f7aea0d7fba1fa3201deed02f61c0e7c4a804
35,998
def proxy_a_distance(source_X, target_X, verbose=False): """ Compute the Proxy-A-Distance of a source/target representation """ nb_source = np.shape(source_X)[0] nb_target = np.shape(target_X)[0] if verbose: print('PAD on', (nb_source, nb_target), 'examples') multiple_search = Fals...
1bdb183717d16daad4377436376ee2d0118fc7e4
35,999