content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _get_dataset_sizes(sdtype): """Get a list of (fit_size, transform_size) for each dataset generator. Based on the sdtype of the dataset generator, return the list of sizes to run performance tests on. Each element in this list is a tuple of (fit_size, transform_size). Args: sdtype (str)...
471fe728f81c6c6493b41a7021c60169f653afa1
3,623,700
def get_glide_score(pdb, label_df): """ searches for pdb's rmsd in combined rmsd df :param pdb: (string) {target}_lig{id} :param label_df: (df) combined rmsd df :return: (float) rmsd value """ return label_df[label_df['target'] == pdb]['glide_score'].iloc[0]
213c288f46c8ddec62ad067bdd3f120e66ff0518
3,623,701
def _test_against_patterns(patterns, entity_id): """Test entity against list of patterns, true if any match.""" for pattern in patterns: if pattern.match(entity_id): return True return False
16881be06e86ae3fe1afc9dc8fb642573cf6fdcf
3,623,702
def emulators_get(username=None, label=None, page=None, per_page=None): # noqa: E501 """List all instances of Emulator Gets a list of all instances of Emulator (more information in https://w3id.org/okn/o/sdm#Emulator) # noqa: E501 :param username: Name of the user graph to query :type username: str ...
cf313ba926cfa226bf77dab9c6ac729813005dba
3,623,703
def get_schema_variables(schema): """ This method returns a set of all variables within the schemas.yml. The set is organised by: (variable_name, locator_method, script, file_name:sheet_name) If the variable is from an input database, the script is replaced by "-" Also, if the variable is not from a...
0dfeae2a3d28a1e2457a6b3da7e84a3e201fe6e7
3,623,704
import zmq from typing import Optional from typing import Tuple from typing import Any import json async def async_zmq_receive_data( reader: zmq.asyncio.Socket, ) -> Optional[Tuple[PeerIdentity, Any]]: """Receive data from the reader. The data is expected to be bytes-encoded JSON representation of a Pyth...
3c21842f93ccbbb3409268e7422da886d2cc49fa
3,623,705
import glob import os def read(filename, **kwargs): """Load GDF2 data package. Arguments: dfn_filename (str) method (str): how to read the data file. Either assume it is delimited by whitespace (``'whitespace'``) or use the field widths specified in the .dfn file (``'f...
5d13e955ecefb1cb687b7e6507e3affcf01458f6
3,623,706
def key_id_or_name_as_string_n(index): """Pull out the nth (0-based) key id or name from a key which has parents. If a key is present, return its id or name as a string. Note that this loses the distinction between integer IDs and strings which happen to look like integers. Use key_type to distinguish them. ...
9642338fa5c2f11bc949c1d7abd06bbe1a4829db
3,623,707
import math def polarToCartesian(polar, radius = 1.0): """ Convert a 2D spherical coordinate into a cartesian 3D coordinate. Polar coordinates are expected to be in radians. Polar coordinate can be of form (theta, phi), in which case the radius parameter is used. Polar coordinate can also be o...
0998eed640a1c2b4582ea047603f6f1ce688e411
3,623,708
def find_root_visual(conn): """Find the xcffib.xproto.VISUALTYPE corresponding to the root visual""" default_screen = conn.setup.roots[conn.pref_screen] for i in default_screen.allowed_depths: for v in i.visuals: if v.visual_id == default_screen.root_visual: return v
930bb700bdcb141aba9fc4370d244b588357f8f1
3,623,709
def get_db_connection(): """Get a connection to the DB. We do this per query to ensure we always have a live connection.""" conn = mysql.connector.connect(user=DB_UNAME, password=DB_PW, host=DB_SERVER, database=DB_DATABASE, autocommit=True) ...
754545b90dc0a88407a3a8eca15d7357b959368c
3,623,710
import json def location_create_mapper(c: ZIAConnector, args): """ Creates a new location. Args: c: API zia_client that must me logged in beforehand. args: Parsed api_parser. Namespace object. Returns: The requests' response. Generally a JSON object. """ with ope...
a8e6b5bf05c390238c0abbc328d260d1fae8ab43
3,623,711
def compute_forward_cost(image, energy): """Computes forward cost map (vertical) and paths of the seams. Starting from the first row, compute the cost of each pixel as the sum of energy along the lowest energy path from the top. Make sure to add the forward cost introduced when we remove the pixel of t...
eebb1ce74a1d027dbe3a8e95b318a752185ec2fa
3,623,712
def delete_note(note_id: str) -> tuple[dict, int]: """Delete an existing note. The user can call this operation only for their own notebooks' notes. This operation requires the following header with an access token: "Authorization: Bearer access_token" Request parameters: - note_id (st...
298f7f3b1d7243ef99edf7c2203145e588787641
3,623,713
import re def creole_slugify(value): """Convert the given string to a slug consistent with heading IDs used by our creole parser. >>> creole_slugify("Only 20%!") "only-20" """ if not value: return value # Only keep alphanumeric and space characters. value = re.sub(r"[^a-zA-Z...
fe621981715372c4a9c03179d862b745551d87f2
3,623,714
import math def change_pitch(samples, rate): """ Change the pitch of a samples array, returning a new samples array with the pitch changed. """ LIMIT = (1 << 15) - 1 index = 0 finished = [] while index < len(samples) - math.ceil(rate): i = int(index); frac = index - i; ...
55e33caf5f1248d250ff6b77935a107fdef41110
3,623,715
def crypto_scalarmult_base(n): """ Computes and returns the scalar product of a standard group element and an integer ``n``. :param n: bytes :rtype: bytes """ q = lib.ffi.new("unsigned char[]", crypto_scalarmult_BYTES) if lib.crypto_scalarmult_base(q, n) != 0: raise CryptoError...
5f5d50e6960f8640a46bd440de36b1ac9e81194e
3,623,716
def verify_ospf3_interface(device, expected_interface=None, expected_interface_type=None, expected_state=None, extensive=True, max_time=60, check_interval=10,...
11baaa70287458641cc22ec72e01fbb5d4d54994
3,623,717
def trainCount( trainData, questionType, questionDict, questionIdict, objDict, objIdict, numAns): """ Calculates count(w, a), count(a) """ count_wa = np.zeros((len(objIdict), numAns)) c...
00f55da3cffd84abecbf6fddae09f876e8af463c
3,623,718
def get_corr_account_full_name(split): """ Iterate through the parent splits and return all of the accounts that have a value in the opposite sign of the value in split. :param split: :return: """ return_value = [] signed = split.value.is_signed() for child_split in split.transacti...
cbfa9109d205824df5a8b668f6c267e07120a013
3,623,719
def data_block(block_str): """ find all thermo data """ thm_dstr_lst = data_strings(block_str) thm_dat_lst = tuple(zip( map(species_name, thm_dstr_lst), map(temperatures, thm_dstr_lst), map(low_coefficients, thm_dstr_lst), map(high_coefficients, thm_dstr_lst))) return...
a58d2bc0e1931988114c853021a26b12b67a4359
3,623,720
import re def is_match(a,b): """Evaluates if a or elements of a are a regex match to the pattern in b.""" if is_array(a): return all(is_match(a=elem,b=b) for elem in a) else: try: result = bool(re.search(b,a)) except ValueError as e: print(e) else: ...
deae8ffab8594f5e853bf1c5fef0ae8cd977aa74
3,623,721
def remove_class(class_name_gen): """ Removes a class on a HTML element **Important**: this works with the assumption that the element is processed with 'html.parser' or something similar, that is the 'class' attribute is a list of classes. If processing with the 'html' parser the 'class' attribute...
0e3483546587a16ae892c12d8dc3c19660e9973c
3,623,722
import math import torch def relative_position_embedding(seq_length, out_dim, repeat_pos_encoding=1): """Creates a [seq_length x out_dim] matrix for rel. pos encoding. Denoted as Phi in [2] and [3]. Phi is the standard sinusoid encoding matrix. Args: seq_length (int): The max. sequence length ...
585e18eed414e5dbb27d537227d58f7b73531905
3,623,723
def previous_line(view, sr): """sr should be a Region covering the entire hard line""" if sr.begin() == 0: return None else: return view.full_line(sr.begin() - 1)
b6c668044d57983d2b66a7ae567b59126031cf9f
3,623,724
def Compress(): """Compresses the go tool into tar.gz and generates sha1 code, renames the archive to sha1.tar.gz and returns the sha1 code.""" print "Compressing go tool, this may take several minutes." os.chdir(INSTALL_DIR) with tarfile.open(os.path.join('a.tar.gz'), 'w|gz') as arch: arch.add('andro...
f0eac2212b5a5d47e9936cc64001cd11bb29c38f
3,623,725
import async_timeout import asyncio import aiohttp async def async_citybikes_request(hass, uri, schema): """Perform a request to CityBikes API endpoint, and parse the response.""" try: session = async_get_clientsession(hass) with async_timeout.timeout(REQUEST_TIMEOUT): req = await...
f215f47f92c8deb5f86fd9085573dd1cf5017fa3
3,623,726
def times(allow_naive=None, timezones=None): """Return a strategy for generating times. .. deprecated:: 3.9.0 use :py:func:`hypothesis.strategies.times` instead. The allow_naive and timezones arguments act the same as the datetimes strategy above. """ note_deprecation('Use hypothesis.s...
ea112f95edf363f1be569d5e814e0209f95f0b3e
3,623,727
import logging from datetime import datetime def split_by_returning(df_train, df_test): """ Split out clients by total number of sessions (single or >=2) :param df_train: :param df_test: :return: """ df = pd.concat([df_train, df_test], axis=0, sort=True) df_grp = df.groupby('fullVisito...
b995033e5e7ea5e16b46f911f79af8f24a54ee22
3,623,728
def senel_noise(SPLt_dBA_max): """This method calculates the effective perceived noise level (EPNL) based on a time history Perceived Noise Level with Tone Correction (PNLT). Assumptions: None Source: None Inputs: PNLT - Perceived Noise Level wit...
99644c61a8f31d3dcf8762ca943908bad13607fc
3,623,729
def convertToVerifaiType(value, strict=True): """Attempt to convert a Scenic value to a type known to VerifAI""" ty = underlyingType(value) if ty is float or ty is int: return float(value) elif ty is list or ty is tuple: return tuple(convertToVerifaiType(e, strict=strict) for e in value)...
da8d5bcb441f666798fb18599efaf287a8afa2e9
3,623,730
def predecessor_to_forwarding(predecessor, source): """ Compute a forwarding table from a predecessor list. """ # Create variable to return (forwarding-table dictionary) FT = {} # Loop over all nodes that AREN'T the source for (key, value) in predecessor.items(): if (key != source)...
af0d241fc2b8447581ea582d756a4a3735220815
3,623,731
from sys import version def index(): """Handle index requests.""" return version.version_string(), 200
ab584fa6cab8c2bd3b333de8d39e85206af57a10
3,623,732
def init_atlas_grid(im_size, nb_patterns, rand_seed=None): """ initialise atlas with a grid schema :param tuple(int,int) im_size: size of image :param int nb_patterns: number of pattern in the atlas to be set :param rand_seed: random initialisation :return ndarray: np.array<height, width> >>> ...
20c372c5668d96ad0176ac94069b6ca1580e5ff5
3,623,733
def block_diag(values, like=None): """Combine a sequence of 2D tensors to form a block diagonal tensor. Args: values (Sequence[tensor_like]): Sequence of 2D arrays/tensors to form the block diagonal tensor. Returns: tensor_like: the block diagonal tensor **Example** >...
5d3c64bd04086af4038c9f392ebeae541ca36407
3,623,734
def parse_menu_command(cmd_addr, sctp_client, keys): """Parse specified command from sc-memory and return hierarchy map (with childs), that represent it @param cmd_addr: sc-addr of command to parse @param sctp_client: sctp client object to work with sc-memory @param keys: keynodes ob...
015df395293108ae82c6e6d78413718e94401d7b
3,623,735
def main_crimmins_func(port_list: list = None) -> bool: """ The Crimmins complementary culling algorithm is used to remove speckle noise and smooth the edges. It also reduces the intensity of salt and pepper noise. The algorithm compares the intensity of a pixel in a image with the intensities of its 8 ...
14696b39b7d814513e7bf79560af1af9d1365fef
3,623,736
from typing import Type from typing import Any from typing import List def find_builtin_server_type(type_name: str) -> Type[Any]: """Find first installed server implementation""" supported_packages = ["sanic", "flask", "tornado"] installed_builtins: List[str] = [] for name in supported_packages: ...
49227ea0397a9a9dc0c76a22b6a6b9580f809291
3,623,737
def uriel_distance_vec(languages): """ Adapted from langrank [https://github.com/neulab/langrank/blob/master/langrank.py] """ geographic = l2v.geographic_distance(languages) genetic = l2v.genetic_distance(languages) inventory = l2v.inventory_distance(languages) syntactic = l2v.syntactic_dist...
cb174066a61496046aca04b460e16a7cf2c61caf
3,623,738
from typing import List def create_platform_product_gui(platforms: List[str], products: List[str], datacube: datacube.Datacube, default_platform:str = None, default_product:str = None,): ...
f739b0f651a84a6aa2c4eba4464ab843e9e88914
3,623,739
def async_wraps(cls, wrapped_cls, attr_name): """Similar to wraps, but for async wrappers of non-async functions.""" def decorator(func): func.__name__ = attr_name func.__qualname__ = ".".join((cls.__qualname__, attr_name)) func.__doc__ = """Like :meth:`~{}.{}.{}`, but async. ...
c93fb2a52bfcb3edc9cbf0442138daa1ecf84dda
3,623,740
def commands_getter(manager_router): """ Gets the command processor using `Client.command_processor` of an ``_EventHandlerManagerRouter``. Parameters ---------- manager_router : ``_EventHandlerManagerRouter`` The caller manager router. Returns ------- handlers : `list` ...
b0411f10a839859c07c2cc86900b110614d3232f
3,623,741
def PowMod(a, e, m): """Deprecated. Use pow(a, e, m) instead.""" if e == 0: return 1%m if e == 1: return a%m return MulMod(PowMod(a, e/2, m), PowMod(a, e-e/2, m), m)
75045e2f45760fee1ffca9b27913186fb82c7308
3,623,742
def uniform_density_prior(d, rlim=30.): """ Uniform space density prior Input: d: distance (typically an array) Optional: rlim: Maximum allowed distance (default: 30 kpc) Output: Uniform density prior """ return np.piecewise(d, [d < 0, (d >= 0)*(d<=rlim), d>rlim]...
37870e5eab3bb27970d8de048bfa16851fed5655
3,623,743
import warnings def _load_cube(input_files, constraints): """Load single :class:`iris.cube.Cube`.""" with warnings.catch_warnings(): warnings.filterwarnings( 'ignore', message='Ignoring netCDF variable', category=UserWarning, module='iris', ) ...
37b92b96af85ee85b9ef417e161be5c03a834b10
3,623,744
import scipy def block_ndi_label_delayed(block, structure): """ Delayed version of ``scipy.ndimage.label``. Parameters ---------- block : dask array (single chunk) The input array to be labeled. structure : array of bool Structure defining the connectivity of the labeling. ...
82afbf8fdf5bc30298530e8466e8e54db28ea585
3,623,745
def weighting_matrix(weights, name=None): """ Creates a weighting matrix. The ith weight is in the ith upper diagonal of the matrix. All other entries are 0. This functions is called once per curriculum update / iteration, but then used for the entire batch. Args: weights: Curriculum w...
8476041f08c5a38e2fdf3cf8a8543bf77ef45c97
3,623,746
import os import re def process_coordinate_file(filename): """ >>> points = process_coordinate_file("day10_example.txt") >>> len(points) 31 >>> points[0].x 9 >>> points[0].y 1 >>> points[2].y -2 >>> points[2].delta_x -1 :param filename: The name of the file to pars...
c59945ffeca6b3f17b15d22d83f86d3e5169bc08
3,623,747
from typing import Union from typing import Collection import re def pattern( text: str, *, pattern: Union[str, Collection[str]] ) -> str: """Remove strings from `text` using a regex pattern. Args: text (str): The text from which patterns will be removed. pattern: The pattern to m...
3aa1959a03b11ee46dcfd4a675733252533d266e
3,623,748
def drawFrequencies(drawType,d,m,Sigma = None): """Draw the 'frequencies' or projection matrix Omega for sketching. Arguments: - drawType: a string indicating the sampling pattern (Lambda) to use, one of the following: -- "gaussian" or "G" : Gaussian sampling > Lambda = N(0,Sigma...
a760f1eb9b707e4e8f6d61f3d684b8a508139021
3,623,749
from typing import Counter def edgearr_tcrude(edgearr, siglev, ednum, TOL=3., tfrac=0.33, verbose=False, maxshift=0.15, bpm=None, skip_bad=True): """ Use trace_crude to refine slit edges It is also used to remove bad slit edges and merge slit edges Parameters ---------- edgearr...
1f249d4a65469504cb32e4c60b064d07e1d47265
3,623,750
def _get_trigger(model, machine, trigger_name, *args, **kwargs): """Convenience function added to the model to trigger events by name. Args: model (object): Model with assigned event trigger. machine (Machine): The machine containing the evaluated events. trigger_name (str): Name of the ...
1f16e62480f0caf661dc144d6dd92feae9426e96
3,623,751
def variogram(stats, t): """ Helper function that computes the variogram for a given lag t. The variogram is the mean of the mean squared sum of deviations of lag t of each sequence. Args: stats: A list of sequences """ m = len(stats) n = stats[0].size return sum([np.sum((s[t+1:...
d490cd0871dbc5b256374d16d038c5a7f0a9ee18
3,623,752
import platform def _environ_cols_wrapper(): # pragma: no cover """ Return a function which gets width and height of console (linux,osx,windows,cygwin). """ current_os = platform.system() _environ_cols = None if current_os == 'Windows': _environ_cols = _environ_cols_windows ...
f199646d10f1e3e3a3a097456dae1401f80a352e
3,623,753
import argparse def _get_parser(): """Return :class:`argparse.ArgumentParser`.""" parser = argparse.ArgumentParser( description=__doc__ ) parser.add_argument( '-f', '--force', dest='force', help='Force installation of packages.', action='store_true', ) parser...
d8de14332326e48f3b5afde60d133350e0ac2908
3,623,754
import os def os_cwd(): """Returns the pathlib object for the current working directory Examples: >>> os_cwd()\n '/home/cooluser/pyplay' """ return os.getcwd()
785477619ea629be3e7862889164471ae9e5de88
3,623,755
import pandas def from_timestamp_to_datetime(timestamp, unit='ms'): """ :param timestamp: timestamp in unix format. :param unit: measurement unit used in the timestamp. :return: the timestamp in date_time format. """ return pandas.to_datetime(timestamp, unit=unit)
48046c91956a9a7195203a84871241d84dd6cd10
3,623,756
import torch def multi_classif_inference( all_outputs, all_labels, criterion, **kwargs ): """Multi classification inference. Parameters ---------- all_outputs All outputs of a forward process of a model. all_labels All labels of the corresponding in...
d37716042a39066cabcb98f87196cef0349efa58
3,623,757
def as_unit_vector(vec): """Divides a vector by its length to give a vector of length 1 (unit vector)""" return vec / np.linalg.norm(vec)
5c05f1ddde8d5eafb64a0a86d15b58f606200213
3,623,758
def followers(request, username, template_name="microblogging/followers.html"): """ a list of users following the given user. """ return _follow_list(request, username, template_name)
a0db1b9d55c562d2646329fcde99cdd00abcadaa
3,623,759
def calc_total_fuel_reqs(filename): """ This function iterates through all modules and find total fuel requirements. """ input_file = open(filename, "r") cumulative_total = 0 # initialize sum as 0 # iterate through list for input_line in input_file: try: mass = input...
519025809b856a1ec40bc93db0a168c333f5d325
3,623,760
def check_valid_user(function): """ Custom decorator for batch views. Check if the authenticated user is a user in the batch database and make the record available in the decorated function. """ @wraps(function) def wrap(request, *args, **kwargs): user = get_user_from_request(reques...
0f877b27c5554ceb5211d8bd558901f3430b232f
3,623,761
def formatTarget(data): """ :param data: int """ good = 0 bad = 0 avg = np.mean(data) for index in range(data.shape[0]): val = data[index] if val < avg: data[index] = 0 good += 1 else: data[index] = 1 bad += 1 # prin...
418df03d2b56728046ff783895ae7de9229d9dc2
3,623,762
def session_maker(engine): # pylint: disable=redefined-outer-name """Create an ORM session from the engine""" return sessionmaker(bind=engine)
f7b872b44a2d7bc31450e728b5c8987d6d451ce6
3,623,763
from typing import Optional import logging def log_me(name: str = "NetEmbs", folder: Optional[str] = None, file_name: Optional[str] = "logs.log", level: Optional[int] = logging.INFO) -> logging.Logger: """ Attach logger to specific file and location Parameters ---------- name : str, de...
a2f9bc9d755e641373e195fa0b4abf89cdabc021
3,623,764
from typing import List def getNextMineToFinish(games: List[Game]) -> Game: """Given a list of games, return the mine that is open and next to finish; returns None if there are no unfinished games (finished=past the 4th our, regardless of whether the reward has been claimed) If a game is alre...
71b85bc5eaac8ed15e391edbe806ea47a8dac214
3,623,765
from pathlib import Path import inspect def caller_module() -> Path: """Returns the name of the file containing the module from which this function was called. This ignores all modules located directly inside the parent directory of the current file (tsfile/*).""" this_file_parent = Path(__file__).par...
a7c01b9b747ef838315f6c41fc01aa2c70ccb1da
3,623,766
def read_file(file_path='', sheet_name=0, na_values=NA_VALUES, encoding='ISO-8859-1', delimiter=None, **kwargs): """ Read pandas dataframe or file. Parameters ---------- file_path : dataframe or string string must refer to file. Currenlty, Excel and csv are supported sheet_name : integer...
10666963d01cce84a0a738e8585d448361e54668
3,623,767
def get_matrices(src, domain): """Reads the STIX and returns a list of all matrices in the STIX""" matrices = src.query([ stix2.Filter('type', '=', 'x-mitre-matrix'), ]) # Filter out by domain matrices = [x for x in matrices if not hasattr(x, 'x_mitre_domains') or domain in x.get('x_mitre_...
95a1a649c4272cc3322ce051c8f0b9a262d602e8
3,623,768
import json import traceback def get_test_queue_contents(vmcfg, courseId): """Get the contents of the test queues for all testers configured in the system.""" try: tstcfg = vmcfg.testers() queue_contents = {} # dict of strings for tester_id in tstcfg: queue_contents[tes...
c7a908e845d737387f87c024965667b3a111e914
3,623,769
def qgrams_to_char(s: list) -> str: """Converts a list of q-grams to a string. Parameters ---------- s : list List of q-grams. Returns ------- A string from q-grams. """ if len(s) == 1: return s[0] return "".join([s[0]] + [s[i][-1] for i in range(1, len(s))])
cc7dc5eb4d5c9e3e5f751cf7c2190e68c3ba11bd
3,623,770
def traverse(coord, np_mask, coord_str): """Edge case: if pixel value in mask is 0 at coord, then bounding box has captured the extreme points in this corner of the image """ x, y = coord if np_mask[y, x] == 0.0: return (x, y) height, width = np_mask.shape store_x, store_y = 0,...
e46889c358deeb2cd26fdba0a6e2eff03034d016
3,623,771
def collect_pc(grasp_, pc): """ grasp_bottom_center, normal, major_pc, minor_pc """ grasp_num = len(grasp_) grasp_ = np.array(grasp_) grasp_ = grasp_.reshape(-1, 5, 3) # prevent to have grasp that only have number 1 grasp_bottom_center = grasp_[:, 0] approach...
53d08217142af77812f98bd6145a899f9c458be5
3,623,772
from typing import Callable from typing import Iterable import functools def change_ids(dataset: Dataset, change_id: Callable, methods: Iterable[str] = ()) -> Dataset: """ Change the ``dataset``'s ids according to the ``change_id`` function and adapt the provided ``methods`` to work with the new ids. ...
51a3efb98f94f1b3a57d135a4ccf50b3b27ba7d4
3,623,773
def _configure_learning_rate(num_samples_per_epoch, global_step): """Configures the learning rate. Args: num_samples_per_epoch: The number of samples in each epoch of training. global_step: The global_step tensor. Returns: A `Tensor` representing the learning rate. Raises: ValueE...
b06843b605c9748c4e5633dc29f0e5d03dc9a8e1
3,623,774
import copy import re def filter(self, mods=None, name_records=None, pattern=None, regex=None): """ Return filtered list of records. Args: mods: Name(s) of modules to preserve name_records: Id(s)/Name(s) of name_records to preserve Return: None """ ...
9023f2b578be99b521ab808c0ea7f6275627025e
3,623,775
import numpy import math def power(inputArray, power_index=3.0, scale_min=None, scale_max=None): """Performs power scaling of the input numpy array. @type inputArray: numpy array @param inputArray: image data array @type power_index: float @param power_index: power index @type scale_min: floa...
f5f903946c0b532cd0f70f49c17cb54c4be7c22a
3,623,776
import uuid def get_key_for_player_ui(game_id: int, player_name: str) -> JSONResponse: """ Method used to generate user private access token for view ui and send moves :param game_id: integer value of existing game :param player_name: string with name of player :return: Response with access token ...
17e41d5fc812bbfcda200c1b64bb4a693a21e24b
3,623,777
def load_speakers(fileobj): """Load a list of speakers from a yaml file. This is a legacy wrapper around load_real_layout; see its documentation for format info. Parameters: file: a file-like object to read yaml from Returns: list of Speaker """ return load_real_layout(fil...
36781a91a4845138a9b879edfdcf32233cf31447
3,623,778
def softmax(x): """Compute softmax values for each sets of scores in x. Copied from Andrew Ng's Deep Learning courses on Coursera """ e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
1030e23642edc52749584b527f682c90b8c3551a
3,623,779
import os import sys def find_libgfortran(): """Get the directory and name of ``libgfortran``. Assumes and checks that this ``libgfortran`` is **only** for ``x86_64``. Exits the program with a status code of 1 if: * there is more than one (or zero) directories that contain ``libgfortran.d...
51e8857d32798687f08eca576fe3027231eed679
3,623,780
import argparse import sys def parse_args(args): """Parse command-line arguments. Parameters ---------- args : list of strings command-line arguments. Returns ------- options : :class:`argparse.ArgumentParser` Command line arguments. """ parser = argparse.Argumen...
522790493b179ef52f1d12097208323c1610efb6
3,623,781
import html from typing import Dict from typing import Any def result(app: dash.Dash, data: GameData) -> html: """Layout for the result page. This page get display after every user prediction. This pages displays the predictions from the user and the ai together with the ground truth. An explanation for t...
031739565654ca3353c8783e51008de0a92329a9
3,623,782
def iterate_module_func(m, module, func, converged): """Call function func() in specified module (if available) and use the result to adjust model convergence status. If func doesn't exist or returns None, convergence status will not be changed.""" module_converged = None iter_func = getattr(module,...
f7221e003dcc627f6e19a9b4961e62d7d98b87e3
3,623,783
def trace_color_table(measurement): """ Returns one of the standard color tables for TRACE JP2 files. """ if measurement == 'WL': return cmap_from_rgb_file(f'TRACE {measurement}', 'grayscale.csv') try: return cmap_from_rgb_file(f'TRACE {measurement}', f'trace_{measurement}.csv') ...
624f5659d39f584617ad2c4726afccf5e9b673e0
3,623,784
def redeemBLVT(tokenName, amount, recvWindow=""): """# Redeem BLVT (USER_DATA) #### `POST /sapi/v1/blvt/redeem (HMAC SHA256)` ### Weight: 1 ### Parameters: Name |Type |Mandatory |Description --------|--------|--------|-------- tokenName |STRING |YES |BTCDOWN, BTCUP amount |DECIMAL |YES | recvWindow |LONG |NO | ti...
0adc7544c10839c09a57ca44a61fae247b6f6731
3,623,785
def getGitInfo(): """Make a build string for svn Returns a string or None if not in a git repository""" (gitLocalVersion, local) = ("","") # need to do a 'git diff' because 'describe --dirty' can get confused by timestamps (gitLocalVersion,stderr) = Popen("git diff --shortstat", shell=True, s...
c133abba0e47cb0803b1e97a4b963c265c5f6c40
3,623,786
from pysat import DataFrame, Series, Panel import warnings def computational_form(data): """ Repackages numbers, Series, or DataFrames .. deprecated:: 2.2.0 `computational_form` will be removed in pysat 3.0.0, it will be added to pysatSeasons Regardless of input format, mathematical oper...
1f506f09c793915a8d3d3b9ed8d34879dd10ea8e
3,623,787
def _check_df_load(df): """Check if `df` is already loaded in, if not, load from file.""" if isinstance(df, str): if df.lower().endswith("json"): return _check_gdf_load(df) else: return pd.read_csv(df) elif isinstance(df, pd.DataFrame): return df else: ...
bfe7f6e311fe99590e9680be0453776991a6914d
3,623,788
import requests def delete_channel(accountId, apiKey, channelId, verbose=False): """Deletes a channel. Parameters ---------- accountId: str apiKey: str channelId: str the channel ID to delete verbose: bool, optional Returns ------- bool True if the channel was...
937422a3f51a036390968e941621ba50d248ca4c
3,623,789
def make_all_figures(close_figs=False): """ Call all the figure generators for this chapter :close_figs: Boolean flag. If true, will close all figures after generating them; for batch scripting. Default=False :return: List of figure handles """ # Find the output directory ...
18afa8c0f344dd05d851f54628a63e0f1df68ace
3,623,790
import os def exists_lite_runner_bin(): """Returns true iff lite_runner binary exists.""" return os.path.exists(_LITE_RUNNER_BIN)
bca7e111634042bee6026e74ed2e6581bb042064
3,623,791
import os def run_pcluster_command(*args, **kwargs): """Run a command after assuming the role configured through register_cli_credentials_for_region.""" region = kwargs.get("region") if not region: region = os.environ["AWS_DEFAULT_REGION"] if region in cli_credentials: with sts_creden...
f82e447a73320b656d4b91c36b7bf44986e6c2ba
3,623,792
import re def arguments_from_docstring(doc): """Parse first line of docstring for argument name. Docstring should be of the form ``min(iterable[, key=func])``. It can also parse cython docstring of the form ``Minuit.migrad(self[, int ncall_me =10000, resume=True, int nsplit=1])`` """ if doc...
4b08f36678247df6119e594ff9859f697f2e8d23
3,623,793
def _check_mod_11_2(numeric_string: str) -> bool: """ Validate numeric_string for its MOD-11-2 checksum. Any "-" in the numeric_string are ignored. The last digit of numeric_string is assumed to be the checksum, 0-9 or X. See ISO/IEC 7064:2003 and https://support.orcid.org/knowledgebase/artic...
685a9e8085000248290c9e482a115c99942c51d1
3,623,794
def fft_convolve3(signal, kernel, conv_mode = CONV_MODE.DEFAULT): """ FFT based Convolution: 3D Parameters ----------- signal: af.Array - A 3 dimensional signal or batch of 3 dimensional signals. kernel: af.Array - A 3 dimensional kernel or batch of 3 dimensional kerne...
4d3034b8dd7c9c67724e387729d1b37b1e391499
3,623,795
def check_en_wik9_dataset(method): """Wrapper method to check the parameters of EnWik9 dataset.""" @wraps(method) def new_method(self, *args, **kwargs): _, param_dict = parse_user_args(method, *args, **kwargs) nreq_param_int = ['num_samples', 'num_parallel_workers', 'num_shards', 'shard_id...
aac1c9757922c3ea29657c2530572c69ae23ac71
3,623,796
import argparse def arg_parser(): """Parser for command line arguments.""" description = ("Script to validate that " "election results XML file(s) " "follow best practices") parser = argparse.ArgumentParser(description=description) subparsers = parser.add_subparsers(dest="cm...
b93645f339fc46bb53b703a2a4d67f3e39ad703a
3,623,797
import time def low_depth_second_order_trotter_error_operator( terms, indices=None, is_hopping_operator=None, jellium_only=False, verbose=False): """Determine the difference between the exact generator of unitary evolution and the approximate generator given by the second-order Trotter-Suz...
4602f73b1fb2998d3ea612f3b09bf5b6aa00f65d
3,623,798
import time from datetime import datetime def get_historical(ticker: str, metric: str) -> pd.DataFrame: """Get historical sentiment data [Source: sentimentinvestor] Parameters ---------- ticker : str Stock metric : str Metric to get Returns ------- pd.DataFrame ...
88e8d968d449d7688f4b4bced7b23cc7b6a77b3d
3,623,799