content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import collections def reorder(fields, order, key): """ Reorders `fields` list sorting its elements in order they appear in `order` list. Elements that are not defined in `order` list keep the original order. :param fields: elements to be reordered :param order: iterable that defines a new order ...
48eb32841f5abec38c74a8ae88615a7c39d3087c
3,610,500
import logging import os def generate_tiles(src_info, st_data_dir, url, wkt, no_data_value, intermediate): """Generate tiles for emissivity standard deviation from ASTER data Args: src_info <SourceInfo>: Information about the source data st_data_dir <str>: Location of the S...
6206cea9a3941b046c570c3d6aa3627269a46cc3
3,610,501
from typing import Union import os def create( model_path: str, model_type: str = "smpl", **kwargs ) -> Union[SMPL, SMPLH, SMPLX, MANO, FLAME]: """Method for creating a model from a path and a model type Parameters ---------- model_path: str Either the path to the model you wish to load o...
5db4621ca5dfb02ba0cbe114f3d9d2d7591135ff
3,610,502
def noisify_dfc2018_asymmetric(y_train, noise, random_state=None): """ mistakes in labelling the land cover classes in 2018 DFC Houstan HSI dataset class 0 --> class 1, class 3 class 1 --> class 5 class 3 --> class4, class 7 class 4 --> class 3, class7, class 10 class 7 --> class9, class 10, (cl...
30560a2c351e11e84d194d71acbe942fe6e4cf08
3,610,503
from typing import Union from typing import Optional from typing import List from typing import Dict from typing import Any from typing import Tuple import io def encoding_quality( image: Union[str, Image.Image], output_path: Optional[str] = None, quality: int = 50, metadata: Optional[List[Dict[str, A...
3babe50b0ba8c657b1c2ea9733c41e8aed544bd1
3,610,504
def extCheck( extention: str ) -> str: """ Ensures a file extention includes the leading '.' This is just used to error trap the lazy programmer who wrote it. :param extention: file extention :type extention: str :return: Properly formatted file extention :rtype: str """ if extentio...
7055c23cd8d2fa0e74dd916aa6d06d9547d49b7f
3,610,505
def ui_routes(): """Import all static routes""" return [static]
23e51c0c32b58007d6001a458a3942473763f695
3,610,506
def create_transaction(sender: str, recipient: str, amount: float): """insert new transaction to mempool""" transaction = transactions.create_transaction( sender=sender, recipient=recipient, amount=amount, type="transfer", ) return transaction
1525a934106c292624dae2722f5b0c7f5e15c3f9
3,610,507
import logging def load_data(in_file, max_example=None, relabeling=True): """ load CNN / Daily Mail data from {train | dev | test}.txt relabeling: relabel the entities by their first occurence if it is True. """ documents = [] questions = [] answers = [] num_examples = 0 f...
da81dcc56469aaccee3da36d1451ac8eaeb4a2b7
3,610,508
import json def sort_dict(original, parent_path=''): """Transforms a dict into the format Authy requires""" flattened_dict = '' for key in sorted(original): value = original[key] if parent_path: flattened_key = parent_path + '[{0}]'.format(key) else: flatt...
f79ea541453bae9f301ca10cd84a97194d019289
3,610,509
def makeA(laplacian_matrix): """ This function create the all neighbor permutations. The output A multiply by Y will be [ Y_i - Y_j ].T for all j > i So the maximum will be C^n_2. But it will be less than this value because of the sparseness of L. Returns ------- A : sparse matrix, shap...
b5cf889649077fd8f92a8d659c908d47d6490202
3,610,510
from ._service import _configure_service from typing import Optional from typing import Union from typing import Callable from typing import cast def service( klass: Optional[C] = None, *, singleton: Optional[bool] = None, scope: Optional[Scope] = Scope.sentinel(), wiring: Optional[Wiring] = Wirin...
dba3ac7e81a54e017f6da316695dbbdcaace5a5b
3,610,511
def svn_diff_output_fns_invoke_output_diff_modified(_obj, output_baton, original_start, original_length, modified_start, modified_length, latest_start, latest_length): """svn_diff_output_fns_invoke_output_diff_modified(svn_diff_output_fns_t _obj, void * output_baton, apr_off_t original_start, apr_off_t original_len...
4cf2f3bcd6818ea5bfb749f07e6129fd51b188a8
3,610,512
import logging import subprocess def check_output(*popenargs, **kwargs): """Run command with arguments and return its output as a byte string.""" if 'stdout' in kwargs or 'stderr' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') logging.debug('Trying to execute %s...
67196a55f85cb3774b931112163e96bb21d8f35a
3,610,513
import copy def delete_items(dictionary, key_list): """ This function performs a deep copy of a dictionary, checks if the specified keys are included in the copy, and deletes key-value pairs accordingly. Parameters: dictionary (dict): a dictionary key_list (list): a list of the key...
45fb652661387ca5d40aea443c1d4a82f74db5bd
3,610,514
from typing import Set def build_deterministic_service_from_transitions( transition_function: TransitionFunction, initial_state: State, final_states: Set[State], ) -> Service: """ Initialize a service from transitions, initial state and final states. The set of states and the set of actions a...
e9ec2cf5cd9280ae0fa40bfa1b73c39c61ec4b37
3,610,515
def spreadLambdaProtocol(switching_values, steps, switching_types='auto', kind='cubic', return_tab_function=True): """ Takes a list of lambda values (either for sterics or electrostatics) and transforms that list to be spread out over a given `steps` range to be easily compatible with the OpenMM Discrete1DF...
cbd4ea39988c374f87c8f8061b7d30deacb5590d
3,610,516
def some_method(a1, a2): """ some_method returns the larger num :param a1: num1 :param a2: num2 :return: 1 or 2 """ if a1 > a2: return 1 elif a1 < a2: return 2 else: return 0
2505053aae5b0e0d1e906881d8de50b7ad97a28e
3,610,517
def restartATS(conf:Configuration) -> bool: """ A convenience function for calling :func:`setATSStatus` for restarts. :param conf: An object representing the configuration of :program:`traffic_ops_ort` :returns: whether or not the restart was successful (or unnecessary) """ doRestart = ( conf.mode is Configurat...
15f9b872a4cd4cec269e4ae718d25e885c968918
3,610,518
from typing import List def generate_res_count_graph( name: str, cloudwatch_data_source: str, loadbalancer: str, target_group: str, grid_pos: GridPos, notifications: List[str], ) -> Graph: """ Generate res graph """ xx2_alias = "2xx" xx3_alias = "3xx" xx4_alias = "4xx"...
e33de89621f25e990ac8bd5fca0546dd6b8bf186
3,610,519
def cost(prog): """Find the cost of a program tree.""" if type(prog) == VecOp: return COSTS["VecOp"] + sum([cost(p) for p in prog.children]) elif type(prog) == Op: return COSTS["Op"] + sum([cost(p) for p in prog.children]) elif type(prog) == Lit: return COSTS["Lit"] elif type...
37cc80ad1355d5a4f5d7abd0df85ab7340d3c28e
3,610,520
from re import T def transform_instance_annotations( annotation, transforms, image_size, *, keypoint_hflip_indices=None ): """ Apply transforms to box, segmentation and keypoints annotations of a single instance. It will use `transforms.apply_box` for the box, and `transforms.apply_coords` for se...
582124cbc98e10d00ca0589f689fa7de27382f97
3,610,521
def to_timestamp(value): """ Convert a time zone aware datetime to a POSIX timestamp (with fractional component.) """ return (value - epoch).total_seconds()
5c065d1056eb38afd25312e1dca5a6e8e260948a
3,610,522
def backends_mapping(custom_backend, private_base_url, lifecycle_hooks): """ Create 2 separate backends: - path to Backend 1: "/echo-api" - path to Backend 2: "/httpbin" """ return {"/echo-api": custom_backend("backend_one", endpoint=private_base_url("echo_api"), hooks=lifecycle_hooks), ...
b98fb61afc00efc902e5bd511fefcea6727a7125
3,610,523
import requests def post(json_attributes): """HTTP POST request.""" url = f"{API_URL}/v1/summaries/plain-text" response = requests.post(url, json=json_attributes) return response
061e4ea9f5aba2ab8503267c245cc8f4a444c972
3,610,524
def get_credentials(args): """ Return current or assumed role credentials """ sess = boto3.session.Session(profile_name=args.profile) sts = sess.client('sts') # Find out who we are ret = sts.get_caller_identity() if not 'Account' in ret: raise Exception('STS: Get Caller Identity fa...
0580e6405a8e8a9b6d0e1365cc57390c14a85ce4
3,610,525
def inf(shape, dtype, allocator=drv.mem_alloc): """ Return an array of the given shape and dtype filled with infs. Parameters ---------- shape : tuple Array shape. dtype : data-type Data type for the array. allocator : callable Returns an object that represents the m...
394b8ddc7746ed17dd0a697a66042436b3c652ca
3,610,526
def belief_propagation(model: GraphModel, max_iter: int = 1000, converge_thr: float = 1e-5, damp_ratio: float = 0.1) -> InferenceResult: """Inference with (loopy) Belief Propagation. Estimates partition function using Loopy Belief Propagation...
e816dbb83676324e08f29127c980b1f997f84b15
3,610,527
def model_loss(input_real, input_z, output_channel_dim, alpha): """ Get the loss for the discriminator and generator :param input_real: Images from the real dataset :param input_z: Z input :param out_channel_dim: The number of channels in the output image :return: A tuple of (discriminator loss,...
0d51ef038536cfbde4989bb1058b359d5be900b6
3,610,528
import json def compile_timestamped_transcript_files(json_filenames): """ `json_filenames` is a list of filepaths with this filename format: 00900-01000.json where the left-number represents the starting time offset and the right-number represents the ending time, in seconds Each file...
75dbf7541fbfc4df109a43cb51531d7d68c5e126
3,610,529
from sympy import Poly def _solve_inequality(ie, s): """ A hacky replacement for solve, since the latter only works for univariate inequalities. """ if not ie.rel_op in ('>', '>=', '<', '<='): raise NotImplementedError expr = ie.lhs - ie.rhs p = Poly(expr, s) if p.degree() != 1: ...
f90151b25d6225e382c0f5dac686f2ff5529cf0e
3,610,530
def verify_bgp_route_is_received( device, vrf, neighbor_address, default_rd, default_vrf, address_family, received_routes, ): """ Verify if VRF and Router Distinguisher have at least one received route Args: device ('obj') : Device object addr...
f8fba8f4fb0869c9fa0fb6a18c2b5e1367e71ad7
3,610,531
def theils_u_matrix(df): """ Wrapper around dython's theils_u. Given a dataframe df containing only categorical data, it calculates Theil's U for each combination of columns, filling an output matrix, and returns the output matrix. Parameters ---------- df : pandas.DataFrame The...
f2e370344abf182186f902cd01db2658f7a4c69b
3,610,532
def support(shape1, shape2, direction): """Find support for the Minkowski difference in the given direction. PARAMETERS ---------- shape1, shape2: Shape The inputs for Minkowski difference. `shape1` is subtracted from `shape2`. direction: Point The direction for finding the support...
4b9292116c9447549f36099d4a6928c4c6e74e28
3,610,533
import os import json def load_metadata(directory, filename='meta.json'): """Load the metadata of a training directory. Parameters ---------- directory : string Path to folder where model is saved. For example './experiments/mnist'. """ path_to_metadata = os.path.join(directory, filen...
d9bb76ea707fa87d4715569f08a7e43ae5373d6c
3,610,534
import random import functools def build_cache_maps(context, configurations, region, installed_region): """Build a giant cache of instances, volumes, snapshots for region""" LOG.info("Building cache of instance, volume, and snapshots in %s", region) LOG.info("This may take a while...") ca...
3e1ff2c365834394c1754e89137a4ecd49475ac0
3,610,535
import sys import scipy def precise(adata: AnnData, x1key: str = 'Ms', x2key: str = 'velocity', n_pcs: int = 50, n_pvs: int = 50, random_state: int = 0, k: int = 10, X1 = None, X2 = None, logX1: bool = False, ...
e55c044d058fe96dfb2120d2f06dc649b0736d00
3,610,536
def get_service(key_file_location, api_name='analytics', api_version='v3', scopes = ['https://www.googleapis.com/auth/analytics.edit', 'https://www.googleapis.com/auth/analytics']): """Get a service that communicates to a Google API. Args: key_file_location: The path to a valid service ac...
b3c06b472eb7ef6bb5d880461bc00d0947dd7214
3,610,537
def render_html_with_traceback(error: HTTPError) -> str: """Bottle's default error handler.""" return tob(template(ERROR_PAGE_TEMPLATE, e=error))
5949c68294f832bf24c6ea19de1b1084c7c317a5
3,610,538
from pathlib import Path def is_empty(path: Path) -> bool: """Checks if a directory has files Args: path: The path to the directory to check Returns: bool: True if the dir is empty, False if it contains any files """ return not any(path.iterdir())
b99045eee29922c7ef2e91cd1b8b71ab54181e1e
3,610,539
import math def match_dist(W_mat, pathways_mat): """ Match latent factors to pathways Parameters ---------- W_mat : np.array pathways_mat : np.array Returns ------- rv : list of tpl each tpl is of the form (<latent_factor_id>, <pathway_id>, <distance>) where W_mat latent factors are ident...
d0a02f1c5f9189876a15e818035801b1a37d7ce5
3,610,540
def bounded_1d_kde( pts, method="Reflection", xlow=None, xhigh=None, *args, **kwargs ): """Return a bounded 1d KDE Parameters ---------- pts: np.ndarray The datapoints to estimate a bounded kde from method: str, optional Method you wish to use to handle the boundaries xlow: ...
631168244db3e4a0b57acc6c0caa122e48ff02ce
3,610,541
import json def parse_manifest_file(filename): """ Parses artifacts from a manifest file into a mapping from region to AMI. Args: filename: the manifest file to parse Returns: A dict mapping region to AMI ID """ with open(filename, 'r') as manifest_file: packer_manifes...
36391fc6de76c431a6d46a3c2afdbecb6aa38823
3,610,542
def find_best_group_or_software(obj_tour_list): """ Find group with step 2 and 3 with 2 or more subtechniques """ # Ideal: find Step 2 and Step 3 with most subtechniques obj_w_best_step_2_3 = {} for obj_tour in obj_tour_list: # First group if not obj_w_best_step_2_3: obj_w_...
e23ad122b4f57143c5d271ebfcf42f23637fb2e2
3,610,543
import time import json def set_password(request): """ User visits confirm link and sets password. User set password if he/she forgot his/her password, if he/she is invited by owner, if he/she signs up. """ params = params_from_request(request) key = params.get('key', '') invitoken =...
c4b03d13f8671706b3864caefb2609ca41cc5d0a
3,610,544
import math def detectPupil(image, threshold=101, minimum=5, maximum=50): """ Given an image, return the coordinates of the pupil candidates. """ # Create the output variable. bestPupilID = -1 ellipses = [] centers = [] area = [] kernel = np.ones((5, 5), np.uint8) # Grayscale...
d77d1beff67254a06ab74563398edc476cb99fe9
3,610,545
def vad_on_unlabelled_data(audio_path: str, output_path: str, session_name: str, strictness_level: int = 3, word_threshold: int = 1, number_of_thread: int = 0, time_type: str = "timestamp"): """ This function is doing the VAD on unlabelled audio data. It will generate a new csv fi...
658a81094b5ad0f6ac12a723fd00616fe694f39f
3,610,546
import os import shutil import json def _get_talairach_all_levels(data_dir=None, verbose=1): """Get the path to Talairach atlas and labels The atlas is downloaded and the files are created if necessary. The image contains all five levels of the atlas, each encoded on 8 bits (least significant octet ...
a922d0655158812f11042b232cc22277c95c94a6
3,610,547
def simplify(g:Graph) -> tuple: """ Performs a single iteration of simplification of Graph instance according to a set or rules. Returns: tuple: list of Graph instances and boolean: whether the graph was successfully simplified """ choices = {(1,1):4,(2,2):4,(0,0):6,(1,0):3,(2,1):2} m ...
d9354eb6c2d2fd7cfc13fa2838ef328ecc2ecd91
3,610,548
def check_duplicates(message): """tweet message 를 최신 세 개의 사용자 tweet 과 대조하여 중복된 게시물이 없는지 확인합니다. 전달인자: message: 게시할 메시지를 포함한 문자열 반환 값: 중복이 발견되었을 경우 True를 나타내는 boolean """ last_three = retrieve_own_tweets() last_three_tweets = [tweet.full_text for tweet in last_three] # 확인할 트윗 메시지 문자열 li...
0d72de184b2a36741f4a20e1ebe81db7bffc81ca
3,610,549
def myKPCA(X, Y, kernel_type='gauss', c=3, deg=2, ncomp=2, dataset='wine', show=False): """ Kernel PCA. Params: -------------- X: n x d samples matrix Y: n x 1 vector of class labels kernel_type: Kernel type (Polynomial, RBF, etc.) c: Gaussian width (Ignored if kernel...
132c3fc1711cb83d27c08910c264963b57fbd702
3,610,550
import os def get_test_subdirs(test_parser, test_root, question_to_grade): """Get list of questions to grade.""" problem_dict = test_parser.TestParser( os.path.join(test_root, 'CONFIG')).parse() if question_to_grade is not None: questions = get_depends(test_parser, test_root, question_to_g...
c005432923d8dc53a27a0232c72236a16d41bfe6
3,610,551
import os def dataset_urls(): """Returns a list of legacy datasets available for testing""" legacy_data_directory = os.path.join(os.path.dirname(__file__), 'data', 'legacy') versions = os.listdir(legacy_data_directory) urls = ['file://' + os.path.join(legacy_data_directory, v) for v in versions] r...
51def92fc81111e01e237c46b0d927c50d0d0146
3,610,552
from typing import Any from typing import ContextManager def _open(path: _StrOrPath, *args: Any, **kwargs: Any) -> ContextManager[Any]: """Opens the file; this is a hook for the built-in open().""" return open(path, *args, **kwargs)
28f5e9339ccee39a355f0fbf0a82c034e5fcc1cd
3,610,553
def partition(groups, train_part=0.8, val_part=0.1, test_part=0.1): """Splits groups into training, validation, and test partitions. Args: groups (list): list of units (e.g. dicts). train_part (float): proportion in [0, 1] of units for training. val_part (float): self-explanatory. ...
c2cf56e54809a7c8c3a75c8b8bdbb3764aa9b988
3,610,554
def click_z_origin(im): """ Records user clicks that indicate the desired origin and z-axis in an image. These can be used to calculate the r-coordinate measured off the z-axis. Parameters ---------- im : (M x N x 3) or (M x N) numpy array of floats or uint8s Image that will be shown...
ff6a28893d246035db0c112df30581e3965a63ce
3,610,555
from typing import Union from pathlib import Path def get_logger_config(caller_file_path: Union[str, Path], name: str=None) -> dict: """ Get logger config as dictionary :param caller_file_path: file path of the caller, __file__ :param name: the name(section in logme.ini) of the config to be passed. (...
c162276330f8d4be205717cf5a365a53592b5f7a
3,610,556
import ast def _optimizer(program, fun_list, n_features, n_program_sum, metric, X, y, weight): """Simplify a program and then optimize its numerical parameters. Parameters ---------- program : list The program to be optimized. fun_list : list of length 6 List mapping the oper...
025c8091f672e6bb3759c6fd9bfcc793a02166a7
3,610,557
def full(): """Returns human friendly full date of current UTC time""" return obj().strftime("%A, %d %B %Y %I:%M%p")
8ceb877afe163c3c55f6195a92f6c709900e13ba
3,610,558
def need_to_login(): """A route used to indicate the user needs to authenicate for some page.""" year = date.today().year return render_template("website/login.html", message="Need to login to proceed further.", route=Routes, y...
fef498363ea9bcfca44b5c86c4da7528a80bd266
3,610,559
def get_peaks(sig, onsets): """ Perform an algorithm to identify a series of peaks given a signal and it's onsets :param sig: The signal requiring the calculation :param onsets: An array of containing the list of onsets for the signal :return: An array containing the list of peaks in the s...
bef20a6c2f13e83bc5d696e8b9983c139edea661
3,610,560
import os import click def combine_datasheets(list_of_dicts,economy): """ Combine individual data sheets into one datasheet. Combined datasheet will be written to Excel then processed by otoole. """ tmp_directory = 'tmp/{}'.format(economy) try: os.mkdir('./tmp') except OSError: ...
f3e2cab0d4a9e39d482a453f279a8588725418b3
3,610,561
import os import yaml def build_schm(tool, source_data, make_shell, override_source_text=None, create=False): """Build schematic data out of YAML description""" print(f"build_schm(\n tool={tool},\n source_data={source_data},\n" " make_shell={make_shell},\n override_source_text={override_source_text})...
b8b04c0a0c0a661dc66e75f4a47b074fa1dbd4a1
3,610,562
def phpinfo(interp, arg): """ Outputs information about PHP's configuration""" if arg & get_const('standard', 'INFO_MODULES'): for ext in EXTENSIONS: interp.writestr(ext + "\n") return interp.space.w_True
9bcb3419cbeba3a7466c214a2c41f93f6ae18c54
3,610,563
import os def prefix_repo_nwo(filename): """ Replaces an absolute path prefix with a GitHub repository name with owner (NWO). This function relies on `git` being available. For example: /home/alice/git/ql/java/ql/src/MyQuery.ql becomes: github/codeql/java/ql/src/MyQuery.ql I...
f42d10381218d17e6bd96c59b5d89dd2c6e32a5e
3,610,564
import json def get_graph(name, hetmat=False, directory=None): """ If hetmat=True, import graph into a hetmat located on-disk at directory. """ if name not in hetnet_urls: raise ValueError( f"{name} is not a supported test hetnet.\n" "Choose from the following currently...
74c55c180f755f8f0feea34630fd5680900632ac
3,610,565
def insert_project_files(sandbox): """ Fixture factory for inserting config files into tmp project dir """ def inner(package=False, lock=False): if package: sandbox['proj_package'].write_text(PACKAGE_JSON) if lock: sandbox['proj_lock'].write_text(LOCK_JSON) return...
e0ebf65c4aeee01b0d708b4cfd63b684561def07
3,610,566
import csv def get_first_last_onset(csv_file): """Gets the first and last onset times.""" with open(csv_file) as f: full_track = list(csv.reader(f)) first_onset = float(full_track[0][0]) if first_onset < 0: first_onset = abs(first_onset) # we only store the first onset if it is ...
d567530abf15fa5e256f7f826a813ad5982e3b0e
3,610,567
def extractBivectorParameters_complicated(B): """ B must be a general rotation object on the format $ \phi*P + t n_{\inf}} $ """ omega = float(B | E0) phi, P, t_par, t_nor = extractBivectorParameters(B - omega * E0) return phi, P, t_par, t_nor, omega
cede286088241caf8a2e28b009ae23a7295a85ec
3,610,568
import os import gzip async def get_file(session, hashval): """ :param session: :param hashval: :return: """ sample_path = os.path.join(SAMPLE_DIR, sha256_key(hashval)) if os.path.exists(sample_path): return "exists" sample_dir = os.path.dirname(sample_path) url = "%s/file/...
ad2500df2d275e52f8fbbdf9e1b838059f274902
3,610,569
def ionic_strength(c,z): """Compute ionic strength from charges and concentrations Arguments: c: bulk concentrations [concentration unit, i.e. mol m^-3] z: number charges [number charge unit, i.e. 1] Returns: float: I, ionic strength ( 1/2 * sum(z_i^2*c_i) ) [concentration unit, i.e. mol m^-3]...
4abe692e499f17d1d38feac48842cc2f3494becb
3,610,570
from typing import Type def sign_extend_3(val, width, tmp): """ Sign extension. High-order bit of val is left extended. :param val: VexValue :param width: VexValue :param tmp: VexValue of 0xffffffff """ mask_sign_bit = (1 << (width-1)).cast_to(Type.int_32) cond_sign_bit_1 = ex...
6bd958e700a25eee3b7dfdaafbab49ede8ca0b45
3,610,571
def __check_if_alive(processes): """ Quickly check if at least one of the list of processes is alive. Returns True if at least one process is still running. """ c = set([x.exitcode for x in processes]) return None in c
22458fa4b2ca07fe8c1c21a60eac87d6546f8abd
3,610,572
def previous_next_placement(doc_filter: DocumentFilter) -> pd.DataFrame: """ Calculate mu teamPlacement before and after a teamPlacement. :param doc_filter: Input DocumentFilter. :type doc_filter: DocumentFilter :return: Previous and next expected placement based on current placement. :rtype: p...
a8585550ec39e6572c5a447d2c17787d821616d0
3,610,573
def prices_to_returns(prices: pd.DataFrame, log: bool = False): """ Calculate the returns given prices. Parameters ---------- :param prices: pd.DataFrame A pandas DataFrame with asset prices :param log: bool Whether to compute logarithmic returns Default is False -> line...
ce01815e530e634daa9500913d073afee1f1fdb9
3,610,574
def check_array(arr: Data) -> np.ndarray: """ Utility function for checking and validating input arrays. """ # Check array type if isinstance(arr, (pd.DataFrame, pd.Series)): arr = arr.to_numpy() elif sparse.issparse(arr): arr = arr.toarray() elif isinstance(arr, np.nd...
8bdb541c1cc92a3c1c22d0570aa5cc773f0ef13a
3,610,575
def _SeriesFactory(ser): """ Return an instance of the appropriate subclass of _BaseSeries based on the xChart element *ser* appears in. """ xChart_tag = ser.getparent().tag try: SeriesCls = { qn("c:areaChart"): AreaSeries, qn("c:barChart"): BarSeries, ...
e0ca78113a68e363c4f3de7acb9086a156fddf47
3,610,576
from typing import Union from typing import Any from datetime import datetime def create_access_token( subject: Union[str, Any], expires_delta: timedelta = None ) -> str: """Encodes a JWT Args: subject (Union[str, Any]): The content of the JWT. expires_delta (timedelta, optional): The JWT...
e4301ca6eed32e5bd417d65fd5caf0483fcd17fb
3,610,577
def peristimulus_time_trial_average_plot(sigs, times, tags, extra_event_times=None, ylim=None, ax=None, method='ci95'): """ TODO: enable feeding error bars Take in list of signal groups plot hued line plots in ax. :param sigs: np.ndarray or list of disparate sign...
d1374e9b9ccf6ad9ab8abfec028866ecff4497c5
3,610,578
def n_mat_propostas(votadas = True): """ Recebe um boleano que define se o retorno. Se votadas for verdadeiro retorna um dicionário cuja chave é o nome do parlamentar e o conteudo é o número de matérias propostas, pelo parlamentar, que foram votadas. Se votadas for falso retorna um dicionário cuja chave é o nome...
12c06ed57e0608ad27af555ac5de7d54f1e32ef3
3,610,579
def CreateDictionary(name_fmt, codeset, src_dir, out_dir, wrapper=None): """Creates a dictionary used for configs.""" exports = {} if wrapper is None: wrapper = lambda c: c for code_class in registry.classes.values(): def Closure(code_class): def Registerer(src, *args, **kwargs): codeset.a...
47bd7c991a5b044b517c023d4199f6700079f0e8
3,610,580
import glob def test_data_list() -> list: """Return the list of paths to the test input data files Parameters: None Returns: list: The list of paths to the test input data files """ return glob.glob("test_data/*.rws.gz")
da3362910d0727fb21f433b34a77ad437ea0ccb1
3,610,581
def test_module(client, params): """ Returning 'ok' indicates that the integration works like it is supposed to. \ Connection to the service is successful. Anything else will fail the test. :param client: client to use :param params: parameters obtained from demisto.params() """ res = clien...
ddf10c97b841f00044d9cc11d04b8725e134d8cf
3,610,582
def _url(data={}): """Helper method to generate URLs.""" data = "&".join(["{}={}".format(name, value) for name, value in data.items()]) return "{}{}locative?{}".format(HTTP_BASE_URL, const.URL_API, data)
09fa191aa45ab4c90390eb99962ba40930531f32
3,610,583
def model_from_json(json_string, custom_objects=None): """Parses a JSON model configuration string and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> config = model.to_json() >>> loaded_model ...
ea22de5736876edd252d25713ffc02a0abffce57
3,610,584
def route_vm_logic(logicFn): """ Decorates a function to indicate the viewmodel logic that should be executed after security checks and business logic passes. :param logicFn: The viewmodel logic function to assign. :return: The decorated function. """ def decorator(fn): fn.route_vm_...
6dcbd274bd35b34f9faffb455d121940821cfa04
3,610,585
def format_obs_ensemble(obs_ensemble, obgnme): """ Reformat observation ensemble. Parameters: =========== obs_ensemble: pd.DataFrame, the observation ensemble Returns: =========== obs_ensemble: pd.DataFrame, the observation ensemble after new format. """ obs_ensemble.index =...
898e6022297616dbd91d96067d883666c932bfa1
3,610,586
from typing import Iterable def to_ideogram_html_str(gene_symbols: Iterable[str]) -> str: """Get an Ideogram HTML document as a string.""" annotations = get_ideogram_annotations(gene_symbols) logger.info("using %d annotations in ideogram", len(annotations)) return get_ideogram_template().render(annota...
27977573f3d64d5c35bd0f69c61e0c3aff82a75e
3,610,587
import struct def read2byte(i2cBus: SMBus, i2cAddr: int, lowByteAddr: int, highByteAddr: int) -> int: """ Read two byte from i2c Bus by using SMBus library :param i2cBus: SMBus instance :type i2cBus: SMBus :param i2cAddr: i2c address, a one byte address :type i2cAddr: int :param lowByteAd...
9a97dd7242930d10298834bb24702da21c29f019
3,610,588
import inspect def typechecked(f): """ Use the @typechecked decorator on a function to perform run-time typechecking. The docstring for `check_type` describes how type annotations should look. """ argspec = inspect.getfullargspec(f) annotations = f.__annotations__ @wraps(f) def g(*args...
0801bb4e418fdc06c9293e6118ffc002b6bbc23f
3,610,589
def top_k_incidence_decision(k: int = 3) -> IncidenceDecisionFunctionType: """Select exactly k subjects with highest probabilities. Chooses random subjects if less than k subjects have positive probability. Parameters ---------- k: int the maximum number of subjects that are selected and r...
56197f0254292be06c285f63bd3c6eb24045dde8
3,610,590
def draw_turn(row, column, input_list, user): """ Draw the game board after user typing a choice. Arguments: row -- the row index. column -- the column index. input_list -- a two dimensional list for game board. user -- the user who type the choice Returns: input_list -- a two ...
6f44e770a2fa04b5992ffd21cad5a799c3423de5
3,610,591
import math def normal_vec(triplet): """ Return the unit normal vector to the plane defined by a triplet of atom positions [[x1,y1,z1],[x2,y2,z2],[x3,y3,z3]] """ p1 = [triplet[0][0], triplet[0][1], triplet[0][2]] p2 = [triplet[1][0], triplet[1][1], triplet[1][2]] p3 = [triplet[2][0], triplet[2...
0d4a13814f75a1747544f348b5e78a0d758b480c
3,610,592
def t_from_CT(SA, CT, p): """ Calculates *in-situ* temperature from Conservative Temperature of seawater. Parameters ---------- SA : array_like Absolute salinity [g kg :sup:`-1`] CT : array_like Conservative Temperature [:math:`^\circ` C (ITS-90)] p : array_like ...
5ddd89c39ee100c3c114f1886d39284feda6587d
3,610,593
import socket def is_open_port(port): """ Check if a port is open (listening) or not on localhost. It returns true if the port is actually listening, false otherwise. :param port: The port to check. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex...
4eb8f52744cc7f330dd101b613d5db4ab8d0d0fc
3,610,594
def hashid(obj, suffix=""): """ Returns a per-class unique hash that combines the object's class name with its idnum and creation time. This makes this id unique also between different typeclassed entities such as scripts and objects (which may still have the same id). """ if not obj: ...
511403801d81576e8f07999e4b27befd5b7429a6
3,610,595
def window_indices(frame, window=30, center=None, **kwargs): """ Get the linear indices for each satellite spot Parameters ---------- frame : ArrayLike image frame window : float, Tuple, optional window size, or tuple for each axis, by default 30 center : Tuple, optional ...
646b92c0a2b057ffb8bc50c6f4d9adc9542c43c8
3,610,596
def open_pbobject(path, pb_class, verbose=True): """Load JSON as a protobuf (pb2) object. Any calls to load protobuf objects from JSON in this repository should be through this function. Returns `None` if the loading failed. Parameters ---------- path: str JSON file path to load p...
d920919086ebd40f9d0e711b8475ebd2ac8d259e
3,610,597
def _is_table(client, dataset_id, table_id, project_id): """Check whether a `table_id` is a view or not.""" if (dataset_id is None) or (table_id is None): return False dataset_ref = bigquery.DatasetReference(project_id, dataset_id) table_ref = dataset_ref.table(table_id) table = client["b...
cf355e9d3d332b30e0cb11f6c9880960de431567
3,610,598
def class_name(n): """ Formats a valid C# class name from the name format used in the XML. @param n: The class name to format in C# style. @type n: string @return The resulting valid C# class name @rtype: string """ if n == None: return None try: return native_types[n] ex...
4bd999c25ee2a51192668bee6534d300241652d9
3,610,599