content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def k1(f, t, y, paso): """ f : funcion a integrar. Retorna un np.ndarray t : tiempo en el cual evaluar la funcion f y : para evaluar la funcion f paso : tamano del paso a usar. """ output = paso * f(t, y) return output
55a358a5d099111bd399bf1a0e0211d6616ab3d0
4,800
import json def script_from_json_string(json_string, base_dir=None): """Returns a Script instance parsed from the given string containing JSON. """ raw_json = json.loads(json_string) if not raw_json: raw_json = [] return script_from_data(raw_json, base_dir)
87845df4f365f05753f48e3988bb6f57e9e327ef
4,801
import subprocess import os def write_version_file(version): """Writes a file with version information to be used at run time Parameters ---------- version: str A string containing the current version information Returns ------- version_file: str A path to the version fil...
8b557b5fa7184172639f6e7b919f6828eaebc0b2
4,802
def check_api_key(key: str, hashed: str) -> bool: """ Check a API key string against a hashed one from the user database. :param key: the API key to check :type key: str :param hashed: the hashed key to check against :type hashed: str """ return hash_api_key(key) == hashed
86784ac5b6e79e009423e32a68fbac814e18fd40
4,803
def travel_chart(user_list, guild): """ Builds the chart to display travel data for Animal Crossing :param user_list: :param guild: :return: """ out_table = [] fruit_lookup = {'apple': '๐ŸŽ', 'pear': '๐Ÿ', 'cherry': '๐Ÿ’', 'peach': '๐Ÿ‘', 'orange': '๐ŸŠ'} for user in user_list: ...
f866cb792b4382f66f34357e5b39254c4f2f1113
4,804
def evaluate_hyperparameters(parameterization): """ Train and evaluate the network to find the best parameters Args: parameterization: The hyperparameters that should be evaluated Returns: float: classification accuracy """ net = Net() net, _, _ = train_bayesian_optimization(net=net,...
28811908e8015cbc95c35368bafd47428b5c31b3
4,805
from bs4 import BeautifulSoup def get_post_type(h_entry, custom_properties=[]): """ Return the type of a h-entry per the Post Type Discovery algorithm. :param h_entry: The h-entry whose type to retrieve. :type h_entry: dict :param custom_properties: The optional custom properties to use for the P...
7d6d8e7bb011a78764985d834d259cb794d00cb9
4,806
def get_start_end(sequence, skiplist=['-','?']): """Return position of first and last character which is not in skiplist. Skiplist defaults to ['-','?']).""" length=len(sequence) if length==0: return None,None end=length-1 while end>=0 and (sequence[end] in skiplist): end-=1 ...
b67e0355516f5aa5d7f7fad380d262cf0509bcdb
4,807
def view_event(request, eventid): """ View an Event. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param eventid: The ObjectId of the event to get details for. :type eventid: str :returns: :class:`django.http.HttpResponse` """ ana...
3b0abfaf2579ef660935d99638d0f44655f5676e
4,808
import matplotlib.pyplot as plt def main(): """Main script.""" (opts, args) = parser.parse_args() if opts.howto: print HOWTO return 1 if not args: print "No sensor expression given." parser.print_usage() return 1 if opts.cm_url in CM_URLS: cm = Ce...
d3872e43262aed4e95f409e99989d156673f9d2f
4,809
def archiveOpen(self, file, path): """ This gets added to the File model to open a path within an archive file. :param file: the file document. :param path: the path within the archive file. :returns: a file-like object that can be used as a context or handle. """ return ArchiveFileHandle(s...
e320299a96785d97d67fd91124fa58862c238213
4,810
def get_masked_bin(args, key: int) -> str: """Given an input, output, and mask type: read the bytes, identify the factory, mask the bytes, write them to disk.""" if args.bin == None or args.mask == None: logger.bad("Please specify -b AND -m (bin file and mask)") return None # get the bytes...
d97806f984a6cad9b42d92bfcf050c1e032c5537
4,811
def count_entries(df, col_name = 'lang'): """Return a dictionary with counts of occurrences as value for each key.""" # Initialize an empty dictionary: cols_count cols_count = {} # Extract column from DataFrame: col col = df[col_name] # Iterate over the column in DataFrame for entry in c...
f933b77c8ff1ae123c887813ca559b410a104290
4,812
def workerfunc(prob, *args, **kwargs): """ Helper function for wrapping class methods to allow for use of the multiprocessing package """ return prob.run_simulation(*args, **kwargs)
620799615b60784e754385fac31e5a7f1db37ed3
4,813
from unittest.mock import patch async def client(hass, hass_ws_client): """Fixture that can interact with the config manager API.""" with patch.object(config, "SECTIONS", ["core"]): assert await async_setup_component(hass, "config", {}) return await hass_ws_client(hass)
c42af4334912c05d2ea3413cb2af2f24f9f1cecf
4,814
def test_curve_plot(curve): """ Tests mpl image of curve. """ fig = curve.plot().get_figure() return fig
033ee4ce5f5fa14c60914c34d54af4c39f6f84b3
4,815
import time import pickle import asyncio async def _app_parser_stats(): """Retrieve / update cached parser stat information. Fields: id: identifier of parser size_doc: approximate size (bytes) per document or null """ parser_cfg = faw_analysis_set_util.lookup_all_parsers( ...
06c363eee075a045e5ea16947253d4fc11e0cd6d
4,816
def update_wishlists(wishlist_id): """ Update a Wishlist This endpoint will update a Wishlist based the body that is posted """ app.logger.info('Request to Update a wishlist with id [%s]', wishlist_id) check_content_type('application/json') wishlist = Wishlist.find(wishlist_id) if not w...
a7f19fa93f733c8419f3caeee2f0c7471282b05b
4,817
def simplifiedview(av_data: dict, filehash: str) -> str: """Builds and returns a simplified string containing basic information about the analysis""" neg_detections = 0 pos_detections = 0 error_detections = 0 for engine in av_data: if av_data[engine]['category'] == 'malicious' or av_data[e...
c6aecf6c12794453dd8809d53f20f6152ac6d5a3
4,818
import time def decompress_hyper(y_strings, y_min_vs, y_max_vs, y_shape, z_strings, z_min_v, z_max_v, z_shape, model, ckpt_dir): """Decompress bitstream to cubes. Input: compressed bitstream. latent representations (y) and hyper prior (z). Output: cubes with shape [batch size, length, width, height, channel(1)]...
3ccd2580c8f2f719e47fc03711f047f78bbf7623
4,819
def GetManualInsn(ea): """ Get manual representation of instruction @param ea: linear address @note: This function returns value set by SetManualInsn earlier. """ return idaapi.get_manual_insn(ea)
d3a292d626ced87d4c3f08171d485aada87cad1d
4,820
from datetime import datetime def feature_time(data: pd.DataFrame) -> pd.DataFrame: """ Time Feature Engineering. """ # print(data) # print(data.info()) day = 24*60*60 year = (365.2425)*day time_stp = data['time'].apply( lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:00") if is...
fd9322837032204e920a438c7a38ebdd2060b060
4,821
from typing import Tuple from typing import List def _transform(mock_file) -> Tuple[List[Page], SaneJson]: """ Prepare the data as sections before calling report """ transformer = Transform(get_mock(mock_file, ret_dict=False)) sane_json = transformer.get_sane_json() pages = transformer.get_pages() ...
01c090f3af95024752b4adb919659ff7c5bc0d0a
4,822
from typing import List from typing import Any from typing import Optional def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str: """ :param rows: 2D array containing object that can be converted to string using `str(obj)`. :param labels: Array containing...
cf175dbf9dd40c7e56b0a449b6bcc4f797f36b20
4,823
import os import gzip def quantify_leakage(align_net_file, train_contigs, valid_contigs, test_contigs, out_dir): """Quanitfy the leakage across sequence sets.""" def split_genome(contigs): genome_contigs = [] for ctg in contigs: while len(genome_contigs) <= ctg.genome: genome_contigs.append...
362f04c97ff2ff15aeea1264e47d3275387b95c2
4,824
def coef_determ(y_sim, y_obs): """ calculate the coefficient of determination :param y_sim: series of simulated values :param y_obs: series of observed values :return: """ assert y_sim.ndim == 1 and y_obs.ndim == 1 and len(y_sim) == len(y_obs) r = np.corrcoef(y_sim, y_obs) r2 = r[0...
ce06c6fffa79d165cf59e98f634725856e44938e
4,825
async def generate_latest_metrics(client): """Generate the latest metrics and transform the body.""" resp = await client.get(prometheus.API_ENDPOINT) assert resp.status == HTTPStatus.OK assert resp.headers["content-type"] == CONTENT_TYPE_TEXT_PLAIN body = await resp.text() body = body.split("\n"...
d86736d8395158f66dc7592eae1d67d3bf06db50
4,826
def simulate(population: int, n: int, timer: int) -> int: """ Recursively simulate population growth of the fish. Args: population (int): Starting population n (int): Number of days to simulate. timer (int): The reset timer of the fish initialised at 6 or 8 depending on ...
e69ce89a586b72cdbdcbc197c234c058d6d959b6
4,827
def normalize_valign(valign, err): """ Split align into (valign_type, valign_amount). Raise exception err if align doesn't match a valid alignment. """ if valign in (TOP, MIDDLE, BOTTOM): return (valign, None) elif (isinstance(valign, tuple) and len(valign) == 2 and valign[0...
e16e3c5cfb0425e3b04e64a6df01dd35407e2fbe
4,828
def svn_auth_open(*args): """ svn_auth_open(svn_auth_baton_t auth_baton, apr_array_header_t providers, apr_pool_t pool) """ return apply(_core.svn_auth_open, args)
1083639e25b612ad47df86b39daedc8ae3dc74e2
4,829
def quote_key(key): """็‰นๆฎŠๅญ—็ฌฆ'/'่ฝฌไน‰ๅค„็† """ return key.replace('/', '%2F')
ce1978ca23ed3c00489c134a35ae8d04370b49dd
4,830
def middle(word): """Returns all but the first and last characters of a string.""" return word[1:-1]
257a159c46633d3c3987437cb3395ea2be7fad70
4,831
def surprise_communities(g_original, initial_membership=None, weights=None, node_sizes=None): """ Surprise_communities is a model where the quality function to optimize is: .. math:: Q = m D(q \\parallel \\langle q \\rangle) where :math:`m` is the number of edges, :math:`q = \\frac{\\sum_c m_c}{m}`,...
7efba73c4948f4f6735f815e32b8700a08fc2d1e
4,832
def advisory_factory(adv_data, adv_format, logger): """Converts json into a list of advisory objects. :param adv_data: A dictionary describing an advisory. :param adv_format: The target format in ('default', 'ios') :param logger: A logger (for now expecting to be ready to log) :returns advisory inst...
737490b4c6c61aeb7fb96515807dffbdc716293d
4,833
import argparse def _validate_int(value, min, max, type): """Validates a constrained integer value. """ try: ivalue = int(value) if min and max: if ivalue < min or ivalue > max: raise ValueError() except ValueError: err = f"{type} index must be an i...
6e85ea9d97a4c906cad410847de6f21eace33afd
4,834
def get_azpl(cdec, cinc, gdec, ginc): """ gets azimuth and pl from specimen dec inc (cdec,cinc) and gdec,ginc (geographic) coordinates """ TOL = 1e-4 Xp = dir2cart([gdec, ginc, 1.]) X = dir2cart([cdec, cinc, 1.]) # find plunge first az, pl, zdif, ang = 0., -90., 1., 360. while zdif...
19b6ec0179223bc453893ffd05fd555f4e6aea76
4,835
def read_embroidery(reader, f, settings=None, pattern=None): """Reads fileobject or filename with reader.""" if reader == None: return None if pattern == None: pattern = EmbPattern() if is_str(f): text_mode = False try: text_mode = reader.READ_FILE_IN_TEXT_MO...
c84407f3f1969f61558dadafef2defda17a0ac0c
4,836
import re from pathlib import Path import json def load_stdlib_public_names(version: str) -> dict[str, frozenset[str]]: """Load stdlib public names data from JSON file""" if not re.fullmatch(r"\d+\.\d+", version): raise ValueError(f"{version} is not a valid version") try: json_file = Pat...
02775d96c8a923fc0380fe6976872a7ed2cf953a
4,837
import psutil import os import itertools import sys import random def deep_q_learning(sess, env, q_estimator, target_estimator, state_processor, num_episodes, experiment_dir, rep...
363bfa7c8996d4a8cbec751240a43018db2f4a58
4,838
def mask_inside_range(cube, minimum, maximum): """ Mask inside a specific threshold range. Takes a MINIMUM and a MAXIMUM value for the range, and masks off anything that's between the two in the cube data. """ cube.data = np.ma.masked_inside(cube.data, minimum, maximum) return cube
b7a1ea1415d6f8e0f6b31372dce88355915bd2e6
4,839
def s3_client() -> client: """ Returns a boto3 s3 client - configured to point at a specfic endpoint url if provided """ if AWS_RESOURCES_ENDPOINT: return client("s3", endpoint_url=AWS_RESOURCES_ENDPOINT) return client("s3")
256c2c52bc65f6899b1c800c2b53b2415ebc0aef
4,840
def tokenize_with_new_mask(orig_text, max_length, tokenizer, orig_labels, orig_re_labels, label_map, re_label_map): """ tokenize a array of raw text and generate corresponding attention labels array and attention masks array """ pad_token_label_id = -100 simple_tokenize_results = [list(tt) for t...
56be66cf1679db07a2f98a4fa576df6118294fa3
4,841
import click def zonal_stats_from_raster(vector, raster, bands=None, all_touched=False, custom=None): """ Compute zonal statistics for each input feature across all bands of an input raster. God help ye who supply large non-block encoded rasters or large polygons... By default min, max, mean, s...
7144a636b2935cc070fd304f1e4e421b68751ad0
4,842
def RMSE(stf_mat, stf_mat_max): """error defined as RMSE""" size = stf_mat.shape err = np.power(np.sum(np.power(stf_mat - stf_mat_max, 2.0))/(size[0]*size[1]), 0.5) return err
b797e07f24f44b1cd3534de24d304d7de818eca8
4,843
def get_read_only_permission_codename(model: str) -> str: """ Create read only permission code name. :param model: model name :type model: str :return: read only permission code name :rtype: str """ return f"{settings.READ_ONLY_ADMIN_PERMISSION_PREFIX}_{model}"
d95e49067df9977aedc7b6420eada77b7206049d
4,844
def hours_to_minutes( hours: str ) -> int: """Converts hours to minutes""" return int(hours)*60
861e8724a2fa752c907e7ead245f0cb370e3fe28
4,845
from matplotlib import pyplot import numpy def core_profiles_summary(ods, time_index=None, fig=None, combine_dens_temps=True, show_thermal_fast_breakdown=True, show_total_density=True, **kw): """ Plot densities and temperature profiles for electrons and all ion species as per `ods['core_profiles']['profil...
d8243bf08f03bf218e2dffa54f34af024ec32c69
4,846
def sir_model(): """ this returns a density dependent population process of an SIR model """ ddpp = rmf.DDPP() ddpp.add_transition([-1, 1, 0], lambda x: x[0]+2*x[0]*x[1]) ddpp.add_transition([0, -1, +1], lambda x: x[1]) ddpp.add_transition([1, 0, -1], lambda x: 3*x[2]**3) return ddpp
b28e92a9cc142573465925e0c1be1bb58f5ad077
4,847
import re def read_cmupd(strip_stress=False, apostrophe="'"): """Read the CMU-Pronunciation Dictionary Parameters ---------- strip_stress : bool Remove stress from pronunciations (default ``False``). apostrophe : str | bool Character to replace apostrophe with in keys (e.g., "COUL...
0cc9ba95eeccf1e49f01a7e77082fd7a6674cd34
4,848
import torch import tqdm import logging import os def validate(loader, model, logger_test, samples_idx_list, evals_dir): """ Evaluate the model on dataset of the loader """ softmax = torch.nn.Softmax(dim=1) model.eval() # put model to evaluation mode confusion_mtrx_df_val_dmg = pd.DataFr...
3bc316f144201030d39655b9b077cbff9070f5f1
4,849
import numpy def my_eval(inputstring, seq, xvalues=None, yvalues=None): """ Evaluate a string as an expression to make a data set. This routine attempts to evaluate a string as an expression. It uses the python "eval" function. To guard against bad inputs, only numpy, math and builtin functions ...
95993e5608e2cd5c8ee0bdedc9fce5f7e6310fc8
4,850
def readlines(filepath): """ read lines from a textfile :param filepath: :return: list[line] """ with open(filepath, 'rt') as f: lines = f.readlines() lines = map(str.strip, lines) lines = [l for l in lines if l] return lines
1aa16c944947be026223b5976000ac38556983c3
4,851
def process_images(): """ TODO """ return downloader(request.args.get('img_url'))
a05f17044dc6f63600055585f37258d26236536d
4,852
import json import os def batch_lambda_handler(event, lambda_context): """Entry point for the batch Lambda function. Args: event: [dict] Invocation event. If 'S3ContinuationToken' is one of the keys, the S3 bucket will be enumerated beginning with that continuation token. lambda_c...
b8c4cd64b00a24e89372363dcba67c4f3b73c814
4,853
import subprocess def get_gpu_memory_map(): """Get the current gpu usage. Returns ------- usage: dict Keys are device ids as integers. Values are memory usage as integers in MB. """ result = subprocess.check_output( [ 'nvidia-smi', '--query-gpu=memory.free'...
64b6d302d5201c5e56dcaf90875b2375b86cbf68
4,854
def n_tuple(n): """Factory for n-tuples.""" def custom_tuple(data): if len(data) != n: raise TypeError( f'{n}-tuple requires exactly {n} items ' f'({len(data)} received).' ) return tuple(data) return custom_tuple
0c5d8f0f277e07f73c4909895c8215427fb5e705
4,855
def novel_normalization(data, base): """Initial data preparation of CLASSIX.""" if base == "norm-mean": # self._mu, self._std = data.mean(axis=0), data.std() _mu = data.mean(axis=0) ndata = data - _mu _scl = ndata.std() ndata = ndata / _scl elif base == "pca": ...
2ab0644687ab3b2cc0daa00f72dcad2bce3c6f73
4,856
def calc_dof(model): """ Calculate degrees of freedom. Parameters ---------- model : Model Model. Returns ------- int DoF. """ p = len(model.vars['observed']) return p * (p + 1) // 2 - len(model.param_vals)
ccff8f5a7624b75141400747ec7444ec55eb492d
4,857
def parse_event_export_xls( file: StrOrBytesPath, parsing_elements: list[str] = _ALL_PARSING_ELEMENTS ) -> ParsedEventResultXlsFile: """Parse a Hytek MeetManager .hy3 file. Args: file (StrOrBytesPath): A path to the file to parse. parsing_elements (Sequence[str]): Elements to extract from t...
7116ffa78d9a4747934fb826cce39035fcf24aa1
4,858
def create_form(request, *args, **kwargs): """ Create a :py:class:`deform.Form` instance for this request. This request method creates a :py:class:`deform.Form` object which (by default) will use the renderer configured in the :py:mod:`h.form` module. """ env = request.registry[ENVIRONMENT_KEY]...
152c82abe40995f214c6be88d1070abffba1df79
4,859
def get_lsl_inlets(streams=None, with_source_ids=('',), with_types=('',), max_chunklen=0): """Return LSL stream inlets for given/discovered LSL streams. If `streams` is not given, will automatically discover all available streams. Args: streams: List of `pylsl.StreamInfo` or...
d18ad5ee2719c451e17742a596989cfd43e4a84d
4,860
def from_dtw2dict(alignment): """Auxiliar function which transform useful information of the dtw function applied in R using rpy2 to python formats. """ dtw_keys = list(alignment.names) bool_traceback = 'index1' in dtw_keys and 'index2' in dtw_keys bool_traceback = bool_traceback and 'stepsTake...
ef2c35ea32084c70f67c6bab462d662fe03c6b89
4,861
def fix_bad_symbols(text): """ HTML formatting of characters """ text = text.replace("รƒยจ", "รจ") text = text.replace("รƒยค", "รค") text = text.replace("รƒย–", "ร„") text = text.replace("รƒย„", "ร„") text = text.replace("รƒยถ", "รถ") text = text.replace("รƒยฉ", "รฉ") text = text.replace("รƒยฅ", "รฅ"...
e128435a9a9d2eb432e68bf9cff9794f9dcd64ba
4,862
def _level2partition(A, j): """Return views into A used by the unblocked algorithms""" # diagonal element d is A[j,j] # we access [j, j:j+1] to get a view instead of a copy. rr = A[j, :j] # row dd = A[j, j:j+1] # scalar on diagonal / \ B = A[j+1:, :j] # Block in corner | ...
16ba7715cc28c69ad35cdf3ce6b542c14d5aa195
4,863
from typing import Optional def _null_or_int(val: Optional[str]) -> Optional[int]: """Nullify unknown elements and convert ints""" if not isinstance(val, str) or is_unknown(val): return None return int(val)
6bd8d9ed350109444988077f4024b084a2189f91
4,864
def stackset_exists(stackset_name, cf_client): """Check if a stack exists or not Args: stackset_name: The stackset name to check cf_client: Boto3 CloudFormation client Returns: True or False depending on whether the stack exists Raises: Any exceptions raised .describe_...
78f6e383a6d4b06f164936edcc3f101e523aee34
4,865
def convert_l_hertz_to_bins(L_p_Hz, Fs=22050, N=1024, H=512): """Convert filter length parameter from Hertz to frequency bins Notebook: C8/C8S1_HPS.ipynb Args: L_p_Hz (float): Filter length (in Hertz) Fs (scalar): Sample rate (Default value = 22050) N (int): Window size (Default va...
b7f7d047565dc08021ccbecbd05912ad11e8910b
4,866
from macrostate import Macrostate def macrostate_to_dnf(macrostate, simplify = True): """ Returns a macrostate in disjunctive normal form (i.e. an OR of ANDs). Note that this may lead to exponential explosion in the number of terms. However it is necessary when creating Multistrand Macrostates, which can only...
b3fa9666f0f79df21744ec08d0ef9a969210f7ae
4,867
def construct_features(all_data): # type: (pd.DataFrame) -> pd.DataFrame """ Create the features for the model :param all_data: combined processed df :return: df with features """ feature_constructor = FeatureConstructor(all_data) return feature_constructor.construct_all_features()
30bf001abdef6e7cdda927d340e640acc902906a
4,868
from typing import Optional import logging def restore_ckpt_from_path(ckpt_path: Text, state: Optional[TrainState] = None): """Load a checkpoint from a path.""" if not gfile.exists(ckpt_path): raise ValueError('Could not find checkpoint: {}'.format(ckpt_path)) logging.info('Restoring checkpoint from %s', c...
297beb0a45c33522c172e59c0a2767b7f2e75ad2
4,869
import logging def _GetChannelData(): """Look up the channel data from omahaproxy.appspot.com. Returns: A string representing the CSV data describing the Chrome channels. None is returned if reading from the omahaproxy URL fails. """ for unused_i in range(_LOOKUP_RETRIES): try: channel_csv ...
6337dc236b310117c8e4f0ec7365c9d37a85a868
4,870
def look(direction=Dir.HERE): """ Looks in a given direction and returns the object found there. """ if direction in Dir: # Issue the command and let the Obj enumeration find out which object is # in the reply # Don't use formatted strings in order to stay compatible to Python 3....
bddae1d8da57cfb4016b96ae4fee72d37da97395
4,871
def process_debug_data(debug_data, model): """Process the raw debug data into pandas objects that make visualization easy. Args: debug_data (dict): Dictionary containing the following entries ( and potentially others which are not modified): - filtered_states (list): List of arrays. Eac...
b305bfa189e089fdb3cffdde9707f35d7a82704e
4,872
from typing import Tuple from typing import Optional import subprocess def check_to_cache(local_object, timeout: float = None) -> Tuple[Optional[bool], Optional[str], Optional[str]]: """ Type-check current commit and save result to cache. Return status, log, and log filename, or None, None, None if a timeout ...
4ab81100746a83653d311706188fbfcdaf667b95
4,873
def merge(a, b, path=None): """Deprecated. merges b into a Moved to siem.utils.merge_dicts. """ if path is None: path = [] for key in b: if key in a: if isinstance(a[key], dict) and isinstance(b[key], dict): merge(a[key], b[key], path + [str(key)]) ...
26b9dc9fc8451dc48b86b3e6fcf5f7870ac0fe7e
4,874
import json import requests def post_attachment(fbid, media_url, file_type, is_reusable=False, messaging_type="RESPONSE", tag=None): """ Sends a media attachment to the specified user :param str fbid: User id to send the audio. :param str media_url: Url of a hosted media. :param s...
fce03f1962038502bef623e227b7a643c2992c44
4,875
def random_categorical(logits, num_samples, seed): """Returns a sample from a categorical distribution. `logits` must be 2D.""" # TODO(siege): Switch to stateless RNG ops. return tf.random.categorical( logits=logits, num_samples=num_samples, seed=seed)
6a7bda20d4ecace2365471a5f312b017efd48b99
4,876
def create_or_update_dns_record(stack, record_name, record_type, record_value, hosted_zone_name, condition_field=""): """Create or Update Route53 Record Resource.""" return stack.stack.add_resource(RecordSetType( '{0}'.format(record_name.replace('.', '').replace('*', 'wildcard')), Condition=cond...
ba0d30dddde17967480a047fdc47242c1deaf4e6
4,877
def med_filt(x, k=201): """Apply a length-k median filter to a 1D array x. Boundaries are extended by repeating endpoints. """ if x.ndim > 1: x = np.squeeze(x) med = np.median(x) assert k % 2 == 1, "Median filter length must be odd." assert x.ndim == 1, "Input must be one-dimensional...
ea9abfd6fd4243b1d959f7b499cdceccd851e53f
4,878
def test_plot_grid(od_cup_anno_bboxes, od_cup_path): """ Test that `plot_grid` works. """ # test callable args def callable_args(): return od_cup_anno_bboxes, od_cup_path plot_grid(display_bboxes, callable_args, rows=1) # test iterable args od_cup_paths = [od_cup_path, od_cup_path, od...
f41b9c54edd120af456195c417c23dbabbf5427b
4,879
import copy def sync_or_create_user(openid_user): """ Checks the user, returned by the authentication-service Requires a user-dict with at least: sub, email, updated_at """ def _validate_user(openid_user): error = False msg = '' if not openid_user.get('sub'): er...
b8fb942900c9fd8c3720f473fb0b88285f91f3aa
4,880
def add_scalar_typesi_coord(cube, value='sea_ice'): """Add scalar coordinate 'typesi' with value of `value`.""" logger.debug("Adding typesi coordinate (%s)", value) typesi_coord = iris.coords.AuxCoord(value, var_name='type', sta...
e303fdc4780a01995a2bbcfeb28dd68f7c4621da
4,881
def related_tags(parser, token): """ Retrieves a list of instances of a given model which are tagged with a given ``Tag`` and stores them in a context variable. Usage:: {% related_tags [objects] as [varname] %} The model is specified in ``[appname].[modelname]`` format. The tag must b...
001b63f40c9f63e814398a3ab0eeb358f694dd97
4,882
from re import T def assess(): """ RESTful CRUD controller """ # Load Models assess_tables() impact_tables() tablename = "%s_%s" % (module, resourcename) table = db[tablename] # Pre-processor def prep(r): if session.s3.mobile and r.method == "create" and r.interactive: ...
7baf776ed295f6ad35272680c140c4283af7e90f
4,883
def local_purity(H, y, nn=None, num_samples=10): """ :param H: embedding to evaluate :param y: ground-truth classes :param nn: number of neighbours to consider, if nn=None evaluate for nn=[1...size of max cluster] :param num_samples: number of samples in the range (1, size of max cluster) """ ...
afbe924bb8516ba6f9172534f57df58689768547
4,884
import re def flatten_sxpr(sxpr: str, threshold: int = -1) -> str: """ Returns S-expression ``sxpr`` as a one-liner without unnecessary whitespace. The ``threshold`` value is a maximum number of characters allowed in the flattened expression. If this number is exceeded the the unflattened S-e...
9109894ca1eeb2055ca48bc8634e6382f9e5557f
4,885
import re def glycan_to_graph(glycan, libr = None): """the monumental function for converting glycans into graphs\n | Arguments: | :- | glycan (string): IUPAC-condensed glycan sequence (string) | libr (list): sorted list of unique glycoletters observed in the glycans of our dataset\n | Returns: | :- |...
b709cd064cc97159e7bf19b90c3dab2016fbc786
4,886
def run(ex: "interactivity.Execution") -> "interactivity.Execution": """Exit the shell.""" ex.shell.shutdown = True return ex.finalize( status="EXIT", message="Shutting down the shell.", echo=True, )
7ab7bbe8b1c276c1b84963c3a8eb9a1bdb79888c
4,887
def get_features(df, row = False): """ Transform the df into a df with basic features and dropna""" df_feat = df df_feat['spread'] = df_feat['high'] - df_feat['low'] df_feat['upper_shadow'] = upper_shadow(df_feat) df_feat['lower_shadow'] = lower_shadow(df_feat) df_feat['close-open'] = df_feat['c...
42e9c54a3357634cc74878909f2f8a33cfc6ee0c
4,888
import torch def match_prob_for_sto_embed(sto_embed_word, sto_embed_vis): """ Compute match probability for two stochastic embeddings :param sto_embed_word: (batch_size, num_words, hidden_dim * 2) :param sto_embed_vis: (batch_size, num_words, hidden_dim * 2) :return (batch_size, num_words) """...
0668f4bc6e3112cd63d33fcb5612368604724359
4,889
import functools def POST(path): """ Define decorator @post('/path'): """ def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): return func(*args, **kw) wrapper.__method__ = 'POST' wrapper.__route__ = path return wrapper retu...
d2c76d57687dc0983d2f00995c7a6e6414e8201b
4,890
def BatchNorm( inputs, axis=-1, momentum=0.9, eps=1e-5, use_stats=-1, **kwargs): """Batch Normalization. `[Ioffe & Szegedy, 2015] <https://arxiv.org/abs/1502.03167>`_. We enforce the number of inputs should be *5*, i.e., it is implemented into a fused version. However, you can still fix th...
642e8ee5cafdf6a416febaff1ddcae5190e27cb1
4,891
def problem_from_graph(graph): """ Create a problem from the given interaction graph. For each interaction (i,j), 0 <= i <= j <= 1 is added. """ n = graph.vcount() domain = Domain.make([], [f"x{i}" for i in range(n)], real_bounds=(0, 1)) X = domain.get_symbols() support = smt.And(*((X[e.source] <= X...
973602abf8a20ffe45a5bcae6ec300ba749ab6d9
4,892
def rotate_points(x, y, x0, y0, phi): """ Rotate x and y around designated center (x0, y0). Args: x: x-values of point or array of points to be rotated y: y-values of point or array of points to be rotated x0: horizontal center of rotation y0: vertical center of rotation ...
8058385185e937d13e2fd17403b7653f3a5f55e7
4,893
from typing import List def xpme( dates: List[date], cashflows: List[float], prices: List[float], pme_prices: List[float], ) -> float: """Calculate PME for unevenly spaced / scheduled cashflows and return the PME IRR only. """ return verbose_xpme(dates, cashflows, prices, pme_prices)[0...
4301e1e95ab4eee56a3644b132a400522a5ab173
4,894
def get_node(uuid): """Get node from cache by it's UUID. :param uuid: node UUID. :returns: structure NodeInfo. """ row = _db().execute('select * from nodes where uuid=?', (uuid,)).fetchone() if row is None: raise utils.Error('Could not find node %s in cache' % uuid, code=404) return...
87988d0c0baa665f1fcd86991253f8fe0cba96a1
4,895
def bisect_jump_time(tween, value, b, c, d): """ **** Not working yet return t for given value using bisect does not work for whacky curves """ max_iter = 20 resolution = 0.01 iter = 1 lower = 0 upper = d while iter < max_iter: t = (upper - lower) / 2 if twee...
f7e1dbeb000ef60a5bd79567dc88d66be9235a75
4,896
def __session_kill(): """ unset session on the browser Returns: a 200 HTTP response with set-cookie to "expired" to unset the cookie on the browser """ res = make_response(jsonify(__structure(status="ok", msg=messages(__language(), 166)))) res.set_cookie("key", value="expired") retu...
9313e46e2dcd297444efe08c6f24cb4150349fdb
4,897
def register_errorhandlers(app): """Register error handlers.""" def render_error(error): """Render error template.""" # If a HTTPException, pull the `code` attribute; default to 500 error_code = getattr(error, "code", 500) return render_template(f"errors/{error_code}.html"), err...
e8e3ddf10fb6c7a370c252c315888c91b26f6503
4,898
def register(key): """Register callable object to global registry. This is primarily used to wrap classes and functions into the bcdp pipeline. It is also the primary means for which to customize bcdp for your own usecases when overriding core functionality is required. Parameters ---------- ...
4f3d7d9e8b49d448d338408de8ceebee58136893
4,899