content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def toalphanum(s): """ gets rid of the unwanted characters """ _s = '' for c in s: if c in '\\ /(.)-': _s += '_' else: _s += c return _s
14ce33504a467406f42c095526cc232364ac6d1a
44,100
def endl_C_yosMultiplicity( C, yi ) : """Returns the list [ nn, np, nd, nt, nHe3, na, ng ] where nn is the multiplicity for neutrons, np is the multiplicity for protons, etc. If C-value is not defined then None is returned. If the reaction is fission then -1 is returned for neutron multiplity (i.e., C =...
7ebd5e8edfdf00f87255f304867fa314dfb67203
44,101
def get_identity(dim, name, conv=True): """ :param dim: dimension of the identity matrix :param name: name for the variable :param conv: BOOLEAN, define variables as matrix or vector :return: created parameters of identity for T-layer """ return ( tf.Variable(tf.eye(dim, batch_shape=...
4b467a690a24a3b74758e9fec86b618d280a8183
44,102
def ip2int(ip_str): """ Convert XXX.XXX.XXX.XXX to integer representation Args: ip_str (str): IP in a XXX.XXX.XXX.XXX string format Returns: ip_int (int): Integer IP representation """ ip_int = None if isinstance(ip_str,str): # clean IP if ip_str.find(':') >...
bb48f28519593222c005df1b009d7e669dde7669
44,103
def gram_matrix(feature_set): """ Given a set of vectors, in the form of a tensor, from a layer, compute the Gram matrix (https://en.wikipedia.org/wiki/Gramian_matrix). Args: feature_set: Tensor of vectors ([1, filter_height, filter_width, num_feature_maps]) Returns: gra...
48f969ba1cef5331aa3b9795cc12c86685e26bca
44,104
from typing import Type def impl_method( target: Type, *, override: bool = False, as_classmethod: bool = False, as_staticmethod: bool = False, ): """ Decorator. Set function as a method of the given class (regular, classmethod or staticmethod) Args: target: Type ove...
a5bc974e59bd643a9a7e3df1b21825e54a8e5cb6
44,105
import itertools def _find_chordless_cycles(bond_graph, max_cycle_size): """Find all chordless cycles (i.e. rings) in the bond graph Traverses the bond graph to determine all cycles (i.e. rings) each atom is contained within. Algorithm has been adapted from: https://stackoverflow.com/questions/402266...
ad7228c31477f457e13e45c789022aca35f00183
44,106
def _get_all_children(base, tag): """Get a list of all child elements with a given tag. Args: base: The base node element. (lxml node) tag: Child elements group tag used to select the elements. (string) Returns: A list with all child node elements found or an empty list. """ ...
9bfa32a7510e854ea90bf1b33f5e3514ac1f9945
44,107
import warnings def evaluate(y, pred_y): """ Revise: test when a key is a review/account. Evaluate the prediction of account and review by SpEagle Args: y: dictionary with key = user_id/review_id and value = ground truth (1 means spam, 0 means non-spam) pred_y: dictionary with key = us...
78a4398b0d85ab6516c3d84f3b06c88bd8a433ec
44,108
from typing import Any def unpack_object(data: MessageData) -> Any: """unpack data Parameters ---------- data : mprpc.message.MessageData data to unpack Returns ------- Any unpacked data Raises ------ mprpc.MPRPCException If msgpack package failed to ...
3c96945665bf6e222fa4969e82cb3291bfffc8d0
44,109
def access_token_generator(token_generator, access_token_template): """A function that generates a signed access token""" def func(**extra_claims): claims = {**access_token_template, **extra_claims} return token_generator(**claims) return func
4a1052b46dc85e3f15375fbbc5062a950fe40874
44,110
def interpolate_aviso(ds, XC, XG, YC, YG, debug=True, verbose=True): """Interpolate aviso dataset onto model coordinates (regular lat lon grid) PARAMETERS ---------- ds : xarray Dataset from reading in Aviso data (e.g. from aviso_products.merge_aviso) XC : numpy.arra...
845d9afcdc2ec1b71ebfd4f738616762270c864f
44,111
def home(request): """ View for homepage. :param request: WSGI request from user :return: Render the wiki page and pass the value from context to the template (home.html) """ hero_image = 'img/home-cover-night.png' hero_image_light = 'img/home-cover-light.jpeg' latest_add_rulesets = [] ...
7efc55e6687c93c0f770b99bb6a3c02b4feb9228
44,112
import os def create_ABC_estimate_config(path_run_ABC, param_num): """ Create ABCtoolbox config file for estimation. :param path_run_ABC: full or relative path to directory to run ABC in. :param param_num: number of parameters :return: """ file_name = '{}/test_ABC_estimate.txt'.format(pa...
31287b0e03d0ae730a503370ebd05447190aa2b2
44,113
def calculate_mixing_param_constants(asm_obj): """Calculate the constants Cs and Cm required for the determination of the Cheng-Todreas mixing parameters Parameters ---------- asm_obj : DASSH Assembly object Contains the geometry and flow parameters Returns ------- tuple ...
336aa6de073fa9eece218deef0d236f47c7fea79
44,114
from typing import Dict from typing import Union from typing import Tuple import random def _get_split_by_type_input_and_validation( input: Dict[str, Union[list, set]], background_mat: Matrix, type_label: str, splited_selection_for_variance = True ) -> Tuple[Matrix, Matrix, Dict[st...
c06fd1337640dccd5072df83f8fe80ca0e14f208
44,115
def get_candidate_targets(graph): """Return all candidate target on a given BEL graph.""" return [ node for node in graph.nodes() if _is_target_node(node) ]
b88c6defb3b28bce63bced9fd355fece7fdaf0ef
44,116
def convert_np_dtype_to_dtype_(np_dtype): """ Convert the data type in numpy to the data type in Paddle Args: np_dtype(np.dtype): the data type in numpy. Returns: core.VarDesc.VarType: the data type in Paddle. """ dtype = np.dtype(np_dtype) if dtype == np.float32: ...
03f90b6f8b0e2a8ebc8bb21b202908cda26e8b6f
44,117
def cast_str_to_bool(input_string: str) -> bool: """Convert string to boolean with special handling for case, "True", 1. Special string parsing for booleans. Args: input_string (str): Evaluate this string as bool. Returns: case-insensitive 'True', '1' or '1.0' is True. It will...
38898f9aaa14ce9d6872941252213431c07878d1
44,118
def HPLake_Op(mdot_kgpers, t_sup_K, t_re_K, t_lake_K): """ For the operation of a Heat pump between a district heating network and a lake :type mdot_kgpers : float :param mdot_kgpers: supply mass flow rate to the DHN :type t_sup_K : float :param t_sup_K: supply temperature to the DHN (hot) ...
546cdafe3152eec230d708235b6faecb780d410a
44,119
import os import logging import sys def get_application_module(application): """ Return the python module of a wrapped application Parameters ---------- application: str The name of the application Return ------ The python module containing the wrapper to the application ...
5f5f1f6722e1f765a53504498bbe5f54f1735f75
44,120
def quantize_annotate_layer(to_annotate, quantize_config=None): """Annotate a `tf.keras` layer to be quantized. This function does not actually quantize the layer. It is merely used to specify that the layer should be quantized. The layer then gets quantized accordingly when `quantize_apply` is used. This m...
e76d05a6d76b6b352513bfa84d389e5a4f3e20a3
44,121
def phi31_v_from_i_skow(phi31_i): """ Calculates the V band phi31 for the given I band phi3 using the relationship found in Skowron et al. (2016). (Skowron et al., 2016) (6) Parameters ---------- phi31_i : float64 The I band phi31 of the star. Returns ------- phi31_v :...
9594e7676bf844908e6555c4064aa795272e529d
44,122
def setNextAvailMachineTimer(intent, session): """Dynamo resource and table""" userTable = DynamoTable('Users') return buildNextAvailMachineResponse(intent, session, userTable)
b2aa3c9a6685b5cbd3a0ab2b933794efe1974d37
44,123
from typing import List import time def read_response_head(lines: List[bytes]) -> response.Response: """ Parse an HTTP response head (response line + headers) from an iterable of lines Args: lines: The input lines Returns: The HTTP response object (without body) Raises: ...
5ad98d9ff65a254a9b333479813d62963559d874
44,124
def prepare_hr_for_events(events_info) -> str: """ Prepare the Human readable info for events command. :param events_info: The events data. :return: Human readable. """ hr_list = [] for record in events_info: hr_record = { 'Event ID': record.get('id', None), ...
cb2ec221388b0a2ab6d1d5f5bdb547e26ca0e4a5
44,125
from collections import Counter from mcmc_convergence_utilities import generate_subtrees from time import time def create_vector(expression,verbose=False): """ Create vector out of the passed expression """ s=time() sub_trees=generate_subtrees(expression).values() v=Counter(sub_trees) if verbose==...
39b3d5387c1d7d20c2771859d99dabaf2ea47576
44,126
def CDLHIGHWAVE(df): """ 函数名:CDLHIGHWAVE 名称:High - Wave Candle 风高浪大线 简介:三日K线模式,具有极长的上/下影线与短的实体,预示着趋势反转。 python API integer=CDLHIGHWAVE(open, high, low, close) :return: """ close = df['close'] return talib.CDLHIGHWAVE(open, high, low, close)
73f211731a83402206d323b422e38253a953bb98
44,127
def thisGroup(): """thisGroup() -> Group Returns the current context Group node. @return: The group node.""" return Group()
5a7d4e36e9f879d161865f4a2fe5c13d45e7365a
44,128
def swap_simple_oxide(oxin, oxout): """ Generates a function to convert oxide components between two elemental oxides, for use in redox recalculations. """ inatoms = {k: v for (k, v) in oxin.atoms.items() if not k.__str__()=='O'} outatoms = {k: v for (k, v) in oxout.atoms.items() if not k.__str...
4625b8517bbd7717d48d1d85f9fb801ea54ac545
44,129
def logout(): """ Display the logout request to the user """ next_page = request.args.get('next', "") if is_connected(): return redirect(next_page) else: return render_template("logout.html", next=next_page)
29bd531732fbc0258ed6e8190205a5e55d6204e5
44,130
def peaks_adaptive(data, mask, rank=5, r0=7.0, dr=2.0, nsigm=5,\ npix_min=1, npix_max=None, amax_thr=0, atot_thr=0, son_min=8) : """Wrapper for liast of 2-d arrays or >2-d arrays data and mask are N-d numpy arrays or list of 2-d numpy arrays of the same shape """ if isinstance(dat...
105b9377d4f0f11fa64ad615b7474ff7dfd3b6ce
44,131
def add_layers_basic(sample, R10, T01, R12, R21, T12, T21): """ Add two layers together. The basic equations for the adding-doubling sample (neglecting sources) are T_02 = T_12 (E - R_10 R_12)⁻¹ T_01 R_20 = T_12 (E - R_10 R_12)⁻¹ R_10 T_21 +R_21 T_20 = T_10 (E - R_12 R_10)⁻¹ T_21 R_0...
70fbe0bf3940d1b0dc3daf5a5dba94e6df4bfbe6
44,132
from typing import Tuple from typing import Dict def act_and_step( key: PRNGKey, env: gym.Env, act_fn: ACT_FN, use_state: bool, ) -> Tuple[PRNGKey, Dict[str, Array]]: """Do one-step and return the results. Args: key (PRNGKey) env (GymEnv) act_fn (ACT_FN) use_st...
e151728297e132ffefbbcb307452f8502fc72585
44,133
from io import StringIO def structure_rebuild_test(pdb_structure, verbose=False): """Test rebuild PDB structure from internal coordinates. :param pdb_structure: Biopython Structure Structure to test :param verbose: bool print extra messages :return: dict comparison dict from c...
5db655a10c3ff7a5f178720b7f020e3c7793019f
44,134
def sklearn_to_pfa(estimator, types, featurizer=None): """ Convert scikit-learn estimator to PFA format. :param estimator: Scikit-learn estimator, must be supported :param types: List of tuples (name, type) """ types = _fix_types_compatibility(types) featurizer = featurizer or _construct_fe...
02d591af4c1815a55350ec082f472d530278c77d
44,135
def rgb_to_hsv(r, g, b): """ Converts RGB to HSV Hue will be normalized and will be on the scale of 0-1 than 0-360 Conversion formula is taken from https://www.rapidtables.com/convert/color/rgb-to-hsv.html :param r: Red (0 to 1) :param g: Green (0 to 1) :param b: Blue (0 to 1) :ret...
d7926acbcf1bae02e1047d76c7c30d9652e7b173
44,136
def format_slug(text: str = None, max_len: int = 50) -> str: """ Format string to create slug with max length. Parameters ---------- text: str name to format into a NetBox slug max_len: int maximum possible length of slug Returns ------- str: input name formatted as ...
d1b8ad0afc97cc86e12ef9e61e1f3acf47113cda
44,137
import os def image_detect_and_compute(detector, img_name): """Detect and compute interest points and their descriptors.""" img = cv2.imread(os.path.join(dataset_path, img_name)) img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) kp, des = detector.detectAndCompute(img, None) return img, kp, des
d8a1168fbe7a4ced29b9c7ffb55291a2daa21fc7
44,138
import aiohttp async def get_xsts_token(token: str): """Gets the XSTS token and the user hash given the XBL token. Args: token: The XBL token to authenticate with. Raises: IncorrectCredentials: If the XBL token is incorrect. """ payload = { "Properties": {"SandboxId": "RE...
aa5eeddfb369be68f76c857f440aba52f3cba9ec
44,139
def tts(df, train_size=0.8): """ Create train and test dataframes with provided datagroup dataframe. --- IN df: datagroup df as created by pull_datagroup_from_db() function (df) train_size: size of training set, test set will be 1-train_size (float) OUT train_df, test_df """ ...
201d25512656eaac9a935e9e309f5e382a6f617b
44,140
def get_object_type(objects: list, types: list) -> list: """Get the object specified. Args: objects: a list of objects. types: a list of the types. Returns: A list of a certain type. """ return [item for item in objects if item.get('type') in types]
bfccc9c838f0a2d3294068acc0d2091c44de4798
44,141
def generate_random_basis(n_points=1000, n_dims=3, radius=1.0, random_seed=13): """Sample uniformly from d-dimensional unit ball The code is inspired by this small note: https://blogs.sas.com/content/iml/2016/04/06/generate-points-uniformly-in-ball.html Parameters ---------- n_points : int ...
af8bdc1100da94a24059cc501c7f20c08d801ced
44,142
import os import shutil async def save_model_to_disk(training_id: str = '', model: UploadFile = File(...)): """ Receives a .zip file containing a tensorflow2 SavedModel object sent by a dataset microservice. Then, will store the .zip file in trained model docker volume, with the naming format of <trai...
c2bc6fa6f62ffb1afcc907d7841d71c447549090
44,143
def load_face_detector_and_embedder(model_path, model_proto_path, embed_model): """Returns loaded face detector and embedder Args: model_path (str): Path to the detector model model_proto_path (str): Path to the proto.txt file from detector model embed_model (str): Path to the embedder...
059485bb631d1ef3cd16008b06cfb8ed6684a5f9
44,144
def guess_avdm_ols(sed_mod, sed_obs, Alambda): """ matrix form OLS solution for Av and DM """ sed_mod = np.array(sed_mod) sed_obs = np.array(sed_obs) assert sed_mod.ndim == 2 assert sed_obs.ndim == 2 n_band = sed_obs.size # color X = np.array([Alambda, np.ones_like(Alambda)]).T y =...
6541fb7203dba78b5084289086e1ceb01d37b996
44,145
def get_stats_example() -> pd.DataFrame: """Return example data for statistical analysis. Returns ------- data : :class:`~pandas.DataFrame` dataframe with example data that can be used for statistical analysis """ return load_long_format_csv(_get_data("stats_sample.csv"))
35acea279db6a718b8035572dfe619de95080140
44,146
def PyEntityFactory( className, context ): """ Build a new class type by calling the factory, and add it to the given context. """ EntityClass = PyEntityFactoryClass( className ) context[ className ] = EntityClass return EntityClass
455463a5dbde00bdec6e5f1cf02cd896785a90bb
44,147
import time def unix() -> int: """ Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. Returns: int """ return int(time.time())
3e5a0933d9a9eaee7c9f4136f651af6f2982dacc
44,148
import re def next_page(url): """Takes Bing search result URL, returns next search result page URL.""" m = re.search('first', url) if m: m2 = re.search('first=(\d+)&', url) page_count = int(m2.group(1)) new_page_count = page_count + 10 to_be_replaced = 'first=' + str(page...
47e09fbff19477fc59046ca8743a74e177f3456e
44,149
def m_mask(elements: str): """Mg Ca A Fe B C --> M A B C""" symbols = elements.split() hasm = False nonmetal = [] for s in symbols: if s in MDefined: hasm = True else: nonmetal.append(s) if hasm: masked = "M " + " ".join(sorted(nonmetal)) else:...
1e5a7f93df150ad2e344781b6c9fee578db9b040
44,150
def sanitize_input(data): """Sanitizes input for reddit markdown tables""" # TODO: maybe the rest of markdown? return data.replace('|', '&#124;').replace('\n', '').replace('*', '\\*')
3921c2495bd13393cf8fef5c8cd33826ca3c1402
44,151
from datetime import datetime def _date2dt(date): """转化 datetime.date 到 datetime.datetime 类型""" return datetime.datetime.combine(date, datetime.time.min)
c24b466f1c3b5ea390f9cb688e13f661d047508d
44,152
def _get_relative_anchors(cluster_medoids, bounds): """Get medoid coords relative to fetched RGB.""" relative_medoids = cluster_medoids.copy() relative_medoids.loc[:, "xmin"] -= bounds["XMIN"] relative_medoids.loc[:, "ymin"] -= bounds["YMIN"] relative_medoids.loc[:, "xmax"] -= bounds["XMIN"] rel...
5b1bf76aa2e5bf21831df573dd85941dc738a5cc
44,153
import requests def get_tv_info_for_season( tv_id, season, verify = True ): """ Finds TMDB_ database information for the TV show and a specific season. :param int tv_id: the TMDB_ series ID for the TV show. :param int season: the season on the TV show. :param bool verify: optional argument, w...
45f28b101ab94a4bfaa9d516e00b1145ff5d966d
44,154
import os def backend_rawfile_load(filename: str, upload_path: str) -> complex: """Load an audio sequence from a wav file using the native sampling rate. Args: filename (str): audio wav filename upload_path (str, optional): Upload folder path on backend server. Returns: numpy ar...
8146df008f59c93f87575c96bee78dea3169f25f
44,155
def get_metric(run_id, metric_id): """ Get a specific Sacred metric from the database. Returns a JSON response or HTTP 404 if not found. Issue: https://github.com/chovanecm/sacredboard/issues/58 """ data = current_app.config["data"] # type: DataStorage dao = data.get_metrics_dao() metr...
f962096ca3e0c40bc31f6c40de2b6bad0d8fb543
44,156
def make_more_vivid(image): """Modify the saturation and value of the image.""" hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) hue, saturation, value = cv2.split(hsv) saturation = np.array(saturation * 1.2, dtype=np.uint16) saturation = np.array(np.clip(saturation, 0, 255), dtype=np.uint8) value...
aae60663191165cdc0a32993be6d6bead5f98836
44,157
def get_image_bookmark(caller, config, hide, start_page=1, end_page=0, tag=None, use_image_tag=False): """Get user's image bookmark""" br = caller.__br__ total_list = list() i = start_page offset = 0 limit = 48 member_id = br._myId total_bookmark_count = 0 encoded_tag = '' while...
254bbb2ddfc69dc8a14552cb410f13ae97906073
44,158
def capacity_cost_rule(mod, g, p): """ """ return mod.DRNew_Cost[g, p]
cb6c7160cbdafa4b884f38083a20f59c155a63dc
44,159
def syncronize_syncs(method_name, config, sync_name=None, host_name=None): """use the config to push paths to hosts syncronize syncs by pulling or pushing sync's paths to hosts if None used as host_name with push method, sync syncronized with all hosts, but in pull method it start syncing sync ...
fd04f169e917a6920014fb6240a4d02d6ed36622
44,160
def Vc_methods(CASRN): """Return all methods available to obtain Vc for the desired chemical. Parameters ---------- CASRN : str CASRN, [-] Returns ------- methods : list[str] Methods which can be used to obtain Vc with the given inputs. See Also -------- Vc ...
c9c94d06293dbeb182f37a45677e3438af636b0a
44,161
from pathlib import Path def get_builtin_specs(): """ Produces a list of all available specs :return: """ # get list of available dicts, assuming the _ separates name_version specs = [s.stem.split("_") for s in Path(pkg_specs_dir()).glob("*.yml")] # gives us list of tuples with valid com...
117b973603f02b11e72e87eb0a235c852b03840a
44,162
import re def get_term_count_list(term, term_field="text_xml", limit=opasConfig.DEFAULT_LIMIT_FOR_SOLR_RETURNS, offset=0, term_order="index", wildcard_match_limit=4): """ Returns a list of matching terms, and the number of articles with that term. Args: term (str): Term or comma separated list of...
6392970a6ff610d433212337c3f92cd48c316abb
44,163
import csv def create_fann_train_from_csv(csv_fname, train_fname, sections, all_species): """ takes the csv file saved by the leaf collection and creates FANN training data from it. """ # format 'binomial nomenclature: [leaf measurements] imported_data = {} total_leaves = 0 # read and ...
d0783c6a78c125250d47bffac753cda1c9df6f2e
44,164
def RHS_func(t, y_flat, mc_inst): """RHS function for the ODEs, get's called in ivp.solve_ivp""" reimport_numerical_libs("RHS_func") # constraint on values lower, upper = (0.0, 1.0) # bounds for state vars # grab index of OOB values so we can zero derivatives (stability...) too_low = y_flat ...
046e3afc09d29577e62d595f11900cc673285343
44,165
def __get_last_successive_rg_area(df: DataFrame, rg_field_name, area=RGAreaTagValue.GREEN): """ 获取最后一段颜色为area的连续区域 @param df: @param rg_field_name: @param area: @return: """ # TODO 全红或者全绿需要处理 if df[df[rg_field_name] != area].shape[0] == 0: return df.copy().reset_index(drop=Tr...
9c5c1a0a3749c4065af7c3ca5b6b58e085ab6b3e
44,166
import html import re def extract_item_text(item_text_elmt: bs4.Tag) -> str: """Extract the text content of an item.""" fins = '' for tag in item_text_elmt.contents: if tag.name != 'div': # since we're using the raw string representation, which would include # named and num...
b4b43c5de38e0602ebf8d7f24b703f7432f0e837
44,167
from pydantic import BaseModel # noqa: E0611 import torch def get_optimizer( beta1: float, beta2: float, eps: float, lr: float, model: BaseModel, wd: float, ) -> torch.optim.AdamW: """Get AdamW optimizer. Parameters ---------- beta1: float First coefficient of gradient moving average. beta...
179b674b5b2a0c87be3c6ba3abb8befbe51ba870
44,168
def get_cached_tags(userkey): """ Fail-safe way to get the cached tags for `userkey` """ try: return all_tags[userkey] except KeyError: return []
7150ef7609f275e77240d09953c062aa37085384
44,169
from typing import Dict from typing import Any from typing import Tuple from typing import Optional from typing import List def parse_config( raw_config: Dict[str, Any] ) -> Tuple[Optional[InfestorConfiguration], List[str], List[str]]: """ Checks if the given configuration is valid. If it is valid, return...
33ce3680e3575f547551471240d099bd02f37b08
44,170
def gps2dyr(time): """ Converte GPS time to decimal years. """ #return Time(time, format='gps').decimalyear return Time(time, format='gps').datetime
e37135ad278e88762e57650cb3da48be37eb0470
44,171
def surface_carre(arete): """ fonction qui calcule et renvoie la surface d'un carré :param arête: la longueur d'un des côtés du carré :type arete: int ou float :return: la surface du carré dans l'unité (au carré) de celle d'arete :rtype: int ou float """ return arete*arete
fecc5ceae98a3549ccc79237cf94423e166a4429
44,172
import os import requests def notify_ifttt(message, title=None, link=None, key=None): """Send notification via IFTTT Parameters ---------- message : str title : str, optional link : str, optional key : str, optional API key for IFTTT. If not set, imports the environmental ...
b453fc2986bfa1f94e1b612663d1b71408c7d696
44,173
import sys def encode(gene, size=SIZE, k=K, h=H, HASH_MAX=sys.maxsize + 1): """Creates a bloom filter. Used to encode a genetic sequence. Args: gene: A string holding all or part of a DNA sequence. size: The size of the bloom filter. Set to the default size if no size is given. ...
23d02bfc9b08d3b3da170fc4a147c6589fdc841c
44,174
from io import StringIO def build_xml_stream(xml_tags_fragment="", xml_items_fragment=""): """Formats the boilerplate XML template with the provided fragment for top level tags.""" return StringIO( xml_stream_header + xml_tags_fragment + xml_items_fragment + xml_stream_footer )
19cecd301e88d24b650770716efecb84f6ffcd73
44,175
def task_status(request, task_id=None, data=None): """ Returns (:http:get:`GET </task/(task_id)/status>`) task status and task result. .. http:get:: /task/(task_id)/status :DC-bound?: * |dc-no| :Permissions: * |UserTask| :Asynchronous?: * |async-...
35e170e7a63e8e31ad051327c33cae6feaa36b2c
44,176
import argparse def getOptions(): """ Function to pull in arguments """ parser = argparse.ArgumentParser(description="Reads a FASTQ file and calculates position bias.") parser.add_argument("-i", "--input", dest="fname", action='store', required=True, help="Name of input FASTQ file [Required]") parser....
fe9df5445547b46070c07b3cf77a55a7f737390f
44,177
def format_inline_cite(entry_list, citation_manager): """Return string, formatted in-text citation (allows *multiple* citations). `entry_list` : list entries to be formatted `citation_manager` : CitationManager instance handles name formatting :note: need the entry formatter bc its determines the field of the...
1c689fbfb2b66d8667434af922312e89b20ca828
44,178
def WY_to_Q(W, YH): """ Retrieves Q from its WY representation. """ m = W.shape[0] Id = jnp.eye(m, dtype=W.dtype) return B_times_Q_WY(Id, W, YH)
2b3910e583d24b48b121445381c6e7faa6c55164
44,179
def compare_identifier(device): """ Compare device canonical name to the Pure Storage identifier. Args: device (string): Device canonical names. (See below for examples) Returns: pure_devices (list): List of confirmed Pure Storage backed devices. """ # Examples of valid device cano...
2f466c44089f3d0226697aebd804f2495d1ccdd2
44,180
def register(): """ Registration method reflects that taught on the CI Task Manager project. Checks the entered registration details for an existing username and email and responds accordingly. If the values are unique; creates new database entry for the user and logs them in as the session user. ...
833dfe96c3ca5ca1cdd225e3d01afdf9d9e11efd
44,181
def gen_pipeline_test_baseline(ds_name='cifar10', tfds_path='', size_batch=100, size_buffer_cpu=5, dataset_cache=False, num_parallel_calls=-1): """ :param ds_name: dataset name for tensorflow datasets ...
39d9f35b54f38980b44b18c7cb74adeabba1879a
44,182
from typing import Union def defer(orig: Union[TNone, dict], parent: Union[TNone, dict], *, info: MutationInfo, ) -> dict: """ Merge two dictionaries. defers conflicting values to another merger. """ output = {} orig_: dict = NULL.default_none(orig, {})...
4a3e2b19e64ac46a0df6ed44de7558391b68bde2
44,183
import requests def _confirm_webpage(url: str) -> bool: """ A function that confirms the existence of a webpage before the object is created """ response = requests.get(url=url, allow_redirects=True) code = response.status_code return True if code == 200 else False
9d16c8eb26457df238d553656c9cc82e12ff9482
44,184
def _transform_masks(y, transform, data_format=None, **kwargs): """Based on the transform key, apply a transform function to the masks. More detailed description. Caution for unknown transorm keys. Args: y: `labels` of ndim 4 or 5 transform: one of {`deepcell`, `disc`, `watershed`, `centro...
7d583e3ca60c87feff2c5eb4d093b1bf793d1ceb
44,185
def set_cors_uri(cors_uri=None): """ Returns list of allowed domains for System Manager Role Method: POST Parameters: cors_uri [string] Valid URL. Path not included. e.g. http://localhost:8000 Path: /api/method/castlecraft.services.settings.set_cors_uri Error: 403 Response: ``` { "message": [ "https...
928a948a896686e64dd92969ff01136d5ae10703
44,186
def DRP_interleaver(K, w, r, s, p): """Inputs: K = interleaver size w = write dither vector, must be a factor of K r = read dither vector, must be a factor of K s = RP interleaver start index, must be in [0,K-1] p = RP interleaver, must be relatively prime to K Returns DRP interleaver """ # DRP interleaver par...
76bfbdb1bd4ae1edd711798ed5cf987b3ccfea51
44,187
def get_face_coordinates(vertex, faces, K_max='None'): """ computes the face_cooridinates used for surface Loss Input: vertex = (N x 3) faces = (F x 3) triangle mesh Output: face_cooridnates = (NxKx9) where K is the max numbers of neighbours. Each row lists vertex coordinates for...
7c66c040fe083f8e6378f50516e9c19abbf0fb1a
44,188
def get_config(infile=None, configspec=None, *args, **kwargs): """Get configuration from a file.""" if configspec is None: configspec = cfg.split("\n") return Config(infile, configspec=configspec, *args, **kwargs)
739b0085728c38fb012fa151b249755e263cc5a0
44,189
def remove_short_cycles(data, min_length=2): """ Remove cycles with length smaller than `min_length`. Notes ----- Modifies `cycles`, `cycles_lengths` attributes of `data`. """ ii = np.where(data.cycles_lengths >= min_length)[0] data.cycles = data.cycles[ii] data.cycles_lengths = dat...
b45a21a5696f4410cb84ab9d5e4111d8bbdb4a88
44,190
def BuildDebugInfoResponse( name, servers = [], items = [] ): """Build a response containing debugging information on a semantic completer: - name: the completer name; - servers: a list of DebugInfoServer objects representing the servers used by the completer; - items: a list of DebugInfoItem objects for ad...
b23ebfd6818db2a6786b5ded804cf58ee4f91b89
44,191
import torch def envs_irm_S(X_train, X_test, T_train, y_train, E, number_environments): """Compute the environments variable required by the InvariantRiskMinimization class for IRM_S / IRM_1 Args: - X_train: training features - X_test: test features - T_train: training treatment - y_train: tr...
25ee85e0ec497f82dccd8c7c7e01ba4ce5d152cb
44,192
import ipaddress def netaddr(host_ip, prefix): """Return network address and subnet mask.""" ip_address = host_ip + '/' + prefix try: ip_net = ipaddress.ip_network(ip_address, False) output = {'network_address': str(ip_net.network_address), 'network_mask': str(ip_net.netm...
2c51d802eb92b7a0542d85d043ecebe420cecc60
44,193
import asyncio def timeout(duration): """Rewrite a coroutine to operate on a strict timeout""" def rewrite(fn): async def wrapper1(*args, **kwargs): try: return await fn(*args, **kwargs) except asyncio.CancelledError: pass async def wrap...
425c00baa597fd3b41d0e2117562c6d8a28dedd1
44,194
def data_preparation(config, save=False): """Split the dataset by :attr:`config['split_strategy']` and call :func:`dataloader_construct` to create corresponding dataloader. Args: config (Config): An instance object of Config, used to record parameter information. save (bool, optional): If `...
4a0943b17c999503e809e5110c39fe9f466c9637
44,195
def app(n, p): """ Parameters ---------- n Order p Dimension of the problem (number of input pi number in the pyVPLM case) Returns Approximates the solution for big n and p ------- """ # c = -0.0027*p + 0.147 return int(p**n/(fact(n) + 1))
6dfb00e4e71acf6eb58a5425edcf974c151c086a
44,196
def bit_count(bin_name, bit_offset, bit_size): """Creates a bit_count_operation to be used with operate or operate_ordered. Server returns an integer count of all set bits starting at bit_offset for bit_size bits. Args: bin_name (str): The name of the bin containing the map. bit_offset (in...
a948136c9515abdfee7bdea19ab57dd5709d8cfc
44,197
from typing import Union def change_message_from_percent(percent_change: Union[str, int, float]) -> str: """Creates a change message from given percentage change. percent_change will be: - "-" in case the last data point was missing - 0 (int) in case there was no change - positive val...
ba4d315eab8e49cad6a9169c11e9ac75d3a28c7f
44,198
from typing import Any def infer_type(value: Any) -> DataType: """Infers a trino type from the given python value. """ if isinstance(value, bool): return boolean() if isinstance(value, int): return infer_integral(value) if isinstance(value, float): return double() if is...
86eed097ccc53516b767e811c3b8055835f92496
44,199