content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compare(isamAppliance1, isamAppliance2): """ Compare Policy Sets between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) for obj in ret_obj1['data']: del obj['id'] del obj['userlastmodified'] del obj['lastmodified'] de...
a727eac5efb4e117413d70191e7a74921e3ac284
7,803
def capacity(quantity, channel, gamma, dim, basis, eps, **kwargs): """ Runs the Blahut-Arimoto algorithm to compute the capacity given by 'quantity' (which can be 'h', 'tc', 'coh' or 'qmi' taking the channel, gamma, dim, basis and tolerance (eps) as inputs). With the optional keyword arguments 'plot...
6624d045fb953d536b082f183a6c1536dcd9ca50
7,804
def get_Teq_from_L(L: ArrayLike, d: ArrayLike, A: ArrayLike) -> np.ndarray: """Calculates the equilibrium temperature of a planet given the stellar luminosity L, planetary semi-major axis d and surface albedo A: Args: L (ArrayLike): Stellar luminosity in erg/s. d (ArrayLike): Planetary ...
9f140c554059074d9569e48ae2f971bc430e2fba
7,805
from typing import Type def lookup_container_plugin_by_type(container: IContainer, plugin_type: Type[ContainerResolutionPlugin]): """ Given a container, finds the first plugin that is an instance of the specified type. :param container: The container to perform the lookup on. :param plugin_type: The ...
b41cfc2e1e1328a8f54e938b7944d3f16924d3cf
7,806
from scipy.ndimage import shift def shift_map_longitude(mapdata, lonshift, spline_order=1): """ Simple shift of the map by wrapping it around the edges Internally uses scipy's ndimage.shift with spline interpolation order as requested for interpolation Parameters ---------- mapdata : 2D ...
72373800f3a53785989cc2e2da4dab08d0976b30
7,807
def aalogoheights(aahistObj, N=20): """For a objhist of AA frequencies, compute the heights of each AA for a logo plot""" aahistObj = deepcopy(aahistObj) keys = list(aahistObj.keys()) for aa in BADAA: if aa in keys: dummy = aahistObj.pop(aa) keys = [aa for aa in aahistObj.sor...
8020605d6c2a9a618e5faed57ba7af5e1315dfec
7,808
def cmdline_opts( request ): """PyMTL options parsed from pytest commandline options.""" opts = _parse_opts_from_request( request ) # If a fixture is used by a test class, this seems to be the only # way to retrieve the fixture value. # https://stackoverflow.com/a/37761165/13190001 if request.cls is not No...
8b3af4ab15a1a5a11a633fa322e4484f2d8257bc
7,809
def replace(index, ndim, axes, rindices): """Replace indexing for a specified dimension Args: index(index): object used in slicing ndim(num): number of dimensions axes(list): dimension to be replaced rindex(list): new indexing for this dimensions Returns: index "...
3a8c9ac8b9bf12a5d416e422ddfb0f4458cf9417
7,810
import select def _closed(sock): """Return True if we know socket has been closed, False otherwise. """ try: rd, _, _ = select([sock], [], [], 0) # Any exception here is equally bad (select.error, ValueError, etc.). except: return True return len(rd) > 0
4de2aee7743cac8e660ab01f2920935faf0ee3e9
7,811
def get_forest_connection(device_name: str, seed=None): """Get a connection to a forest backend Args: device_name: the device to connect to Returns: A connection to either a pyquil simulator or a QPU """ if device_name == "wavefunction-simulator": return WavefunctionSimulat...
291c92508b097908fa86fb957b42d73066d65ebd
7,812
def add_suffix(path, suffix=""): """Adds a suffix to a filename *path*""" return join(dirname(path), basename(path, ext=False) + suffix + extname(path))
dd95548e06e29c91f0a35c5dd0979889ab945076
7,814
def MdAE_np(preds, labels): """ Median Absolute Error :param preds: :param labels: :return: """ preds = np.reshape(preds, [-1]) labels = np.reshape(labels, [-1]) return np.median(np.abs(preds - labels))
4a725eb35e5f7bd1f77b8433b7ea7393bbdae92e
7,815
from botocore.exceptions import ClientError, BotoCoreError async def s3_fetch_object(url, s3, range=None, **kw): """ returns object with On success: .url = url .data = bytes .last_modified -- last modified timestamp .range = None | (in,out) .error = None On failu...
0da8fadb248abe8c4c23e75367b3ddc884df71d3
7,816
from . import darwin from . import linux from . import windows import platform def mss(**kwargs): # type: (Any) -> MSSMixin """ Factory returning a proper MSS class instance. It detects the plateform we are running on and choose the most adapted mss_class to take screenshots. ...
057916bf6b13bd6089ccb6f46b1a2ceb583d5bf8
7,817
def reshape_fps(X): """Reshape 4D fingerprint data to 2D If X is already 2D, do nothing. Returns: reshaped X """ if len(X.shape) == 4: num_factors = X.shape[3] num_fps = np.prod(X.shape[:3]) X.shape = (num_fps,num_factors) else: num_factors = X.shape[1] ...
ab2cd286194dd6d35fb27a540378a132d25db575
7,818
def df_fc_overlap_2(): """Scenario case with 2 fragments overlapping, bound to a common fragment.""" mol = Chem.MolFromSmiles('NC1CC(CCC1O)C1CCC1') return DataFrame([ ['mol_fc_overlap_2', 'XXX', 'O1', 0, 'O1:0', 'O2', 0, 'O2:0', 'ffo', 'fusion', 'false_positive', 'overlap', (7, 6, 5, 4...
7ee533aa1c7bb821ae6a73a27d39d6a7e796087f
7,819
from datetime import datetime def strfnow(fmt=HUMAN_DATETIME): """ Returns a string representation of the current timestamp """ return datetime.now(tzlocal()).strftime(fmt)
50fe38d37dfe8581f6cfa07aaaeb588a2e6e72a9
7,821
def tag_to_dict(node): """Assume tag has one layer of children, each of which is text, e.g. <medalline> <rank>1</rank> <organization>USA</organization> <gold>13</gold> <silver>10</silver> <bronze>9</bronze> <total>32</total> </medalline> """ d =...
e2131e070dce8620630e994cc25578a9a8438c64
7,822
from typing import Any def compute_contact_centroid(molecular_complex: Any, cutoff: float = 4.5) -> np.ndarray: """Computes the (x,y,z) centroid of the contact regions of this molecular complex. For a molecular complex, it's necessary for various featurizations that compute voxel g...
53b83e6814f6f59645d84c36de458952918123fc
7,823
def general_operator_gamma_norm(matrix, gamma, max_j, max_q): """ Returns the gamma operator norm of matrix, summing up to max_j and considering the sup up to max_q. Assumed that matrix is a function accepting two arguments i,j and not an array () for efficiency. """ max_j_sum = -1 q = ...
56993d0f406af3cead83e662aecb19d9082878fa
7,824
def crop_image_single(img, device): """ Implementation of the MTCNN network to crop single image to only show the face as shown in the facenet_pytorch doc: https://github.com/timesler/facenet-pytorch/blob/master/examples/infer.ipynb :param device: pytorch device :param img: s...
b2755a1bf464dca74cbfc32a5bf5c61f106758ae
7,825
def tf2zpk(b, a): """Return zero, pole, gain (z,p,k) representation from a numerator, denominator representation of a linear filter. Parameters ---------- b : ndarray Numerator polynomial. a : ndarray Denominator polynomial. Returns ------- z : ndarray Zeros...
3d83d4053a89be19c3738650a11216d38845d6a6
7,826
def gpiod_line_is_free(line: gpiod_line) -> bool: """ @brief Check if the calling user has neither requested ownership of this line nor configured any event notifications. @param line: GPIO line object. @return True if given line is free, false otherwise. """ return line.state == _L...
939320d0737406789bbb81bc9c73023dff71fb51
7,827
import random def train_step(optimizer, inputs, learning_rate_fn, dropout_rng=None): """Perform a single training step.""" weights = jnp.where(inputs > 0, 1, 0) # We handle PRNG splitting inside the top pmap, rather # than handling it outside in the training loop - doing the # latter can add some stalls to...
2dae63fcfb9fc5bc059b084bf748886d3d257c4c
7,828
def doublet_line_polar_u(rcp,zcp,dmz_dz, bSelfInd=False): """ Velocity field induced by a semi-infinite doublet line (on the z axis) of intensity `dmz_dz` Control points defined by polar coordinates `rcp` and `zcp`. \int 1/(r^2 + (z-x)^2 )^(3/2) dx \int 1/(r^2 + (z-x)^2 )^(5/2) dx """ i...
9dcee49192273a6482b269120af01683a11916b6
7,829
def paginate(text: str): """Simple generator that paginates text.""" last = 0 pages = [] for curr in range(0, len(text)): if curr % 1980 == 0: pages.append(text[last:curr]) last = curr appd_index = curr if appd_index != len(text) - 1: pages.append(...
f40b97e0f221b4c6afffcc4dd707daf48685d04a
7,830
def get_batch_copy(vocab_size, batch_size, seq_len): """Generates random data for copying.""" batch = np.random.choice( vocab_size - 1, size=[batch_size, seq_len // 2 - 1]) + 1 batch = np.concatenate([np.zeros([batch_size, 1], dtype=int), batch], axis=1) batch = np.concatenate([batch] * 2, axis=1) batc...
f1b6092393a0b8e7cb6c2a2ae191c29d28d2d89f
7,831
import pandas def buildCompareDFs(strTodayFileName): """read in and return today's CSV as DF, determine appropriate old CSV as DF, and the old file name for use later""" # get today's file dfTodaysCards = pandas.read_csv( DATA_DIR_NAME + strTodayFileName, dtype={'Card Number': object}) dfToda...
488afcd0704b9c73a83cab3bd898703d290ac557
7,832
def __cvx_eda(y, delta, tau0=2., tau1=0.7, delta_knot=10., alpha=8e-4, gamma=1e-2, solver=None, options={'reltol': 1e-9, 'show_progress': False}): """ CVXEDA Convex optimization approach to electrodermal activity processing This function implements the cvxEDA algorithm described in "cvxEDA: a ...
5d4b333c7ab99a339d20adc379ea48792e2b43aa
7,834
import torch def pulsar_from_opencv_projection( R: torch.Tensor, tvec: torch.Tensor, camera_matrix: torch.Tensor, image_size: torch.Tensor, znear: float = 0.1, ) -> torch.Tensor: """ Convert OpenCV style camera parameters to Pulsar style camera parameters. Note: * Pulsar does ...
854349a4442e5e57554995439e62de74000c9b3d
7,835
def identity(gender:str = None) -> dict: """ Generates a pseudo-random identity. Optional args gender: 'm' for traditionally male, 'f' for traditionally female. Returns a dict with the following keys: name -> full name given -> given name / first name family -> family name ...
1917b6723a5bfe2c0b7477dca18f450c8a0e07c3
7,836
def matthews_corrcoef(y_true, y_pred): """Returns matthew's correlation coefficient for binary classes The Matthews correlation coefficient is used in machine learning as a measure of the quality of binary (two-class) classifications. It takes into account true and false positives and negatives and is ...
b4af31bac942a99fabb6f20c29ed59aa7b55e32d
7,837
from typing import Dict from typing import Any import yaml def yaml_dump(dict_to_dump: Dict[str, Any]) -> str: """Dump the dictionary as a YAML document.""" return yaml.safe_dump(dict_to_dump, default_flow_style=False)
4635514ba8ff901656b8a4b5869a6ae101528fa8
7,839
def completeness(importance_matrix): """"Compute completeness of the representation.""" per_factor = completeness_per_code(importance_matrix) if importance_matrix.sum() == 0.: importance_matrix = np.ones_like(importance_matrix) factor_importance = importance_matrix.sum(axis=0) / importance_matrix.sum() re...
39407833b501e974f2ddb421ecad59055153260e
7,840
def image_stat(image_id): """ Return the statistics ofd an image as a pd dataframe :param image_id: :return: """ counts, total_area, mean_area, std_area = {}, {}, {}, {} img_area = get_image_area(image_id) for cl in CLASSES: polygon_list = get_polygon_list(image_id, cl) ...
a20c1d702f983c576ab506061ab19181b90c8684
7,841
def delete_original(): """ Decorator that deletes the original Discord message upon command execution. :return: boolean """ async def predicate(ctx): if ctx.invoked_with != "help": # Don't try to delete if help command if isinstance(ctx.message.channel, discord.TextChannel...
08f71c271b679fb6389754c21a896e11ae6f05c0
7,842
def get_H_OS(): """屋根又は天井の温度差係数 (-) Args: Returns: float: 屋根又は天井の温度差係数 (-) """ adjacent_type = '外気' return get_H(adjacent_type)
cb3b68063d2c734b03d96b261e5cba23b79c3bc7
7,844
def forward_softmax(x): """ Compute softmax function for a single example. The shape of the input is of size # num classes. Important Note: You must be careful to avoid overflow for this function. Functions like softmax have a tendency to overflow when very large numbers like e^10000 are computed. ...
8c0f54294c2dc5b385466398726b67a3acd674b0
7,845
import numpy def applySpectralClusters(kmeansObj, img, imgNullVal): """ Use the given KMeans object to predict spectral clusters on a whole image array. The kmeansObj is an instance of sklearn.cluster.KMeans, as returned by fitSpectralClusters(). The img array is a numpy array of...
2b2fb5616c20c4e5d9278bf8555c888bfab80cb8
7,846
def get_config() -> ConfigParser: """ Parse the config file. :return: config """ cfg = ConfigParser() cfg.read(CONFIG_PATH) return cfg
14f9ce4719bf665d62f1a2d06c980f4e85d2b8a5
7,848
from calendra.registry import registry def iso_register(iso_code): """ Registers Calendar class as country or region in IsoRegistry. Registered country must set class variables ``iso`` using this decorator. >>> from calendra.core import Calendar >>> from calendra.registry import registry >>>...
7fcb55a37f5af948ff6be8baf797d00328f241a8
7,849
def dict_check_defaults(dd, **defaults): """Check that a dictionary has some default values Parameters ---------- dd: dict Dictionary to check **defs: dict Dictionary of default values Example ------- .. ipython:: python @suppress from xoa.misc import d...
8edc3fdb351f7ec2d4ec3b1e788e6aa5cc0f8787
7,850
def get_invested_and_worth(account): """Gets the money invested and the actual worth of an account""" data = query_indexa(f"accounts/{account}/performance") invested = data["return"]["investment"] worth = data["return"]["total_amount"] return {"invested": round(invested, 2), "worth": round(worth,...
fc1542f54c8954622aff86d59d7d6fb82e63832b
7,852
def make_album(singer, name, number = ''): """Return singers' names and album""" album = {'singer': singer, 'name': name} if number: album['number'] = number return album
1f1bfaaeb501be0aa6fefd358177922246488b31
7,853
from typing import Dict from typing import List from typing import Generator def fit_ctmp_meas_mitigator(cal_data: Dict[int, Dict[int, int]], num_qubits: int, generators: List[Generator] = None) -> CTMPExpvalMeasMitigator: """Return FullMeasureErrorMitigator...
2dab6ca0da19acb174b6d0e8b96c7833d5de74e8
7,854
def discounted_item(data): """ DOCSTRING: Classifies item purchases as 'Promoted' or 'Not Promoted' based on 'Item Discount' column. Also 'COD Collectibles' column gets restructured by eliminating undesired default values, like 'Online'. INPUT: > data : Only accepts Pandas DataFrame or TextParser, that ...
178c5e7d8e9c2e3bdd91d4606ea52c34c7cf099c
7,855
def NamespacedKubernetesSyncer(namespace, use_rsync=False): """Wrapper to return a ``KubernetesSyncer`` for a Kubernetes namespace. Args: namespace (str): Kubernetes namespace. use_rsync (bool): Use ``rsync`` if True or ``kubectl cp`` if False. If True, ``rsync`` will need to be ...
9da5a049a12a248623040c1ace79c2ebedd3400c
7,856
def _cons8_88(m8, L88, d_gap, k, Cp, h_gap): """dz constrant for edge gap sc touching 2 edge gap sc""" term1 = 2 * h_gap * L88 / m8 / Cp # conv to inner/outer ducts term2 = 2 * k * d_gap / m8 / Cp / L88 # cond to adj bypass edge return 1 / (term1 + term2)
7c48c4999ce2dd3dbdec799edd7ad441a6f66e7b
7,857
import hashlib def cache_key(path): """Return cache key for `path`.""" return 'folder-{}'.format(hashlib.md5(path.encode('utf-8')).hexdigest())
6b9afe1267e0cc0c7168bf3b0d5c7536e2b3c768
7,858
def ref_731(n): """Reference number calculator. Returns reference number calculated using 7-3-1 algorithm used in Estonian banks. :param string n: base number (client id, etc) :rtype: string """ return "%s%d" % (n,((10 - (sum(map(\ lambda l: int(n[-l])*(7,3,1)[(l-1) % 3], \ ...
b1958511947d9f369db2547cde15222603dc0773
7,859
import traceback async def exception_as_response(e: Exception): """ Wraps an exception into a JSON Response. """ data = { "message": str(e), "traceback": "".join(traceback.TracebackException.from_exception(e).format()) } return web.json_response(data, status=500)
60f226cb7cd4c3aba3026d44d28e774928e6bbf7
7,860
def canvas_merge_union(layers, full=True, blend=canvas_compose_over): """Blend multiple `layers` into single large enough image""" if not layers: raise ValueError("can not blend zero layers") elif len(layers) == 1: return layers[0] min_x, min_y, max_x, max_y = None, None, None, None ...
ffbb3b78e908ed1e131a1f0827f2d3097415edc9
7,861
import json def exception_response(request, code=400, exception=None): """ Create a response for an exception :param request: request instance :param code: exception code :param exception: exception instance :return: exception formatted response """ code = code if code in [400, 403, 40...
1ef145ea4b07557fbc31a9d5c52621e79c2b99ff
7,862
def entropy(series): """Normalized Shannon Index""" # a series in which all the entries are equal should result in normalized entropy of 1.0 # eliminate 0s series1 = series[series!=0] # if len(series) < 2 (i.e., 0 or 1) then return 0 if len(series1) > 1: # calculate the maximu...
30f8f3cc6fed73d8cfa0b3705008891a60af028a
7,864
def spatially_whiten(X:np.ndarray, *args, **kwargs): """spatially whiten the nd-array X Args: X (np.ndarray): the data to be whitened, with channels/space in the *last* axis Returns: X (np.ndarray): the whitened X W (np.ndarray): the whitening matrix used to whiten X """ ...
a0c9ae88e8f451378503754e4768ee554e50ed3e
7,865
from pathlib import Path import yaml def get_settings(basename: str="settings.yml", path: Path=PROJECT_ROOT / "conf") -> dict: """ Loads settings file Args: basename (str, optional): Basename of settings file. Defaults to "settings.yml". path (Path, optional): Path of seetings file. Defau...
2317f9fbd125a16a7c34086d35b02973f1be5d8f
7,866
import torch def quaternion2rotationPT( q ): """ Convert unit quaternion to rotation matrix Args: q(torch.tensor): unit quaternion (N,4) Returns: torch.tensor: rotation matrix (N,3,3) """ r11 = (q[:,0]**2+q[:,1]**2-q[:,2]**2-q[:,3]**2).unsqueeze(0).T r12 = (2.0*(q[:,1]*q[:...
feeed764ee179b31674790f9d2afc7b606a02aef
7,867
def _expand_and_tile(tensor, multiple, dim=0, name=None): """Slice `tensor` shape in 2, then tile along the sliced dimension. A new dimension is inserted in shape of `tensor` before `dim`, then values are tiled `multiple` times along the new dimension. Args: tensor: Input `Tensor` or `SparseTensor`. m...
aa9840fdaee56fee19937c8f632c72628fbd3995
7,868
import random def eval_model(opt, print_parser=None): """Evaluates a model. :param opt: tells the evaluation function how to run :param bool print_parser: if provided, prints the options that are set within the model after loading the model :return: the final result of calling report() ""...
153dbead7ebd37ba2f61d745bc499f9eddfa0d03
7,869
def login(request): """ Login with Dummy Test Account. """ if 'user' in request.environ['beaker.session']: return app.redirect('index') users.store_to_session(request, users.create()) return app.redirect('index')
0f2d06e7a6ac2fed0daee73e4c2e216012452e08
7,870
def safe_plus(x,y): """ Handle "x + y" where x and y could be some combination of ints and strs. """ # Handle Excel Cell objects. Grrr. if excel.is_cell_dict(x): x = x["value"] if excel.is_cell_dict(y): y = y["value"] # Handle NULLs. if (x == "NULL"): x = 0 ...
e3f5e43ee3e083669d0b744c7fb46a4ae62b4eec
7,871
import types def full_like(a, fill_value, dtype=types.float32, split=None, device=None, comm=None, order="C"): """ Return a full array with the same shape and type as a given array. Parameters ---------- a : object The shape and data-type of 'a' define these same attributes of the returne...
4a615e493ae20d925eeda7c0bd6ca9508c338bc2
7,872
import glob def gather_pulled_downloads(input_dir, output_dir): """ Gather MPEG stream files from input_dir into a single MP4 file in output_dir """ dash_globstr = f"{input_dir.absolute() / '*.dash'}" dash_glob = glob(dash_globstr) if len(dash_glob) < 1: raise ValueError(f"No dash file...
a1b9c334ab717292db006666bdcdd0749b2620d7
7,873
import functools def Parallelize(ListIn, f, procs = -1, **kwargs): """This function packages the "starmap" function in multiprocessing, to allow multiple iterable inputs for the parallelized function. Parameters ---------- ListIn: list each item in the list is a tuple of non-keywor...
84fc1509c96c7bf765246e46983f2fa01745f4b2
7,874
def method_not_found(e): """ Custom response for methods not allowed for the requested URLs :param e: Exception :return: """ return response('failed', 'The method is not allowed for the requested URL', 405)
18a48d53d602c1a90017e3f00adc75c4c33479b5
7,875
def get_total_trainsets(df_anual_data, segments): """ # Fill the training_sets dict :param df_anual_data: :return: """ rows_per_day = int(((60 / 15) * 24)) training_sets = {'ID_SEGMENT': [], 'MES': [], 'COD_LABORALIDAD': [], 'TRAINING_SET': []} for seg_id in segments: # 1) Particionar ...
968c3af1fdba5eb759eb93618ed48e3ca3ce5223
7,876
def uni2diff(u): """Convert speed and angular rate to wheel speeds.""" v = u[0] omega = u[1] v_L = v - ELL / 2 * omega v_R = v + ELL / 2 * omega return np.array([v_L, v_R])
83b743758aa7a549eda9067843a03eb57efde523
7,877
import re def extract_service_and_module(repo_url): """Extract service and module from repository url. :param str repo_url: repository url :return (service, module) :rtype (str, str) """ m = re.match(r'.+[/@]([^\.]+\.[^\.]+)[:/]([^/]+/[^/]+)\.git/?$', repo_url) if not m: m = re.m...
eafe6cf39fc2fe4153830c491147633fb07f95dd
7,878
def format_hexa(value: str) -> ColorBytes: """ Examples: "bda" => (187, 221, 170, 255) "4fcd" => (68, 255, 204, 221) "60B0C4" => (96, 176, 196, 255) "2BEA40D0" => (43, 234, 64, 208) """ if len(value) in {3, 4}: expanded_color = ''.join(s * 2 for s in value) else: ...
4865e1498ed87c933160e5666adcc41b45162fdd
7,880
def normalize_community_features(features): """ This performs TF-IDF-like normalization of community embedding features. Introduced in: Tang, L., Wang, X., Liu, H., & Wang, L. (2010, July). A multi-resolution approach to learning with overlapping communities. In Procee...
9f5018ad3e20810d2bb66443bac4c2f7f6359d0f
7,881
def __extend_prefixed(pu): """ :param pu: :return: """ parts = pu.split(':') if len(parts) == 1: parts = ('', parts[0]) try: return URIRef(_prefixes[parts[0]] + parts[1]) except KeyError: return BNode(pu)
d6e5c25c94e8b3252d8b0925e8d37747caceebdd
7,882
def angle(u: Vec, v: Vec) -> float: """ Returns the cosine (angle) between two vectors u and v :param u: (Vec) vector u :param v: (Vec) vector v :return: The scaled dot product, cosine of u and v's angle """ if u.is_zero or v.is_zero: raise ValueError("Angle with lower dimensional 0 ...
6c79390af1ed38fc1a99006165684234dabb0b4a
7,883
def find_most_similar(top_k, probs, cache_dict, num=10): """返回最相似的num张照片的文件名,如果找到相似的, 则返回一个包括匹配元组的列表,否则返回一个空列表 top_k : 包含最佳分类的索引的列表 probs : 包含最佳分类索引对应的概率 cache_dict: 缓存中的索引和概率 num : 返回最近匹配的数目 """ similar = [] for filename in cache_dict: score = 0 count =...
471083e1ed2b0fadb98cafad64d314ba779aa9e6
7,884
import time import torch def evaluate_full_batch(model, minibatch, mode='val'): """ Full batch evaluation: for validation and test sets only. When calculating the F1 score, we will mask the relevant root nodes. """ time_s = time.time() loss, preds, labels = model.eval_step(*minibatch.one_batch...
b1d183118b304edf6f076caefa2b1160316ad92c
7,886
from operator import mul from operator import inv def berlekamp_massey(s): """Given a sequence of LFSR outputs, find the coefficients of the LFSR.""" C, B, L, m, b = [1], [1], 0, 1, 1 for n in range(len(s)): d = s[n] for i in range(1, L + 1): d ^= mul(C[i], s[n - i]) if...
351f52dce7e4a95b986cc169f380347f317f851a
7,887
from typing import Optional def sample(image: type_alias.TensorLike, warp: type_alias.TensorLike, resampling_type: ResamplingType = ResamplingType.BILINEAR, border_type: BorderType = BorderType.ZERO, pixel_type: PixelType = PixelType.HALF_INTEGER, name: Optional[...
c9a202a6415d13bddac38cfa75e280ad45f1bda6
7,889
def normalize_parameter(kv): """ Translate a parameter into standard form. """ (k, v) = kv if k[0] == 'requiressl' and v in ('1', True): k[0] = 'sslmode' v = 'require' elif k[0] == 'dbname': k[0] = 'database' elif k[0] == 'sslmode': v = v.lower() return (tuple(k),v)
933ea71f452a16c1d4ae2630d6b58a92da1cbec0
7,890
def pulse_broadening(DM, f_ctr): """ pulse_broadening(DM, f_ctr): Return the approximate pulse broadening (tau) in ms due to scattering based on the rough relation in Cordes' 'Pulsar Observations I' paper. 'f_ctr' should be in MHz. The approximate error is 0.65 in log(tau). """ ...
48830e02774247e551605e5e8ad693ece68634ad
7,891
def logged_in_student(browser, override_allowed_hosts, base_test_data): """ Fixture for a logged-in student user Returns: User: User object """ return LoginPage(browser).log_in_via_admin(base_test_data.student_user, DEFAULT_PASSWORD)
4513e8c8356cd8fbd643e9018e1019c5ec403bcd
7,893
import numpy as np import tqdm def test_model(data_set=None, langider=None, lang_to_idx=None, ) -> np.ndarray: """ Tests a given langid.py model on the given data set. :param data_set: data set to test on :param langider: model to test :param lang_to_idx: mapping of languages to ids """ la...
2b955b637a289d0596c0584ac0761d8014e27e86
7,894
from bs4 import BeautifulSoup def search(querry, lim=5): """Search the querry in youtube and return lim number of results. Querry is the keyword, i:e name of the song lim is the number of songs that will be added to video array and returned """ # Replace all the spaces with + querry = querry....
92771e6aaa88ea65034981ff0c0c3b203addacec
7,895
def calculate_center_of_mass(symbols, coordinates): """Calculate the center of mass of a molecule. The center of mass is weighted by each atom's weight. Parameters ---------- symbols : list A list of elements for the molecule coordinates : np.ndarray The coordinates of ...
34a32e86c42875db59ad9d1bd1a6801d6fd51eb1
7,896
def __iadd__(self, other): """Pythonic use of concat Example: xs += ys Returns self.concat(self, other)""" return self.concat(self, other)
713980aed9713c2882a19ae9837315a431611bbc
7,897
def remove_stopwords(texts, stop_words): """ Define functions for stopwords :param texts: Processed texts from main module :return: Texts that already removed a stopwords """ return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]
9e2f4bcf87886a35c3877de34d6746942af19065
7,898
import json def dumps(obj): """Output json with formatting edits + object handling.""" return json.dumps(obj, indent=4, sort_keys=True, cls=CustomEncoder)
a9ad97c589a8f610d3186723566420604d99f4de
7,899
def find_asg_using_amis(ami_ids): """ take a list of ami ids and return a dictionary of launch configs that use them """ # ref: return = { ami_id : "lc_arns":[]} ami_ids = listify(ami_ids) result = {id: [] for id in ami_ids} client_asg = boto3.client('autoscaling') lc = client_asg.d...
951d20144be55a699911a690ee35405d3e4fa08b
7,900
def tokenize_nmt(text, num_examples=None): """Tokenize the English-French dataset.""" source, target = [], [] for i, line in enumerate(text.split('\n')): if num_examples and i > num_examples: break parts = line.split('\t') if len(parts) == 2: source.append(par...
f77def3cdd2eee6a9ecc3bb7fa007eccfcd9e8a8
7,901
def setup_snicar(input_file): """Builds impurity array and instances of all classes according to config in yaml file. Args: None Returns: ice: instance of Ice class illumination: instance of Illumination class rt_config: instance of RTConfig class model_config: inst...
14fc40bb6c555cf94f8f8c7ddf2133e208b5ee02
7,902
async def list_model_config(model_name: str): """ Lists all the model's configuration. :param model_name: Model name :return: List of model's configuration """ try: return ApiResponse(data=dl_service.get_config(model_name)) except ApplicationError as e: raise e except Exception: raise ApplicationError('un...
8ce01caee8fe7dacc381ea4ed23a5d885ab0da01
7,903
def signup_post(request): """Получаем данные пользователя с формы и заносим их в базу проверяя, если удачно то предоставляем вход в базу потом дополнительные идентификац""" mess = "login please" data = get_post( request ) mail = data.POST['mail'] name = data.POST['name'] captcha = data.POST['captcha'] hash = da...
22e4a8508849f9c4879c65e3347a0fabf6bffeb8
7,904
def make_onehot(label, num_classes, axis=-1): """ Create one hot tensor based on the input tensor Args: label: input tensor, the value must be positive integer and less than num_class num_classes: the number of class in one hot tensor axis: The axis to fill (default: -1, a new inner-...
3329f5f135b1fea383b389012aeeb37ea923cb46
7,905
def kohn_sham_iteration( state, num_electrons, xc_energy_density_fn, interaction_fn, enforce_reflection_symmetry): """One iteration of Kohn-Sham calculation. Note xc_energy_density_fn must be wrapped by jax.tree_util.Partial so this function can take a callable. When the arguments of this cal...
f016e1d8c6ab9072065183d3fa1d37cfa12eb8ee
7,906
def calculate_reliability(data): """ Calculates the reliability rating of the smartcab during testing. """ success_ratio = data['success'].sum() * 1.0 / len(data) if success_ratio == 1: # Always meets deadline return ("A+", "green") else: if success_ratio >= 0.90: return ("A", "green") elif success_ratio...
d1c9ad7bba220beeae06c568cfd269aaaebfb994
7,907
def cache_mat_calc(dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cor=None, l_max=1, fit_type="full", num_iter=None): """Calculate cache matrix for future use Parameters ---------- dra/ddc : array of float R.A.(*cos(Dec.))/Dec. differences dra_err/ddc_err : array of fl...
805ecc94165ae1162341abdc7c4dd3557af5f8c4
7,908
def get_android_replacements(): """Gets a dictionary of all android-specific replacements to be made.""" replacements = {} compileSdk = 'compileSdkVersion {}'.format(COMPILE_SDK_VERSION) targetSdk = 'targetSdkVersion {}'.format(TARGET_SDK_VERSION) buildToolsVersion = 'buildToolsVersion \'{}\''.form...
e3b78d7ccd897d79db66740d46aa05410dd2a83f
7,909
from typing import List from typing import Set from typing import Dict def process_long_term_idle_users( slack_data_dir: str, users: List[ZerverFieldsT], slack_user_id_to_zulip_user_id: SlackToZulipUserIDT, added_channels: AddedChannelsT, added_mpims: AddedMPIMsT, dm_members: DMMembersT, z...
4a372837ed5497117227e18534c91c6f0ce840bf
7,910
def clear_cache(): """ Clears internal cache. Returns something that can be given back to restore_cache. """ global FS_CACHE old = FS_CACHE FS_CACHE = {} return old
492513177a70cd663671616e034c6f3b287ceb75
7,911
import tqdm def extend_gdf(gdf_disjoint, id_col): """ Add duplicates of intersecting geometries to be able to add the constants. This function adds rows with duplicate geometries and creates the new `id` column for each of the new rows. This function is called by another function `complete_disjoi...
5d6667b67c47125f8668bb6127b4a295fb2d61c9
7,912
def schedule_news_updates(update_interval:int, update_name:str)->dict: """ Functionality: --------------- Schedules a new news data update Parameters: --------------- update_interval: int The time until the scheduler should update the news dat...
1e2bf07aae3e2468f1ee0ff119b492820d866460
7,913
def get_digits(text): """ Returns all numeric characters (digits) in string *text* in a new (concatenated) **string**. Example: >>> get_digits('Test123') '123' >>> int(get_digits('The answer is 42')) 42 :param text: The string to search. :type text: str, uni...
78bcd49b74dbdfd7d9f40af3806c2b984adca780
7,914