content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def deduce_look_back(in_features, target_features): """From the feature names, determine how large of a look back is used. Args: in_features (list of str): Names of input features target_features (list of str): Names of target features. Returns: int: Number of look ...
bae20baec986c888acfff159b491635e2e75a455
57,300
def parse_response(resp: dict, city: City) -> Temperature: """parse json response from Weather API into a Temperature Obj""" data = resp.get("main", {}) city.country = resp.get("sys", {}).get("country", "") city.name = resp.get("name", city.name) return Temperature( temp_max=data.get("temp_m...
04e9d96d4d679aa0b6e469f62ad6694adf6c1f33
57,301
from typing import List async def create_journal_entry_tags( db_session: Session, journal_spec: JournalSpec, tag_request: CreateJournalEntryTagRequest, user_group_id_list: List[str] = None, ) -> List[JournalEntryTag]: """ Tags the given journal entry. """ journal = await find_journal( ...
aa69c795258727fb3a253ded9a39af1d0da989dc
57,302
def runFairOracles(chosed_atts,current_file,alpha_default=0.05,k_threshold=200,k_percentage=0.5): """ Run all fairness oracles: FA*IR, Pairwise and Proportion Attributes: chosed_atts: list of sensitive attributes current_file: file name that stored the data (with out ".csv" suffix) ...
c9e3f23f91fe6b70637893a2261179c803f62368
57,303
def is_v2_behavior_enabled(): """Returns if user called tf.enable_v2_behavior.""" # Since there is no actual tf.is_v2_behavior enabled, check that the # settings were enabled. return tf2.enabled()
202e4f07f9bc68da76da278f0b999d9e3b71b8fb
57,304
def calc_burst(data): """ Recalculate values from d_calc for a run with bursts where each measurement is one pulse form the burst :param data: :return: """ pulse_energy = [] burst_energy = 0 burst = len(data) freq = data[0]['burst_f'] print("Burst with "+str(burst) + ' pulses') ...
4c099d11ea7e0b6e8cff1912bb72d9d9e996f5b3
57,305
def reorder_inplace(x, y, ordv, midx, midy): """ This function plays an integral role in tree formation and does several things: 1) Determine which points belong to which subnodes 2) Reorder x, y, and ordv variables 3) Compute the number of points in each new subnode Inputs: ...
452cb0891f43ec8f134d1df7d989397d1baed5a8
57,306
def restore_origin_data(data, make_copy=True): """ :param data: xarray :param make_copy: if True the initial data isn't changed :return: xarray with origin data """ if make_copy: data = data.copy() dims = data.dims data = data.transpose(ds.FIELD, ds.TIME, ds.ASSET) data.loc[f...
5b8848447f9903cacd2e0adf47f6b2cd86acd8f4
57,307
import inspect def use_np_shape(func): """A decorator wrapping a function or class with activated NumPy-shape semantics. When `func` is a function, this ensures that the execution of the function is scoped with NumPy shape semantics, such as the support for zero-dim and zero size tensors. When `func` ...
2bf86970984c2128c76fda6ce9004c5d611607f2
57,308
import json import requests def discover_device(ip_address, headers, discover_user_name, discover_password, list_of_ip, device_type): """ Discover devices """ discover_payloads = get_discover_device_payload() discover_payload = discover_payloads.get(device_type) discover_payload["DiscoveryConfigModels...
0dbf6bcf717c74e8fef84d2ff3db07e0f6602abd
57,309
def plaintext(text, keeplinebreaks=True): """Extract the text elements from (X)HTML content :param text: `unicode` or `genshi.builder.Fragment` :param keeplinebreaks: optionally keep linebreaks """ if isinstance(text, Fragment): text = text.generate().render('text', encoding=None) else:...
4e26b05065e64a77099a8e2238d5aa834686bc50
57,310
def permutations_deprecated(s): """Get all the permutations of a string, i.e. anagrams E.g. 'abc' => ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] """ if len(s) == 0: all_permutations = [] elif len(s) == 1: all_permutations = [s] else: all_permutations = [] stri...
a486a10a4a41175fcd6ba7819369161494177af3
57,311
from typing import Union from typing import Tuple def _expand_kernel( kernel_size: Union[int, Tuple[int,...]], n: int = 2 ) -> Tuple: """ Expand an integer kernel size to tuple Arguments: kernel_size : int or tuple of ints that determines the kernel's spatial dimensions ...
12388a0e61b0fcd447a33b9155a62d359effcd1d
57,312
import os def in_continuous_integration() -> bool: """Returns `True` if currently running inside a continuous integration context.""" return any(env in os.environ for env in CI_ENVIRONMENT_TELL)
8790a2d796eea8502dfea71d6b3b4c8b606da5d1
57,313
from operator import sub def strd(V): """ Stretching Deformation <div class=jython> STRD ( V ) = DDX ( u ) - DDY ( v ) </div> """ return sub(ddx(ur(V)),ddy(vr(V)))
374d16444e6e00e91201d602a909f767ac085bc1
57,314
def get_all_network(tenant_id): """Get all networks for a tenant. :param tenant_id: Neutron tenant identifier """ session = db.get_session() with session.begin(): model = HuaweiSwitchNetwork none = None all_network = (session.query(model). filter(model.te...
5e80c90ecdee10c237e61a59c8b9f0dbd7ba2472
57,315
def bbox_transform_inv(bbox): """convert a bbox of form [xmin, ymin, xmax, ymax] to [cx, cy, w, h]. Works for numpy array or list of tensors. """ with tf.variable_scope('bbox_transform_inv') as scope: xmin, ymin, xmax, ymax = bbox out_box = [[]]*4 width = xmax - xmin + 1.0 height = ymax - ymin ...
2fa1a38915a0e90e5af211e4761dda1b68c33eb1
57,316
def GetStackTrace(debugger_dir, symbol_path, dump_file): """Gets and prints the stack trace from a crash dump file. Args: debugger_dir: the directory where the debugger is installed. symbol_path: symbol path for debugger. dump_file: the path to dump file. Returns: A string representing the stack ...
1fba6caf2d1b1a70dccca7560197555721a22ea2
57,317
from typing import Optional from typing import List from typing import Tuple def _pedigree_checks( b: hb.Batch, samples_df: pd.DataFrame, reference: hb.ResourceGroup, sites: hb.ResourceFile, ped_file: hb.ResourceFile, overwrite: bool, # pylint: disable=unused-argument fingerprints_bucket:...
8566af9b4cf0d11dc3f9e5bd7ac7292c984498b9
57,318
def insert_paragraphs(renderable_items): """Returns a new list of renderable_items where contiguous items of type TEXT and URL are collapsed into a ParagraphItem instance. """ new_renderable_items = [] curr_paragraph = [] def _end_curr_paragraph(): if curr_paragraph: renderable_item = Renderable...
da26210660142d7db4c663f289913c73b587d51c
57,319
def round_based_player(*bot_moves): """ A Player which makes a decision dependent on the round index in a dict or list. (Or anything which responds to moves[idx].) Parameters ---------- moves : list or dict of moves the moves to make, a move is determined by moves[round] """ def mov...
2c3e57aae7d6a89c76f735bd7a267ff965d67256
57,320
import os def is_directory_executable(directory): """ check if a pathlib.Path() directory is executable """ return os.access(str(directory), os.X_OK)
80d4077014228b8b91c6f4aef5bb0c0e919e21d5
57,321
def view_newsletter_contact(request, slug, uidb36, token): """Visualization of a newsletter by an user""" newsletter = get_object_or_404(Newsletter, slug=slug) contact = untokenize(uidb36, token) ContactMailingStatus.objects.create(newsletter=newsletter, contact=c...
1142431ed982ae75a2e404f44c2f6ac1edc9666a
57,322
import argparse def _error_rate_arg(val): """Validates the error_rate for the arg parser""" try: val = float(val) except ValueError: raise argparse.ArgumentTypeError(f"{val} is not a floating-point literal") if val >= 0.0 and val <= 1.0: return val raise argparse.ArgumentT...
22e985cd3df59746c364316f289b65fe7bc768d2
57,323
def to_Mw(rho): """ Converts from Tape2012 magnitude parameter to moment magnitude """ return ((np.log10(rho/np.sqrt(2))-9.1)/1.5)
3d75cd040704abc3ba8bc681ba47f163722ff126
57,324
import re def add_post(post, title=None, link=None, tags=None, author=None, to=None, private=False, type='post', auto_subscribe=True, files=None): """ Add a new post """ if isinstance(post, Post): if post.id: raise PostUpdateError elif isinstance(post, (str, unicode)): ...
0492a76272faa1bf4b69baab0cde453521eba0ed
57,325
import joblib def GetModel(a="Model.pkl"): """ :param a: 模型文件名 :return: [socre: MAE评估结果, X_test: 预测数据集] """ # 取到数据 [X_train, X_valid, y_train, y_valid, X_test] = ProcessData() # 用XGB模型,不过用有bug # modelX = XGBRegressor(n_estimators=1000, learning_rate=0.05, random_state=0...
becbf90180d2bf362cb8144fee2f4a651324a43e
57,326
def permutations_exact(n, k): """Calculates permutations by integer division. Preferred method for small permutations, but slow on larger ones. Note: no error checking (expects to be called through permutations()) """ product = 1 for i in range(n - k + 1, n + 1): product *= i retur...
4244e446aad6b36185575c8c7991bd05984b0796
57,327
def parse_header(file,string): """Function to extract instrument settings from FORC data file header Inputs: file: name of data file (string) string: instrument setting to be extracted (string) Outputs: output: value of instrument setting [-1 if setting doesn't exist] (float) """ ...
4865e1e54629585281f4ea04258cb44aa68eada7
57,328
import os import subprocess import warnings def get_git_devstr(sha=False, show_warning=True, path=None): """ Determines the number of revisions in this repository. Parameters ---------- sha : bool If True, the full SHA1 hash will be returned. Otherwise, the total count of commits ...
abcc0db0e19f1c3fc34f5d1d03910ab283df6270
57,329
import random import networkx def subgraph_stable_topsort_test(graph): """Test that sort is stable for subgraph""" def shuffle_graph(graph): nodes = list(graph.nodes()) random.shuffle(nodes) new_graph = networkx.DiGraph() for name in nodes: new_graph.add_node(name) ...
c76cb214aef90e769ad66a88e945819a4bc4878d
57,330
import pandas def get_functions(name=None, **kwargs): """Returns all available functions as pandas dataframe. :param name: optional filter expression for the functions, if it is not included in the name, the function will not be added to the data set. :type name: str...
6c71288f90aa46b8bc78b74b214f2485a1dd4b18
57,331
def copy_wings(original_wings): """ This copies VLM attributes for every wing object in original_wings into a new wings container with new Data objects Inputs: original_wings - the original wings container """ return copy_large_container(original_wings, "wings")
340561b594002ac7114a381e07fd1e2c638f4d8b
57,332
def document_toc(document_instance, setting_key="default"): """ Get the TOC (Table Of Content) from the content of the given instance (*Pages* or *Insert*) and settings """ return mark_safe( get_toc_with_cache(document_instance, setting_key=setting_key) )
d4d4b23c1a0f060d2f5fb2db42332a6f22c00c5a
57,333
def get_group(machine, num): """ """ cores = [] idx = 0 r = 0 while num>0: assert r<machine.get_cores_per_node() cores.append(idx) idx += machine.get_cores_per_node() if idx>=machine.get_num_cores(): r += 1 idx = r num -= 1 retu...
2a295b0dc11cc9e195fc54787b5355e340dce366
57,334
import os import traceback def load_jekyll_site(docroot, defaults): """ Loads the Jekyll content from the given docroot folder. """ documents = [] for root, dirs, files in os.walk(docroot): for name in files: path = os.path.join(root, name) try: doc ...
eb1d622e86b96009e09264ab31c96fba4bee3390
57,335
def do_footer(_, token): """ Create a footer containing a github link and domain registration information. Take no arguments. """ if len(token.split_contents()) != 1: raise template.TemplateSyntaxError('%r tag requires no arguments' % token.contents.split()[0]) return FooterNode()
3f11d2eefc909db122df7de03b22c1b03948f10b
57,336
def attachment(url: str, filename="") -> dict: """ Returns a dictionary using the expected dicitonary format for attachments. When creating an attachment, ``url`` is required, and ``filename`` is optional. Airtable will download the file at the given url and keep its own copy of it. All other attac...
24564ca3e7dfb8cc35242b1d16fb7351fc9576ce
57,337
def convert_coverage_to_lookup(country, coverage): """ Takes a list of dicts and returns a dict for each access. """ GID_level = 'GID_{}'.format(country['regional_level']) output = {} for item in coverage: output[item[GID_level]] = { '2G': item['2G'], '3G': ite...
0190c76efee993d8f27f58dca01338c076b04cb2
57,338
def _exchange_coupling_terms(coupling_symbols, ordered_edges): """Exchange coupling terms between systems Args: coupling_symbols (list): coefficients of exchange couplings ordered_edges (list): list tuples of system indices for the couplings Returns: list: exchange coupling strings ...
30a90118adf783c8cd4116fca415c0df28d3d700
57,339
import psutil import sys def calculate_thread_pool(): """ Returns the default value for CherryPY thread_pool: - calculated based on the best values obtained in several partners installations - value must be between 10 (default CherryPy value) and 200 - servers with more memory can deal with more t...
0a3ee895b6c9cb08bc257fab16569d9f0da27370
57,340
import os def find_file( top_directory_name, cyclone_id_string, valid_time_unix_sec, raise_error_if_missing=True): """Finds NetCDF file with satellite data. :param top_directory_name: Name of top-level directory with satellite data. :param cyclone_id_string: Cyclone ID (must be accepted b...
625449c53e093c1ace8d302acb4ecf6305185c4b
57,341
import torch def inv3d(H, sym=False): """ Calculates the inverse of a batched 3-D matrix """ detH = determinant_3d(H) Hinv = torch.empty_like(H) Hinv[..., 0, 0] = H[..., 1, 1] * H[..., 2, 2] - H[..., 1, 2] * H[..., 2, 1] Hinv[..., 1, 1] = H[..., 0, 0] * H[..., 2, 2] - H[..., 0, 2] * H[...,...
a154268fc9b93b704d4a4c1312e9e0a4d8e3a51b
57,342
def NIST_SU(results): """Number of segmentation errors (missed segments and false alarm segments) over number of reference segments. """ assert len(results) == 3 TPs = results[0] FPs = results[1] FNs = results[2] if (FNs + FPs) == 0: return 0.0 return ((FNs + FPs)/(TPs + ...
3c60a612223dc247109d24be45b32739af8587ef
57,343
def _get_identity(op, dtype): """Get an appropriate identity for a given operation in a given dtype.""" if op is lax.scatter_add: return 0 elif op is lax.scatter_mul: return 1 elif op is lax.scatter_min: if jnp.issubdtype(dtype, jnp.integer): return jnp.iinfo(dtype).max return float('inf')...
7e92d8df2dc25c8b9d6f423105f7d1ae73cbb6ba
57,344
def val_interm(hsl1, hsl2, pos): """ Valeur intermédiaire entre la couleur 1 et la couleur 2 pos correspond à la postion dans la transition, entre 0 (couleur 1) et 1 (couleur2) """ # res_h = (hsl2[0]-hsl1[0])*pos + hsl1[0] # hue value transition can be tricky to compute # we have to decide if we...
8f4b9ecd5d2e1db084e1a41772086d37d398aa04
57,345
def pathCountX(stairs: int, X): """number of unique ways to climb N stairs using 1 or 2 steps""" #we've reached the top if stairs == 0: return 1 elif stairs < 0: return 0 else: validSteps = [] for num in X: if stairs >= num: validSteps.app...
8ee8bf554f6176b5f666fe33eea51a3ee982deee
57,346
def top_value_counts(df, n=5, only_categories = True, cols_to_include = None, cols_to_exclude = None): """ Function to generate summary information for string or categorical data in dataframes""" if cols_to_include: df = df[cols_to_include] if cols_to_exclude: df = df[df.columns[~df.col...
bea88ab28985d71591ad9587b025223ea075aeb4
57,347
import torch def tik_reg(mat: ComplexTensor, reg: float = 1e-8, eps: float = 1e-8) -> ComplexTensor: """Perform Tikhonov regularization (only modifying real part). Args: mat (ComplexTensor): input matrix (..., C, C) reg (float): regularization factor eps (float) Returns: r...
b148e551b690407cb557e4ad90736af28ae66616
57,348
def current_cloud_token(service): """Get the the current state of the account. Args: service: Drive API service instance. Returns: int """ response = service.changes().getStartPageToken().execute() return response.get('startPageToken')
dc2b61c2c0e5548269a6c746cf8dc1d152ec953d
57,349
def workflow_create(request, workflows_definition): """Create workflow. :param workflows_definition: Workflows definition """ return mistralclient(request).workflows.create(workflows_definition)
93e4fd97b9f745ed5e609399748926329b6d687c
57,350
import re import yaml def scan_info(cell_id, basedir): """ Scans the info.dat for meta information about the recording. Args: cell_id: id of the cell basedir: base directory where the data lives """ info = open(basedir + cell_id + '/info.dat').readlines() info = [re.sub(r'[^...
e5404b048827fdb0d52bfa9f52bd26ccbe67748e
57,351
def geo_disjoint(left, right): """ Check if the geometries have no points in common. Parameters ---------- left : geometry right : geometry Returns ------- disjoint : bool scalar """ op = ops.GeoDisjoint(left, right) return op.to_expr()
0628258944c90230fb4edcf88b529685c1cce0e9
57,352
import datasets import tqdm import torch def train(model, optimizer, Y, epoch, batch_size, data_path, gpu, version, dicts, quiet): """ Training loop. output: losses for each example for this iteration """ print("EPOCH %d" % epoch) num_labels = len(dicts['ind2c']) losses = [] #...
462e9d7836d6b6ec3a7e44f02afa04cafaf6e71c
57,353
def split_line_and_comment(line): """ Returns a tuple(line, comment) based on a '//' comment delimiter. Either `line` or `comment` may be ''. Does not strip whitespace, nor remove more than two slashes. """ split = line.split('//', 1) if len(split) == 1: return split[0], '' ...
32f478d4ce90b012d63ae48a2c75ed59a9dc00fc
57,354
import os import hashlib def verify_checksum(checksum_file): """Verify checksums supplied with the raw data. Parameters ---------- checksum_file : :class:`str` The checksum file. Returns ------- :class:`str` An string that describes the errors encountered while verifying ...
ed6fd9ca186d3ffb7dcff3698e8f6d2e31a36f9f
57,355
def compare_descriptor_types(a, b): """Compare two metric types to sort them in order.""" # pylint: disable=invalid-name a_root = a['type'][len(StackdriverMetricsService.CUSTOM_PREFIX):] b_root = b['type'][len(StackdriverMetricsService.CUSTOM_PREFIX):] return (-1 if a_root < b_root else 0 if a_root ...
ad6e5f36beb6cf1e766891c4d34cae48c34820c4
57,356
def build_dict_as_specific_ppdcases_per_member(path_to_file): """ Build a dict with the key being the member ASN and the value a set of the ASNs belonging to its customer cone. """ print "Cones ASes dataset: {}".format(path_to_file) if path_to_file.lower().endswith('.txt'): # customer cone datas...
ee5a212318aa1f47b7f1d69121a51801018a23e0
57,357
def _(tag, child_element_list_or_other=None, attrib_custom={}): """XML Element.""" tag_real = tag.split('-')[0] child_element_list_or_other = child_element_list_or_other or [] attrib = DEFAULT_ATTRIB_MAP.get(tag, {}) attrib.update(attrib_custom) attrib = dict(zip(attrib.keys(), list(map(str, at...
0e6c48d4659e10161df2204e797b8969a1ba0ed4
57,358
import logging import six def log_method(log, level=logging.DEBUG): """Logs a method and its arguments when entered.""" def decorator(func): func_name = func.__name__ @six.wraps(func) def wrapper(self, *args, **kwargs): if log.isEnabledFor(level): pretty_a...
b9c2c95db93df55c5e4427594c03c08f623254bd
57,359
def sort_stack(stack_object: list) -> list: """ Sorts stack. :param stack_object: stack object, iterable object :return: sorted stack, iterable object """ tmp_stack = [] while stack_object: # complexity check print(f'stack 1') element = stack_object.pop(-1) w...
ebdca3c263dfdc72bcdb0843b9e6e7d397ba2236
57,360
def execute(circuits, backend, config=None, basis_gates=None, coupling_map=None, initial_layout=None, shots=1024, max_credits=10, seed=None, qobj_id=None, hpc=None, skip_transpiler=False): """Executes a set of circuits. Args: circuits (QuantumCircuit or list[QuantumC...
217bd6bb02a87bf9c95ec40eda5f985e7c69937a
57,361
import torch def calculate_interaction_nominal(genotypes_t, phenotypes_t, interaction_t, residualizer, return_sparse=False, tstat_threshold=None): """ genotypes_t: [num_genotypes x num_samples] phenotypes_t: [num_phenotypes x num_samples] interaction_t: [1 x num_s...
f3270e7623d8c3d3e6cdd706142b43650d21a7b4
57,362
from datetime import datetime def sync_run_job(job, settings=None, pid=None, tables=[], silent=False): """ Run synchronization job """ # Notification helpers error = lambda message, pid=pid, silent=silent: not silent and \ s3_sync_push_message(message, pid=pid, error=True) notify ...
a6572843f6cb0a9021763029b21ea6f8e65b6170
57,363
from typing import List def remove_too_short(utterances: List[Utterance], _winlen=25, winstep=10) -> List[Utterance]: """ Removes utterances that will probably have issues with CTC because of the number of frames being less than the number of tokens in the transcription. Assuming char...
0c64a0a60c34498d7c99f906b08d16bfa710def7
57,364
from typing import Union def test_set(startDate: str = None, endDate: str = None, ticker: Union[str, list] = "AAPL", **kwargs) -> pd.DataFrame: """Test sets which are called from Quandl each time. The function currently calls the given ticker close prices from the WIKI/PRICES database from Quandl. If no s...
4c2f529887d65370c6d5b793fa9966a2ccf3788d
57,365
def parse_default_kv(default, default_dict): """parse a string in form key1=value1;key2=value2,... as used for some template fields Args: default: str, in form 'photo=foto;video=vidéo' default_dict: dict, in form {"photo": "fotos", "video": "vidéos"} with default values Returns: di...
4d461589118915cde5461b6b8ea7cd5e5e4d5165
57,366
import copy def train_network(model, train_data, val_data, optimizer, loss_function, num_epochs=300, patience=20, print_progress=True): """Trains NN. Parameters ---------- model: NeuralNetwork instance train_data: torch.utils.data.DataLoader Training data. val_data : t...
46b8c600e61625a72a4d515a55e560d47c15c9ee
57,367
def Npts(*args): """ (read) Get Number of points in active Loadshape. (write) Set number of points to allocate for active Loadshape. """ # Getter if len(args) == 0: return lib.LoadShapes_Get_Npts() # Setter Value, = args lib.LoadShapes_Set_Npts(Value)
a7f778b9adb086290b35cd6be71399d56463f7bf
57,368
def normalize_01(inp: np.ndarray): """Squash image input to the value range [0, 1] (no clipping)""" inp_out = (inp - np.min(inp)) / np.ptp(inp) return inp_out
c9d62cbf80883dbdcf9dccf455f64cc961d8cb1e
57,369
def rate_map(Hx, Hy=0, Hz=-400, T=3.21): """Finds the slowest nonzero eigenvalue of the rate matrix for a given transverse field H, hard plane angle phi, and longitudinal field Hz.""" return np.sort(np.abs(rate(Hx, T, ph1, ph2, Hy, Hz).eigenenergies()))[1]
7657e3b361c587b9eb89830bd1fe65e0db0c952a
57,370
def prefix_connection_id(connection_id, parent_connection_id): """Used to distinguish connection ids when they have the same id as a parent_connection. """ if not len(connection_id) > len(parent_connection_id): return parent_connection_id + connection_id return connection_id
bdc1f92625a03c6b88dd6c81097aca0522db0929
57,371
def try_to_open(file_name, mode): """Try to open file and retry twice if unsucessful.""" file_handle = None success = True try: file_handle = open(file_name, mode) except: sleep(2) try: file_handle = open(file_name, mode) except: sleep(10) ...
97dcdf210743bab360adc9940d2599d633b308da
57,372
import itertools def get_data_for_lang(language): """ Extracts Trending data from twitter for a specified language Input-> language - a string which specifies the language the tweets are required in. Output -> x - A dataframe consisiting of data for the language specified. """ ...
616c6918b3ab48c9a656b1a95de309f6bf5fc458
57,373
def extract_other_features(paths, path2gt, model_type): """Extracts MusiCNN or OpenL3 features and their corresponding ground_truth and identifiers (the path). OpenL3 features are extracted from non-overlapping audio patches of 1 second, where each audio patch covers 128 mel bands. MusiCNN f...
1c5cefb762a9ce019589766a357667a011c224bc
57,374
import os def read_tree(path): """ Read the directory structure of a path into a dictionary where files are True values, and subdirectories are more dictionaries.""" tree = {} for dirpath, dirnames, filenames in os.walk(path): d = tree for x in os.path.relpath(dirpath, path).split(os.s...
f340ac968ad3617843c3643f9af58ef0738ab72c
57,375
import numpy def detect_frame(surf, vacuum=(255, 255, 255)): """Returns a Rect of the minimum size to contain all that is not <vacuum>""" if not HAS_NUMPY: miscgui.functions.debug_msg("Numpy was not found on this machine.\ Cannot call detect_frame. Returns surface's size instead.") ...
ad781104e968ef7acd3759df091758f483915396
57,376
def press_key(v_key): """ 按下某个按键 :param v_key: :return: """ return send_kb_event(v_key, True)
a94d5f3bbc4cbe3c13c2e7b9b964158b11133eac
57,377
def trotz(theta): """ Rotation about Z-axis @type theta: number @param theta: the rotation angle @rtype: 4x4 homogeneous matrix @return: rotation about Z-axis @see: L{trotx}, L{troty}, L{rotz} """ return r2t(rotz(theta))
909db720d7924ca0000670603cd8ff786a728312
57,378
def read_input_file(input_filename): """Read a formatted input file and return a dictionary of keywords. :param input_filename: Filename of the SENKIN input file. """ # Initialize the dictionaries and lists that will be filled by # the parsing. keywords = {} reactants = [] oxidi...
8280073efa57469e25bbadb73830455d69e826fa
57,379
import os def idl_basename(f): """returns the base name of a file with the last extension stripped""" return os.path.basename(f).rpartition('.')[0]
201756c58254c1ac70de136289a23917e86718be
57,380
def welcome(): """List all available api routes.""" return ( f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start (enter as YYYY-MM-DD)<br/>" f"/api/v1.0/start/end (enter as YYYY-MM-DD/YYYY-M...
5062f97d9db404fd3883d0861e2a2e3f9bdb4479
57,381
def new_keyset(lang: str, template: tink_pb2.KeyTemplate) -> bytes: """Returns a new KeysetHandle, implemented in lang.""" global _ts return _primitives.new_keyset(_ts.keyset_stub(lang), template)
84fd2e59d3138f2eaac9d4df71476cb832ad5aa1
57,382
import re def extract_intro_and_title(filename, docstring): """ Extract the first paragraph of module-level docstring. max:95 char""" # lstrip is just in case docstring has a '\n\n' at the beginning paragraphs = docstring.lstrip().split('\n\n') # remove comments and other syntax like `.. _link:` ...
f1ae63f112f0c4ff91ba8863313b9bd978e16eb4
57,383
def _process_symbols(exp, symbol_type, symbols): """ Args: exp (ExperimentSet): The current experiment set symbol_type (str): CONSTANT, FUNCTION, or TABLE symbols ([[str]]): List of symbol names and values usually ["SYM","=","VALUE"] Returns: ExperimentSet: the passed exper...
33e03eb4e327becdf472bff9d62a6d2cf046cfdd
57,384
import os from datetime import datetime import re def get_info_from_modis_tif(file_path) -> dict: """ file_path: "MCD12Q1.A2018001.h25v04.006.2019200013451_08.tif" or absolute path > get_info_from_modis_tif(r"MCD12Q1.A2018001.h25v04.006.2019200013451_08.tif") """ print(file_path) res = {} ...
a26e10e3bff2796b6bdfada51d0830c8757a8656
57,385
def interp(prec: np.ndarray, method: InterpType = InterpType.ALL) -> np.ndarray: """Interpolate the precision over all recall levels. See equation 2 in http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.167.6629&rep=rep1&type=pdf for more information. Args: prec: Precision at all recall l...
832737de9fdce27c62d6b5468e23737d0d3ce8bd
57,386
def test_array_access_needs_frozenset(): """Array access fails without frozenset?""" l = lattice.PartialOrderLattice(3, lat_dir='../lattices') return l[4]
5a7d2e726824f146d0166ed60ae87b14e891ce9d
57,387
from pathlib import Path import os def get_logs_dir(): """ This is to get the absolute path of the logs folder :return: logs_dir, the absolute path of the logs """ logs_dir = Path(get_project_folder_dir()) / "logs" if not Path(logs_dir).exists(): os.mkdir(logs_dir) return logs_dir
af1243eb0a94e772d15d7fe464ebe160d1b575df
57,388
def likelihood(X, mean, cov, pi): """対数尤度関数""" summation = 0.0 for n in range(len(X)): temp = 0.0 for k in range(K): temp += pi[k] * gaussian(X[n], mean[k], cov[k]) summation += np.log(temp) return summation
a4891947b4abce50701093d796654419b188170d
57,389
def str2dec(s): """ string to decimal number. """ if not len(s): return 0 return int(str2hex(s), 16)
ce8befd465843675324886edccb0cfd01ead965a
57,390
def show_k8s_extension(client, resource_group_name, cluster_name, name, cluster_type): """Get an existing K8s Extension.""" # Determine ClusterRP cluster_rp, _ = get_cluster_rp_api_version(cluster_type) try: extension = client.get( resource_group_name, cluster_rp, cluster_type, clus...
7f174c2b4cb670bce95d88b9391270a455621a9f
57,391
def get_current_connection(): """Returns the current SMTP connection (i.e. the topmost on the connection stack). """ return _connection_stack.top
12d3b615123e6fe616fd1f218c623337f199263f
57,392
def __radd__(self, other): """Computes the addition between two numbers. Parameters ---------- self : ee.Number Right operand. other : ee.Number | numeric Left operand. If numeric, an ee.Number is created from its value. Returns ------- ee.Number Addition of two...
8f2e1bde381a2c482c62b6530f0508423cc34e71
57,393
def getLMPfile(filepath, filename, tz, squeeze=False, product='lmp'): """ To use for MCC, MCL, MCE (instead of LMP): * Keep default filepath, to io/lmp-nodal/da/, and specify product='mcc' (or 'mcl' or 'mce') * OR keep product as 'lmp' or None, and set filepath to the folder containing the ...
5c41fec7df3fe41a71515bc698a4ba7c0cc21398
57,394
import os def get_html_directory(): """ Returns directory for raw HTML to scrape. """ return os.path.join(os.path.dirname(__file__), 'html')
9c34953712760652f42d7f5700fd9c5966061012
57,395
def is_valid_customer_category(process_id: int, customer_category: str) -> bool: """Checks whether a customer_category string is part of the customer categories of a certain process. :param process_id: process to be checked :param customer_category: category to be checked :return: True or False """...
4e0cdd2a0641a6eff7608cdaa8b003c64980788c
57,396
import os import numpy def MakeExtension(ext_name, file_extension): """Generates an Extension object from its dotted name.""" ext_path = ext_name.replace(".", os.path.sep) + file_extension return Extension( ext_name, [ext_path], include_dirs = ['.', numpy.get_include()], extra_compile_a...
ced079eb9b3a2d178130c37b4a397ef37ca94843
57,397
def _map_job_status_to_human_representation(status, resource, token): """ Map an Job Status type code (e.g., 1, 2) to a human readable name. :param status: integer with the value that we want to transform :param resource: resource containing all the values and keys :param token: user token """ ...
d135b6dd2dce665ecd50f232496ccf8f7866a7ec
57,398
import importlib.resources as pkg_resources import importlib_resources as pkg_resources from cortex import binary def get_cli_path() -> str: """ Get the location of the CLI. Default location is the directory containing the `cortex.binary` package. The location can be overridden by setting the `CORTEX...
bb97dc1e68616f4d9bc483844724867ef101ad7d
57,399