content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def fft_fftn(*args, **kwargs): """Call the core fft library function fftn. If the anfft library is used, enable 'measure' optimization. """ if using_fft_library == "anfft": return fft.fftn(*args, measure=True, **kwargs) else: return fft.fftn(*args, **kwargs)
804bd06b668edb98e646885561df833a4eedcdfa
42,595
import psutil def total() -> int: """ The total amount of space provided by the storage. :return: The amount of storage space in Bytes. """ storage = psutil.disk_usage('/') return storage.total
26435b41c0fa894db2bb24c6a04b1e39ae35b386
42,597
import functools import time def timing(unit="millisecond", message="{func.__name__}() {time:.3f} {unit}"): """Measures the execution time of the function. The value that can be used for specified the ``unit`` parameter are: ======== ================= ================== Short Long ...
73a7b2db1ebf01ee16a811f67ca6c10ca55b379d
42,599
import copy import six def cloud_init_interface(name, vm_=None, **kwargs): """ Interface between salt.cloud.lxc driver and lxc.init ``vm_`` is a mapping of vm opts in the salt.cloud format as documented for the lxc driver. This can be used either: - from the salt cloud driver - because y...
d6ff5cae7655e6a30e1d6f1a95af948ab78aeebb
42,601
def fdc_flux_and_wind(timestamp, sonicU, sonicV, sonicW, sonicT, heading, rateX, rateY, rateZ, accX, accY, accZ, lat): """ Description: Calculates the 3 L2 flux data products and the 3 L1 wind direction data products from the FDCHP instrument. It is anticipated that wrappe...
404034af0f70f7e9aeb49a3b7b00a6267bc3c546
42,602
def to_class_name(value): """Convert the current view's object to a usable class name. Useful for outputting a css-class for targetting specific styles or javascript functionality on a per-view basis, for example: <div class="siteContainer {% if request.path == '/' %}home{% else %}{{ object|to_class_n...
384f566d3808c19d7ba1357b7cddc69a92ca0b5a
42,603
def _create_fold(X, ids): """Create folds from the data received. Returns ------- Data fold. """ if isinstance(X, list): return [x[ids] for x in X] elif isinstance(X, dict): return {k: v[ids] for k, v in X.items()} else: return X[ids]
8c1308913f470632657b909114806875a30fa17f
42,605
def kill_background_grayscale(image, bg): """Make the background 0 Args: image (3-D array): Numpy array (H, W, C) bg (tuple): RGB code of background (R, G, B) Returns: image (2-D array): Binarized image of shape (H, W) The background is 0 and everything else is 1 """ ...
11314c91224b545365302d48bf124c40da1fd7fb
42,606
def smooth(x: np.ndarray, window_len: int = None, window: str = "flat") -> np.ndarray: """Smooths the data using a window with requested size. Code from https://scipy-cookbook.readthedocs.io/items/SignalSmooth.html This method is based on the convolution of a scaled window with the signal. The signal i...
a7be7852401828ada3012cdc2a1fb897e7c0a353
42,607
def average_inter_cluster_distance(data, cluster_labels, centroids): """ Computes the average inter-cluster distance i.e the average distance between all clusters. We have assumed the distance between two clusters is the distance between the centroids of said clusters Args: data (ndarray):...
01a2348650dc656d1b293d9138a8450955e6a2d0
42,608
def is_model(val): """Returns true if the value represents a valid model. This is a custom validator that Connexion uses to verify the model field in request bodies. Keyword arguments: val -- the model value """ if val is None: return True model = Model() allowed_models = ...
96d8482b32b42cf510fe3dd0b49559885428bcbb
42,611
def eval_one_epoch(sess, coord, model, cv_num_batch, epoch): """ Cross validate the model on given data. """ d_counter = 0 g_counter = 0 cv_g_adv_loss = 0.0 cv_g_mse_loss = 0.0 cv_g_l2_loss = 0.0 cv_g_loss = 0.0 cv_d_rl_loss = 0.0 cv_d_fk_loss = 0.0 cv_d_loss = 0.0 # We run D...
02d58f04c514dfd20a7be139a9daa0352c540945
42,612
def calculateCurvature(yRange, fit_cr): """ Returns the curvature of the polynomial `fit` on the y range `yRange`. """ return ((1 + (2*fit_cr[0]*yRange*ym_per_pix + fit_cr[1])**2)**1.5) / np.absolute(2*fit_cr[0])
6f949d46604287e0555f297ee4b777b0f132f594
42,614
def globals_videos_filter(find): """ SECTION : channel, videos, comment DESCRIPTION : Find substrings from the channel title to narrow down the search results. USAGE : Extraction of the comments takes less number of videos after the tile search. """ # ====================== Setup ===============...
1dd65be99dc570bcf2b1be2b6c9f74e877b889f3
42,615
def Msg(schema, msg): """Report a user-friendly message if a schema fails to validate. >>> validate = Schema( ... Msg(['one', 'two', int], ... 'should be one of "one", "two" or an integer')) >>> validate(['three']) Traceback (most recent call last): ... InvalidList: should be on...
16d1382ef0fe9d8c8476b8773d98405e89e75f85
42,616
def leaf_hyponyms(synset): """ Get the set of leaf nodes from the tree of hyponyms under the synset """ hyponyms = [] _recurse_leaf_hyponyms(synset, hyponyms) return set(hyponyms)
fef038beadca56b8c1ff9af2313b669aff667276
42,617
def rand_sol(A, b): """Generate a random solution to the equation Ax=b.""" assert np.linalg.matrix_rank(A) <= len(b) A_plus = np.linalg.pinv(A) x = A_plus @ b return x + (np.eye(x.shape[0]) - A_plus @ A) @ np.random.normal(size=x.shape)
df5256180f50bebe6fb9836247694e2a63c3d0b6
42,619
def get_fig_axes_lpr(dims=(8, 6), facecolor='#ffffff', gridcolor='#e0e0e0'): """ Get a matplotlib figure object, with lpr-themed face and gridcolors. This theme is white background, gray gridlines, and .5 alpha. """ fig, ax = get_fig_axes(dims, facecolor, gridcolor) fig.patch.set_alpha(0.5) ...
f6f096f24c54f4f522c84fbc9df910d9d5a7dd6d
42,620
import functools def read_dataset(cfg, file_pattern, training=False): """Reads a dataset, and handles repetition and shuffling. Args: file_read_func: Function to use in tf.contrib.data.parallel_interleave, to read every individual file into a tf.data.Dataset. file_pattern: A file patte...
6db095958ac9d809fce32ca9a0c725e6169bcc2d
42,621
def _add_option_if_supported(repository_ctx, cc, option): """Checks that `option` is supported by the C compiler. Doesn't %-escape the option.""" result = repository_ctx.execute([ cc, option, "-o", "/dev/null", "-c", str(repository_ctx.path("tools/cpp/empty.cc")) ]) return [o...
458c750790e1518b362d76299c5b1c23cde0fc17
42,622
from typing import Optional from typing import Sequence from typing import Mapping def get_volume(filters: Optional[Sequence[pulumi.InputType['GetVolumeFilterArgs']]] = None, most_recent: Optional[bool] = None, tags: Optional[Mapping[str, str]] = None, opts: Optional[pulum...
b70f9331ffea137144c57d6076c40bf26b7d11d4
42,623
import requests async def getWikiSummary(message, title): """ Display the wikipedia article summary of the article with the given title Parameters: message - discord.client.message object being responded to title - string of the wikipedia article title """ try: query = ( ...
a0443a1f7954b02c80ba9cc1de0de931cbc07af8
42,624
def tilted_L1_prox_1d(x, step, quantile=0.5): """ prox(x) = argmin_z rho_quantile(z) + (0.5 / step) * ||x - z||_2^2 See Lemma 1 of ADMM for High-Dimensional Sparse Penalized Quantile Regression """ if step < np.finfo(float).eps: return 0 t_a = quantile * step # tau / alpha if x >...
68597383b68c5cc8cf44aabe23fd6815d54bd2ec
42,625
import pickle import json def set_task_params(data, workspace): """根据request设置task的参数。只有在task是TaskStatus.XINIT状态时才有效 Args: data为dict,key包括 'tid'任务id, 'train'训练参数. 训练 参数和数据增强参数以pickle的形式保存在任务目录下的params.pkl文件 中。 """ tid = data['tid'] train = data['train'] assert ...
01b1ca6aaf981fb8835d0c45ad48d0602dda4185
42,627
import opcode def extractPkScriptAddrs(version, pkScript, netParams): """ extractPkScriptAddrs returns the type of script, addresses and required signatures associated with the passed PkScript. Note that it only works for 'standard' transaction script types. Any data such as public keys which are ...
db417d2dc486835b9510c106be2396de6d561665
42,628
from app import app import re def process_dollar(api_dict): """ 输入:{'value': 'xfjc@zb', 'lx': "xfxs_cfxfbz", "name": "$index", "index": "xfjc"} 输出:{'value': 'xfjc@zb', 'lx': "xfxs_cfxfbz", "name": "xfjc", "index": "xfjc"} """ # 处理 $引用 # order = -$index name=$timetype name=$qh # tra...
54d28069fa87ce1a59e6b7ebf39fc47e2f93dd0c
42,629
def dict_map(**fs): """Map especific elements in a dict. Examples: ```pycon >>> dict_map(a=int, b=str)(dict(a='1', b=123, c=True)) {'a': 1, 'b': '123', 'c': True} >>> ``` """ def _change_dict(d): d = d.copy() for k, f in fs.items(): if k in d: ...
ac67bf69df2aa1aead3da7443a83a09974f8a545
42,630
def Create(database_ref): """Create a database session.""" client = apis.GetClientInstance('spanner', 'v1') msgs = apis.GetMessagesModule('spanner', 'v1') req = msgs.SpannerProjectsInstancesDatabasesSessionsCreateRequest( database=database_ref.RelativeName()) return client.projects_instances_databases_s...
9b132156d2fc5b3c7081806373f32092cd2b268c
42,632
def q12_jac(qs, epsilon): """The Jacobian of the mapping from q1, q2 to costheta, phi """ s2 = sinh(epsilon*qs[1]) c2 = cosh(epsilon*qs[1]) sp = sinh(epsilon*(qs[0] + qs[1])) sm = sinh(epsilon*(qs[0] - qs[1])) cp = cosh(epsilon*(qs[0] + qs[1])) cm = cosh(epsilon*(qs[0] - qs[1])) cs...
484226905c6da48b5ae6ba8fa185bfb8a11e0292
42,633
from typing import Any def lambda_handler(event: dict, context: Any): """ :param event: S3 notification event :param context: Lambda Context runtime methods and attributes """ input_prefix = 'raw/' input_suffix = '.csv' output_prefix = 'transformed/' output_suffix = '.snappy.parquet' ...
bbf03e278a5c908d8d903db7a7d867d34c5d3b31
42,634
def normalize_name(name): """ Given a key name (e.g. "LEFT CONTROL"), clean up the string and convert to the canonical representation (e.g. "left ctrl") if one is known. """ if not name or not isinstance(name, basestring): raise ValueError('Can only normalize non-empty string names. Unexpect...
bfb07c13c1cbe9ec92c43cb87edb19aab7135fc9
42,635
from typing import Callable from typing import Any import asyncio def bmasync(func: Callable[[Any], Any]) -> Callable[[Any], Any]: """async function decorator""" _setup_loop() @wraps(func) def wrapper(*args, **kwargs) -> Any: return asyncio.ensure_future(func(*args, **kwargs)) return wra...
88782e0b71d5aa19b741973d03f0c959723deb95
42,637
def goto_y(new_y): """ Move tool to the new_y position at speed_mm_s at high speed. Update curpos.y with new position. If a failure is detected, sleep so the operator can examine the situation. Since the loss of expected responses to commands indicates that the program does not know the exact po...
de28ca9d2b495f5a7915b76c291a060c91292884
42,638
import copy def _nested_loop_join_outer(g_list, arg_str, bindings, operands): """ E.g Join two Predicates P1(x,y) and P2(x,z,y) with groundings (x1,y1) : g11 (ground object) and (x1,z1,y1) : g12 (x2,y2) : g21 (ground object) and (x2,z2,y2) : g22 (x1,y3) : g31 (ground object) an...
b54f45cd1bbc1f92dd85d25e57400bafe7a92a29
42,639
def StrContains(input_string, substring): """ Return True if the substring is contained in the concrete value of the input_string otherwise false. :param input_string: the string we want to check :param substring: the string we want to check if it's contained inside the input_string :return: Tr...
b04c22d567be6d1fce664f99719169b4585d75ea
42,640
def rescale_frontoparallel(p_fp,box_fp,p_im): """ The fronto-parallel image region is rescaled to bring it in the same approx. size as the target region size. p_fp : nx2 coordinates of countour points in the fronto-parallel plane box : 4x2 coordinates of bounding box of p_fp ...
6a3f817146ad22c67e99b558c24358cc39f40c62
42,641
from typing import Iterable def get_closest(iterable: Iterable, target): """Return the item in iterable that is closest to the target""" if not iterable or target is None: return None return min(iterable, key=lambda item: abs(item - target))
9548954317e90574d7a6d232bc166bde2eea7863
42,642
def has_tf_tensor(input): """Check if a variable is a `tf.tensor` or nested list of `tf.tensor`s.""" return has_tensor(input, 'tf')
171622c11ec9dd79176a8abd544cbf2dd0a309a4
42,643
from datetime import datetime def datetime_from_isformat(date_string): """Construct a datetime from the output of datetime.isoformat().""" if not isinstance(date_string, str): raise TypeError('fromisoformat: argument must be str') # Split this at the separator dstr = date_string[0:10] tst...
46df2bbba6160f6931ed9d3fe122178be1498da0
42,644
def merge_two_reconstructions(r1, r2, config, threshold=1): """Merge two reconstructions with common tracks.""" t1, t2 = r1.points, r2.points common_tracks = list(set(t1) & set(t2)) if len(common_tracks) > 6: # Estimate similarity transform p1 = np.array([t1[t].coordinates for t in com...
2982da052533bb7bb822c0d313c952f6a21c340a
42,645
def _reorder_for_extension_array_stack(arr, n_rows: int, n_columns: int): """ Re-orders the values when stacking multiple extension-arrays. The indirect stacking method used for EAs requires a followup take to get the order correct. Parameters ---------- arr : ExtensionArray n_rows, n_...
7e7521137d62ed4d98f11aead367c0e00c8aad65
42,646
import scipy def RemoveBackground(_tod, rms,x,y, sampleRate=50, cutoff=1.): """ Takes the TOD and set of indices describing the location of the source. Fits polynomials beneath the source and then applies a low-pass filter to the full data. It returns this low pass filtered data """ time = np....
796cf3361753823d4ae456d05c78af24cf6d4017
42,647
import collections def utils_vlan_ports_list(duthosts, rand_one_dut_hostname, rand_selected_dut, tbinfo, ports_list): """ Get configured VLAN ports """ duthost = duthosts[rand_one_dut_hostname] cfg_facts = duthost.config_facts(host=duthost.hostname, source="persistent")['ansible_facts'] mg_fac...
e9d0c5aa6fbfbfe9fe5ecce4e389c6f286ee875b
42,648
def GetExtraVars(): """Returns the captured variables by the function.""" g = tf.get_default_graph() if isinstance(g, func_graph.FuncGraph): return g.variable_captures return function.get_extra_vars()
f460ef66895d07b28f18001d5602cd20c1e581f6
42,649
def get_log(): """Get the filtered setAttr commands from the logs. :return: List of all setAttr commands. """ with open(FILE_NAME, "r") as f: attr_log = [line for line in f.read().splitlines() if line.startswith("setAttr") and not "|" in line] return attr_log
c0f55748dc6153b8beb7b6a9cd1cb19742354ab6
42,650
from typing import Callable def on_epoch_complete(func: Callable) -> FunctionCallback: """Decorator for creating a callback from a function. The function will be executed when the ``Events.EPOCH_COMPLETE`` is triggered. The function should take :class:`argus.engine.State` as the first argument. """ ...
35603f263f65b99d05dfd54dcae06b208523922c
42,651
def normalise(matrix): """Normalises the agents' cumulative utilities. Parameters ---------- matrix : list of list of int The cumulative utilities obtained by the agents throughout. Returns ------- list of list of int The normalised cumulative utilities (i.e., utility share...
594a46c9f1f741509ac56439779597545e63f25d
42,652
def rgb_to_irg(rgb): """ converts rgb to (mean of channels, red chromaticity, green chromaticity) """ irg = np.zeros_like(rgb) s = np.sum(rgb, axis=-1) + 1e-6 irg[..., 2] = s / 3.0 irg[..., 0] = rgb[..., 0] / s irg[..., 1] = rgb[..., 1] / s return irg
09a2e76c85c1f08d4db4332bdc32db7d94270710
42,653
def basic_nmt_bilstm_luong_att(): """Hparams for LSTM with luong attention.""" hparams = base_nmt_bilstm(base_att(base_nmt())) hparams.add_hparam("attention_gnmt", False) hparams.add_hparam("attention_mechanism", "luong") return hparams
99c7e3fbd693043bffca3f6b577c15544d733511
42,654
def remove_projection_from_vector(v: Vector, w: Vector) -> Vector: """projects v onto w and subtracts the result from v""" return subtract(v, project(v, w))
6bae31bb928bb6638334895a182ffab177921d31
42,655
def KK_RC77_fit(params, w, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params["Rs"] R1 = params["R1"] R2 = params["R2"] R3 = params["R3"] R4 = params["R4"] R5 = params["R5"] R6 = params["R6"] ...
bf613e9cd228ceb42679a36e1225f72092dd898b
42,656
import glob def check_scope( outdir: str, logger: Logger = getLogger(__name__) ) -> int: """ Check if result is present in outdir. Parameters ---------- outdir : str The folder where results heve been written. logger : Logger The logger object. Returns -------...
71462c2d2a892c36cc8cade32a94cceaac644665
42,657
def cvRetrieveFrame__Deprecated(*args): """cvRetrieveFrame__Deprecated(CvCapture capture, int streamIdx = 0)""" return _highgui.cvRetrieveFrame__Deprecated(*args)
58608bda7bf2cf8c75f5268586be20e3521a5a46
42,658
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('ups_view'...
e8380d1fb4df37ed26c9a24494571657a3cd3e10
42,659
def polynomial_graph_filter(coeff: np.array, laplacian: np.ndarray): """ Return the laplacian polynomial with coefficients 'coeff'. """ power = np.eye(laplacian.shape[0]) filt = coeff[0] * power for n, c in enumerate(coeff[1:]): power = laplacian @ power filt += c * power return filt
b0276c1e392f258adc9479760a171e06378310aa
42,660
def normalize(comic, face): """ Normalize the images to [-1, 1] """ # YOUR CODE HERE comic = (tf.cast(comic, tf.float32) /255.0 *2) -1 face = (tf.cast(face, tf.float32) /255.0 *2) -1 return comic, face
6299e3640a623006d24720bbf371d7cdfd471df8
42,661
from typing import Tuple from typing import Mapping def label_array_3d() -> Tuple[np.ndarray, Mapping[Coordinates, ArrayLike[Number]]]: """Convenience method to return a 3D label array with corresponding physical coordinates.""" label_array = np.zeros((2, 5, 6), dtype=np.int32) label_array[0, 0] = 1 l...
052728d13210fe3b97717e5e38f42f1a3fd4ce78
42,665
def cmdline_from_pid(pid): """ Fetch command line from a process id. """ try: cmdline= open("/proc/%i/cmdline" %pid).readlines()[0] return " ".join(cmdline.split("\x00")).rstrip() except: return ""
61ca5cf3f109863e516a861f76dafd1d6e9dc749
42,666
def none_if_empty(tup): """Returns None if passed an empty tuple This is helpful since a SimpleVar is actually an IndexedVar with a single index of None rather than the more intuitive empty tuple. """ if tup is (): return None else: return tup
26ee7bb9720eaa532d901b9c1f6c4a0fb6f7a340
42,667
def print_melhor_time(funcao_atual_ou_futuro): """Função que imprirmi o melhor time. Parameters ---------- funcao_atual_ou_futuro : list Lista contendo um time de jogadores Returns ------- str Texto organizando o time por posição """ gol, zag1, zag2, l...
99c41728dea118cbcd8b6c61188f33f25a8663d1
42,668
def info_from_giphy(info, url): """Populate info object with info from *.giphy.com url.""" log("--- Detected giphy") url = url.replace("media.giphy.com", "i.giphy.com") url = url.replace("media1.giphy.com", "i.giphy.com") url = url.replace("media2.giphy.com", "i.giphy.com") url = url.replace("gi...
dc3ce8ba6614b0a9d300fd779e1bffa24db21cce
42,669
def gcf(): """获取当前Axis""" global g_figure return g_figure
d77418bfb11b8327cbbf4715ebe778c7b0458649
42,670
def postrefine_frames(i_iter, frames, frame_files, iparams, pres_set, miller_array_ref, avg_mode): """postrefine given frames and previous postrefinement results""" miller_array_ref = miller_array_ref.generate_bijvoet_mates() txt_merge_postref = 'Post-refinement cycle '+str(i_iter+1)+' ('+avg_mode+')\n' txt_mer...
bb64a6e26ad4188d69eee027e1e19188db95d759
42,671
def backend2(threescale, backend_usages): """ Second bound backend Should deliver slight performance improvement """ return threescale.backends.read(backend_usages[1]["backend_id"])
4111d6f536aaea2e407e8ce00db27612561d4156
42,672
from typing import List from typing import Optional import numpy def gen_cr_from_active_set(program: MPQP_Program, active_set: List[int], check_full_dim=True) -> Optional[ CriticalRegion]: """ Builds the critical region of the given mpqp from the active set. :param program: the MQMP_Program to be sol...
40c12cb236b077385001b32acea311fa38473e06
42,673
def get(): """Get peaks dataset. """ # Get hosp. capacity data data = capacidad_hospitalaria.get() # Do not consider rows with UCI status. data = data[~data['estatus_capacidad_uci'].isnull()] # Find peaks and its statistics peaks = [] for hospital, hospital_data in data.groupby('n...
f807aca8a380c441b9fcd4b35eef95c6410f5d1e
42,674
import re def extract_group_to_individual_class(df, parts_group, df_body_parts): """ Extract multiple keys from dataframe and combine them in a trackedgroup Inputs: _______ df : dataframe parts_group : string df_body_parts: list of strings """ parts_group_label = list(filter(lambda...
89bfe6cd5ab664bff4c04fc1df208354775572ba
42,675
import functools def without_apply_rng(f: TransformedT) -> TransformedT: """Removes the rng argument from the apply function. This is a convenience wrapper that makes the ``rng`` argument to ``f.apply`` default to ``None``. This is useful when ``f`` doesn't actually use random numbers as part of its computat...
e7fbc7c483602a35eb92218ce81592d3e78ac14d
42,676
def has_events(doc, include_negatives=False): """ Parameters ---------- doc: Document include_negatives: Count document as having events when at least one trigger is not an abstain Returns ------- Whether the document contains any (positive) events """ if "events" in doc and doc...
f477acc68b7e4f539984c7b1fb227300a08d6e9e
42,677
def update_named_ports(mig, named_ports): """ Set the named ports on a Managed Instance Group. Sort the existing named ports and new. If different, update. This also implicitly allows for the removal of named_por :param mig: Managed Instance Group Object from libcloud. :type mig: :class: `GC...
3a2bd1f591e32629b6257454a491173fb96824e2
42,678
from typing import List def get_allowable_kernels() -> List[str]: """Get all allowable kernel families. :return: """ return list(KERNEL_DICT.keys())
4824c23003e34f56d78473e2065fb03f6907655d
42,679
def lrCostFunction(theta, X, y, lambda_): """Compute cost and gradient for logistic regression with regularization J = lrCostFunction(theta, X, y, lambda) computes the cost of using theta as the parameter for regularized logistic regression and the gradient of the cost w.r.t. to the parameters. :pa...
3a1dcc2f1c8a739ef1ee7363dc13080fadc4d538
42,680
def coe2rv(coe, mu): """ Convert from Keplerian to Cartesian. Ref: Vallado 4th Ed. pg 118 Args: coe (numpy.array): 6x1 array with Keplerian orbital elements 1: semimajor axis (LU) 2: eccentricity 3: inclination (radia...
6b6ee90eee920c1db75ed6deaa904f37b5397420
42,681
import scipy def adjacency(dist, idx): """Return the adjacency matrix of a kNN graph.""" M, k = dist.shape assert M, k == idx.shape assert dist.min() >= 0 # Weights. sigma_list = [] for i in range(len(dist)): pos = 0 while dist[i, pos + 1] != np.inf: pos += 1 ...
424cfddb3ebc7e48c3ffb660c50ddca4f31e0782
42,684
import ipaddress def discover_webmention_endpoint(target: str) -> WebmentionDiscoveryResponse: """ Return the webmention endpoint for the given target. :param target: The target to discover the webmention endpoint for. :type target: str :return: The discovered webmention endpoint. :rtype: str...
1777dd340389d70b9b05846b98c3aa89a008ec80
42,685
def get_fts_endpoint(endpoint_str, key=None): """ Make a request to the FTS API for the given endpoint_str, and optionally takes a key for additional json filtering. Return the normalized json response as a pandas dataframe if successful, or None if not. Example: endpoint_str = '/public/fts/flow?year=20...
b9ed08af1bd76d803dd606d116d701878c7ecfa6
42,687
def highest_paying_jobs(fse_client, plane_type, distance_limit=None, minimum_pay=0, top_n=5, desired_trip_type=fse.TripTypes.TRIP_ONLY): """ For a type of aircraft find the top N which are rentable and have best $/NM jobs (accounting for capacity) :param desired_trip_type: Set the t...
533662fa9c968be69791b3edeee3d0f973a0379a
42,689
def load_raf_db(): """ load RAF-Db dataset :param batch_size: :return: """ print('loading RAF-Db dataset...') train_dataset = RafFaceDataset(train=True, type='basic', transform=transforms.Compose([ transforms.Resize(22...
f1a6f42d4383d1b9c9c7a2f466ba76bdbca2815f
42,690
import decimal def compute_tuple(lat, lon, resolution, slice): """Computes the tuple Geobox for a coordinate with a resolution and slice.""" decimal.getcontext().prec = resolution + 3 lat = decimal.Decimal(str(lat)) lon = decimal.Decimal(str(lon)) slice = decimal.Decimal(str(1.0 * slice * 10 ** -resolution)...
95d10fd9fcc87f611234a335b32f689625969c79
42,691
def cast_as_int(input_val): """ Args: input_val: A value of unknown type Returns: Int of the value, defaults to 0 if the value cannot be cast as an int. Examples: >>> cast_as_int('3') 3 >>> cast_as_int(3.55) 3 >>> cast_as_int('Three') 0 ...
a7b6f3c03573c7db7d814f13e5493adaee3327e4
42,692
def get_encoder(layer, in_features, hidden_size, bidirectional=True): """Returns the requested layer.""" if layer == "lstm": return LSTMEncoder(in_features, hidden_size, bidirectional=bidirectional) elif layer == "rcnn": return RCNNEncoder(in_features, hidden_size,...
106870327feae14e3c763ecdddfbe8dd2375666f
42,693
from typing import Tuple def sim_seird_decay( s: float, e:float, i: float, r: float, d: float, beta: float, gamma: float, alpha: float, n_days: int, decay1:float, decay2:float, decay3: float, decay4: float, end_delta: int, fatal: float ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """Sim...
5175c7445ac3b95677b6283085f040df16470ec3
42,695
def toR3(Q): """ Transformation from Dual Quaternion to Euclidian Space Coordinates Q: Symbolic Matrix (two - dimensional) """ z = np.array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, ...
e1a9b9baa888c656ffc1688d957133356005f9ef
42,696
def discharge(da_x, da_y, feats, key='name', reverse=False): """ Wrapper function to compute discharge over line segments in a geopackage (opened with fiona) :param da_x: DataArray - containing x-directional flow :param da_y: DataArray - containing x-directional flow :param feats: fiona features - ...
a7a3a61f51e2f1c0d4d8c336d8b9f9a8feee257a
42,697
from orchestra import settings def render_email_template(template, context): """ Renders an email template with this format: {% if subject %}Subject{% endif %} {% if message %}Email body{% endif %} context must be a dict """ if not 'site' in context: url = urlparse(setting...
41ec8b4342494cf80e1a1629c140fe37bc31288c
42,698
import re def parse_BIO_tag(tag): """Parse given string as BIO tag. The expected format is "[BIO]-TYPE", where TYPE is any non-empty nonspace string, and the "-TYPE" part is optional. Args: tag (string): tag to parse. Returns: string pair: tag ("B", "I" or "O") and TYPE. """ ...
63b8eb2cb3ac183f668a0e9bf788fb7bd4e1ac88
42,700
from typing import Sequence from typing import Mapping from typing import Any from datetime import datetime def create_schema( events: Sequence[Mapping[str, Any]], links: Sequence[Mapping[str, str]], tracking: Sequence[Mapping[str, Any]], schema_id: str, schema_name: str, schema_dscpt: str, ) ...
fbd0712edc694b0b45f67c452dbd84cdacb7ed68
42,701
import math def dadda_4to2_reduction(previous_bit_heap): """ BitHeap Wallace reduction using 4:2 compressors """ next_bit_heap = BitHeap() carry_bit_heap = BitHeap() max_count = previous_bit_heap.max_count() new_count = int(math.ceil(max_count / 2.0)) # each step reduce the height of the bit h...
0256791f9be19af3c64eaa93036fb3cffbc5ac95
42,702
def modification_oeuvre(identifier): """ Route gérant la modification d'une oeuvre :param id_publ: identifiant de l'oeuvre :return : affichage du template modifier_oeuvre.html ou redirection """ # On renvoie sur la page html les éléments de l'objet oeuvre correspondant à l'identifiant de la route if request.meth...
68e808c41f12300b37fcd74746fd0dbfe88e9def
42,703
def VisualizeAll3D(pts3D,ax,dataset_name, xlim, ylim, zlim): """ this function visualizes all 3D skeletons from one image the form if pts3D is 4 by n numpy array, rows 0,1,2 are x,y,z, row3 is always 1 """ bright_orange_cv2 = (255/255,79/255,0) bright_blue_cv2 = (0, 229/255, 238/255) ...
78eba088e513a3967dfe53a0ed02e3f218e9f640
42,704
def _contourf(darray, x='lon', y='lat', transform=None, # Facetgrids arguments figsize=None, size=None, aspect=None, ax=None, row=None, col=None, col_wrap=None, ...
d6e1ed39851f00323fad0ea154cd29d62e7a4bad
42,706
def chunk_textgrid_parser(textgrid_obj): """ Parsses the Textgrid of One Chunk and Returns a List Parameters ---------- textgrid_obj : praatio.Textgrid() One Chunk's Textgrid Object imported using praatio Returns ------- textgrid_dict : dict Dictionary of all of the Tiers f...
ab4d97da02ba0271e1549d4cb67a668e47008de6
42,708
def _set_values(loop_data): """Find rows corresponding to values in data This is a private function, not meant for general use. Input: dataframe Output: dataframe """ # These are the indexes of all the data that are unassigned value_indexes = loop_data.ix[(loop_data.loop==0)&...
8b246756a12e48f39cd0d1c04c282cbc1a537e5b
42,709
def abs(x): """Element-wise absolute value. # Arguments x: input tensor. # Returns A tensor. """ return KerasSymbol(mx.sym.abs(data=x.symbol))
9bc1f174aae297699f663aea4bb71a3954ec311f
42,710
def build_module( mod, target, params=None, enable_acl=True, tvm_ops=0, acl_partitions=1, disabled_ops=["concatenate"], ): """Build module with option to build for ACL.""" if isinstance(mod, tvm.relay.expr.Call): mod = tvm.IRModule.from_expr(mod) with tvm.transform.PassCo...
82b6c732f59b759fea8f886f7f8b9399f0be7a27
42,711
def plus_frequente_occurence(vecteur, valeur_par_defaut=None): """Wrapper de la méthode first_valid_index d'un Pandas.Series. Arguments d'entrée: vecteur (pandas.Series) valeur_par_defaut Arguments de sortie: (Python Object) """ return vecteur.value_counts(ascending=Fals...
e601ec1bf14a3668277767194615f98c28cae432
42,712
def _get_git_version(): """Return version of git we use (might be bundled)""" return __get_git_version(_git_runner)
07d598f345cff674ad4a6d52f14ecbf46e0df0ed
42,713
import rdflib as rl from nidm.core import Constants import json def create_cde_graph(restrict_to=None): """Create an RDFLIB graph with the FSL CDEs Any CDE that has a mapping will be mapped """ with open(cde_file, "r") as fp: fsl_cde = json.load(fp) fsl = Constants.FSL nidm = Consta...
00b8235cde1ab37f3c65586b1b4d3fb354e299ef
42,714
def trajectory(ddir, file_prefix): """ generate trajectory DataFile """ name = autofile.name.trajectory(file_prefix) writer_ = autofile.write.trajectory reader_ = _not_implemented return factory.DataFile(ddir=ddir, name=name, writer_=writer_, reader_=reader_)
f2a90ddcf96c040b0132b2f2b466089c443e36c4
42,715
import re import base64 def _decode_base64(data, altchars=b'+/'): """Decode base64, padding being optional. :param data: Base64 data as an ASCII byte string :returns: The decoded byte string. """ data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data) # normalize missing_padding = len(data...
b5acd6beefd5183889391ee2e6c0b92352b77870
42,716