content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Iterable from typing import List from typing import Dict def after_attack_all(skills: Iterable[Skill], arena: ActiveArena, data: AfterAttackData) -> List[Dict]: """ Executes the after_attack_effect for all the given skills, if such exists, returning a list of their cumulative output, if...
3491d58d8b6412c3366e9fd902043cfe020754cb
50,700
from typing import Tuple from typing import Any def _get_laplace_matrix_2d(bcs) -> Tuple[Any, Any]: """get sparse matrix for laplace operator on a 2d Cartesian grid Args: bcs (:class:`~pde.grids.boundaries.axes.Boundaries`): {ARG_BOUNDARIES_INSTANCE} Returns: tuple: A sparse ...
2e2845ea64829d98b01484a0f5268ed352999cfc
50,701
def build_zooma_query(trait_name: str, filters: dict, zooma_host: str) -> str: """ Given a trait name, filters and hostname, create a url with which to query Zooma. Return this url. :param trait_name: A string containing a trait name from a ClinVar record. :param filters: A dictionary containing fi...
0fb22b1f44319c2fa8e87d8e720de248dd1a7eba
50,702
def _flatten_nested_jacobian(jacobian, state_shape): """Flattens a nested Jacobian into a matrix. The flattening and concatenation follows the interpretation of the structure as being a leading 'axis', meaning that if the input has 'shape': [input_structure, A, B], and the output has 'shape': [output_structu...
f03af541be656b3c21d088f561fa92d016372b17
50,703
def figletbulbhead(txt): """ FigletBulbLook Text """ f = Figlet(font='bulbhead') return f'{f.renderText(txt)}'
1eebc94b7f3ffa5c8f158533ccc9234b0a129e29
50,704
import struct def bytes_to_element(type, bytes, byteorder = 'little'): """Returns a python object parsed from bytes :param type: the type of the object to parse :param bytes: the bytes to read :param byteorder: little or big endian """ if type == 'char': return ord(struct.unpack('<b',...
02bfd7e6e5858fb265dfc9c3a2d57109e65f8e5e
50,705
import os import pickle def pickle_load(cwd,file_Name): """ Load pickled data from current working directory. INPUT: cwd - Current working directory. file_name - Name of pickled data to be loaded. OUTPUT: filePickle - Loaded pickle data. """ print('\nLoading data...\n') os.ch...
63ded4f9511e066d23aa8c99603c3a54f085b5e4
50,706
def extract_predictions(data, predictions): """' Joins a dataframe containing match data with one containing predictions, returning a dataframe with team names, predicted values, and if available, the actual outcome (in points). """ probs = _team_test_prob(predictions) teams0 = [] teams1...
2fb6a99e5f1afbd5ebeecb7ffc20a26edf642ce5
50,707
def naturalnumber(value: int | float, *, caps: bool = True, digits=1) -> str: """ Makes a number to a human-readable string. Examples: naturalnumber(1000) -> "1k" naturalnumber(100000) -> "100k" naturalnumber(1000000) -> "1m" naturalnumber(1000000000) -> "1b" naturalnumber(1000000000, c...
9d2fbef692ff228ae1344ee78c16944afc82dd16
50,708
import inspect import pickle def request_analysis(user, analysis_func, subject, *other_args, **kwargs): """Request an analysis for a given user. :param user: User instance, user who want to see this analysis :param subject: instance which will be used as first argument to analysis function :param ana...
d49b8ed51641157051b47be6b76b1152db563992
50,709
def sequences_to_one_hot(sequences, chars='ACGTN'): """ :param sequences: :param chars: :return: """ seqlen = len(sequences[0]) char_to_int = dict((c, i) for i, c in enumerate(chars)) one_hot_encoded = [] for seq in sequences: onehot_seq = [] integer_encoded = [ch...
76af4e23d0dc4e6a0cd6098df4e5966aa79a8258
50,710
def __virtual__(): """Only load keystonev3 if requirements are available.""" if REQUIREMENTS_MET: return 'keystonev3' else: return False, ("The keystonev3 execution module cannot be loaded: " "os_client_config or keystoneauth are unavailable.")
08edf53888d9fe5adacff283d74ec6b3142b8776
50,711
def combined_equal_all_basic_types() -> tuple: """Combined tuple of all basic types""" combined_types: tuple = tuple( (value, value) for value in _ALL_BASIC_TYPES_1.values() ) return combined_types
e030e46e07a0481bd81338e51f14ef01c423c277
50,712
def n_cyber_object_to_node(graph): """ Initial function to create the blank nodes for each of the file's facet nodes :param graph: rdflib graph object for adding nodes to :return: The four blank nodes for each fo the other functions to fill """ cyber_object_facet = rdflib.BNode() n_raster_fa...
af401ef618fc00920505192face4e804470b5f0e
50,713
def freeze_module_until(module, name): """ Freeze all submodules inplace before and including `name`. If `isintance(name, list)`, submodules before and including every `name` will be frozen. Args: module (nn.Module): torch.nn.Module name (list(str)): submodule name """ def _is_c...
8d649f973f772f02f56594d365a05cb902734999
50,714
def pad_to_batch(dataset, batch_size): """Pad Tensors to specified batch size. Args: dataset: An instance of tf.data.Dataset. batch_size: The number of samples per batch of input requested. Returns: An instance of tf.data.Dataset that yields the same Tensors with the same structure as the origin...
e102abdc097f2983e01766444b728b3c6a76269d
50,715
import ast def apply_ast_transformations(source): """Used to convert the source code into an AST tree and applying all AST transformer specified in the source code. It returns a (potentially transformed) AST tree. "AST transformers" are modules which must contain a function trans...
b20fff4ad328bacb5bddfe7b7d106d621576ad96
50,716
def create_full_name_without_space_fields(romanize_method, given_name, family_name): """ Creates fields with the full name without white spaces. Returns: fullname fields, romanized_name_list: (for check) """ fields = [] romanized_name_list = [] ...
e57bf553e74f70faa425a48061218c6bd3f47c2c
50,717
import time import calendar def read_wdnr_monthly_water_use(wu_file, wu_points, model, active_area=None, drop_ids=None, minimum_layer_thickness=2 ): """Read water use data from a master ...
0eb8b0a55836fd85d76f5db227b178fbe871084e
50,718
import random import string import requests def create_coupon(auth_token: str, mavenseed_url: str, args: Args) -> None: """Creates a coupon with the given coupon code on the Mavenseed platform.""" def generate_random_coupon_code() -> str: """Generates a random coupon code with 8 characters.""" ...
8708f99e1de3f6b05fa0159e3c37d5ae29fd7cd3
50,719
def validate_clockwise_points(points): """ Validates that the points that the 4 points that dlimite a polygon are in clockwise order. """ if len(points) != 8: raise Exception("Points list not valid." + str(len(points))) point = [ [int(points[0]) , int(points[1])], ...
53a785fe6dfc9613200c4d5e05890340e3d6e910
50,720
def get_available_recipes(): """ Returns a dict of the available user-recipes """ recipes = {} for name, data in custom_recipes.items(): recipes[name] = { 'name': name, 'parameters': data['parameters'] } return recipes
3dd5525f199ecbf9ceb61b95c9abe2c4b8c64f6b
50,721
from datetime import datetime import time def wait_for_workflows(client, namespace, names, timeout=datetime.timedelta(minutes=30), polling_interval=datetime.timedelta(seconds=30), status_callback=None): """Wait for multiple workflows to finish. Ar...
e17da62443ab8e72d583f0c0169846747864c2f0
50,722
def _uncomment_magic(line): """Reverts the comments applied to magics (line level) """ if line.startswith(_PREFIX): return line[_PREFIX_LEN:] parts = _is_commented_line_magic(line) if parts: code, magic = parts return f'{magic} {code}' else: return line
e41a93fc763360d24bf5fec4cd948c97d631a730
50,723
import builtins import six def get_context(entity): """Returns the operating context of the given object. If the object is a subclass of Context, returns the top most context (or containing instance) of the object. If the object is a builtin object, returns the operating module (if available). ...
3eb1d6edb0c5c8136c10043968c18d273bae5ac9
50,724
from typing import Any def ret(d: dict, key: str) -> Any: """ Unwrap nested dictionaries in a recursive way. Parameters ---------- d: dict Python dictionary key: str or Any Key or chain of keys. See example below to access nested levels. Returns ---------- out...
86d07ba6dbe2610ceabb0bcee3099b5734c770ae
50,725
import os def distribute_product(immutability, product_name, source_path, packaging_path, parms, user, group): """ Determines if the distribution method is set to local or remote and calls the correct distribution method. Args: immutability: Whether or not to set the im...
b74118cee4bc0b88234379d492587bd2978cfa10
50,726
import os import struct def decrypt_config(file_path: str): """ Decrypts the configuration from REvil :param file_path: Unpacked payload :return: JSON config """ if not os.path.isfile(file_path): print("[-] Invalid file path") return None # Loads the PE file pe = pefil...
a3239a52740ee30602f04742e18298dcb39b2b34
50,727
import types def _conical_frustum_to_gaussian(z_vals: f32['... num_samples 1'], rays: types.Rays): """Approximate a conical frustum as a Gaussian distribution (mean+cov). Assumes the ray is originating from the origin, and rays.base_radius is the radius at dist=1. Doesn't assum...
df48aabfac89372ce451b3190e59cc559246ca8d
50,728
import argparse def train_arguments(): """Used only for training""" parser = argparse.ArgumentParser(parents=[generic_arguments()]) parser.description = 'Train the network' # General parameters parser.add_argument('--lr', default=3e-4, type=float, help='Learning rate during training') parser....
78cb76edc8959e0bd49d6070be22098ec0f59b6d
50,729
import time def MLE_NQB_sim(n, measurements, paulis, variances, density_matrix, tolerance, random_initialization, max_iter_num, nlvl=2, plot_convergence=False, verbose=False, directory_path=""): """Maximum likelihood estimation for n_qubit n_level qubit state tomography. F...
ce8d6cb6bc915c1359c77272e999964346683e30
50,730
def run_interp_back(kdat, tm, params): """Interpolates kdat to on-grid coordinates. Args: kdat (tensor): The off-grid frequency data. tm (tensor): Normalized frequency coordinates. params (dict): Dictionary with elements 'dims', 'table', 'numpoints', 'Jlist', and 'table_over...
75d46a26e76008d1a8d81a713aa5745baee9d502
50,731
def portmap_portstat_route(port): """generate port statistics fragment""" stats = db.session.query(Service.proto, func.count(Service.id)).join(Host) \ .filter(Service.port == port) \ .group_by(Service.proto).order_by(Service.proto) infos = db.session.query(Service.info, func.count(Service....
03dda63f4ab8e91f903226688ca5994326081704
50,732
def authenticate(data): """Admin broadcast channel authentication""" if "token" in data: current_user = User.verify_auth_token(data["token"]) if current_user is not None and current_user.can(Permission.ADMIN): room = Channel.get_room() join_room(room) emit("au...
73b9eddff09d80a1d39171cc2dbb415c0c649ebb
50,733
from pathlib import Path import textwrap import os import random def main(quote, **kwargs): """ Creates a PIL Image with 'quote' printed on it. :param quote: The message to be printed on the image :keyword shadow: Whether to add shadow to the text or not. :keyword noise: The amount of graphics to be overlaid o...
1a9515579466d026ed6e582abca30804f4c44e25
50,734
def closet_common_manager(ceo: Employee, first_employee: Employee, second_employee: Employee)->Employee: """ 得到our boss :param ceo: 起始节点,Employee :param first_employee: 第一个雇员, Employee :param second_employee: 第二个雇员, Employee :return: 一般会返回一个正确的结果, 异常情况:Employee.EmployeeNotIn -> 雇员不在ceo管辖范围 ...
f2f4d119024d1b2f16bae9a027962e0162af64e9
50,735
def instance_destroy(context, instance_uuid, constraint=None, update_cells=True): """Destroy the instance or raise if it does not exist.""" rv = IMPL.instance_destroy(context, instance_uuid, constraint) if update_cells: try: cells_rpcapi.CellsAPI().instance_destroy_at_top(context...
0b2d78445561c1bf40321507bec58784a9cb969a
50,736
import sys from io import StringIO import traceback def get_traceback(exc=None): """ Returns the string with the traceback for the specifiec exc object, or for the current exception exc is not specified. """ if exc is None: exc = sys.exc_info() if not exc: return None tb =...
6ea863d57489d7f91e38da7a859946cd810cb52b
50,737
def group_excessive_points(gdf: gpd.geodataframe.GeoDataFrame, cell_size: float): """ Creates groupings of collocated points exceeding a threshold. By default, a grouping is defined as three times the average cell size of the input file. :param gdf: :param cell_size: :return: """...
68bdab8ae34e7ba7b8f3311a36509200a490ac8d
50,738
def local_conv2d(inputs, kernel, kernel_size, strides, output_shape, data_format="channels_last"): """Apply 2D conv with un-shared weights. Arguments: inputs: 4D tensor with shape: (batch_size, filters, new_rows...
7fe612725b16c157d9dda7eff28dd3126e583a68
50,739
def convex_hull(points, return_copy=False): """Computes the convex hull of a set of 2D points. Input: an iterable sequence of (x, y) pairs representing the points. Output: a list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically...
526f29fe04e84e68098015b2a8a5d2a82fb78940
50,740
def unit_to_altaz(x, y): """Convert coordinates on the projected skydome to alt,az coordinates Args: x, y: float coordinates, normalised to the unit circle Returns: Tuple[float, float]: alt, az coordinates in degrees """ R = min(sqrt(x**2 + y**2), 1) alt = degrees(a...
91d73fb997e3b0c020925213b2af7374c683ec6e
50,741
from typing import Any from pydantic import BaseModel # noqa: E0611 from datetime import datetime def fields_in_create(obj: Any): """Build dictionary for data insert by adding createdAt field""" if isinstance(obj, BaseModel): return { **obj.dict(), "createdAt": datetime.utcnow(), "updatedAt": None} ...
a7cdff857329f953b495b634942fa4e94b2baf74
50,742
def build_matrix(node, m, k, D, beta): """Compute k-tree algorithm matrices for each node of the tree. Args: node (KTreeNode): the top node of the tree. m (int): the alphabet size. k (int): the number of trees requested. D (int): the depth of the tree. Returns: int: t...
634fc4ff32c2fe24f450bad2505aed77e0100c97
50,743
import ast def mesh_select_face(mesh, message="Select a face."): """Select a single face of a mesh. Parameters ---------- mesh: :class:`compas.datastructures.Mesh` message: str, optional Returns ------- int or None """ guid = rs.GetObject(message, preselect=True, filter=rs.fi...
d2bae92384e445b0eba917a4b667fd1e5bc911ff
50,744
def simpleMergeMotifs(motifs, window=0): """ aggregates the motifs if they overlap, into one motif file Args: ---- motifs: df bed-like of motifs locations window: int maxsize around motif for which to still merge Returns: -------- df bedlike of merged motif: df bedlike of motifs that were not merged as ...
ff0735b293d8c26849bab79b9b7169c36236888f
50,745
def to_minutes(hour, minute): """ converts hours to minutes and adds extra minutes in the time... returns the sum """ return (hour * 60) + minute
05cc1cada49c7a2c84b3fa32cd9fb7bf805be751
50,746
import os import pickle def plot_map_region(lon,lat,var,name,title='',lb=20,ub=30,spacing=0.25): """ This function plots a map of the variable you specify. Arguments are: lon, lat, variable to plot, name of file to be saved to, title (optional). A large range is used for the variable and the spacing. This...
9e9157a67058b350f3ea5cef0932c22a38adaea3
50,747
import copy def _copy_to_tail_args(args: Namespace, as_router: bool = True) -> Namespace: """Set the incoming args of the tail router """ _tail_args = copy.deepcopy(args) _tail_args.port_in = random_port() _tail_args.port_ctrl = random_port() _tail_args.socket_in = SocketType.PULL_BIND _ta...
5146d68499a308ac07186a0e0a9f6bed55871746
50,748
import binascii def encodeAsMarket(data): """ Hide data inside a url commonly used for email personalization Parameters: data - the data to encode Returns: a dictionary with the key 'url' referencing a string holding the url and the key 'cookie' holding an array of 0 or more cookies. Note: Cookies ...
3792899bdbe1187ccd3ecb49b0c638ac1c4de02e
50,749
def is_identity(u): """Checks if the unit is equivalent to 1""" return u.unitSI == 1 and u.unitDimension == (0,0,0,0,0,0,0)
afc9029eeb44739a38869f06f84ba36b2a19da6f
50,750
def m_seq_inx_to_int(seq, args=0): """ 将列表中单个列表中元素转成int,返回新的列表 :param seq: 列表形成的列表 :param args: 列表的次序 :return: 转换后的列表 example: :seq [['30', 0], ['5', 1]] :args 0 :return [[30, 0], [5, 1]] """ for i in seq: ...
f6ba3c4060edffd704c53752df88b4dcfbdbef68
50,751
def convert_df_dates_to_str_or_none(df, cols): """Convert dataframe dates to str or None. Parameters: df (pd.DataFrame): The input dataframe cols (sqlalchemy table columns): The colums for the associated table Returns: df (pd.DataFrame): DataFrame with idntified date columns as str...
e8653c6017afe5844f6f7be36be28eede2ce9d62
50,752
def find_nearest(df, value, value_col="Insertion Loss (dB)", index_col="Frequency (Hz)"): """Given a pandas dataframe, find value corresponding to nearest index""" index = (np.abs(df[index_col]-value)).argmin() return df[value_col][index]
05ddf693cba3a63187a955a3d8f9356f9f2e8b2f
50,753
def source_df() -> pd.DataFrame: """ Produces a dataframe containing source coordinates for testing. Contains ra and dec. Returns: Dataframe with coordinates. """ source_df = pd.DataFrame( data={ 'ra': [ 12.59305887, 12.68310734, ...
4a04eea15119ee854cb4b87cc788ec738d136f55
50,754
import os def get_dzi_path(filepath): """ Get a path for the DZI relative to a rendered output file. """ return "%s/dzi/%s.dzi" % (os.path.dirname(filepath), os.path.splitext(os.path.basename(filepath))[0])
f78a88e37130f444e1398c603bfdeda3d30845bd
50,755
from pathlib import Path def read_from_csv(path): """read data from csv""" if not Path(path).exists(): return None if not path.endswith('.csv'): return None with open(path, 'r') as file: data = pd.read_csv(file, header=0) return data
84e4b6ead3bfe18165aea5b69effd7c8c815c120
50,756
def compute_moments(features, input_channels=3): """ Computes means and standard deviation for 3 dimensional input for normalization. """ means = np.zeros(input_channels, dtype=np.float32) stddevs = np.zeros(input_channels, dtype=np.float32) for i in range(input_channels): # very specifi...
1701e63481241a6e3eb1d90ca289eed6dad54945
50,757
def _normalizeGlifContourFormat2(element): """ - Don't write unknown subelements. """ # INVALID DATA POSSIBILITY: unknown child element # INVALID DATA POSSIBILITY: unknown point type points = [] for subElement in element: tag = subElement.tag if tag != "point": co...
909b4027e379fa4d4576c90ab50d021c7ec8699e
50,758
def _compile_fragment_ast(schema, current_schema_type, ast, location, context): """Return a list of basic blocks corresponding to the inline fragment at this AST node. Args: schema: GraphQL schema object, obtained from the graphql library current_schema_type: GraphQLType, the schema type at the...
c4a87bbde57d26f51e03cc95be0a9db59a138d0c
50,759
def _parse_one_service_message(s): """ Parses one service message. :type s: str :rtype: service_message """ b1 = s.index('[') b2 = s.rindex(']', b1) inner = s[b1 + 1:b2].strip() space1 = inner.find(' ') if space1 >= 0: name_len = space1 else: name_len = inner....
78e70a3974b2302d10fdd00222423f8ee4fb4e61
50,760
import os import re import subprocess import traceback from sys import stderr import trace def getPropValue(nm, encrypted=False, cfg=None, dflt=None, skipComplaining=False): """ Return a value from the specified configuration file """ if cfg is None: return None global getPropDict if ...
d21cab9a0c477124cdc77bbd8a1bdb9e151622d3
50,761
def medidasChars(T): """Medidas de letras TTM formatar para passagem como dicionário""" nchars=len(T) # nspaces=T.count(" ") nletters=sum([t.isalpha() for t in T]) nuppercase=sum([t.isupper() for t in T]) nvowels=sum([t in ("a","e","i","o","u") for t in T]) npunctuations=sum([t in puncts for...
1a66b4535dc5b42b8c40512132c6010e44f13aa9
50,762
from datetime import datetime def read_chl(filename, field_names=None, additional_metadata=None, file_field_names=None, exclude_fields=None, use_file_field_attributes=True): """ Read a CSU-CHILL CHL file. Parameters ---------- filename : str Name of CHL file. ...
e6df2de26331eb72838b050d6050da6ca5eee70c
50,763
import pathlib def get_tree(tree_type, cfg, section, option): """Load a tree from file or parse a string. If the provided value is the name of an existing file, read the contents and treat it as a Newick tree specification. Otherwise, assume the provided value is a Newick tree specification. Trees c...
077ff497e32a9695ae146c381a29361187511bc6
50,764
def common(first_list, second_list): """Receives two lists, returns True if they have any common objects and false otherwise. Note that this implementation should theoretically work with any container-like object for which the in operator doesn't have a different meaning.""" # iterate over the elements ...
da48a3a559bc26a79bc5aa06ca6efa15053e1cd4
50,765
def base_download_namespace(api_keypath, path_fixtures_base, tmp_path): """Base namespace for the pyani download subcommand.""" return Namespace( outdir=tmp_path / "C_blochmannia", taxon="203804", email="my.email@my.domain", retries=20, batchsize=10000, timeout=10...
e1487b8295edd27e1b04f8cebd42c81126325b87
50,766
def Correct_Surface_Temp(Surface_temp,Temp_lapse_rate,DEM_resh,Pair,dr,Transm_corr,cos_zn,Sun_elevation,deg2rad,ClipLandsat): """ Function to correct the surface temperature based on the DEM map """ #constants: Gsc = 1367 # Solar constant (W / m2) cos_zenith_flat = np.cos((90...
bd98e5d211ad6203793078a74396852c177b90c9
50,767
from typing import Dict from typing import Tuple from typing import Collection from typing import Any from typing import Set def aggregate_unique_objects(edges: Dict[str, Dict[Tuple[str, str], Collection[Any]]]) -> Dict[ str, Dict[Tuple[str, str], Set[Any]]]: """ Performs an aggregation of the occurrences...
a89fb6a1e4203610ee00756d1486cd147ddee49e
50,768
import logging def receive(conn): """Receive a message conn has to be the socket which receive the message A message has to end with the bytestring b'\xDE\xAD\xE1\x1D' """ ip, port = conn.getpeername() logging.info('Receiving a message from '+ip+':'+str(port)) data = b'' while...
0b6f4e9c6fd3a38a33f625fe6b736020a044ca61
50,769
import tqdm import os def _load_trial_data_asvspoof(filelist, feature_dir, skip_spoof=True): """ Preload data for speaker trials for ASVSpoof2019 .trl list. Each line in filelist is four items [claimed_identity, utterance, system, target]. """ trial_list = [] for claimed_identity, utterance...
13c8d3efc9738764fae2dfcdd70269e50d00f97b
50,770
def lstm(token_embeddings, hid_dim=128, hid_dim2=96): """ LSTM network. """ # lstm layer fc0 = fluid.layers.fc(input=token_embeddings, size=hid_dim * 4) lstm_h, c = fluid.layers.dynamic_lstm( input=fc0, size=hid_dim * 4, is_reverse=False) # max pooling layer lstm_max = fluid.lay...
6e398cebf01f47800c45c46832ef7fc7b82d1c1f
50,771
def SetVPNClusterPath(ref, args, request): """Sets the vpnConnection.cluster field with a relative resource path. Args: ref: reference to the cluster object. args: command line arguments. request: API request to be issued Returns: modified request """ # Skips if full path of the cluster res...
629bafca1da8a479b72c936c352ade9fe53d27b7
50,772
def list_nmmr_option_bitfield(fp, child, sfrname, offset): """ Format a single bitfield of NMMR OPTION pseudo register Input: - index in .pic - register node Notes: - Expected to be used with 12Fs only """ if (child.nodeType == Node.ELEMENT_NODE): if (child.nodeName == "edc:Adjust...
834e3f16f00fc6ff2324f908a0ec0f95a5571956
50,773
from typing import Sequence from typing import List def qubit_pairs_to_qubit_order(qubit_pairs: Sequence[Sequence['cirq.Qid']]) -> List['cirq.Qid']: """Takes a sequence of qubit pairs and returns a sequence in which every pair is at distance two. Specifically, given pairs (1a, 1b), (2a, 2b), etc. returns...
7bb23f99266d5cfab4b587831d6ae5a182a0cbb7
50,774
def calculate_carryover_vector(model, car, last_10_rows): """ calculates carryover vector by iterating over each channel, and running carryover on each channel given the sampled car value """ cv = [] post = model.trace.posterior for idx, channel in enumerate(model.feature_names_in_): ...
6d23ff7654efc41cd635756a0116f61cb76d6781
50,775
import os import shutil def copy_file_to_tmp(test_case, name): """ Copy file `name` to a new dir in the tmp dir and return its pathname Args: test_case (:obj:`unittest.TestCase`): a test case name (:obj:`str`): the name of a file to copy to tmp; `name` may either be an absolute pathname, ...
8423512e7a3856b48ca6d2761105f317d54009ff
50,776
def semantic_model(user_preferences, dataset_metadata, data_model): """ This function implements the Semantic Content-based Recommendation Model. Given the user preferences and the entities mapped to the Aviation Data Model for each column of each dataset, the model computes a score (dot product) for each ...
0fdc34bb4887f1300c0ff134debf7188c0ae4c3d
50,777
from typing import Callable import click def config_path_option(exists: bool = True) -> Callable: """ A convenience decorator As we'll probably want to be able to specify the config in pretty much every console command """ def decorator(f: Callable) -> Callable: option = click.option( ...
b3e62578b6a2c6e16d5e0f622fd07130c4e7b079
50,778
import itertools def gabor_filter_parallel(image, mask, parameters=dict(), n_jobs=1, backend='threading'): """ Apply gabor filters to image, done in parallel. Note: on a cluster, where parallelisation of the gabor filters is not possible, use backend="threading" """ ...
4352d086371523eec922e49055207930864abb38
50,779
def from_numpy_array(A, create_using=Graph): """ Initializes the graph from numpy array containing adjacency matrix. Parameters ---------- A : numpy.array A Numpy array that contains adjacency information create_using: cugraph.Graph (instance or class), optional (default=Graph) ...
2fb0c48a32b31abaa21e9878f752244624e73649
50,780
def _genFlat(vizMTX): """Returns trace of flat surface with intensity as surface elevation and color. Parameters ---------- vizMTX : array_like Matrix holding spherical data for visualization Returns ------- T : plotly_trace Trace of desired surface TODO ---- ...
7b8863dc1604d1ea6653f3b2330fec612a1c23e1
50,781
def success_centroid_error(gt_poly, res_poly, thresholds, n_frame): """ :param gt_poly: [Nx8] :param result_bb: :param n_frame: :return: """ success = np.zeros(len(thresholds)) centroids_gt = [] centroids_res = [] for i in range(gt_poly.shape[0]): poly1 = res_poly[i].r...
a15175cc2813be15f554eb362735bcfffc2c161a
50,782
def is_path_head(path: str) -> bool: """ Determin if a path string is a path head. >>> is_path_head('path.ext') True >>> is_path_head('/dir/path.ext') False Args: path (str): Path string. Returns: bool: If the path string is a path head. """ return path_head(p...
93530bbd51413dfc14ca992a7243f961e4f22ec1
50,783
def read_tif(file=None): """Read tiff files. Works with 16 bit rgb data""" if file is not None: img = tif.imread(file) return img else: print("No file provided")
4fecf1f9009316157fdbe268d63ea3f9bb0964db
50,784
def verify_predictions(predictions): """Ensures that predictions is stored as a numpy array and checks that all values are either 0 or 1. """ # Check that it contains only zeros and ones predictions = np.array(predictions, copy=False) if not np.array_equal(predictions, predictions.astype(bool)):...
a139cbd5574c81fbe10556bec50e01e6404de884
50,785
def merge_bbox(left: Box, right: Box) -> Box: """ Merge bounding boxes in format (xmin, xmax, ymin, ymax) """ return tuple([ f(l, r) for l, r, f in zip(left, right, [min, max, min, max]) ])
54918e88be43a6fe4cb5218944185105fd9da68f
50,786
def sumRowDotProdsNEW(origMatrix): """ Makes more sense to use on Jacobian than on Hessian. """ rowNormalized = normRows(origMatrix) n = rowNormalized.shape[0] sumDotProds = sumAllDotProds(rowNormalized[0:n/2]) + sumAllDotProds(rowNormalized[n/2:n]) return sumDotProds
c15346cedffa3486bb3a3513de62bb337553c7dc
50,787
import io def img_from_fig() -> Image.Image: """ Convert a Matplotlib figure to a PIL Image and return it. The figure is pulled from the current pyplot context, therefore the figure must be created and then drawn before calling this function. Returns: PIL Image array. """ buf = i...
df88a688d632a26ed905f272fad30eb6afc2113e
50,788
from django.contrib.auth import get_user_model def get_subscriber_model(): """ Users have the option of specifying a custom subscriber model via the DJSTRIPE_SUBSCRIBER_MODEL setting. This method attempts to pull that model from settings, and falls back to AUTH_USER_MODEL if DJSTRIPE_SUBSCRIBER_M...
f2931195f65c68a56f6b3fd826589119baa95702
50,789
def get_mnist(): """ Returns tuple containing the concatenated train and test_images, train and test_labels, the image size, and the test length for the MNIST dataset. """ #pull data (train_images, train_labels), (test_images, test_labels) = tf.contrib.keras.datasets.mnist.load_data('datasets') ...
48c4b8d7eb700309e87bf8a1c680d80759c01636
50,790
def PreOpL(op, items): """ Uses algorithm from SecureSCM WP9 deliverable. op must be a binary function that outputs a new register """ k = len(items) logk = int(ceil(log(k,2))) kmax = 2**logk output = list(items) for i in range(logk): for j in range(kmax//(2**(i+1))): ...
b6f9be5612e06c7d3da5988ad89e25d8ee3bdb18
50,791
def generaGraph (pcapfile, macgraph, ipgraph, pathresults = 'results'): """ Genera graphs for connections between IPs and MAC addresses. This function also can be used to read the MACs and IPs in the .pcap or .pcapng file. :param pcapfile: path to the .pcap or .pcapng file :param pathresulst: path t...
5303fd46b7e07194673f40aa618e99bc9f2f1f8a
50,792
def uploader() -> _Uploader: """An _Uploader object with all of its fields filled in.""" return _UploaderFactory()
ba8669f43d07a5f43792a30b0a692325b7d4f10b
50,793
def existingusercheck(userdata): """Checks if the input username is already in the userdata file, and if user entry is in valid format. If valid, returns username, password, and user permissions.""" for line in userdata: if (len(line) > 1 and line.split()[0] == username): if (len(line.split()) == 3): re...
101a01078926c6c4733e7420b37463cc9912193f
50,794
def calc_linear_crossing(m, left_v, right_v): """ Computes the intersection between two line segments, defined by two common x points, and the values of both segments at both x points Parameters ---------- m : list or np.array, length 2 The two common x coordinates. m[0] < m[1] is assum...
3f5eeab9fa906b6858e249f97c7e175e427cb2d7
50,795
from typing import get_args def run_fresh_full_train_DARTS(epochs,output_path_fulltrain, cell_list = None, sep_conv_list = None): """ Perform model evaluation for DARTS/DARTS+ """ GLOBALS.FIRST_INIT = False #optimizer,scheduler=network_initialize(new_network,train_loader) parser = ArgumentPa...
32e49e8eb868ef42a007565a675fe433515fadbd
50,796
def get_program_no_movement(blending): """Test program with two joint steps no movement in between""" j1 = [58, -70, 107, 64, -60, 43] steps = [ # Step: name, move_type, tcp, pose, blending, speed, accel): Step("1", MoveType.Joint, 0, j1, blending, 0, 0), Step("2", MoveType.Joint, 0,...
1ae24d1683cc737a1bd2791cc51202d3a63a848f
50,797
def validate_input(input_string): """ :param str input_string: A string input to the program for validation that it will work wiht the diamond_challenge program. :return: *True* if the string can be used to create a diamond. *False* if cannot be used. """ if not isinstance(input_string, st...
cf18344ddd336d878837bc5654a3ea3b98eec729
50,798
from sys import version_info def _open_csv_file(filename): """Opens a file for writing to CSV, choosing the correct method for the current version of Python """ if version_info.major < 3: out_file = open(filename, 'wb') else: out_file = open(filename, 'w', newline='') return ou...
527b7d216d6ecd2d30ac716e993edee6a95766bc
50,799