content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def tempdir(files=None, **kw): """ A decorator for building a temporary directory with prepopulated files. The temporary directory and files are created just before the wrapped function is called and are destroyed immediately after the wrapped function returns. The `files` keyword shou...
300104a0540cd3e723879cec72badf63bf16abdd
42,600
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
from typing import Optional import os def convert_latex_to_xml( zip_file: str, latex_dir: str, norm_dir: str, xml_dir: str, log_dir: str, cleanup=True ) -> Optional[str]: """ Run expansion, normalization, xml conversion on latex :param zip_file: :param latex_dir: :param norm_dir: :para...
d7db481092b0172dd5d69d1f2608e7d67311c7e5
42,604
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
from os import getenv from typing import Mapping from typing import Any def _get_env_defaults() -> "Mapping[str, Any]": """ Produce a mapping of configuration keys to values set in the environment through environment variables. """ kwargs = {} for fld, param in config_fields(_FlatConfig): ...
04e2b1e86845272a93b50bc46b7771715d5105fc
42,609
def download_entity(): """Get entity file corresponding to ID=entity_id Returns: 200 OK: file (on success) 403 Forbidden 404 Not Found: Entity not found (on NotFoundWarning) 500 Internal Server Error (on error) """ user = set_user() try: if not 'ID' in reques...
d5949a11b89971b3b911fc99b7d412e26eb7075d
42,610
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
import os def load_image(path): """Load image to memory.""" imagelist = [] for image_file in os.listdir(path): image_path = os.path.join(path, image_file) image = Image.open(image_path).resize([224, 224]) image = np.array(image).astype(np.float) / 128 - 1 imagelist.append(...
72e7c9f865c6f8c0be65442e9e5e6f13aa7bc40a
42,613
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
import argparse def parse_args(argv): """Function parsing command-line arguments Args: argv: a list containing command line arguments Returns: src_dir: a list with source directory names, full path sulcus: a string containing the sulcus to analyze number_subjects: number ...
aa29d03df3d4550821e63e6e186581a29a35245b
42,618
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
def make_insert_sql( table, data, auto_update=False, update_columns=(), insert_ignore=False ): """ @summary: 适用于mysql, oracle数据库时间需要to_date 处理(TODO) --------- @param table: @param data: 表数据 json格式 @param auto_update: 使用的是replace into, 为完全覆盖已存在的数据 @param update_columns: 需要更新的列 默认全部,当指...
b9b699dc224a5660dfd87997787da09b93900bcb
42,626
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
import fileinput import logging import json def generate_tx_dict(): """Read files from stdin generated by print_txs.py and return a {tx_hash: tx} dictionary.""" txs = {} for i, raw_line in enumerate(fileinput.input()): if i % 100 == 0: logging.debug('processing tx %d', i) json...
60ced10384aa277175cd45921b460972f2989e35
42,631
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
import os import errno def check_pid(pid): """Check whether pid exists in the current process table.""" # Copied from psutil # https://github.com/giampaolo/psutil/blob/5ba055a8e514698058589d3b615d408767a6e330/psutil/_psposix.py#L28-L53 if pid == 0: return True try: os.kil...
1eae7b63bb6a9e6be89bf1883981700b8113ed63
42,636
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
import os def findFile(input): """ Search a directory for full filename with optional path. """ _fdir, _fname = os.path.split(input) if _fdir == '': _fdir = os.curdir flist = os.listdir(_fdir) found = False for name in flist: if not name.find(_fname): found = Tr...
6b9fe7ad0facef2f38cab67f0228e7ca68c7ca36
42,662
def build_argument_parser() -> ArgumentParser: """Build the argument parser.""" opts = ArgumentParser() opts.add_argument( dest='videopath', help='Path to the video to introspect', nargs='*', type=str, ) provider_opts = opts.add_argument_group('Providers') provid...
ef4f2a557c324854423443efbaae4bd895df6eb1
42,663
import os def get_latest_sha(repo): """ Returns latest git sha of given git repo directory. """ cwd = os.getcwd() command = "git rev-list -1 HEAD -- {0}".format(repo) os.chdir(repo) git_sha = process_helpers.run(command.split(" ")) os.chdir(cwd) return git_sha.strip()
fe32f5b4e58f6946ef56b86acd654e39d8f47c56
42,664
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 argparse def add_motifclust_arguments(parser): """Parsing arguments using argparse Returns ------- ArgumentParser an object containing all parameters given. """ parser.formatter_class = lambda prog: argparse.RawDescriptionHelpFormatter(prog, max_help_position=40, width=90) description = "Cluster mot...
d929975019efbdd8236d55cecdddd335915023ad
42,682
def out_line(name, attributes, value, formatter, join_char=";"): """Returns a single field correctly formatted and encoded (including trailing newline) @param name: The field name @param attributes: A list of string attributes (eg "TYPE=intl,post" ). Usually empty except for TEL and ADR...
99c0bf0d384d9a41ac199301977aa4d6da406aad
42,683
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
import sys import json def create_tokens(): """Creates a token from posted JSON request""" new_token = EmailToken.from_json(request.get_json(force=True)) existing_token = EmailToken.query.filter_by( token=new_token.token, token_type=new_token.token_type, ).first() print( ...
897f7cb2b801973f8b06628622faccc5f5cd082c
42,686
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
import os def get_dataset(inputs, args): """get dataset""" dataset = fluid.DatasetFactory().create_dataset() dataset.set_use_var(inputs) dataset.set_pipe_command("python ./dataset_generator.py") dataset.set_batch_size(args.batch_size) dataset.set_thread(int(args.cpu_num)) file_list = [ ...
ca3c2d33fb5393b52d1bbce5befb56de490e69f3
42,688
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
def make_input_fn(hparams, mode): """Construct a input function for training.""" def _input_fn(params): """Input function.""" if mode == contrib_learn.ModeKeys.TRAIN: src_file = "%s.%s" % (hparams.train_prefix, hparams.src) tgt_file = "%s.%s" % (hparams.train_prefix, hparams.tgt) else: ...
a24baa12ba8c12f3d539e0e713eaa0609cd15c41
42,694
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 sys def FF_Normal(inferred, ground_truth): """Compute the fitness for an individual. Takes in two images and compares them according to the equation (p + 2)^log(|m - n| + 2), where p is the pixel error, m is the number of segments in the inferred mask, and n is the number of segments in th...
7010c85080364dd23e41d8694c58b08bdf1d2378
42,699