content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import requests import random def handle(req): """handle a request to the function Args: req (str): request body """ r = requests.get("http://api.open-notify.org/astros.json") result = r.json() index = random.randint(0, len(result["people"]) - 1) name = result["people"][index]["nam...
7d951443bc5b6f3db86602d635a8c9ce84b703fb
14,400
import hashlib def get_file_hashsum(file_name: str): """Generate a SHA-256 hashsum of the given file.""" hash_sha256 = hashlib.sha256() with open(file_name, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_sha256.update(chunk) return hash_sha256.hexdigest()
d515b6b7b743396240ada8d888b8bfbc4c316373
14,401
def generate_primes(n): """Generates a list of prime numbers up to `n` """ global PRIMES k = PRIMES[-1] + 2 while k <= n: primes_so_far = PRIMES[:] divisible = False for p in primes_so_far: if k % p == 0: divisible = True break ...
4ea29f8dc8dad11bf6c71fcb1dcc6b75b91bece5
14,402
def Convex(loss, L2_reg): """ loss: src_number loss [loss_1, loss_2, ... loss_src_number] """ src_number = len(loss) lam = cp.Variable(src_number) prob = cp.Problem( cp.Minimize(lam @ loss + L2_reg * cp.norm(lam, 2)), [cp.sum(lam) == 1, lam >= 0] ) # prob.solve() prob.so...
f2a6ecc464e2f87684d1537775816d22dc30d837
14,403
from limitlessled.pipeline import Pipeline def state(new_state): """State decorator. Specify True (turn on) or False (turn off). """ def decorator(function): """Decorator function.""" # pylint: disable=no-member,protected-access def wrapper(self, **kwargs): """Wrap...
156b7bbad0a943af6bb4280e4fdb1dde2b6e320a
14,404
def rotTransMatrixNOAD(axis, s, c, t): """ build a rotate * translate matrix - MUCH faster for derivatives since we know there are a ton of zeros and can act accordingly :param axis: x y or z as a character :param s: sin of theta :param c: cos of theta :param t: translation (a 3 tuple) :...
f6e8d6474ba90e3a253229124e0571d67025c818
14,405
def angular_diameter_distance(z, cosmo=None): """ Angular diameter distance in Mpc at a given redshift. This gives the proper (sometimes called 'physical') transverse distance corresponding to an angle of 1 radian for an object at redshift `z`. Parameters ---------- z : array_like In...
694f9fcaa6ce2585315f63e69351ac47589e248c
14,406
def main(stdin): """ Take sorted standard in from Hadoop and return lines. Value is just a place holder. """ for line_num in stdin: # Remove trailing newlines. line_num = line_num.rstrip() # Omit empty lines. try: (line, num) = line_num.rsplit('\t', 1) ...
811e184d9425c1c76681c823b463b99ebde2c25c
14,407
def _ignore_module_import_frames(file_name, name, line_number, line): """ Ignores import frames of extension loading. Parameters ---------- file_name : `str` The frame's respective file's name. name : `str` The frame's respective function's name. line_number : `int` ...
8f3e506e99b32d2945ea665367d5447ef1b05732
14,408
def get_tf_tensor_data(tensor): """Get data from tensor.""" assert isinstance(tensor, tensor_pb2.TensorProto) is_raw = False if tensor.tensor_content: data = tensor.tensor_content is_raw = True elif tensor.float_val: data = tensor.float_val elif tensor.dcomplex_val: ...
f2d62a7ccba252d5c94cd9979eb01a0b44282d4a
14,409
def _createPhraseMatchList(tree1, tree2, matchList, doEquivNodes=False): """ Create the list of linked phrases between tree1 and tree2 """ phraseListTxt1 = tree1.getPhrases() phraseListHi1 = tree2.getPhrases() if PRINT_DEBUG or PRINT_DEBUG_SPLIT: print "\nPhrase 1 nodes:" pr...
99d7e6fb13120ea84b671331940fc232cf061786
14,410
def coth(x): """ Return the hyperbolic cotangent of x. """ return 1.0/tanh(x)
92d490563c8595b8c11334cd38afbf9ef389dfe8
14,411
def param_is_numeric(p): """ Test whether any parameter is numeric; functionally, determines if any parameter is convertible to a float. :param p: An input parameter :return: """ try: float(p) return True except ValueError: return False
b92579ba019389cf21002b63ca6e2ebdfad7d86f
14,412
def convert_graph_to_angular_abstract_graph(graph: Graph, simple_graph=True, return_tripel_edges=False) -> Graph: """Converts a graph into an abstract angular graph Can be used to calculate a path tsp Arguments: graph {Graph} -- Graph to be converted simple_graph {bool} -- Indicates if ...
2f81743824549d8e19f70f1843d6449eb12e7e5d
14,413
def login_to_site(url, username, password, user_tag, pass_tag): """ :param url: :param username: :param password: :param user_tag: :param pass_tag: :return: :raise: """ browser = mechanize.Browser(factory=mechanize.RobustFactory()) browser.set_handle_robots(False) browser.se...
6c906e037a619031eb45bb26f01da71833fa3e41
14,414
async def test_db( service: Service = Depends(Service) ) -> HTTPSuccess: """Test the API to determine if the database is connected.""" if service.test().__class__ is not None: return { "message": "Database connected." } else: return {"message": "Database not connected." }
67e4530af6959fef03f55879ee3781ebf993f11c
14,415
import tqdm def model_fit_predict(): """ Training example was implemented according to machine-learning-mastery forum The function takes data from the dictionary returned from splitWindows.create_windows function https://machinelearningmastery.com/stateful-stateless-lstm-time-series-forecasting-python...
753ca4e90034864e709809cc1bd2f30640554f28
14,416
from functools import partial import multiprocessing as mp import gc def mp_variant_annotations(df_mp, df_split_cols='', df_sampleid='all', drop_hom_ref=True, n_cores=1): """ Multiprocessing variant annotations see variantAnnotations.process_variant_annotations for description ...
8569a4eb82ff04db1bee46b00bbd9eedf8b4d094
14,417
def find_attachments(pattern, cursor): """Return a list of attachments that match the specified pattern. Args: pattern: The path to the attachment, as a SQLite pattern (to be passed to a LIKE clause). cursor: The Cursor object through which the SQLite queries are sent to...
614649f6fd5972b026b191bb1a272e270dedffe5
14,418
def generate_symmetric_matrix(n_unique_action: int, random_state: int) -> np.ndarray: """Generate symmetric matrix Parameters ----------- n_unique_action: int (>= len_list) Number of actions. random_state: int Controls the random seed in sampling elements of matrix. Returns ...
acb5d537762f2f306be8f300845dc6560c1dd121
14,419
def model_fields_map(model, fields=None, exclude=None, prefix='', prefixm='', attname=True, rename=None): """ На основании переданной модели, возвращает список tuple, содержащих путь в орм к этому полю, и с каким именем оно должно войти в результат. Обрабатываются только обычные поля, m2m и generic сюда...
812247543e5f714e0d2ef57cf018b0741679f83e
14,420
from typing import Union from typing import List from typing import Dict from typing import Set import tqdm def scaffold_to_smiles(mols: Union[List[str], List[Chem.Mol]], use_indices: bool = False) -> Dict[str, Union[Set[str], Set[int]]]: """ Computes the scaffold for each SMILES and return...
2a45731a5574bb37e81042fa19ac7c2f015c21ef
14,421
import crypt def encontrar_passwords(): """ Probar todas las combinaciones de 6 letras, hasheando cada una para ver si coinciden con los hashes guardados en los /etc/shadow Para el tema de equipos, basicamente fui probando con copiar y pegar contenido en texto de distintas paginas de wikipedia en ...
5762fed1f5e493c2399d40dbbc1e19ad24c6718e
14,422
def queue_merlin_study(study, adapter): """ Launch a chain of tasks based off of a MerlinStudy. """ samples = study.samples sample_labels = study.sample_labels egraph = study.dag LOG.info("Calculating task groupings from DAG.") groups_of_chains = egraph.group_tasks("_source") # magi...
448365e799001d09281707cab69c71c3be05408e
14,423
import math def sphere_mass(density,radius): """Usage: Find the mass of a sphere using density and radius""" return density*((4/3)*(math.pi)*radius**3)
8c1a2dc949980ca96a4f56f3918bacd19568965e
14,424
def generate_stats_table(buildings_clust_df): """ Generate statistical analysis table of building types in the area Args: buildings_clust_df: building footprints dataframe after performed building blocks assignment (HDBSCAN) Return: stat_table: statistical analysis results ...
732f035e591dc9f0b03673584f3a6e21dad03cad
14,425
def make_multisat(nucsat_tuples): """Creates a rst.sty Latex string representation of a multi-satellite RST subtree (i.e. merge a set of nucleus-satellite relations that share the same nucleus into one subtree). """ nucsat_tuples = [tup for tup in nucsat_tuples] # unpack the iterable, so we can che...
16c1808267087beea6cea21811cd3c1f7d70932e
14,426
import io def plot_to_image(figure): """Converts the matplotlib figure to a PNG image.""" # The function is adapted from # github.com/tensorflow/tensorboard/blob/master/docs/image_summaries.ipynb # Save the plot to a PNG in memory. buf = io.BytesIO() plt.savefig(buf, format="png") # Closing the figure ...
24a63f7b27d47421baf2c7913bf989903e4d9545
14,427
async def getDiscordTwitchAlerts(cls:"PhaazebotDiscord", guild_id:str, alert_id:int=None, limit:int=0, offset:int=0) -> list: """ Get server discord alerts, if alert_id = None, get all else only get one associated with the alert_id Returns a list of DiscordTwitchAlert(). """ sql:str = """ SELECT `discord...
00c1bad85f4f7891d36e5fab5c651f10c79abf02
14,428
def is_visible_dir(file_info): """Checks to see if the file is a visible directory. @param file_info: The file to check @type file_info: a gnomevfs.FileInfo """ return is_dir(file_info) and not is_hidden(file_info)
776361d4cbe16a5b3c45dc3073a37192e31e87a9
14,429
def add_model_components(m, d, scenario_directory, subproblem, stage): """ :param m: :param d: :return: """ # Import needed availability type modules required_availability_modules = get_required_subtype_modules_from_projects_file( scenario_directory=scenario_directory, subpr...
2ecca392e718bf72023702c13621d9d54e764b3d
14,430
def read_file(item): """Read file in key path into key image """ item['image'] = tf.read_file(item['path']) return item
06b87851717bd486b13f964ad5b45cbdc7a97142
14,431
def make_joint(withdraw, old_password, new_password): """Return a password-protected withdraw function that has joint access to the balance of withdraw. >>> w = make_withdraw(100, 'hax0r') >>> w(25, 'hax0r') 75 >>> make_joint(w, 'my', 'secret') 'Incorrect password' >>> j = make_joint(w,...
f40073429aea946486263a7d6e0fc8b24cd60a84
14,432
def should_parse(config, file): """Check if file extension is in list of supported file types (can be configured from cli)""" return file.suffix and file.suffix.lower() in config.filetypes
1c2258d405ef715574b557d99cdf87e461627ffd
14,433
def _get_pipeline_per_subband(subband_name: str): """ Constructs a pipeline to extract the specified subband related features. Output: sklearn.pipeline.Pipeline object containing all steps to calculate time-domain feature on the specified subband. """ freq_range = FREQ_BANDS_RANGE[subband_n...
2b1d8bd2543ae07b861df6f979297a82e3f5e827
14,434
def get_credentials_interactively() -> Credentials: """ Gets credentials for the bl interactively """ return ("placeholder-user", "placeholder-pass")
b5e4d55015155589632b958252a3c078b5920e59
14,435
def reynolds(find="Re", printEqs=True, **kwargs): """ Reynolds Number = Inertia / Viscosity """ eq = list() eq.append("Eq(Re, rho * U * L / mu)") return solveEqs(eq, find=find, printEq=printEqs, **kwargs)
df5ad0c0279894e8f671942ceddb64e08e35fa0d
14,436
def data_app(): """ Data Processer and Visualizer """ st.title("Data Cake") st.subheader("A to Z Data Analysis") file = ['./dataset/Ac1',[0,1]] def file_selector(): filename = st.file_uploader("Upload Excel File", type=['xls','xlsx']) if filename is not None: sheetname...
b6286064757d276a5319ef0b3cffe1515c4a7fb1
14,437
def derivative(x, y, order=1): """Returns the derivative of y-coordinates as a function of x-coodinates. Args: x (list or array): 1D array x-coordinates. y (list or array): 1D array y-coordinates. order (number, optional): derivative order. Returns: ...
23a1213721e553e5b72a0bd92877675b499f9848
14,438
from typing import Dict def get_ff_parameters(wc_params, molecule=None, components=None): """Get the parameters for ff_builder.""" ff_params = { 'ff_framework': wc_params['ff_framework'], 'ff_molecules': {}, 'shifted': wc_params['ff_shifted'], 'tail_corrections': wc_params['ff_...
d87008dba0b9d835f71366eb64486b1d18fe2381
14,439
def healpix_header_odict(nside,nest=False,ordering='RING',coord=None, partial=True): """Mimic the healpy header keywords.""" hdr = odict([]) hdr['PIXTYPE']=odict([('name','PIXTYPE'), ('value','HEALPIX'), ('comment','HEALPIX pixelisation')]) ordering =...
1202d7564b94a3c2288a513f42e4b781a583e41c
14,440
def hello(): """Test endpoint""" return {'hello': 'world'}
91ad620815a6371a4723e21bc79aad8c1d49e73e
14,441
import logging import json def get_config_data(func_name: str, config_file_name: str = "config.json")\ -> tuple[str, str, str, str] | str | tuple[str, str]: """Extracts the data pertaining to the covid_news_handling module from the provided config file. A try except is used to get the encoding st...
9f665277d0e1a0c2d02ba6e487d20ade139ab5d6
14,442
def permute_channels(n_channels, keep_nbr_order=True): """Permute the order of neighbor channels Args: n_channels: the total number of channels keep_nbr_order: whether to keep the relative order of neighbors if true, only do random rotation and flip if false, random perm...
5491f181d32a5ff77ef1d9f6ac3327e6b0a746e0
14,443
def from_file(file,typcls): """Parse an instance of the given typeclass from the given file.""" s = Stream(file) return s.read_value(typcls._ep_typedesc)
90507278f33fe30a73c31f94ab046c07962250cc
14,444
def read_test_ids(): """ Read sample submission file, list and return all test image ids. """ df_test = pd.read_csv(SAMPLE_SUBMISSION_PATH) ids_test = df_test['img'].map(lambda s: s.split('.')[0]) return ids_test
cc4d53d28631fe0e22cabe30704a1844ff3e3a5b
14,445
def chuseok(year=None): """ :parm year: int :return: Thanksgiving Day of Korea """ year = year if year else _year return LunarDate(year, 8, 15).toSolarDate()
28a3170153862bda2ae52176d4931ee10050c3e1
14,446
def DELETE(request): """Delete a user's authorization level over a simulation.""" # Make sure required parameters are there try: request.check_required_parameters( path={ 'simulationId': 'int', 'userId': 'int' } ) except exceptio...
7ac7c6277126a827790e786cbfdf9f84ccaace7b
14,447
def process_query(data): """ Concat query, question, and narrative then 'preprocess' :data: a dataframe with queries in rows; query, question, and narrative in columns :return: 2d list of tokens (rows: queries, columns: tokens) """ lst_index = [] lst_words = [] for index, row in da...
8a8067f1766abdc08aa7b8995508d6cdc9057bd2
14,448
import argparse def parameter_parser(): """ A method to parse up command line parameters. The default hyperparameters give a high performance model without grid search. """ parser = argparse.ArgumentParser(description="Run SimGNN.") parser.add_argument("--dataset", nar...
fa79c8ad15250cc7709d267551b570584fc8d86a
14,449
def nb_view_patches(Yr, A, C, S, b, f, d1, d2, YrA=None, image_neurons=None, thr=0.99, denoised_color=None, cmap='jet'): """ Interactive plotting utility for ipython notebook Args: Yr: np.ndarray movie A,C,b,f: np.ndarrays outputs of matrix factorization algorithm ...
84db2e40734b21ebb6be5eef8eeb89bbe2838542
14,450
def menu(): """Manda el Menú \n Opciones: 1: Añadir a un donante 2: Añadir a un donatario 3: Revisar la lista de donantes 4: Revisar la lista de donatarios 5: Realizar una transfusion 6: Estadisticas 7: Salir Returns: opc(num):Opcion del menu "...
805d1ef48fbe03f8185e3c7be71ce3d9aa6104df
14,451
import shutil def get_engine(hass, config): """Set up Pico speech component.""" if shutil.which("pico2wave") is None: _LOGGER.error("'pico2wave' was not found") return False return PicoProvider(config[CONF_LANG])
d03a19dcff4bc8556a84b434d14468a45ffc7e6c
14,452
from typing import Tuple from typing import List def load_cp() -> Tuple[List[str], List[List[float]]]: """ Loads cloud point data; target values given in Celsius Returns: Tuple[List[str], List[List[float]]]: (smiles strings, target values); target values have shape (n_samples, 1) ...
84b11da1b3cd1a9ecaf5e1419d69b877c160e2aa
14,453
def look_up(f, *args, **kwargs): """ :param f: :type f: :param args: :type args: :param kwargs: :type kwargs: :return: :rtype:""" ag_hash = hash(args) + make_hash(kwargs) if f in global_table: if ag_hash in global_table[f]: return global_table[f][ag_hash]...
ebc9015066959f66cd98db226178cdf087fc897b
14,454
def getenv(key, default=None): """Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default. """ return environ.get(key, default)
0e355c73dbbdc971e4442123dc5945dc04fac8fc
14,455
def read_tag(request, tid, *args, **kwargs): """read_tag(tid) returns ...""" s = api.read_tag(request, tid, *args, **kwargs) return render_to_response('read/tag.html', s)
7582e752563f35eb8d025625eaac87d8a9f45f32
14,456
def ber_img(original_img_bin, decoded_img_bin): """Compute Bit-Error-Rate (BER) by comparing 2 binary images.""" if not original_img_bin.shape == decoded_img_bin.shape: raise ValueError('Original and decoded images\' shapes don\'t match !') height, width, k = original_img_bin.shape errors_bits...
f5768aa5435a76bcd82b331d76dadf554749e82d
14,457
def get_fractal_patterns_WtoE_NtoS(fractal_portrait, width, height): """ get all fractal patterns from fractal portrait, from West to East, from North to South """ fractal_patterns = [] for x in range(width): # single fractal pattern f_p = get_fractal_patterns_zero_amounts() for y in...
ad5e2025515231ae8efb256b5dc466d66fedb467
14,458
import time from datetime import datetime import requests import io def rating(date=None): """P2peye comprehensive rating and display results. from https://www.p2peye.com Args: date: if None, download latest data, if like '201812', that download month data. Returns: DataFrame...
d76205c933c07764938b38fbfcdcbbe84b584471
14,459
def crop_image(src, box, expand=0): """Read sensor data and crop a bounding box Args: src: a rasterio opened path box: geopandas geometry polygon object expand: add padding in percent to the edge of the crop Returns: masked_image: a crop of sensor data at specified bounds ...
84948cf3c81fe650d15acd834f89c532e9658466
14,460
def add_msgpack_support(cls, ext, add_cls_methods=True): """Adds serialization support, Enables packing and unpacking with msgpack with 'pack.packb' and 'pack.unpackb' methods. If add_method then enables equality, reading and writing for the classs. Specificly, adds methods: bytes <- obj...
fa8a6fcce7103466f923b84eeb6f5bdae8383b79
14,461
import os import configparser def parse_conf(): """(Dictionary) Function that parses the config file and/or environment variables and returns dictionary.""" # Following tuple holds the configfile/env var versions of each config ALL_CONFIGS = ( # Name of the variable in code, Path to config in the...
30d1776e2cf2f316a8a4d03312273fbf4d82e7fa
14,462
def UnN(X, Z, N, sampling_type): """Computes block-wise complete U-statistic.""" return UN(X, Z, N, Un, sampling_type=sampling_type)
0e2fb8c62cbcca99017bc7d0ff2c13dbecad1ab3
14,463
def view_log_view(request, model_name, object_id): """view log view Arguments: request {object} -- wsgi request object content_type {str} -- content type object_id {int} -- admin_log id Returns: retun -- html view """ if model_name not in register_form: re...
55ebd2d5226e06b1f5833595b0efad3de81140d7
14,464
from typing import Tuple from typing import Dict def parse_markdown(source: str) -> Tuple[str, Dict]: """Parse a Markdown document using our custom parser. Args: source (str): the Markdown source text Returns: tuple(str, dict): 1. the converted output as a string ...
2bf5a8d43f3763d6b1356dc0496ab4ed1896fe99
14,465
def flatten_list(nested_list): # Essentially we want to loop through each element in the list # and check to see if it is of type integer or list """ Flatten a arbitrarily nested list Args: nested_list: a nested list with item to be either integer or list example: [2,[[...
d79b350167cd1fdf35582e9b149bfb364741d566
14,466
import inspect def detect_runner(): """ Guess which test runner we're using by traversing the stack and looking for the first matching module. This *should* be reasonably safe, as it's done during test discovery where the test runner should be the stack frame immediately outside. """ i...
881758d42e5047fe58106a99377dcc7191c0010c
14,467
def retinanet( mode, offsets_mean=None, offsets_std=None, architecture='resnet50', train_bn=False, channels_fmap=256, num_anchors_per_pixel=9, num_object_classes=1, pi=0.01, alpha=0.25, gamma=2.0, confidence_threshold=0....
a3cdb088345740583c7ea08049e5f03f8d496cad
14,468
from typing import Union from typing import Tuple from typing import List from typing import Literal def default_chap_exec(gallery_or_id: Union[Gallery, int], chap: Chapter, only_values=False) \ -> Union[Tuple[str, dict], Tuple[int, Union[str, List[str]], int, bytes, int, Literal[0, 1]]]: """Pass a Galler...
8bd8cbfc47ce3463f2ea6da313cc871d8b6dcdf5
14,469
def _list_all(listing_call, output_format='dict', *args, **filters): """Helper to handle paged listing requests. Example usage: ``evaluations = list_all(list_evaluations, "predictive_accuracy", task=mytask)`` Parameters ---------- listing_call : callable Call listing, e.g. list_evalua...
0b57d047b9ba2e3fdbe391a338a2392780d969fc
14,470
from typing import List from typing import Dict from typing import Literal from typing import Any def get_matching_based_variables(match_definitions:List[Dict[Literal['name', 'matching'],Any]], global_dict=None, local_dict=None, ...
6722bb4f258ef69c4aab74970f8f924ca938bbf5
14,471
def _AStar_graph(problem: BridgeProblem) -> (list, list): """Used for graphing, returns solution as well as all nodes in a list""" all_nodes = [problem.initial_node] pq = [(problem.initial_node.path_cost + problem.h(problem.initial_node.state), problem.initial_node)] closed = set() while True: ...
a1616f7d499f12a229843007d7bc4939cbd02a7a
14,472
def plot_setup(name, figsize=None, fontsize=9, font='paper', dpi=None): """ Setup a PDF page for plot. name: PDF file name. If not ending with .pdf, will automatically append. figsize: dimension of the plot in inches, should be an array of length two. fontsize: fontsize for legends and labels. font...
4f9595757df57ee451dddc82815a91b727feb1f1
14,473
def author_endyear(pub2author_df = None, colgroupby = 'AuthorId', datecol = 'Year', show_progress=False): """ Calculate the year of last publication for each author. Parameters ---------- pub2author_df : DataFrame, default None, Optional A DataFrame with the author2publication information. ...
8a3ebf5e1870a8aa79ed2cba18fbb18fa634e604
14,474
def to_gif(images, fps): """Converts image sequence (4D numpy array) to gif.""" imageio.mimsave('./animation.gif', images, fps=fps) return embed.embed_file('./animation.gif')
b329da4710a5ad2da57ed2cf6b774ac4b6b8c7dd
14,475
import logging def get_half_max_down(signal, peak): """See `get_half_max_up` for explanation. This is a minor modification of the above function. """ if peak['peak'] == 0: return np.nan fflag = False half_max = signal[peak['peak']] / 2 falling_signal = signal[peak['peak']:(peak['r...
0b9b20b66a82d8a60aa650bc1bacd24f67f217f1
14,476
import os import io import json import sys def connect2server(env=None, key=None, keyfile=None, logger=None): """Sets up credentials for accessing the server. Generates a key using info from the named keyname in the keyfile and checks that the server can be reached with that key. Also handle...
f80b6482fcba70b291735b0cc938433f38b19f99
14,477
import copy def ternary(c): """ Encodes the circuit with ternary values Parameters ---------- c : Circuit Circuit to encode. Returns ------- Circuit Encoded circuit. """ if c.blackboxes: raise ValueError(f"{c.name} contains a blackbox") t ...
6fd813b957da408c23cc8a37038b8f3b660fdc73
14,478
from typing import List from typing import Dict def eval_lane_per_frame( gt_file: str, pred_file: str, bound_ths: List[float] ) -> Dict[str, np.ndarray]: """Compute mean,recall and decay from per-frame evaluation.""" task2arr: Dict[str, np.ndarray] = dict() # str -> 2d array gt_byte = np.asarray(Imag...
571cd737151576869170e33d181f89d22bc0657b
14,479
import torch def membrane(field, voxel_size=1, bound='dct2', dim=None, weights=None): """Precision matrix for the Membrane energy Note ---- .. This is exactly equivalent to SPM's membrane energy Parameters ---------- field : (..., *spatial) tensor voxel_size : float or sequence[float...
5e238ca2253fc7105b1bbfba58947ac442c05699
14,480
from typing import Tuple import struct def get_uint64(dgram: bytes, start_index: int) -> Tuple[int, int]: """Get a 64-bit big-endian unsigned integer from the datagram. Args: dgram: A datagram packet. start_index: An index where the integer starts in the datagram. Returns: A tuple cont...
e5ed2470656e3c0d1a8efe02bd638ac05245f187
14,481
import torch from typing import Optional from typing import List def fftshift(x: torch.Tensor, dim: Optional[List[int]] = None) -> torch.Tensor: """ Similar to np.fft.fftshift but applies to PyTorch Tensors Args: x: A PyTorch tensor. dim: Which dimension to fftshift. Returns: ...
a1ff7a81df83df63dcbcf56cf89d9b0e54c16ba0
14,482
def flatten(x): """Flattens nested list""" if isinstance(x, list): return [a for i in x for a in flatten(i)] else: return [x]
7d348f8287dfccfbb77a52a84a5642c265381eb1
14,483
import copy def get_capture_points_gazebo(bag, odom_topic='/gazebo/model_states', sync_topic='/mavros/imu/data_raw', camera_freq=20, sync_topic_freq=100, method='every'): """ method(string): method for sampling capturing points. 'every': Sample IMU for every n msgs, and then capture odometry msg whic...
75d351c0ecd6ad8dad6e7cfcd2ecd04d0826405b
14,484
import fileinput def parse_input(): """Parse input and return array of calendar A user can either pass the calendar via the stdin or via one or several icalendar files. This method will parse the input and return an array of valid icalendar """ input_data = '' calendars = [] for line...
a60a760968f139da0b7753ae5717d78b640cb232
14,485
def identity(obj): """Returns the ``obj`` parameter itself :param obj: The parameter to be returned :return: ``obj`` itself >>> identity(5) 5 >>> foo = 2 >>> identity(foo) is foo True """ return obj
a3271a831d2e91fe6eebed7e80c18e7c81996da6
14,486
def percent_clipper(x, percentiles): """ Takes data as np.ndarray and percentiles as array-like Returns clipped ndarray """ LOWERBOUND, UPPERBOUND = np.percentile(x, [percentiles[0], percentiles[1]) return np.clip(x, LOWERBOUND, UPPERBOUND)
3d114a956bfd0b6b8349c39f5c42f4487a812ee7
14,487
def check_prob_vector(p): """ Check if a vector is a probability vector. Args: p, array/list. """ assert np.all(p >= 0), p assert np.isclose(np.sum(p), 1), p return True
f9a6ea74fe9e5ff8a7244e7cc8aee2cbf5ae512e
14,488
def relabel_subgraph(): """ This function adapts an existing sampler by relabelling the vertices in the edge list to have dense index. Returns ------- sample: a function, that when invoked, produces a sample for the input function. """ def relabel(edge_list, positive_vertices): sha...
e9b8269640663b830c894c4aa4f8a8cce2b49af7
14,489
import os import re def get_activation_bytes(input_file=None, checksum=None): """ Get the activation bytes from the .aax checksum using rainbow tables. None is returned if the activation bytes can't be computed. """ if (not input_file and not checksum) or (input_file and checksum): ...
97c0619579ffa05ef7b878300d64c09ff638c9d2
14,490
def init_binary(mocker): """Initialize a dummy BinaryDigitalAssetFile for testing.""" mocker.patch.multiple( houdini_package_runner.items.digital_asset.BinaryDigitalAssetFile, __init__=lambda x, y, z: None, ) def _create(): return houdini_package_runner.items.digital_asset.Binar...
34a3ee5fb09f413bf07b36f1b73189472c188f3d
14,491
def with_setup_(setup=None, teardown=None): """Decorator like `with_setup` of nosetest but which can be applied to any function""" def decorated(function): def app(*args, **kwargs): if setup: setup() try: function(*args, **kwargs) f...
f9e8eddfd01ee99e458857de403c49b91dafa92c
14,492
import click def post_options(): """Standard arguments and options for posting timeseries readings. """ options = [ click.argument('port'), click.argument('value', type=JSONParamType()), click.option('--timestamp', metavar='DATE', help='the time of the reading'...
7b7c386bfcbf36f1365392a6ba2562fa0ed520ce
14,493
def authenticated(f): """Decorator for authenticating with the Hub""" @wraps(f) def decorated(*args, **kwargs): token = request.cookies.get(auth.cookie_name) if token: user = auth.user_for_token(token) else: user = None if user: return f(u...
1149f14ad540521b71efa3a3240c13719ccf8a17
14,494
def json_complex_hook(dct): """ Return an encoded complex number to it's python representation. :param dct: (dict) json encoded complex number (__complex__) :return: python complex number """ if isinstance(dct, dict): if '__complex__' in dct: parts = dct['__complex__'] assert len(parts) == 2 return pa...
a3c8cb13485279ab3b222eb63efdfdf6421c17a6
14,495
def reg_logLiklihood(x, weights, y, C): """Regularizd log-liklihood function (cost function to minimized in logistic regression classification with L2 regularization) Parameters ----------- x : {array-like}, shape = [n_samples, n_features + 1] feature vectors. Note, first column of x mu...
4a13bac09a6989463014784c72c72729ec40e718
14,496
def smooth_internal(xyzlist, atom_names, width, allpairs=False, w_morse=0.0, rep=False, anchor=-1, window='hanning', **kwargs): """Smooth a trajectory by transforming to redundant, internal coordinates, running a 1d timeseries smoothing algorithm on each DOF, and then reconstructing a set of consistent cart...
68c5bc7cacc0c14d2e9fad49d3017e5154d57a83
14,497
import argparse def cli(): """Define the command line interface of the script.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument("--output", help="the directory to store the archives") parser.add_argument("...
a555ea585cc26fe41ce1d9f95b75ee2ca443cdae
14,498
import itertools def estimate_gridsearch_size(model, params): """ Compute the total number of parameter combinations in a grid search Parameters ---------- model: str name of the model to train. The function currently supports feedforward neural networks (model = 'FNN'), long-short ...
8105a457b3ec30c3cdc6c42bb71afd229770b376
14,499