content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def pubkey_to_bech32_address(data: bytes, witver: int) -> BTCAddress: """ Bitcoin pubkey to bech32 address Source: https://github.com/bitcoin/bips/blob/master/bip-0141.mediawiki#witness-program https://github.com/mcdallas/cryptotools/blob/master/btctools/address.py May raise: - EncodingErr...
348c68db3feaa994ea55161456f5559613f86a2f
36,000
def get_gender(id): """ :param id: feature id :return: feature dictionary """ for gender in __gender_dict: if __gender_dict[gender] == id: return gender raise ValueError("Id does not correspond to a Universal Dependency gender")
26d399507159a6992d67000c2e03164b3de6c82b
36,001
import torch def create_supervised_evaluator( model, prepare_batch, metrics=None, device=None, non_blocking=False, output_transform=val_transform, ): """Factory function for creating an evaluator for supervised segmentation models. Args: model (`torch.nn.Module`): the model to train. prepar...
7c5cd0f778ed7785af9fe7460c5c0d452201fbe1
36,002
from pathlib import Path import os import string def cipher_core(): """ This is the general function of Cipher, it is from it that users can encrypt or decrypt their various messages. """ def display_options_message(): """ Allows the user to choose to encrypt or decrypt a message he h...
825c90b39e598bf7e12e26a7c206bfe0431d2a37
36,003
def fit_datapack(datapack,template_datapack,ant_idx = -1, time_idx=-1, dir_idx=-1, freq_idx=-1): """Fit a datapack to a template datapack using Bayesian optimization of given kernel. Conjugation occurs at 350km.""" antennas,antenna_labels = datapack.get_antennas(ant_idx) directions, patch_names = datap...
804b2b5e7b8bf31d9301e16636e7a14202e23b76
36,004
def get_similar_pkg_installed_by_conda(ggd_recipe): """Method to get a list of similarly installed package names, referring to package installed by conda get_similar_pkg_installed_by_conda ================================== Method to identify if there are similar packages to the one provided installed ...
1d8083626fe1dd71eb6d706b3f2440e803d930a6
36,005
from re import T import numpy def pinv(mat: T.Tensor) -> T.Tensor: """ Compute matrix pseudoinverse. Args: mat: A square matrix. Returns: tensor: The matrix pseudoinverse. """ return numpy.linalg.pinv(mat)
028c0376dcab3838e31d8b247e4ccf630905d54f
36,006
def devices_date_stamper(devices): """ Return a function that given a date time will return the dates when devices will make their requests. :param devices: :return: """ def mapper(date): def stamper(x): return date + timedelta(seconds=x) return map(stamper, next...
3ce0d377f1bdb3938a38e5fc60e6e3098ecc66e5
36,007
from typing import List def getTestFragments() -> List[str]: """ Returns a small list of testing fragments. >>> len(getTestFragments()) 5 """ return ['tttttt', 'ttttgg', 'tggaga', 'agacgc', 'cgcggg']
4bd66b0a0c90df0d20f3d66d9b789a31419e63f6
36,008
def json_response(data, code=200, mimetype='application/json'): """ For ajax(json) response, wrapper json data to convert HttpResponse. """ resp = HttpResponse(data, mimetype) resp.code = code return resp
ebcbcc94026892d7de9d4be629a8be29c660dfd1
36,009
def get_funds_list(country=None): """ This function retrieves all the available funds and returns a list of each one of them. All the available funds can be found at: https://www.investing.com/funds/ Args: country (:obj:`str`, optional): name of the country to retrieve all its available funds f...
d9eed610752d87a797e922fa90dd300ebc5c4526
36,010
def powerlaw_dl(p, x): """ p are parameters of the model """ return p[0]*(x/80.)**(p[1]+2)
d2d0a331b260514a3e5a6dd0d78d2a55e6d1eedd
36,011
import math def poisson_trunc(expectation, top): """ Returns a random variable following a Poisson distribution with expected value `expectation`, truncated so that values greater than `n` are not possible. The probability that the value exceeds `n` is added onto the probability for `n`. ...
6dd786220afbf655ecc509c514c0f432a15bbc48
36,012
from typing import Optional import os import logging def start_run(param_prefix: Optional[str] = None, experiment_name: Optional[str] = None, run_name: Optional[str] = None, artifact_location: Optional[str] = None, **args) -> mlf.ActiveRun: """Close alias of m...
792d89426aee50c61870ac4228c0eb421c09913f
36,013
def get_forecast_metadata_variables(ds): """ Returns a list of variables that represent forecast reference time metadata. :param netCDF4.Dataset ds: An open netCDF4 Dataset. :rtype: list """ forecast_metadata_standard_names = { "forecast_period", "forecast_reference_time", ...
83b8fe0eb785c1a3129ec19df680ce135cd3fa82
36,014
def feet(i): """ feet(i) Return i (in inches) converted to feet. """ return i / 12
bff46c1399aabee1f589dea98c9c43ced30d0756
36,015
def confirm_action(msg): """Ultra-lightweight confirmation dialog""" return ConfirmAction(app.window, _("Are you sure?"), msg).run()
119d8cdbb8ad1ef65d4bba67a4026f4335c451b8
36,016
def create_dataset(path, column_name, label_name, defaults, batch_size, shuffle): """ Create tf.dataset from csv file. Args: path (str): Path to the csv file. column_names (list:str): List of string to specify which columns to use in dataset (including label). label_name (str): Colu...
91428eef76aed05e8b5c79cdc9227e6cf759d81c
36,017
def canonical_letter_permute_form(F, word): """ Apply a permutation of the letters of F so that the different letters appearing in the word appear in order (1,2,3,...). """ assert is_FreeGroup(F), "F must be a free group" r = F.rank() assert word in F, "word must be in F" word_rep =...
f12897c981137a672b1e64391aee2763a670b547
36,018
def get_16bytes_from_seed(n): """TI pseudo-random number generator""" mod1 = 2147483563 mod2 = 2147483399 mult1 = 40014 mult2 = 40692 if n: seed1 = (mult1 * n) % mod1 seed2 = n % mod2 else: seed1 = 12345 seed2 = 67890 result_arr = bytearray(16) for i...
4e1d3aad238d0d6a13921052b12d18a474ad9b08
36,019
def remove_first_space(x): """ remove_first_space from word x :param x: word :type x: str :return: word withou space in front :rtype: str """ try: if x[0] == " ": return x[1:] else: return x except IndexError: return x
f84819fe7d486851749945e932590900c125abe7
36,020
def sum_merge_tables(df1, df2, policy_id_column_name, df1_group_by, df2_group_by, df1_kpis, df2_kpis, df_no_dupl=None): """ Sums separately two dataframes and merge them Arguments --> the two 2 dataframes to sum and merge, the policy id column name the variables to aggregate on in ...
955505efc0535f198c4ac557d62f05350e315b31
36,021
def thcf_partial1(x): """ Partial derivative of the Three-Hump Camel Function with respect to x1. """ partial = x[1] + 4 * x[0] - 4.2 * (x[0] ** 3) + (x[0] ** 5) return partial # Gradient 1
cccc2505978cc49fffa0a445157ba5fdaf0abc30
36,022
def props(prop_name: str, *prop_names: str) -> "PropertyFilter": """ Factory to create filter using list of props """ def prop_filter(*, prop: "PropertyName", path: "PropertyPath") -> bool: return any(str(prop) == p for p in (prop_name, *prop_names)) return prop_filter
b3bf389ebe63b11ad4c79fab244491e25b39bca0
36,023
def add_coords(filtered_lst): """ Find coordinates for list of films """ for line in filtered_lst: try: location = line[2] location = location.split(", ") geolocator = geopy.Nominatim(user_agent="main.py") geocode = RateLimiter(geolocator.geocode, min_del...
31ee2bd4c856afef2d51f72ad130e2be37556594
36,024
def rphiz_to_xyz(values): """Converts axis values from cylindrical coordinates into cartesian coordinates Parameters ---------- values: array Values of the axis to convert (Nx3) Returns ------- ndarray of the axis (Nx3) """ r = values[:, 0] phi = values[:, 1] z = va...
523631b90957819826e244614258dbb6be77bfd0
36,025
def build_load_statement(tablename, retry=True, options=""): """build a command line statement to upload data. Upload is performed via the :doc:`csv2db` script. The returned statement is suitable to use in pipe expression. This method is aware of the configuration values for database access and th...
8917396c7d5650bf1777f3b2e31c495a2b28baf2
36,026
def recentlist(): """ Return a list of recently completed games for the indicated user """ rq = RequestData(request) user_id = rq.get("user") versus = rq.get("versus") count = rq.get_int("count", 14) # Default number of recent games to return # Limit count to 50 games if count > 50: ...
8d85da92a452d279db94e225d625688d5956b799
36,027
def nice_std(ls): """ Method to return standard deviation of a list or equivalent array with NaN values Args: ls: (list), list of values Returns: (numpy array), array containing standard deviation of list of values or NaN if list has no values """ if len(ls) > 0: ret...
e812d351e67f38cbdf062ebd3a54e972501bc9f3
36,028
def check_pano_submission(path): """Checks if all files required for the submission exist and are in the right format.""" ready_for_submission = True # check if path contains a predictions.json json_path = path / 'predictions.json' print('Checking for "predictions.json" ... ', end='', flush=True) if json_path...
f9f03b581d4af5d603694b7c29b2ab6fd42e81b0
36,029
def leftmostNonzeroEntries(M): """Returns the leftmost nonzero entries of M.""" return [ abs(M[l][M.nonzero_positions_in_row(l)[0]]) for l in range(0,M.dimensions()[0]) if M.nonzero_positions_in_row(l) != [] ]
9e42297dc3000a41dcdceebff10c4fc53e1709ac
36,030
def tophat_binary(image, kernel=None, n=None): """ It is the difference between input image and opening of the image """ tophat = cv2.morphologyEx(image,cv2.MORPH_TOPHAT, kernel) return tophat
6903257998cc78cd1d86fa8af318fbde3e6ed725
36,031
def kl_div(input, label, reduction='mean', name=None): """ This operator calculates the Kullback-Leibler divergence loss between Input(X) and Input(Target). Notes that Input(X) is the log-probability and Input(Target) is the probability. KL divergence loss is calculated as follows: $$l(x, y) =...
ef7629de18522ffd310e490fe171c1c0de5dcbfd
36,032
def _json_target_decode(dct): """Target json object decoder""" if "itf" in dct: dct["itf"] = CanedgeInterface[dct["itf"].upper()] if "chn" in dct: dct["chn"] = CanedgeChannel[dct["chn"].upper()] if "db" in dct: dct["db"] = dct["db"].lower() if "method" in dct: dct["me...
8a252e097c71bd9cdf967c9242aa76d157e01f8c
36,033
def init_ax(fontsize=24, nrows=1, ncols=1): """ :param fontsize: :return: """ font = {'family': 'Times New Roman'} mpl.rc('font', **font) mpl.rcParams['legend.fontsize'] = fontsize mpl.rcParams['axes.labelsize'] = fontsize mpl.rcParams['xtick.labelsize'] = fontsize mpl.rcParams[...
b163c6ae2bfc99d06941088fc202bd6650dab038
36,034
def is_sequence(arg): """Returns True is passed arg is a list or a tuple""" return isinstance(arg, list) or isinstance(arg, tuple)
12a0a0186695f8b79a48905a22c0c1c69cde219f
36,035
async def validate_captcha(data: str) -> bool: """Verify `data` with hcaptcha's API.""" url = f'https://hcaptcha.com/siteverify' data = { 'secret': zconfig.hCaptcha_secret, 'response': data } async with zglob.http.post(url, data=data) as resp: if not resp or resp.status != ...
b6d0c1e695437b564bf4d278efa7dcdff12fa43d
36,036
def _Levy(x): """ Global Minimum at `z_1 = (1, 1, ..., 1)` with `f(z_1) = 0`. """ w = 1 + (x - 1) / 4 w_mid = w[:, :-1] f = np.sum(np.multiply((w_mid - 1)**2, 1 + 10 * np.sin(np.pi * w_mid + 1)**2), axis = 1) f += np.sin(np.pi * w[:, 0])**2 + (w[:, -1] - 1)**2 * (1 + np.sin(2 * np.pi * w[:, -1])**2) ...
f648e2b417ed8c7c025d5e8d09f6e8b44cd4ab11
36,037
def generateWorld2(): """ Generates world with collidable walls and grass paths\n Types:\n Grass -> 0\n Wall -> 1 """ walls = 0 grass = 0 #possibility = [None, 0, 1, None, None] for i in range(0, worldSize): for j in range(0, worldSize): worldmap[i][j]["TYPE"...
bfc13e2345049aadcb3d6216759cd8787ac4b89b
36,038
import torch def pad_shift(x, shift, padv=0.0): """Shift 3D tensor forwards in time with padding.""" if shift > 0: padding = torch.ones(x.size(0), shift, x.size(2)).to(x.device) * padv return torch.cat((padding, x[:, :-shift, :]), dim=1) elif shift < 0: padding = torch.ones(x.size(...
95f883714222787eb5fd92f7a0c6f1777c989399
36,039
import asyncio async def async_million_state_changed_helper(hass): """Run a million events through state changed helper.""" count = 0 entity_id = 'light.kitchen' event = asyncio.Event(loop=hass.loop) @core.callback def listener(*args): """Handle event.""" nonlocal count ...
c8cb579e277fc889da4e2732164e95c70ae4b7ac
36,040
def add_dim(*, opt=False, shapes=None, typ=None, use_var=False): """Construct a new dimension type based on the list of 'shapes' that are present in a dimension. """ if use_var: offsets = [0] + list(accumulate(shapes)) return "%svar(offsets=%s) * %s" % ('?' if opt else '', offsets, ty...
a8cd553c736ff8f20d043c873e9c71589d807698
36,041
def _allocate_returned_states(model, inputs, return_states=None): """Create empty placeholders for model outputs.""" seq_len = inputs[list(inputs.keys())[0]].shape[0] vulgar_names = {"reservoir": model.reservoir, "readout": model.readout} # pre-allocate states if return_states == "all": sta...
722259f07fbd1b0f5ced0883112ecfb5fea4f81a
36,042
from typing import Dict from typing import Mapping import logging def from_obographs( jsondoc: Dict, curie_map: Dict[str, str], meta: Dict[str, str] = None ) -> MappingSetDataFrame: """ Converts a obographs json object to an SSSOM data frame Args: jsondoc: The JSON object representing the...
3b91af2fceb49ea1ff1c43edb6273c54309f105a
36,043
from typing import List import torch from typing import Optional def nll_loss_multimodes(pred: List[torch.Tensor], data: torch.Tensor, mask: torch.Tensor, modes_pred: torch.Tensor, noise: Optional[float]=0.0 ) -> float: """NLL loss multimodes for training. Args: pred is a list (with N modes) of predictions ...
4d0b342b936111a65fdea4a880d122c6d4837b2e
36,044
def pmps_to_mpo(pmps): """Convert a local purification MPS to a mixed state MPO. A mixed state on n sites is represented in local purification MPS form by a MPA with n sites and two physical legs per site. The first physical leg is a 'system' site, while the second physical leg is an 'ancilla' site...
53ec35adbe5943f08ebf5370e1329f252f8422be
36,045
def pynautobot_api(): """Factory to create pynautobot api instance.""" return Api(url="https://mocknautobot.example.com", token="1234567890abcdefg")
bb8f4094e6700140473d03b76168ab31269fd7cb
36,046
def actionAngle_physical_input(method): """Decorator to convert inputs to actionAngle functions from physical to internal coordinates""" @wraps(method) def wrapper(*args,**kwargs): if len(args) < 3: # orbit input return method(*args,**kwargs) ro= kwargs.get('ro',None) ...
754aae2faf086036853be029b56452edd5567400
36,047
import numpy import os import glob def import_dicom_directory(parent = None, dtype = numpy.single, recursive=False, load_all_images=False): """ Import an image from a directory containing DICOM files parent : parent wx Window for dialogs dtype : type to cast ima...
53ccd0b3bf3c2132010596123525fd1402a0c0fc
36,048
def super_reduced_string(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/reduced-string/problem Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest length by doing a series of operations. In each operation he selects a pair of ...
09c48f38a877ff9ae92b985bd793224bd81247c8
36,049
import os def parsefile(settingfile): """Parse the input settingfile""" def func_remove_comments(string): if string.find('#') != -1: string = string[:string.find('#')] return string.strip() if not os.path.isfile(settingfile): print('not a file: {:}'.format(setting...
7a4596f3204d9e84c8e6d507b8fd47cd8497e4fa
36,050
from IPython import get_ipython def is_in_notebook(): """Determines if current code is executed from an ipython notebook. If is_in_notebook() is True, then is_in_ipython() must also be True. """ is_in_notebook = False if is_in_ipython(): # The import and usage must be valid under the execution path. ...
7e1a49e74e116798dbb6bbcd72a80405fe3228a9
36,051
def xor_hex_strings(str1, str2): """ Return xor of two hex strings. An XOR of two pieces of data will be as random as the input with the most randomness. We can thus combine two entropy sources in this way as a safeguard against one source being compromised in some way. For details, see http://c...
2a992bd8cc2542e1bffd5d3ab29f7f96b66acfdc
36,052
def CreateIonDataFromInput(ionInputList): """ input: ionInputList <list>(string, string, string, string): list of ions to specify and their properties summary: takes values in each entry of the ionInputList and makes a IonDataDict output: dictionary<string, Ionic>: dict of Ionic class wich contains info...
8bcdc503a4a82c959f69134c375e26971942677a
36,053
import torch def batch_img(data, vocab): """Pad and batch a sequence of images.""" c = data[0].size(0) h = max([t.size(1) for t in data]) w = max([t.size(2) for t in data]) imgs = torch.zeros(len(data), c, h, w).fill_(1) for i, img in enumerate(data): imgs[i, :, 0:img.size(1), 0:img.si...
e123813b14e7e35bea4786a7fc1772bdfb0673a1
36,054
def _build_neural_network_formulation(block, network_structure, layer_constraints, activation_constraints): """ Adds the neural network formulation to the given Pyomo block. Parameters ---------- block : Block the Pyomo block network_structure : NetworkDefinition the neural netw...
5df1cb370d3d6aec19102e966fd9468b7fcc129d
36,055
def Add(path, value, ttl_seconds=DEFAULT_TTL_SECONDS): """Atomically adds an entry to memcache only if it does not already exist. Args: path: A list of items (see ToCacheKey). value: The value to store in the cache. ttl_seconds: An integer number of seconds to keep the value in the cache. Returns: ...
c105aaad0fd6e053c245431a85ea0148dda19c8b
36,056
def node(helper): """ Report any storage capacity and useage inconsistencies between the storage node and the API """ # Get a list of active LVM Volumes lvs = [lv for lv in helper.volumes._scan_volumes() if lv['origin'] == ''] # Get our node id node_id = request(helper, 'node...
9a5ceaa695c9ab0394826ae1046c0c66436f0284
36,057
def rotate_tour(tour, start=0): """ Rotate a tour so that it starts at the given ``start`` index. This is equivalent to rotate the input list to the left. Parameters ---------- tour: list The input tour start: int, optional (default=0) New start index for the tour Returns ------- rotated: ...
b2356aaecb00dc993e88b5f7105c0b4aed495521
36,058
def get_mesh(X, h=0.02, padding=0.5): """Build a regular meshgrid using the range of the features in X """ x_min, x_max = X[:, 0].min() - padding, X[:, 0].max() + padding y_min, y_max = X[:, 1].min() - padding, X[:, 1].max() + padding xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min,...
e67756a6dacd62db1d77bfd4a75c6d55e512a8b4
36,059
def setting(key, default=None, domain=None): """ Settings helper based on saltstack's query Allows a simple way to query settings from YAML using the style `path:to:key` to represent path: to: key: value """ rtn = settings.PROMGEN lookup = key.split(":") if domain: ...
d7afd5be423e8934490d99d9090fec9ac53809dc
36,060
def literal_schema(literal, theories, default_theory=None, theory_assertion=None): """Return the schema that applies to LITERAL or None. :param: LITERAL is a Literal for which we want the schema :param: THEORIES is a dictionary mapping the name of the theory to the theory obje...
d9848dc3311732201745000b3ecc514652192a89
36,061
def green(inputs, value=255, **kwargs): """Generate pure green channel""" x = np.zeros_like(inputs) x[..., 1] = value return x
f1258447501737b13540fe1e83656a082eef88a8
36,062
import torch def solve_kernel(data: torch.Tensor, kernel: Kernel, koopman: bool = True): """Pseudoinverse solution for Koopman & Perron-Frobenius operators over RKHS Args: data: simulation data (see `prep_snapshots`) kernel: positive-definite kernel. koopman: if True, Koopman operator, else Perron-Frobenius...
87e2e0ccb9f05bf8807b2adb84e14ad9c1248a1f
36,063
def cadindateDetailsofEvent(request): """ Returns candidate details :param request: :return: boolean """ try: if request.method=='GET': id=request.GET.copy() if 'id' in id : eventRegistrationId = id['id'] if EventRegistration.object...
dcdca50d76d8a4caae0033849eb1326dc08a9363
36,064
def no_space(original_str, keyslist, replace_str): """ :param original_str: A string found in the keyslist :param keyslist: A list of keys found in the each of the two knowledge graph dictionaries (nodes and edges) :param replace_str: A string to replace the original_str in the keysl...
1184effc9dc301b234e01c469839783f2c16e25b
36,065
import uuid import os import io def generate(proid, name, client=None): """Generates a credential spec file for the given GMSA proid and returns the path to the file. """ credential_specs_path = _get_path(client) dc_name = win32security.DsGetDcName() account_name = win32security.LookupAccount...
60f9720f034234ad7cf1ef6896b2c5a9f1fdc37a
36,066
from typing import Callable from typing import Optional from typing import Union from typing import Tuple from typing import List def scipy_expm_solver( generator: Callable, t_span: Array, y0: Array, max_dt: float, t_eval: Optional[Union[Tuple, List, Array]] = None, ): """Fixed-step size matri...
fc1c9c1a40ee1b272b520ac33c1f52d198999d7c
36,067
from datetime import datetime def time_to_hhmmss(tm: datetime.time) -> str: """Convert a datetime.time to HHMMSS string.""" if tm is not None: return "%.2d%.2d%.2d" % (tm.hour, tm.minute, tm.second) else: return ""
936cc1784d1f3cd5d3ec2809e3aaedc98a2fb7ef
36,068
def parse_devices(header, lines): """Parses output of lsblk""" cols = parse_header(header) mappings = {} flat = {} parents = [] indent = 0 last = None for line in lines: index = 0 name = None mapping = {'children': [], 'parent': None} for col in cols: ...
1757dfb4901d78c4f543d440e3580a9a51919252
36,069
from typing import List from typing import Dict def _calc_j5_dependants(conf: List[BaseJoint], flag_sum: int, theta123: List[float], j5_solutions: Dict[bool, float], tf14: np.ndarray, xdir: np.ndarray, zdir: np.ndarray) -> JointSolution: """ Calculate the dependant last joint for given...
6501c82b90c2874eb36afde2f78328b68b695407
36,070
def format_data(value): """ 返回百分数据的值 """ return round(value*100, 1)
add5b16641f3cd0fef69f2cb54ce9448a2e1ad1b
36,071
import json def check_downsample_queue(args): """ Check queue for downsample jobs. Also marks downsample as in progress if message found. Args: (dict): { 'queue_url': <URL of SQS queue>, 'sfn_arn': <arn of the downsample step fcn> } Returns: (dict): { 'start_downsamp...
adce4257b14f5dda17df9ccc29929a6a1c34b863
36,072
def pindajya(k: int): """ Return the kth pindajya computed by the nilakantha recurrence Inputs: k (int) : index from 0 to 23 Outputs: int : kth pindajya """ assert ((k>=0) & (k<24)), f"Input must be between 0 and 23 inclusive, got {k}" return float(_b[k])
63ddf7ab855b9fc8056a66264e6748f7c53240bf
36,073
from typing import Iterable from typing import Tuple from typing import Sequence def g2xys(m: Basemap, coords: Iterable[Tuple[float, float]]) \ -> Tuple[Sequence[float], Sequence[float]]: """ Convert an iterable with geographical coordinates into two sequences with x- and y-coordinates in the pl...
e6e1d761351c28bc23061ae0c4ed323ac33d17ae
36,074
def create_linear_transform(linear_transform, features): """Function for creating linear transforms. Parameters ---------- linear_transform : {'permutation', 'lu', 'svd'} Linear transform to use. featres : int Number of features. """ if linear_transform.lower() == 'permutati...
96cac529cc6e20e7d2976fcad9b22e9e4f05c60a
36,075
def cross_entropy(y_pred,y): """ Cross entropy loss for classification purposes""" epsilon = 0.001 # To prevent overflow and ensure numerical stability return sum(-y*np.log(y_pred+epsilon))
96eddb997a706dc0c1b92fa2f423bb00b5f216c1
36,076
def create(name, root, *args, **kwargs): """ Create a dataset instance. Parameters ---------- name : str The dataset name. Can be one of 'pitts', 'tokyo'. root : str The path to the dataset directory. """ if name not in __factory: raise KeyError("Unknown dataset:...
0a36c94451aad03edc819bfa97007166efdd5ba3
36,077
from typing import cast def get_time_stamp_from_lidar_pc(lidar_pc: LidarPc) -> int: """ Extracts the time stamp from a LidarPc. :param lidar_pc: Input lidar pc. :return: Timestamp in micro seconds. """ return cast(int, lidar_pc.ego_pose.timestamp)
245111bafebe9b2e9ec701d9c4a7f0912bb655da
36,078
import torch def infer_mask(seq, eos_ix, batch_first=True, include_eos=True, dtype=torch.float): """ compute length given output indices and eos code :param seq: tf matrix [time,batch] if batch_first else [batch,time] :param eos_ix: integer index of end-of-sentence token :param include_eos: if Tru...
6038291eecc96898491e685c63f69187dca7e8fc
36,079
def print_alignment(match,test_instance,gold_instance,flip=False): """ print the alignment based on a match Args: match: current match, denoted by a list test_instance: instances of AMR 1 gold_instance: instances of AMR 2 filp: filp the test/gold or not""" result=[] for i...
27e17e2ecdcf08325667d753bed7301fbb15c111
36,080
def beta_labelling(LLR,ln_beta): """ apply a filter to the LLR array : if the LLR is above log_beta : return 1 else : return 0 """ beta_func = np.vectorize(lambda a,b: 1 if a>b else 0) return beta_func(LLR,ln_beta)
c424ae565ca3b43a9fe696eaebe3e01838a87725
36,081
def tr_sqrt(A, rank=None): """Return the trace of the sqrt of a positive semidefinite operator. """ if rank is None: el = eigvalsh(A, sort=False) else: el = eigvalsh(A, k=rank, which='LM', backend='AUTO') return np.sum(np.sqrt(el[el > 0.0]))
2b86a07f51efaa3d0e89e84bffb5425ee67c4bdc
36,082
def myBasicTreeXMLLines(tree): """ Takes: - tree (ete3.TreeNode) Returns: (list): list of xml lines """ lines = ["<phylogeny>"] indentChar = " " tmp = myBasicTreeXMLLinesAux(tree) for l in tmp: lines.append( indentChar + l ) lines.append("</phylogeny>") ...
ffdb4ec91d9f70dc2d320ba19c4b7207f87b30d5
36,083
from typing import Iterator def parse(tokens, parse_until=None, start_from=0): """ :param tokens: Tokens to parse :type tokens: list[Token] :param parse_until: :param start_from: :return: AstTree """ tree = AstTree() it = Iterator(tokens, start_from=start_from) wh...
9e712ab053fe66aeca3ebdeada5dd03bfd654102
36,084
import torch import json def silero_lang_detector_116(**kwargs): """Silero Language Classifier (116 languages) Returns a model with a set of utils Please see https://github.com/snakers4/silero-vad for usage examples """ hub_dir = torch.hub.get_dir() model = init_jit_model(model_path=f'{hub_di...
fb3c5ce00f145c6f9b37184b65059d6a44bb3317
36,085
def isPrime(n): """Returns True if n is prime.""" if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w ...
a11dc193b69d3f16b67a32c39ac24c90ed9b096c
36,086
def is_saved(response: Response, name: str, port: int) -> bool: """Wait for the response showing that saving has taken place.""" expected_url = f"http://localhost:{port}/api/contents/{name}" method = response.request.method try: t = response.json().get("type") except AttributeError: ...
46939fed0eee343b48ead3ccdb21959ac20ed7f4
36,087
def filter_polygons(state, header): """ Removes any non-polygon sources from the state file. We are only interested in parsing parcel data, which is marked as Polygon in the state file. """ filtered_state = [] for source in state: if 'Polygon' in source[header.index('geometry type'...
d100e6a4e87dccdc42c7217dc1e793e4353237e2
36,088
def conv_out_init(obj: MyArray, results: ArgTuple[BaseArray], outputs: OutTuple[BaseArray], conv: _ty.Sequence[bool] = ()) -> ArgTuple[MyArray]: """Process outputs in an __array_ufunc__ method using a constructor. Creates an instance of ``type(obj)`` with `...
9a54fbb82be9ff70cce2cd3f1de20071a1d3a503
36,089
def detect_blobs(im,im_out,params): """ :param im: input image to track :param im_out: image to display bounding boxes :param params: Blob detector params :return: blob, im_disp, bbox """ detector = cv2.SimpleBlobDetector_create(params) blob_im = im blob = detector.detect(blob_i...
4ee4c48be0f1df07f43336b0c33ca68083c015b3
36,090
import copy def get_thermal_instance(wildcards): """ Returns a formatted template Arguments: rest_base - Base URL of the RESTful interface ident - Identifier of the chassis """ c = copy.deepcopy(_TEMPLATE) c['@odata.context'] = c['@odata.context'].format(**wildcards) ...
06997ea9468c034a276a852e096a8d1e0f55a263
36,091
def getWorldSimState(world): """Returns a dict containing a copy of all variables that are simulated in the world. Can be used with setWorldSimState to save/ restore state. NOTE: this does not perfectly save the state of a Simulator! To do that, you must use the Simulator().getState()/saveState()...
f9198abab6e78dee9b0407d6a64adc062a505a13
36,092
import unicodedata def unicode_normalize(text): """Return the given text normalized to Unicode NFKC.""" normalized_text = unicodedata.normalize('NFKC', text) return normalized_text
1b6defacd09665412a1b31dd48f5291c4984d044
36,093
import importlib def import_obj(clsname, default_module=None): """ Import the object given by clsname. If default_module is specified, import from this module. """ if default_module is not None: if not clsname.startswith(default_module + '.'): clsname = '{0}.{1}'.format(default...
8cb064348b7b38e1e3f659240f4bc9677237d3fd
36,094
def _SelectUploadCompressionStrategy(object_name, is_component=False, gzip_exts=False, gzip_encoded=False): """Selects how an upload should be compressed. This is a helper function for _UploadFileToObject...
1ddb0d8640a05aa12ce8ee7ba76a84c03f99e7ec
36,095
def polynomial_features(X, degree): """ Make polynomial feature. Parameters: ----------- X: ndarray of shape (n_samples, n_features) The input samples degree: int The highest of the degrees of the polynomial's monomials (individual terms) with non-zero coefficients Returns: -...
914715295ffa5469dbc1342ba6c78720de81b271
36,096
def flesch_reading_ease_score(sentences: int, words: int, syllables: int, *, is_russian: bool = False) -> float: """ Calculate the Flesch-Kincaid score. """ if not sentences or not words: return 0.0 # Flesch-Kincaid score constants: x_grade: float = FRES_RU.X_GRADE if is_russian else FR...
9ab6abd5ddf874de4a14e02a580502aa103086eb
36,097
import select def add_publication_to_group(project, publication_id): """ Add a publication to a publication_group POST data MUST be in JSON format POST data MUST contain the following: group_id: numerical ID for the publication_group """ request_data = request.get_json() if not reque...
966984eb8994c38259795500dfbad7fd9e4f1044
36,098
def is_compatible(feature: Feature, other: Feature): """Determines if two features are compatible with one another.""" return feature.api == other.api and not ( other.version.major > feature.version.major or ( other.version.major == feature.version.major and other.version...
5cb4f94a9fb8b8faf666aa018bbec7cd33abedc9
36,099