content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def top(request): """ Return movies from top 3 ranks based on comments amount in some time period :param request: :return: """ movies = Movie.objects.all() serializer = TopMovieSerializer(movies, many=True, context={'request': request}) filtered_list = [movie for movie in serializer.data...
372cf9877db43cbc1e76e5a362762e895dace022
44,095
def LargestPrimeFactor(num): """Calculate greatest prime factor using length of list It is best practice to use greatest prime factor for hash table's capacity. This method calculates the greatest prime factor using the int passed in and returns the prime integer. Time complexity of O(logn) :p...
ccb09b7bd385a8b4795dbdeb3a4e886cd0922f20
44,096
def generate_tool_metadata( tool_config, tool, repository_clone_url, metadata_dict ): """Update the received metadata_dict with changes that have been applied to the received tool.""" # Generate the guid. guid = suc.generate_tool_guid( repository_clone_url, tool ) # Handle tool.requirements. tool_re...
6f2f4bd7b4ec8517c574908499de001457df390f
44,097
from inspect import signature import warnings def fit_gaussian(data, weight=None, func=elliptical_gaussian): """Fit a gaussian on a map. Parameters ---------- data : array_like the input 2D map weight : array_like (optional) the corresponding weights func : function th...
b69b1c286fe7b09bf6531c47d2b2c1c8ad4f8c7c
44,098
def lua_property(name): """ Decorator for marking methods that make attributes available to Lua """ def decorator(meth): def setter(method): meth._setter_method = method.__name__ return method meth._is_lua_property = True meth._name = name meth.lua_setter...
97cd57cf21c4afdb43b6504af56139228df751cd
44,099
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 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
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
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 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
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
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
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
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
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
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
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
def load_trajectory_to_npy(filename, name="", begin=0, end=None, stride=None): """ Loads the trajectory into four numpy arrays containing: * the number of particles per frame (shape=(n_frames,)) * the positions of the particles for each frame (shape=(n_frames, max_n_particles_per_frame, 3)) * the t...
06d60f0d673c47e2b2fbc907f179b40c10a86f60
44,200
def recurse(gentle_output, audio_file, anchor_length): """ Recursively align the unaligned segments of a given Gentle output. Parameters ---------- gentle_output : list of Word objects outputted by previous Gentle run audio_file : PyDub object representing the entire audio file anchor_lengt...
e285a5367e7810037fa9fd87d0d09d06b0dcf43c
44,201
import json import urllib def get_released_versions(package_name): """ Fetches the released versions & datetimes of the specified Python package. Examples -------- >>> get_released_versions("scikit-learn") {'0.10': '2012-01-11T14:42:25', '0.11': '2012-05-08T00:40:14', ...} """ url = "...
53116bb1cc6a91938aaf7710e6b6ed416d95f84a
44,202
def total_loss_function(c_image,s_image,g_image,alpha,beta): """ Args: c_image_path (str): To take the content image path s_image_path (str): To take the style image path g_image_path (str): To take the generate image path Returns: int: The totoal loss...
11c99b1199a726823838f59329599e276174a836
44,203
def cartesian_to_spherical(x, y, z): """ Convert cartesian coordinates to spherical in the form (theta, phi[, r]) with the origin remaining at the center of the original spherical coordinate system. """ r = np.sqrt(x**2 + y**2 + z**2) #theta = np.arccos(z / r) theta = np.arctan2(y, x) p...
b6b2f88a36c1459e445bf8ca1ff1cdf9d5824191
44,204
def logistic(z: np.ndarray, a: float, b: float) -> np.ndarray: """ Compute logistic function Inputs: a: exponential parameter b: exponential prefactor z: numpy array; domain Outputs: f: numpy array of floats, logistic function """ den = 1.0 + b * np.exp(-...
61ae563b89b33cc7581bb8537ce885cadaf176d7
44,205
import logging import re def get_diamond_predicted_domains(predicted_domains, protein_accession): """Retrieve the CAZyme domains predicted by DIAMOND, from the overview.txt file. :param predicted_domains: list of strings, each string contains a unique CAZyme domain prediction :param protein_accession: st...
5c6aa1ba54777ad49ed91a7b50fcaa1d39b356d7
44,206
import time def review(): """ user wants to toggle a paper in his library """ # make sure user is logged in if not g.user: return 'NO' # fail... (not logged in). JS should prevent from us getting here. idvv = request.form['pid'] # includes version if not isvalidid(idvv): return 'NO' # fail, malf...
1dda1faeaf599651e310b6d13c584564ccac9bef
44,207
async def find_busy_consumers(engine): """Returns a list of busy consumers that can be used to run.""" Consumer = namedtuple('Consumer', ['ip', 'status', 'port', 'job_chunk_id']) try: async with engine.acquire() as connection: query = sa.text(''' SELECT ip, status, port,...
e9be4fefe889a6da8818b0f53175fcc32407b54b
44,208
def mlp_missing_biology_occurrences(): """ Function to identify occurrences that should also be biology but are missing from biology table :return: returns a list of occurrence object ids. """ result_list = [] # Initialize result list # Biology occurrences should be all occurrences that are ite...
e93cdbe038ae18fe6540b84907406415572912cf
44,209