content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import warnings def derivest(fun, x, par = None, **kwargs): """ Estimate the derivative of a function of one variable. Arguments: fun : Callable object with signature fun(x, *args) -> float, with x the (scalar) argument, and args an optional list of parameters. ...
7a66b5499ccb5e72125a2b323929c2196d747c48
56,979
def norm(vec): """ Calculate norm of a vector or list thereof Args: vec (Vector or List[Vector]): vector(s) to compute norm of Returns: Scalar or List[Scalar]: norms """ if len(vec.shape) == 1: # it's just a single column vector return np.sqrt(vec.dot(vec)) else: # tr...
c225467905ccd30b826d8ef5e0112bb23f106ec9
56,980
import PIL def get_image_size(img_filename,img_directory_path): """ Return the size of the specified image img_filename : the name of the image file img_directory_path : the path to the directory where the image is Return : (width, height) width : the width in pixel of the image height : t...
b46934940f1c62f9110efa219e042a39026db76c
56,981
import torch def train_deep_encoder(torch_dataset, model, optimizer, criterion, lr, n_epochs, batchsize, verbose=False): """Train label encoder for categorical features Parameters ---------- torch_dataset : Torch_Dataset Dataset to feed the NN containing categorical fea...
c89aa6be474233d7521361190f7fdfc0b1cc29a3
56,982
def convert(s): """ Convert a probability string to a float number. :param s: probability string. :return: a float probability. """ try: return float(s) except ValueError: num, denom = s.split('/') return float(num) / float(denom)
84333f21edfdcb2f3c917f23c23b9d399c5f6e56
56,983
def tree_ones_like(tree: Pytree) -> Pytree: """ Return a new tree with the same structure as t, but with all values set to 1. """ return jax.tree_util.tree_map(lambda x: jnp.ones_like(x), tree)
3fa06e05111741eda6a5af8f558e2e6dce29755e
56,984
def writeOctetStream(oStr, minValue = 0): """ @summary: write string as octet stream with per header @param oStr: octet stream to convert @param minValue: min length value @return: per header follow by tuple of UInt8 """ length = len(oStr) mlength = minValue if length - minValue...
0eeb4578f51b4488e762d3f49b1d5c5accdd5b4d
56,985
from typing import Sequence def _find_fuzzy_line( py_line_no: int, py_by_line_no: Sequence[str], cheetah_by_line_no: Sequence[str], prefer_first: bool, ) -> int: """Attempt to fuzzily find matching lines.""" stripped_line = _fuzz_py_line(py_by_line_no[py_line_no]) cheetah_l...
07e088df7ca73d52d47d37ff0971c43c496bc68a
56,986
def S_vib(r,r0,B0,M,grun,T): """Vibrational entropy.""" x = debye_temp(r,r0,B0,M,grun) / T return 3*kb*(4.0/3*debye_func(x) - np.log(1-np.exp(-x)))
4fbbde4a33219947d523e2ab3d190a441a77333d
56,988
def countExtn(fimg, extname='SCI'): """ Return the number of 'extname' extensions, defaulting to counting the number of SCI extensions. """ closefits = False if isinstance(fimg, string_types): fimg = fits.open(fimg) closefits = True n = 0 for e in fimg: if 'extn...
44051dcef1bef901d4905d7b4b805dc9140a32c0
56,989
def tensor(dimensions): """ Create a tensor :param dimensions: The list of dimensions :return: A tensor """ global csp check_engine() csp.variables.append(csp.int(size=None, deep=dimensions)) return csp.variables[-1]
e96338ed9df016bb425642f4fd05de4775aa2d92
56,990
import random def makeData(test=False): """ Make the data and return a dict that contains the data and goal.""" # open the files, I already made them smaller; they contain 3000 pics each Ball = np.load("../data/sBasketball.npy") LightBulb = np.load("../data/sLight_bulb.npy") Sun = np.load("../dat...
427fca4cb41b776f4281dadda2971930214a2864
56,991
from typing import Union from pathlib import Path import re def model_from_checkpoint( filename: Union[Path, str], model_name=None, backbone_name=None, classes=None, is_coco=False, img_size=None, map_location=None, strict=False, revise_keys=[ (r"^module\.", ""), ], ...
4296da4efc9499a8d10d09a5c0a2329bbc8cb54d
56,992
def get_problem(pid=None, name=None, tid=None, show_disabled=True): """ Gets a single problem. Args: pid: The problem id name: The name of the problem show_disabled: Boolean indicating whether or not to show disabled problems. Defaults to True Returns: The problem dictio...
5e781b867bd4ebc26d451e522262a954dd2ea27c
56,993
def mock_boto_client_upload_success(*args, **kwargs): """ Mock boto client, so uploading always returns success """ return MagicMock()
3fec23fa670a9066ae9fc881d0cf1d874f9cf480
56,994
def git_log_file(file_name): """要求文件路径是相对于git仓库更目录到文件完整路径""" cmd = "git log -1 %s |grep Date" % file_name return cmd
e7d0481d4ee7e1a68492df07ed9c35e95a87ab5c
56,995
import json def sfjson_loads(s): """Exception safe json.loads()""" try: return rlk_jsonloads(s) except json.decoder.JSONDecodeError: return {}
cbc7bc01d895cc0cce46b9c8d865eeee31442e3d
56,996
import math def calc_tols(polys_truth, tick_dist=5, max_d=250, rel_tol=0.25): """ Calculate tolerance values for every GT baseline according to https://arxiv.org/pdf/1705.03311.pdf. :param polys_truth: groundtruth baseline polygons (normalized) :param tick_dist: desired distance of points of the baseline...
c26cecf5a8bdd2fbca85aa1d3bc6fce4593869e2
56,997
def to_terminal(group: list, outcomes: list) -> float: """ Create a terminal node value :param group: group of samples with target as last element :return: most representative class value for group """ outcomes = [row[-1] for row in group] return [max(set(outcomes), key=outcomes.count), outc...
886c397aaef82d1e38c371436c69b4152f6ce760
56,998
def _log_multivariate_normal_density_spherical(X, means, covars): """Compute Gaussian log-density at X for a spherical model.""" cv = covars.copy() if covars.ndim == 1: cv = cv[:, np.newaxis] if cv.shape[1] == 1: cv = np.tile(cv, (1, X.shape[-1])) return _log_multivariate_normal_dens...
f74f18c76103bed534c1d98c4931dab9a2f12a72
56,999
from typing import Union from pathlib import Path from typing import Any def load_from_cache(filepath: Union[Path, str]) -> Any: """Load a Python object pickled in a file located at `filepath`. This function will raise a `FileNotFoundError` if the cache file doesn't exist. It is the responsibility of the...
79155d66afb6915bc8bbe4aeae0529615bb961e7
57,001
from typing import Coroutine def _coro_get_awaitable_iter(o): """Interal helper function to get an awaitable iterator. Corresponding impl.: https://github.com/python/cpython/blob/3.5/Objects/genobject.c#L783-L823 """ if isinstance(o, (Coroutine, CoroWrapper)) or gen_is_iterable_coroutine(o): ...
d47e3d1df45beb6ea2622ee90bdcbcebdc17e48b
57,002
def kronecker_prod(x, y): """Returns the tensor / Kronecker product of 2 complex matrices, x and y. :param x: A complex matrix. :type x: torch.Tensor :param y: A complex matrix. :type y: torch.Tensor :raises ValueError: If x and y do not have 3 dimensions or their first ...
1b968d0eb9132419a476b0631f8be7184999b2d7
57,003
def _instance_data(data): """Returns input data with correct shape. For any one-element array, i.e. array of shape (1, ) or (1, 1) returns the single object inside it as a built-in type. Parameters ---------- data : array_like or scalar or NotImplemented Data to be converted. Could be...
2bad0dae958f69a2221e4f11b7a0a3c1f4abb114
57,004
def get_koji_build_info_url_from_flask(id_: int = None,) -> str: """ provide absolute URL to p-s koji build logs view meant to set in a commit status """ with application.app_context(): return url_for( "builds.koji_build_info", id_=id_, _external=True, # _ext...
578e07300a47d73984a6cbce95b45b2ba26bf0b6
57,005
def remove_well_known_protos(filenames): """Remove "well-known" protos for objc. On those platforms we get these for free as a part of the protobuf runtime. We only need them for nanopb. Args: filenames: A list of filenames, each naming a .proto file. Returns: The filenames with members of google/p...
9aa14b70e9251fe4d8ff42277be969d23f3ecdba
57,006
def count_cigar_ops(cigar): """ For curious people: regexes are very slow for parsing CIGAR strings. cigar: Unicode """ b = 0 num_m, num_i, num_d = 0, 0, 0 for i in range(len(cigar)): if cigar[i] <= '9': continue # Check if there are no digits before the op char....
7efacce3a9b13249718ae140e79a5800b8682ff5
57,007
def get_dwtype_floor_area(dwtype_floorarea_by, dwtype_floorarea_ey, sim_param): """Calculates the floor area per dwelling type for every year Parameters ---------- dwtype_distr_by : dict Distribution of dwelling types base year assump_dwtype_distr_ey : dict Distribution of dwelling ...
3b87386bbf5bf051aec5d43ebd47f3359885c8b4
57,008
def generate_field_shift(mask_image, vector_shift=(10, 10, 10), gaussian_smooth=5): """ Shifts (moves) a structure defined using a binary mask. Args: mask_image ([SimpleITK.Image]): The binary mask to shift. vector_shift (tuple, optional): The displacement vector applied to the entire binar...
1082bd23455d138ee69f3c2663d61cd346e1d917
57,009
def Credible_Set(position, pos_prob, threshold): """Function that finds the credible set according to a set threshold""" total = sum(pos_prob) bounds = threshold*total #make into tuples tuple_vec = [] for i in range(0, len(position)): tup = (position[i], pos_prob[i]) tuple_vec.ap...
01a587c0e7e6de995fd77c85f30011784018c383
57,010
def apply_size_filter(segmentation, input_, size_filter, exclude=None): """ Apply size filter to segmentation. Arguments: segmentation [np.ndarray] - input segmentation. input_ [np.ndarray] - input height map. size_filter [int] - minimal segment size. exclude [list] - list of se...
8a5ee3f88c609cad09a5d179c24dfb0f77f7034e
57,011
def load_Sentinel1(site, StartDate, EndDate): """ Function to retrieve and filter Sentinel-1 images args: aoi: region of interest StartDate: Starting date to filter data EndDate: End date to filter data returns: Image collection of Sentinel-1 images """ filtere...
4887a2aabdfee9c689b774fef323a783ac50cd58
57,012
import logging def recover_lost_connection(connection:obd.OBD, fast:bool, timeout:float)->obd.OBD: """ Recover lost connection and return a new working connection handle. """ logging.info("recovering lost connection") connection.close() sleep(CONNECTION_WAIT_DELAY) connection = get_obd_con...
f68968193c80be49142e05de8aae02e3fc3e144e
57,013
def get_ps_aux(connection_obj, search_string, device="dut"): """ API to get the ps aux output Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) :param conn_obj: :param search_string: :param device: :return: """ command = "sudo ps aux" if search_string: command ...
d9f359f607a3b9f83fd8300874008ce35be2d750
57,014
def estimate_power(sim, test, auto=False): """Compute the mean of the estimated power of 5 replications over sample sizes.""" if test == "MaxMargin": test = ["MaxMargin", "Dcorr"] dim_range = find_dim_range(find_dim(sim)) est_power = np.array( [ np.mean( [ ...
67550a596285cff028712f9558ba8ec6e699a892
57,015
from pathlib import Path import re def listdir_with_only(path, names=None, ext=None): """Lists items in the directory conforming name regexes or extensions.""" dir_ = Path(path) if not dir_.is_dir(): raise ValueError('path must be a directory.') names = names if names else [] ext = ext if ...
66aab005255f1a52c88577df02c53c2ab020469f
57,016
def look_and_say(n): """Returns the nth term of the "look and say" sequence, which is defined as follows: beginning with the term 1, each subsequent term visually describes the digits appearing in the previous term. The first few terms are as follows: 1 11 21 1211 111221 Ex: the fo...
5cb341d0bce8bc363b2b734e9da66a07b7da2434
57,017
def compound_alternative_forms(forms, sec_pos, forms_ind_or_con, forms_imp): """ compuond all alternative forms into a set :return: """ if not forms: if forms_imp: forms = {sec_pos: forms_ind_or_con, 'imp': forms_imp} else: forms = {sec_pos: forms_ind_or_con} ...
9b81aea6ef9edbe71560d2ca1d001a3971928c00
57,018
def hasher_unsigned(first_last_name: str, mask, init: int=HASH_INIT) -> int: """The hash function to hash the combined first + last name into a check value""" h = init for c in first_last_name: h = (h * HASH_PRIME + ord(c)) & mask return h
e0b4133762ad7fb41c3aac89bcfe3849ffcfb4f2
57,019
async def get_weakness_chart(type_name: str, generation: int = APP_DEFAULT_GEN): """This path returns the weaknesses of pokemon with type {type_name}.""" if not is_valid_type(type_name.capitalize(), generation=generation): return {"error": "%s is not a valid type for generation %s" % (type_name, generat...
2637488f22ca353427d5febbd60058041ef4132f
57,020
def difficulty_rank(sentence: Text) -> int: """Calculates 'sentence' difficulty level. Returns Integer.""" chars = len(sentence) words = len(word_tokenize(sentence)) return words + (chars//5)
2b072b1518d850c2aa88198e20d331459753e278
57,021
def read_list(filename): """ Read a list from a JSON file. :param filename: file name (string). :return: list. """ _list = [] # open output file for reading try: with open(filename, 'r') as filehandle: _list = load(filehandle) except IOError as e: logge...
f798234633e84a2082a0394e5480b2b355edc57c
57,022
def _preprocess_hash(hash_str: str) -> SanitizedObservable: """Ensure Hash has minimum entropy (rather than a string of 'x').""" str_entropy = entropy(hash_str) if str_entropy < 3.0: return SanitizedObservable(None, "String has too low an entropy to be a hash") return SanitizedObservable(hash_st...
efe932c6df9b6e2ab566ba2029bf75bc7b6c6233
57,023
from typing import Union def make_wordcloud(data: Union[dict, list, object, str, tuple], opts: dict = None, round: int = None ): """Make a word cloud. Accepts data from a string, list of lists or tuples, a dict with terms as keys and counts/frequenc...
0a9b1b9dfe5311ae7a4edd0b909526cd0d4d9e13
57,025
def deleteDuplicates2(self, head: ListNode) -> ListNode: """ recursive :param self: :param head: :return: """ if not head: return head if head.next and head.val == head.next.val: while head.next and head.val == head.next.val: head = head.next return s...
185c15ebe61dba769d8ef04aa1f5a28603b807d1
57,026
import random def generate(length: int = 1) -> str: """Generates a random string of alphanumeric characters of the given length. If no length is specified, a single character is returned. On Python 3.5, this string is pseudo-randomly generated using :py:mod:`random`. With 3.6 and later, the randomnes...
b04f0e448e4308601741121dd2892f990fe6ee64
57,027
def get_balance(user): """ Get UND Balance for a user \b :param user: The EOS user account name. """ cleos = get_cleos() ret = cleos.run(['get', 'currency', 'balance', 'unif.token', user, 'UND']) stripped = ret.stdout.strip() if len(stripped) > 0: my_balance = stripped ...
8a2d2d863139ddbbe2ea61b8cc32a7f2ad282fa5
57,028
import requests import json def get_recommended_fees(): """Retrieves current recommended fastest fees from bitcoinfees API in satoshis """ uri = 'https://bitcoinfees.earn.com/api/v1/fees/recommended' response = requests.get(uri) if response.status_code == 200: fees = json.loads(response...
1311f6de617caf1755c1588378d106b252f24c4e
57,029
from typing import Tuple import numpy def clip_solution( x: ndarray, g: ndarray, H: ndarray, constraints: Tuple[ndarray, ndarray, ndarray, ndarray], delta: float, ) -> Tuple[ndarray, bool, int]: """ x: S个N-dim的列向量 先 assert 它们都是单位向量 - 根据a = argmin f(a): a * gx + a^2 * 0.5xHx获得缩放尺度 ...
6444b5d7d913796b0c7a008a23a4e93210b2c6cd
57,030
def property_node_uriref(property_name): """ Create a Survol property node. """ return rdflib.URIRef(LDT[property_name])
9994639f3883bfa8ccf97c15bfee6e2e7839f8d1
57,031
from typing import Tuple from typing import Optional from datetime import datetime def try_to_format_date(might_be_date: str, date_format: str) -> Tuple[bool, Optional[date]]: """ return a datetime object is parsed """ try: d = datetime.strptime(might_be_date, date_format) return True, d except ValueError: ...
0bfa9be5d4b3a542f80682a53b9bd63d8efbeb51
57,032
def get_text_ls(filename): """Returns text of file as a list of strings""" with open(filename, 'r') as f_in: return f_in.readlines()
5b788f38e683c82648224b7cc1b5875a0f602dce
57,033
def rebuild_command(args): """Rebuilds a unicode command string prepared to be stored in a file """ return "%s\n" % (" ".join(args)).replace("\\", "\\\\")
38643f1e2c7414683a4b2d89c517aa8c432bb9a3
57,034
import string import secrets def generate_secure_random_string(stringLength=10): """Generate a secure random string of letters, digits and special characters """ password_characters = string.ascii_letters + string.digits + string.punctuation return ''.join(secrets.choice(password_characters) for i in rang...
66a0d5863f1955b036e95479bbde40c6ee031437
57,035
def get_title(soup): """Given a soup, pick out a title""" if soup.title: return soup.title.string if soup.h1: return soup.h1.string return ''
bcec80e0c6e5163ed90a4975b81a5c5a3d418132
57,036
def locate_peaks(data,sorted=False): """<numpy array> return all (index,value) pairs of the spectral peaks in the given data, with the option of being sorted in descending order of data value""" indices = filter(lambda j: data[j]>=max([data[j-1],data[j+1]]),range(1,len(data)-1)) result = zip(in...
9f6e09e96d4490fc9e848e833f531883b844f41c
57,037
def get_quality(all_qualities, pref=0, *args): """Gets the best, middle or lowest quality from the Quality types given. Args: all_quality: iterable having all qualities from best to lowest *args: qualities to sort pref: (0,1,2) int ...
94d0aeb3d15f07e860d8779df0d181607ad2b38e
57,038
def blur(rgb: np.ndarray, sigma: float) -> np.ndarray: """ぼかし。sigmaは0~1程度がよい?""" rgb = cv2.GaussianBlur(rgb, (5, 5), sigma) if rgb.ndim == 2: rgb = np.expand_dims(rgb, axis=-1) return rgb
a836903535a47e916590ba0685eb4158301ec962
57,039
import numpy import pandas def bin_library_quantification(quantification, quantification_name, bins=None): """Bin a library quantification file default bins are [0.1, 1, 2, 5, 10, 50, 500, 5000, 1e9] """ if bins is None: bins = DEFAULT_BINS histogram = {} for col in quantification: ...
3f6923284a3e1ac771c82f35567536839548ddc2
57,040
def add_motif(genome, motif, index): """ Replace from the index to index+len(motif) in the genome with the motif selected """ try: # If this can be done is because index is an integer index = index-len(motif) return genome[:index]+motif+genome[index+len(motif):] except: ...
b4fa3f957fc440a837a0f65fd431f1fc9119f077
57,041
from datetime import datetime def get_yearly_mb_temp_prcp(gdir, time_range=None, year_range=None): """Read climate file and compute mass balance relevant climate parameters. Those are the positive melting temperature at glacier terminus elevation as energy input and the amount of solid precipitation onto ...
e4889eb7dcf629d700402135ce9c56bde60990c6
57,042
def get_nsx_resource_binding(client, name, id): """ :param client: nsx resource client :param name: name of neutron object :param id: id of neutron object :return: return the nsx resource id """ nsx_name = utils.get_name_and_uuid(name, id) nsx_resource = client.find_by_display_name(nsx_n...
34d680fb2f54352ff10acdc9a04f833ab1ec09a9
57,043
def latest(name, minor_only=True, region=None, keyid=None, key=None, profile=None): """ Ensures the Elasticsearch domain specifies runs on the latest compatible version of elasticsearch, upgrading it if it is not. Note that this operation is blocking until the upgrade is complete. :param str name:...
5e7ac23220d92cf8c638bdd4ff89cca014059fec
57,045
def annotate(query_text: str): """ annotate plain text with links to wikipedia pages """ plain_text = unquote(query_text) response = model.annotate(plain_text) return { "request": query_text, "response": response }
f1862d697267075edff64dcea5cf196cc187a8c5
57,046
def collect_mysqldump_options(config, mysqldump, client): """Do intelligent collection of mysqldump options from the config and add any additional options for further validation""" options = [] if config['flush-logs']: options.append('--flush-logs') if config['flush-privileges']: if ...
c1e1b45bf62b6b7c5c8701bb78cc198cde4c2a16
57,047
from .model import Model from .detail.model_implementation import ( force_offset_model, offset_model_jac, offset_model_derivative, offset_equation, offset_equation_tex, ) def force_offset(name): """Offset on the the model output. Parameters ---------- name ...
127aa452877e12d95850d98bbcc8416c15e2df10
57,048
def parse_user_agents(text): """.""" user_agents = ioc_grammars.user_agent.searchString(text) return _listify(user_agents)
dede1b1b5ce99e663efc891466683e7ac13af9eb
57,051
def featurizeDoc(doc): """ get key : value of metadata """ doc_features = [] for key in doc: doc_features.append("{0}: {1}".format(key, doc[key])) return doc_features
7204fe1ded828112e69c120c944a5a16cc00f628
57,052
def get_lsr_pwaves(p_idx, lsr, post_stim=0.1, sr=1000., lat_th=0): """ Get indices of laser-triggered P-waves, spontaneous P-waves, successful laser pulses, and failed laser pulses @Params p_idx - indices of P-waves lsr - laser stimulation vector post_stim - P-waves within $post_stim s of la...
5e27bc106d649d4924e9ff5e2a6894ebb995f39d
57,053
def get_flux(shot, time, phis=[222.5*deg2rad], labels=['TS']): """ """ flux_grids = {} flux = {} for label,phi in zip(labels,phis): flux_grids[label] = get_flux_grid(shot, time, phi=phi) # Build the interpolation functions for label in labels: sample_coords = list(zi...
ef2d2d78f76ae3c0a61336b3b3ab038eb0fa204d
57,054
def log_sum_exp(Z): """ Compute log(\sum_i exp(Z_i)) for some array Z.""" return np.max(Z) + np.log(np.sum(np.exp(Z - np.max(Z))))
808329e0cfe14e124433cb0ad48eb4e4f78ebe14
57,055
def f(f_prob): """Deterministic forecast matching observation o.""" return f_prob.isel(member=0, drop=True)
4163e9a40916bd6c1dbf00e6ed635cf2b78bcfc7
57,056
def setup(the_model, rolling_length, rolling_radius, vertical_load, cycles=[1], speed=1.0, slip=0.0, rail_ext=0.0, num_cycles=1, initial_depression=0.1, inbetween_step_time=1.e-6, inbetween_max_incr=100, max_incr=1000, min_incr=100): """Setup the loading for the rollover simulation ...
b76efc23a43986fed7032ede6c707227d6de267c
57,057
def wait_for_handshake(sim, ifname, basename="s_axi_control_", dataname="DATA"): """Wait for handshake (READY and VALID high at the same time) on given interface on PyVerilator sim object. Arguments: - sim : PyVerilator sim object - ifname : name for decoupled interface to wait for handshake on ...
41f35cf15751fab44bca275cc2381e83e8908cd1
57,058
def mysin(x): """ My sine. Note that this is only accurate for small x. """ return x
9589b1a3106b13ff230e614dcfc1477b422c9879
57,060
import logging def get_module_logger(module_name, level=None): """ Get a logger for a specific module. :param module_name: str Logic module name. :param level: int :param sh_level: int Stream handler log level. :param log_format: str :return: Logger Logger object. ...
0fd2c8be1463da464700964c2d5ad895a40f4a9c
57,061
from typing import Optional def get_transit_gateway_multicast_group_source(group_ip_address: Optional[str] = None, network_interface_id: Optional[str] = None, transit_gateway_multicast_domain_id: Optional[str] = None, ...
a834db7d20610870ae7c64d0bae139ed262f9341
57,062
import glob def getAllOfAFile(file_dir, ext): """ Returns a list of all the files the direcotry with the specified file extenstion :param file_dir: Directory to search :param ext: The file extension (IE: ".py") """ return glob.glob(file_dir+"/*"+ext)
876a4f4b30653bd08454db9ee425d56fe408623d
57,063
def support_jsonp(f): """Wraps JSONified output for JSONP""" @wraps(f) def decorated_function(*args, **kwargs): print('s') callback = request.args.get('callback', False) if callback: content = str(callback) + '(' + str(f().data) + ')' return current_app.respon...
0ccfed2ef7702a0d364376e84b1eb3bd1c917d68
57,064
def topk(x_in, weights, num_top_k, verbose=False): """ x_in: BNK4 weights: BNK num_top_k: int """ # rate num_kp = tf.shape(weights)[2] # num_top_divider = config.num_top_divider # num_top_k = tf.to_int32(num_kp / num_top_divider) B = tf.shape(weights)[0] num_pairs = tf.shape(...
d90bedffb6d5b406ff0406eb0d367dab1760858a
57,065
def accumulate_strings(values, name="strings"): """Accumulates strings into a vector. Args: values: A 1-d string tensor that contains values to add to the accumulator. Returns: A tuple (value_tensor, update_op). """ tf.assert_type(values, tf.string) strings = tf.Variable( name=name, in...
2b59fe76c6c74d378db2ebe3521c72c3ab3cbc2a
57,066
from typing import List import tqdm def sliding_convert_examples_to_features( examples: List[InputExample], label_list: List[str], max_length: int, tokenizer: PreTrainedTokenizer, ) -> List[InputFeatures]: """ Loads a data file into a list of `InputFeatures` """ label_map = {label: i ...
50d2cf1f7aa94801aa91d3c39226a7b230bbdf7d
57,068
def http_date(epoch_seconds=None): """ Format the time to match the RFC1123 date format as specified by HTTP RFC7231 section 7.1.1.1. `epoch_seconds` is a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, it defaults to t...
91f6fb9cd8ca69959669661d2a4ffe2c2d1fbfa2
57,069
def rms_error(observed_values, estimated_values): """Root-mean-squared Error function.""" N_values = np.prod(observed_values.shape) sse = ss_error(observed_values, estimated_values) rmse = sse_to_rmse(sse, N_values) return rmse
7899752378a38796fcc7974c3ff5728dd3a8744d
57,070
def parse(data, raw=False, quiet=False): """ Main text parsing function Parameters: data: (string) text data to parse raw: (boolean) unprocessed output if True quiet: (boolean) suppress warning messages if True Returns: List of Dictionaries. Raw ...
cac4424857335484e9ef9258d6742e487d5d40d0
57,071
def convert_onnx_sub(operator, device=None, extra_config={}): """ Converter for `ai.onnx.Sub`. Args: operator: An operator wrapping a `ai.onnx.Sub` model device: String defining the type of device the converted operator should be run on extra_config: Extra configuration used to sele...
4cfb98714ec23e1ea3e70be1bdede0fb805afd63
57,072
def infer_tree_dp(model: PairWiseFiniteModel, subtree_mp=False) -> InferenceResult: """Inference using DP on tree. Performs dynamic programming on tree. Applicable only if the interaction graph is a tree or a forest. Otherwise throws exception. :param model: Model for which to p...
e5cd16e5229846c2e038d47885fd5b6c477f20f6
57,073
from typing import Union import platform def get_platform_ca_certs() -> Union[bool, str]: """Get correct platform value for 'verify' parameter specifying CA certificates for TLS @return: (bool or str) True for Windows, LINUX_CA_FILE for Linux""" if platform.system() == 'Windows': return True ...
396edecf3e78c9e1171e4e08fc2cb1410e562f49
57,074
def set_weight_decay(model, weight_decay, skip_list={"decoder.attention.v", "rnn", "lstm", "gru", "embedding"}): """ Skip biases, BatchNorm parameters, rnns. and attention projection layer v """ decay = [] no_decay = [] for name, param in model.named_parameters(): if not param.requir...
7e2702d544497b03fffda4558f4aa5fcd2dd4f43
57,076
def extract_sample_info(sample_str): """Extract kit, sample, and technical replicate from sample_str. Inputs - sample_str - string from sample name Returns - tuple (kit, biological sample name, technical replicate) """ s = sample_str.replace('Ftube', '') # The biological sample...
f67440528391e1c463bb940cad9e59e8e61aa4c3
57,077
def OffsetPosition(in_ra,in_dec,delta_ra,delta_dec): """ Offset a position given in decimal degrees. Parameters ---------- in_ra: float Initial RA (decimal degrees). in_dec: float Initial DEC (demical degrees). delta_ra: float Offset in RA (decimal degrees). ...
7b027a2e0bf87dba9d1136e68af258b21223cedb
57,078
def input_checks(catalogue, config, completeness): """ Performs a basic set of input checks on the data """ if isinstance(completeness, np.ndarray): # completeness table is a numpy array (i.e. [year, magnitude]) if np.shape(completeness)[1] != 2: raise ValueError('Completeness T...
4fb5e2a3241a2953ae2432add64dc69c1c2af4f6
57,079
def mad_outliers(x, cutoff=2, z_score_coeff=0.6745): """ Median Absolute Deviation outliers method. It returns values as outliers if their residuals relative to the median exceeds 'n' times the ratio to the MAD. The cutoff parameter represents this 'n' times quantity. Main code: x_mad = np...
0718a71d2fcde75356f016df4c56621534b379a7
57,080
def function_executor(type=None, mode=None, config=None, backend=None, storage=None, runtime=None, runtime_memory=None, workers=None, rabbitmq_monitor=None, remote_invoker=None, log_level=None): """ Generic function executor """ return FunctionExecutor( ...
3b0fe732f0c87b13da44bae460d486608b685694
57,081
def create_mssql_adapter_with_integrated_security( server: str, db_name: str, port: int = 1433, encrypt: bool = False, trust_certificate: bool = False, ) -> Adapter: """ Creates a SQL Alchemy database engine for Microsoft SQL Server, using integrated security (aka SSPI, aka Windows domai...
74f721a2a474dcbb92b742a5919b39a8473895f0
57,082
def datetime_isoformat( tdt, format=DATE_EXT_COMPLETE + "T" + TIME_EXT_COMPLETE + TZ_EXT ): """ Format datetime strings. This method is just a wrapper around isodate.isostrf.strftime and uses Extended-Complete as default format. """ return strftime(tdt, format)
269d675600a10ca75b754e2f4c9b92cf46f94ef5
57,083
def get_prime_factors(n): """ Find all prime factors in N and return them as a list. """ i = 2 factors = set() while n > 1: if n % i == 0: factors.add(i) n = n / i else: # only increment if we did not find a factor. i = i + 1 i...
da6f13b1c910f4b90cf84bbb7cfe6ecc2b735863
57,084
import tqdm from pathlib import Path import concurrent def download_list(uids, username, password, outdir, threads=1, show_progress=True): """Downloads a list of UIDS Parameters ---------- uids: A list of UIDs username: Username password: Password outdir: O...
4a7b4f7724b41fb05580ebd2540c73b77b31d0ac
57,085
def ping(): # pragma: no cover """ ignore connection validation with task server (celery) """ """Simple task that just returns 'pong'.""" return "pong"
9967a01f8c509e272e7215a843e513ce4dc9a2be
57,086
def deep_index_items_by(items, key): """ Index a list of dicts by a given key. Returns a dict of the arrays of items based on the value of `key` in each item. """ index = {} for item in items or []: try: index_key = str((dpath.util.get(item, key) or "")).lower() excep...
1ce8788aab61401d3767c4d00e5cd1c477b1010f
57,087