content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import json def show_quick_pick(items: list, options: QuickPickOptions = None) -> QuickPickItem: """ Shows a selection list allowing multiple selections. Returns either the selected items or undefined. """ data = [] for item in items: if isinstance(item, QuickPickItem): da...
d30c376ea97c35b23ae43fd03ad2fb26eb7a4c9b
36,300
def merge(nums1, m: int, nums2, n) -> None: """ Do not return anything, modify nums1 in-place instead. """ if len(nums1) >= m + n: for num in nums2: nums1[m] = num m += 1 nums1.sort() return nums1
2c2e372e05b71981cab4796f62116e72e278c352
36,301
def create_sample_user(**params): """Creates sample user""" return get_user_model().objects.create_user(**params)
7e9ce097d699b1eb7b94916998d628c10f943935
36,302
from typing import Optional from typing import Tuple import torch def subset_model( model: Model, objective_weights: Tensor, outcome_constraints: Optional[Tuple[Tensor, Tensor]] = None, objective_thresholds: Optional[Tensor] = None, ) -> SubsetModelData: """Subset a botorch model to the outputs us...
cd220d39282f89b2abdca87a5b0b8e3a9ea08c8e
36,303
def relu_derivative(dA, Z): """ Implement the backward propagation for a single RELU unit. Arguments: dA -- post-activation gradient, of any shape cache -- 'Z' where we store for computing backward propagation efficiently Returns: dZ -- Gradient of the cost with respect to Z """ ...
8102fda6fbf03c01ff1ba2692faa7f8d918f011c
36,304
def compute_coupled_cell(f1,f2) : """ Computes the full-sky angular power spectra of two masked fields (f1 and f2) without aiming to deconvolve the mode-coupling matrix. Effectively, this is equivalent to calling the usual HEALPix anafast routine on the masked and contaminant-cleaned maps. :param NmtField ...
4ea78e0f2f330a42cd1e47f6684901ce87c3ac1c
36,305
def get_dates(time): """Obtain pandas datetime objects from date objects. Sometimes there are problems with 360 days calendars and cftime units in pandas. This function uses `dates_from_360cal` to circumvent this problem when pandas can't be used directly to generate a DatetimeIndex. Param...
ab20f97b835edfb3e49196646529f6ebe80025d5
36,306
def build_1tdm_costly(no,bra_space,ket_space,basis,spin_case): """ Copy of ca_ss Compute a(v1,v2,j) = <v1|a_j|v2> Input: no = n_orbs bra_space = (n_alpha,n_beta) for bra ket_space = (n_alpha,n_beta) for ket spin_case: 'a' or 'b' basis = dict of basis vectors ...
b6373204d19efc58e8bbe28fbd63dfb1d7eadb97
36,307
def read_words_pos(parse): """ Read the given parse string and return a list of tuples (token, pos_tag) in lower case. """ parse = parse.lower() tree = nltk.Tree.fromstring(parse) word_pos = [(word, map_wn_pos(pos)) for word, pos in tree.pos()] return word_pos
5d2ad55052df3d7f336eb75a061441688b4ec51f
36,308
def get_state_02y1_pure_state_vector() -> np.ndarray: """returns the pure state vector of :math:`\\frac{1}{\\sqrt{2}} (|0\\rangle - j|2\\rangle)`. Returns ------- np.ndarray the pure state vector. """ vec = np.array([1, 0, -1j], dtype=np.complex128) / np.sqrt(2) return vec
7efc28ee76f75fdc32052fc2b1658efebca13889
36,309
def check_input_allowed(object): """ This is a generic function called with the object being commented. It's defined as the default in 'COMMENTS_INK_APP_MODEL_OPTIONS'. If you want to disallow comments input to your 'app.model' instances under a given conditions, rewrite this function in your code ...
fae4c59a4326af5257302a48e7be18131e378371
36,310
import torch def eval_dev(dev_file, batch_size, epoch, shuffle, cuda, top_k, sender, receiver, desc_dict, map_labels, file_name, callback=None): """ Function computing development accuracy """ desc = desc_dict["desc"] desc_set = desc_dict.get("desc_set", None) desc_s...
c64f03d3c674b1cbfd4ebf6b6767d4e0b7c0f0a3
36,311
import tempfile import os import string def create_temp_dir(tmpdir=None): """Create a new unique directory at a given temporary directory""" if tmpdir is None: tmpdir = tempfile.gettempdir() elif not os.path.isdir(tmpdir): os.makedirs(tmpdir) # running into a rare issue with MAPDL on ...
eaaf54260a5462f013234480b5a8518e0cb4db5b
36,312
from typing import Any def is_dataclass_instance(obj: Any) -> bool: """Return True if the given object is a dataclass object, False otherwise. In py36, this function returns False if the "dataclasses" backport is not available. Taken from https://docs.python.org/3/library/dataclasses.html#dataclasses.is...
daca965952ab34fdefddd648152b8a974765c43e
36,313
import os def project_raster_ds(input_ds, output_raster, resampling_type, output_osr=None, output_cs=None, output_extent=None, input_nodata=None): """Project raster dataset to new spatial reference and/or cellsize Args: input_raster: output_raster: ...
444affd7563afa557decfe35ff40b3a26ea122dc
36,314
import re def isChr(s, c): """ :param s: String :param c: Chromosome, number or X or Y :return: Whether s matches c """ if 'X' == c: return 'X' in c if 'Y' == c: return 'Y' in c return str(c) in re.findall("[1-9][0-9]*", s)
b54666e3cf2c376bfbd687734eb40fc65f233c20
36,315
def get_mxnet_module_arg_params(x): """ given parameter name, get the updated value from mxnet module arg_params :param x: parameter values to (e.g. kernels, bias) :return: updated parameter values """ # retrieve from bind values first, which is up to date with # arg_params in mxnet mod...
d93b7fe25439bdb8fe032ec2c564d57b144dbaac
36,316
def psnr_denoise(y_true, y_pred): """"Calculating peak signal-to-noise ratio (PSNR) between two images.""" return tf.image.psnr(y_pred, y_true, max_val=1.0)
f5d061db0343b696c2fb01ad0f6db72baf59d02e
36,317
import os import csv def _count_files_to_amber(tumor_counts, normal_counts, work_dir, data): """Converts tumor and normal counts from GATK CollectAllelicCounts into Amber format. """ amber_dir = utils.safe_makedir(os.path.join(work_dir, "amber")) out_file = os.path.join(amber_dir, "%s.amber.baf" % dd....
c7430bd4f1d38df67dc8e846d96c6cb939077755
36,318
def humanize_duration(time_delta, show=None, sep=" "): """ Humanize a timedelta object. :param time_delta: the timedelta object to humanize. :param sep: specify a separator for days, hours, minutes and seconds in the final string. :return: a dict with keys: ``days``, ``hours``, ``mi...
0a1af033846805e461a4922e331147db08a8be25
36,319
import json def process_stats(args): """Process the VPP Stats. :param args: Command line arguments passed to VPP PAPI Provider. :type args: ArgumentParser :returns: JSON formatted string. :rtype: str :raises RuntimeError: If PAPI command error occurs. """ try: stats = VPPStat...
4dbf7cead63bbe7e7610a8d8a85d7e5f66c896e2
36,320
def loads(s, **kwargs): """ Deserialize an object from a bytestring. :param bytes s: the bytestring to deserialize :param kwargs: keyword arguments passed to :class:`CBORDecoder` :return: the deserialized object """ with BytesIO(s) as fp: return CBORDecoder(f...
117e293b66eace069a4fecfbc9b36323b722192b
36,321
import csv def TsvToXY(filePath): """This method reads .tsv file and returns the data, XY split in a tuple""" with open(filePath, 'r') as file: lines = list(csv.reader(file, delimiter='\t')) data = [] for line in lines: # for each line, split the PCM into a list listedLine = [] for column in line[:-1...
8cc05fba66d0f7f9c346955765e5a50c2cd7e33f
36,322
def nondimensional(): """ Factory associated with Nondimensional. """ return Nondimensional()
114372c208d70f51cdc09a5b84968256000ef8f3
36,323
def patch_configuration(client, configuration_id, patches): """ :param patches: List of patches in format [ {"op": op, "path": path, "value": value}, {"op": op, "path": path, "value": value} ] :return: requests Response """ data = [] data = patches return client._patch("/compa...
a229390fd8845238e1b5eeddb9922f79772b9840
36,324
def distributed_grads_and_ops_dedicated_workers( task_id, is_chief, num_worker_tasks, num_ps_tasks, master, checkpoint_dir, loss, accuracy, layer_collection): """Minimize loss with a synchronous implementation of K-FAC. Different workers are responsible for different parts of K-FAC's Ops. The first 60% o...
e2c93a30128f2ce9a6d87d22dbec5d45b9dd8355
36,325
def f_next_point_zeta(f2new: float,free_energyb: np.ndarray,za: np.ndarray,zb: np.ndarray,cova: np.ndarray,covb: np.ndarray,f1new: float,fa: np.ndarray,fb: np.ndarray) -> float: """ Free energy difference function of the next point to be optimized if the Number of points is greater than 1 Specialized for t...
b797a830401bc2ac30fac31c277a194fe6fc8104
36,326
async def async_setup(opp, config): """Set up ZHA from config.""" opp.data[DATA_ZHA] = {} if DOMAIN not in config: return True conf = config[DOMAIN] opp.data[DATA_ZHA][DATA_ZHA_CONFIG] = conf if not opp.config_entries.async_entries(DOMAIN): opp.async_create_task( o...
cc9d908c65bdf423338f64a5476a66937dd12591
36,327
def choice(*args, **kwargs): """ Wraps numpy random.choice call in ASPIRE Random context. """ seed = None if "seed" in kwargs: seed = kwargs.pop("seed") with Random(seed): return np.random.choice(*args, **kwargs)
1b35f02dac0d4639d9e2063a6ee9208cca798ea1
36,328
def convert_state_quara_to_qiskit( quara_state: State, ) -> np.ndarray: """converts Quara State to densitymatrix in Qiskit. Parameters ---------- quara_state: State Quara State. Returns ------- np.ndarray Qiskit density matrix of quantum state. """ qiskit_state...
cf581f24bea8dd1cb397fe6a4abb6aab80bccec1
36,329
import re def camel2snake(name): """ Args: name (str): camelCase Returns: str: snake_case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
9d4581b1f6731d7d572214676736d4e623d3fac0
36,330
def calc_nu_b(b): """Calculate the cyclotron frequency in Hz given a magnetic field strength in Gauss. This is in cycles per second not radians per second; i.e. there is a 2π in the denominator: ν_B = e B / (2π m_e c) """ return cgs.e * b / (2 * cgs.pi * cgs.me * cgs.c)
a4d6f15ce0e4e710f92954e2a978ef61ada60f01
36,331
def checking_if_table_exists(): """ Checking if table exists or not """ conn = connect(dbpath) c = conn.cursor() try: c.execute(""" SELECT name FROM sqlite_master WHERE type='table' AND name='webhooks'; """) res = c.fetchall() ...
274749e2210ee04aa33a840532f8a6bdfe6248f9
36,332
def can_represent_dtype(dtype): """ Can we build an AdjustedArray for a baseline of `dtype``? """ return dtype in REPRESENTABLE_DTYPES or dtype.kind in STRING_KINDS
06ea2f41cd3063e81a963a322509d1b87c180be8
36,333
from functools import reduce from operator import add from operator import sub from operator import mul from operator import truediv def calc_apply(operator, args): """Apply the named operator to a list of args. >>> calc_apply('+', as_scheme_list(1, 2, 3)) 6 >>> calc_apply('-', as_scheme_list(10, 1, ...
09fdb5ec5606bcfcf84606b925666de836a2afb2
36,334
def build_mpo_list(single_mpo, site_num, regularize=False): """ build MPO list for MPS. :param single_mpo: a numpy ndarray with ndim=4. The first 2 dimensions reprsents the square shape of the MPO and the last 2 dimensions are physical dimensions. :param site_num: the total number of sites :para...
7781bbd3f27905f685412a59a48dddf93e51cccf
36,335
def efun_git_status(paths: ldmud.Array) -> ldmud.Array: """ SYNOPSIS mixed** git_status(string* paths) DESCRIPTION For the given directories or files list any changes that are not committed. Returns an array for each such file: [0] Repository ...
6f126d4735dbcb46ffd65749a3713d9ba12831e3
36,336
import json import requests async def tx_t(context): """ PagerMaid universal translator. """ reply = await context.get_reply_message() message = context.arguments lang = 'zh' if message: pass elif reply: message = reply.text else: await context.edit("出错了呜呜呜 ~ 无效的参数。...
5070fc40a26599aaf727f824abef9bbee19dfb09
36,337
def resize_convex_hull_polygon(_convex_hull_points, _resize_ratio): """ 对凸包的多边形进行缩放 Args: _convex_hull_points: 凸包多边形的轮廓 _resize_ratio: 缩放比例 Returns: 缩放后的点 """ center_point = np.mean(_convex_hull_points, axis=0) diff_points = _convex_hull_points - center_point r ...
e7b46e54f4fb1983df117d1e47848ebf22a97527
36,338
def convert_xyz_to_rgb(source_color_xyz: tuple) -> tuple: """ Converts a color from the CIE XYZ 1931 to the RGB colorspace. Args: source_color_xyz: a tuple with X, Y and Z values of the color. Returns: a tuple with the R, G and B values of the color. """ logger.trace("Convert...
0d0ce8e01d286ff2ca218ec168659a21b3733c5e
36,339
def _lower_triangular_solve_sparse(M, rhs, dotprodsimp=None): """Solves ``Ax = B``, where A is a lower triangular matrix. Parameters ========== dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control exp...
6aaff272ff43c94cf80d1ea406b6603700469e06
36,340
def clip_to_frames_all(lena_mappings, human_mappings, consider_overlapped, frame_length=10): """ Returns the accumulated labelled frames for all 60 clips. """ total_lena = [] total_human = [] for i in range(1, 61): y_lena, y_human = clip_to_frames_single(i, lena_mappings, human_mappings, ...
ecc6ea71ba03599fd9b4de65a2e97f7731bc68ab
36,341
def _cart_id(request): """ If the user is logged in, retrieve the user associated cart_id from the database. If the user is anonym, then use the session to retrieve the cart_id. """ if request.session.get(CART_ID_SESSION_KEY, '') == '': request.session[CART_ID_SESSION_KEY] = _genera...
89599e3c43f433b5c09bfa929453c543c5a9ece2
36,342
def flatpage_nav(_): """ Context processor which adds data required for the main navigation of flatpages to the context. """ categories = flatpages_models.Category.objects.all() pages = flatpages_models.Flatpage.objects_without_category.all() return {'all_categories': categories, 'pages_withou...
acb3a6c76d830673f807204384d5aef99d18acc4
36,343
def ortho(left, right, bottom, top, znear, zfar): """Create orthographic projection matrix Parameters ---------- left : float Left coordinate of the field of view. right : float Right coordinate of the field of view. bottom : float Bottom coordinate of the field of view....
767e34a6b8a8538adb62545d9222567ac06b29a5
36,344
def to_str(bit_str): """Transform bit string in a string of characters""" chars = [] for i in range(int(len(bit_str) / 8)): byte = bit_str[i * 8:(i + 1) * 8] if byte == "11111111": break chars.append(chr(int(''.join([str(bit) for bit in byte]), 2))) return ''.join(cha...
db75acd548805eb06a383c8443a0a85631d8e65d
36,345
import os def get_scale_factor(value_dict, max_length=os.get_terminal_size().columns): """ Gets the scale factor from a dict of keys with numerical values """ max_value = max(value_dict.values(), key=abs) try: scale = max_length / abs(max_value) except ZeroDivisionError: scale ...
91aee90577a9ad9615128345276a98f83bc459d6
36,346
def compute_coeffs(track_y, track_t): """ Least squares polynomial fit to obtain step size. Parameters ---------- track_y : 1-D array with shape (3, ) Array containing the three smallest function values from applying either forward or backward tracking. Mus...
a46a07047fd564c10b7c553370e211c23bd0cc51
36,347
import os def get_debug_switch(): """The debug switcher >>> import os, jumon >>> os.environ['JUMON_DEBUG'] = 'True' >>> jumon.get_debug_switch() True >>> os.environ['JUMON_DEBUG'] = '' >>> jumon.get_debug_switch() None >>> value = os.environ.pop('JUMON_DEBUG') >>> jumon.ge...
f73f4d78aa94a8566d0c11b09b095b928daf84bb
36,348
import json async def test_route_message_with_existing_route(base_central_system, boot_notification_call): """ Test if the correct handler is called when routing a message. Also test if payload of request is injected correctly in handler. """ @on(Actio...
002b8d7bce1a68d51bc77472dc169b2d65015c89
36,349
def PyTmYDSminusYDS(y1, d1, s1, y2, d2, s2): """ Get difference between two year-day-seconds entries NOTE: the original Caris function doesn't take leap seconds into account Parameters ---------- y1: int, year 1 d1: int, day 1 s1: int, seconds 1 y2: int, year 2 d2: int, day 2 ...
891043cc38d9683a067e3f330bc213df2059f630
36,350
def random_pos(z_offset=0.2): """generate random position for dropping sphare Parameters ---------- z_offset : float, optional z offset, by default 0.2 Returns ------- pos list [x, y, z] random position """ pos = [np.random.randn() * 0.05, np.random.rand...
849a59542d55f9caa4eb6ab73d163f533274ee7a
36,351
import torch def filter2D(input, kernel, border_type='reflect', normalized=False): """ Convolve a tensor with a 2d kernel. """ if not isinstance(input, torch.Tensor): raise TypeError("Input border_type is not torch.Tensor. Got {}" .format(type(input))) if not ...
0e419bc6d6b0ea9d23689bdc49415be02bf0fc75
36,352
def get_all(ip_string): """ @ date: 2017-12-2 @ author: wxw @ function: 接口函数,产生num个线程,在队列中取出IP进行爬取 @ input: C段地址 如:182.40.12 @ output: 完成标志 0 (int) """ global queue_ip, mutex_href_get, mutex_href_put threads = [] # 线程数量 num = THREAD_NUM class_ip = ip_string proxy_ip...
900261d93ce070e4454b8cd88692a39479fc68a6
36,353
def scale(df, resolution=0.5): """ :param df: 5d-array [sample, steps, height, width, channels] :param resolution: float (0,1) """ df = ndimage.zoom(input=df, zoom=(1, 1, resolution, resolution, 1), order=1) print("Scaled") return df
fe55959c833cac6db202c468cdcb82f0cecfe661
36,354
def view_image(): """ View a Fullscreen version of an Image - called from Reports """ try: _id = request.args[0] except: return "Need to provide the id of the Image" table = s3db.doc_image record = db(table.id == _id).select(table.name, ...
10d2704a54cd32a67de8418de3db4a94674673c4
36,355
import struct def bits_ip_to_str(bit_ip : bitarray) -> str: """ 将比特形式的ip转成字符串形式,形如 '192.168.3.5' """ bytes_ip = bit_ip.tobytes() ip_num_list = struct.unpack('!BBBB', bytes_ip) str_ip = '' # 首次循环标志,如果不是首次循环的话就加一个'.' first_flag = 1 for i in range(0,4): if(1-first_flag): s...
39fcbeba281d8de0712f9c06c00d100c4ef4be17
36,356
def resolve_user_by_user_id(slack_wrapper, user_id): """ Resolve a user id to an user object. """ return slack_wrapper.get_member(parse_user_id(user_id))
eb6931f0902d1bc0fbdda883788e9e5cd90fff0a
36,357
from typing import Optional from typing import List from typing import Any def get_handler( theme: str, # noqa: W0613 (unused argument config) custom_templates: Optional[str] = None, setup_commands: Optional[List[str]] = None, **config: Any, ) -> PythonHandler: """Simply return an instance of `Py...
a6255211af0dbcc03dc95bed478347f0a38643d2
36,358
import logging def extract_temperature( df, value_threshold = 0, grad_threshold = 10, curve_threshold = 1e5, side = 'high', mask_window = 75, ): """ Finds the temperature coefficient from a PL curve. Performs a linear fit on the log of PL spectra on the low or high energy side. ...
ca04b8a6f9f48bf1ff1702ca38f47b89e9dfc8bd
36,359
import torch import warnings def near_eye_init( shape: tuple, is_complex: bool = False, noise: float = 1e-3 ) -> Tensor: """ Initialize an MPS core tensor with all slices close to identity matrix Args: shape: Shape of the core tensor being initialized. is_complex: Whether to initializ...
53fc514cec263be07f9e90e60370f1c06021b142
36,360
def stft( # pylint: disable=unused-argument signal, ax=None, limits=None, log=True, colorbar=True, batch=0, sample_rate=None, stft_size=None, stft_shift=None, x_label=None, y_label=None, z_label=None, z_scale=None, ): """ Plots a spectrogram from an stft signal as input. This is a wrapp...
25b9e71e510d5cfbc0d150dc545e8edf8958bb87
36,361
def match_text(pattern: str) -> Predicate: """ predicate for filtering messages which text matches the given regex :param pattern: regex to match :type pattern: str :return: Predicate :rtype: Predicate """ return match(pattern, "text")
66b66471d60df3e8312725e48ce96e1bf6d5a48f
36,362
import argparse from typing import List def create_optimizer_config(args: argparse.Namespace, source_vocab_sizes: List[int]) -> OptimizerConfig: """ Returns an OptimizerConfig. :param args: Arguments as returned by argparse. :param source_vocab_sizes: Source vocabulary sizes. :return: The optimiz...
278f834873458ef3f2244c3143fc54792aef946c
36,363
from typing import Tuple from typing import List def compute_lane_following_features( scene_df: pd.DataFrame, agent_list: list, precomputed_lanes: pd.DataFrame, raw_data_format: list, map_inst: ArgoverseMap, seq_id: int, obs_len: int, precomputed_physics: pd.DataFrame, # Configurab...
722f80219a128796b982aad917ef1e8477e3ef93
36,364
import platform def identify_operating_system(): """identify current operating system Returns: (str): 'Windows', 'Linux', or 'Darwin' for mac """ return platform.system()
05f4ec68aa535cdbef61c4cbf36d9cfc5a75fbcc
36,365
def vlog_exd(v:np.ndarray,t:np.ndarray,FileHeader:dict): """ Interpolation function used in genereatevmodel2 """ dt=FileHeader['dt'] nt=FileHeader['ns'] t2 = np.arange(0,nt*dt,dt) return np.interp(t2,t,v)
b4718b240639a56b3312b1bf45cb5dc7fcf26b76
36,366
def unpad(outputs, lengths): """Unpads a padded batch of waveforms to their initial lengths args: outputs ([B, num_samples_max] array): padded waveforms lens (list of ints): initial lengths before padding in features space. This needs to be multiplied by hop length to...
de93cd4f325920819c62d5f9bf10d4ca22102de5
36,367
def quote_preview_pdf(request, pk): """ This view returns a preview of our PDF file for a given quote """ # we get the selected item to use as the "object" context to be able to have some mockup data quote_instance = invoice.models.Quote.objects.get(pk=pk) quote_pdf_name = "quote-%s.pdf" % str(quote...
2837a15262a9e844345f8d684adb8129fbd1a1df
36,368
def check_uniq(X): """Checks whether all input data values are unique. Parameters ---------- X: array-like, shape (n_samples, ) Vector to check whether it cointains unique values. Returns ------- bool """ s = set() return not any(x in s or s.add(x) for x in X)
9a332ae5378374672201488637d76bd656b53264
36,369
def PrettyPrint(oData=None, hOutputFile=None, bToConsole=True, nIndent=0, sPrefix=None, bHexFormat=False): """ | **Function:** **PrettyPrint** Wrapper function to create and use a ``CTypePrint`` object. This wrapper function is responsible for printing out the content to console and to a file (depending on ...
f7b9957f9627d72c02cff0649c2609962cc66bac
36,370
def _get_object(lst, _id): """ Internal function to grab data referenced inside response['included'] """ for item in lst: if item['id'] == _id: return item
f18c6f330750f72d9495d1283ef28ef41cf58a97
36,371
def projected_projectedLinearEccentricity(a,e,W,w,inc): """ Args: a (numpy array): semi-major axis in AU e (numpy array): eccentricity W (numpy array): Longitude of the Ascending Node in Radians w (numpy array): Argument of periapsi...
ecc12d44022dda5dc744beab1122c0471389b82e
36,372
def isAntiCapability(capability): """Returns True if capability is an anticapability; False otherwise.""" if isChannelCapability(capability): (_, capability) = fromChannelCapability(capability) return isCapability(capability) and capability[0] == '-'
0ece8135d72ebc16d869a83e2848e00630ff9a04
36,373
import argparse def parse_args(): """ Parse input arguments """ global arguments parser = argparse.ArgumentParser( description='extract all the called apis from md or reST files.') parser.add_argument( 'dir', type=str, help='travel all the files include this dir...
453393fdf997aae35ec9266c2dbf5f9975abe1cd
36,374
import csv import json def decrypt_accession_id(request): """HTTP Cloud Function. Args: request (flask.Request): The request object. <http://flask.pocoo.org/docs/1.0/api/#flask.Request> Returns: The response text, or any set of values that can be turned into a Response obje...
04c41a7352b381dea9fb8453dea88c18342959f0
36,375
def search_astroph(keywords, arxiv_channel, old_id=None): """ do the actual search though astro-ph by first querying astro-ph for the latest papers and then looking for keyword matches""" today = dt.date.today() day = dt.timedelta(days=1) max_papers = 1000 # we pick a wide-enough search r...
1106794e8949d92800257c93c23e80fd0e9957c3
36,376
import argparse def _parse_args(argv): """Parses command-line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "--dataset", help="""Dataset to use for training and evaluation. """, required=True, ) parser.add_argument( "--job-dir"...
f991664fdd18766c60ce495fd216445e10b02aac
36,377
from typing import Tuple def make_cdl_pars_data_from_linregress( Cdl_dataprep: pd.DataFrame, xcol="scanrate", ycol="j_A_cm2", grpbykeys=[EvRHE, "SweepType"], ) -> Tuple[pd.DataFrame, pd.DataFrame]: """ Parameters ---------- Cdl_dataprep : pd.DataFrame A frame that is prepared f...
79436e80cf25f11fee1a834654273196be7c27c5
36,378
import yaml def increment_version(image_name: str, current_version: str, increment: str) -> str: """ :brief: increment app version. :param: current_version - current app version :param: increment - number to add to minor part of the current version :example: number - 2, 2+ 0.1.40(current version) ...
86aae5b4b3fc04c1d23f54afed166b07e869c739
36,379
def getfrom(v): """ pass through function for using the filter_for decorator directly """ return v
7a01fecbac63bca67fef10bfb39f8641e0cacda7
36,380
import math def projected_distance(ra1, ra2, dec1, dec2): """ Function that returns the projected distance (in arcminutes) between two points. """ if ra1 == ra2 and dec1 == dec2: return 0.0 else: dist = math.acos(math.sin(deg2rad(dec1)) * math.sin(deg2rad(dec2)) + math.cos(deg2rad(dec1)) * ...
6403b01cca702019edbe9d3cf6685d1b0b82ca7d
36,381
def get_dishes(restaurant, data): """ :type restaurant: meican.models.Restaurant :type data: dict :rtype: list[meican.models.Dish] """ sections = {} for section_data in data.get("sectionList", []): section = Section(section_data) sections[section.id] = section dishes = []...
8f3cfa00c48e2e75be70c016944f0cfae30c5939
36,382
import os import tqdm import json import re def cut_into_cells(input_path, output_path, labels_source, image_source, prediction_features, cell_shape, __test__=False, verbose=False): """ Divides a large image into cells fit for training using the data in the geojsons. :return X...
6e24da773069946e21ce4c9c726c87935b1953cb
36,383
import logging def setup_logger(level): """ Setup a logger for the REST handler """ logger = logging.getLogger('splunk.appserver.service_account_keys_rest_handler.rest_handler') logger.propagate = False # Prevent the log messages from being duplicated in the python.log file logger.setLevel(le...
dab40d34f7fcf47cf4506e3fbf838b423a13d823
36,384
def callit(callback, *args, **kargs): """Inspect argspec of `callback` function and only pass the supported arguments when calling it. """ maxargs = len(args) argcount = (kargs['argcount'] if 'argcount' in kargs else getargcount(callback, maxargs)) argstop = min([maxargs, argcoun...
92232a4c8c0927cbf8a3f0c592b5406862f7b9f0
36,385
def drop_nan_columns(data, settings): """ :param data: A list with pandas's DataFrame. :param settings: A dictionary with: * subset: optional list of column names to consider. * thresh: int, default None If specified, drop rows that have less than thresh non-null values. This overwrites th...
0a49305d03924f9f25ae6b3e159124e1d9b1fea5
36,386
from typing import Optional def crf_log_likelihood( inputs: Tensors, tag_indices: Tensors, sequence_lengths: Tensors, transition_params: Optional[Tensors] = None, ) -> tf.Tensor: """Computes the log-likelihood of tag sequences in a CRF. Args: inputs: A [batch_size, max_seq_len, num_tags]...
82ca8c7a3cda8fe91a37daa45112c9624a38367d
36,387
from datetime import datetime import time from typing import OrderedDict import os def memory_monitor(slot=0.1): """ Decorator: memory monitor. Args: slot(float): sampling frequency. Returns: func, memory: function output and memory usage. """ def _get_memory(monitor): ...
d491a44c5ef4331c4d6c48018fdf7d7037e540ba
36,388
def t_POUND(t): """header token""" # 如果header前面有换行 if t.value[0] == '\n': t.value = str(len(t.value) - 1) else: t.value = str(len(t.value)) return t
8625bb266d4ad9eec9f08a3edc81483c41e87aff
36,389
def nearby_difference(x): """Compute L2 norms for nearby entries in a batch.""" # This is a very rough measure of diversity. with tf.device('cpu'): x1 = tf.reshape(x, shape=[int(x.shape[0]), -1]) x2 = tf.roll(x1, shift=1, axis=0) return tf.sqrt(tf.reduce_sum(tf.square(tf.subtract(x1, x2))))
ead36d7e085024f67c717aa53e2cf651ec6f9cc6
36,390
import re def _split_article_sentences(article_text): """ Recieves a string containing the plain text of a wikipedia article Returns a list containing the sentences of the recieved article text """ def not_image_thumb(paragraph): """ True if the paragraph is wikitext for displayin...
5fca6ac2113a7c54456132d3afb2171bd8644603
36,391
import functools def get_metric(fn, tags): """ Wraps the metric function to decorate with additional tags """ @functools.wraps(fn) def wrapper(name, *args, **kwargs): # the metric name starts as the name of the function itself metric = fn.__func__.__name__ _tags = tags.cop...
a108c4610dc32495604c2e224f4d8ac2fae289c2
36,392
from pathlib import Path import os def run_NEMO_hindcast(parsed_args, config, *args): """ :param :py:class:`argparse.Namespace` parsed_args: :param :py:class:`nemo_nowcast.Config` config: :return: Nowcast system checklist items :rtype: dict """ host_name = parsed_args.host_name ssh_ke...
79fcfa5cf4cd4437512658bca8de5aef511ca339
36,393
import os import time def equation_plot(): """ Plot the "christmas equation" and some christmas background. """ def format_plot(sx, sy, st_x, st_y): # change plot style plt.xkcd() # switch off all labels plt.tick_params( axis='both', which='both...
89c04647452249ad42bc33bffd5226618eef5862
36,394
from typing import List import time def import_data(table: List[str] | None = None, url: str | dict | None = None, chunksize: int | None = None) -> tuple[DataFrame | Series, ...]: """ Importing data from database as a pandas DataFrame. :param table: List of table n...
d9749253eb387d7d6ff8163c08081df2e67b98d6
36,395
def accuracy_plot(a, b, z, ref, func): """Plot the relative error in using func to approximate hyp1f1. Parameters ---------- a, b: array_like Meshgrid of a and b values. z : float Value of the argument. ref : array_like An array of reference values, of the same shape as ...
df5bb002f2cb891c91ab702e81e5da05a8136d17
36,396
def plot_zero_check(amplitudes, properties, vars=['polar_angle', 'eccentricity'], hue='hemi', sum_idx=1, nan_check=False): """plot properties of voxels with zero or NaN amplitude after interpolation, some voxels may end up with zero amplitude for some reason, including because their coo...
091a4eeb507bd0124948c2e919923da3bcd72e7f
36,397
from typing import List def cum_sound_chunks(audio_frames: List) -> AudioSegment: """cummulate sound frames""" sound_chunk = pydub.AudioSegment.empty() for audio_frame in audio_frames: sound = pydub.AudioSegment( data=audio_frame.to_ndarray().tobytes(), sample_width=audio_f...
afa665459175422c1ab76b3bf11bd533ca68eb1e
36,398
import re def _nowiki_sub_fn(m): """This function escapes the contents of a <nowiki> ... </nowiki> pair.""" text = m.group(1) text = re.sub(_nowiki_re, _nowiki_repl, text) text = re.sub(r"\s+", " ", text) return text
dc6b7ed50d3828563863f01aff9a7eb2afd5a27b
36,399