content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def weighted_moments(values, weights): """Return weighted mean and weighted standard deviation of a sequence""" w_mean = np.average(values, weights=weights) sq_err = (values - w_mean)**2 w_var = np.average(sq_err, weights=weights) w_std = np.sqrt(w_var) return w_mean, w_std
84775550c54f285f9a032641cf27976eebf94322
6,400
def forestplot(data, kind='forestplot', model_names=None, var_names=None, combined=False, credible_interval=0.95, quartiles=True, r_hat=True, n_eff=True, colors='cycle', textsize=None, linewidth=None, markersize=None, joyplot_alpha=None, joyplot_overlap=2, figsize=None): ...
e2170c4bdbfc2fbf5c3db24688e8ab09a2ec498c
6,401
import yaml import sys import io import csv import gzip def write_file(filename, data, plain=False): # pylint: disable=too-many-branches """ Write a file, use suffix to determine type and compression. - types: '.json', '.yaml' - compression: None, '.gz' write_file('variable.json.gz') """ ...
e68c05b3d1b10fde32e89ce547e2c882e2862c7c
6,402
import glob import os def SetupPythonPackages(system, wheel, base_dir): """Installs python package(s) from CIPD and sets up the build environment. Args: system (System): A System object. wheel (Wheel): The Wheel object to install a build environment for. base_dir (str): The top-level build directo...
38b12bd7a7040d67a2172d1497f4d295739217b4
6,403
def tf_dtype(dtype): """Translates dtype specifications in configurations to tensorflow data types. Args: dtype: String describing a numerical type (e.g. 'float'), numpy data type, or numerical type primitive. Returns: TensorFlow data type """ if dtype == 'float...
0c51804974e7e1bb36fcc32f181cfab713fca263
6,404
from typing import Tuple import timeit def decode_frame(raw_frame: bytes, frame_width: int, frame_height: int) -> Tuple[str, np.ndarray]: """ Decode the image bytes into string compatible with OpenCV :param raw_frame: frame data in bytes :param frame_width width of the frame, obtained from Kinesis pay...
a38d7362997701756767cf466bb3fbb76b77a92e
6,405
def preprocess(picPath): """preprocess""" #read img bgr_img = cv.imread(picPath) #get img shape orig_shape = bgr_img.shape[:2] #resize img img = cv.resize(bgr_img, (MODEL_WIDTH, MODEL_HEIGHT)).astype(np.int8) # save memory C_CONTIGUOUS mode if not img.flags['C_CONTIGUOUS']: i...
ae44fdbf3613e159f28db0d9417470872439f76d
6,406
import requests def live_fractal_or_skip(): """ Ensure Fractal live connection can be made First looks for a local staging server, then tries QCArchive. """ try: return FractalClient("localhost:7777", verify=False) except (requests.exceptions.ConnectionError, ConnectionRefusedError): ...
b121e33a2294edc80d336abbb07c9a12f3301aea
6,407
def get_legendre(theta, keys): """ Calculate Schmidt semi-normalized associated Legendre functions Calculations based on recursive algorithm found in "Spacecraft Attitude Determination and Control" by James Richard Wertz Parameters ---------- theta : array Array of colatitudes in ...
8afd34e7e4805fab9393c2efff15c0cffcb9466a
6,408
def table_4_28(x_t, c_): """ Вывод поправочного коэффициента, учитывающего влияние толщины профиля arguments: относительное положение точки перехода ламинарного пограничного слоя в турбулентный (Х_т_), относительная толщина профиля return: Значение поправочного коэффициента""" nu_t_00 = [1.00, ...
954c272bde503363f354b33f6af4f97bee5ad740
6,409
def random_spectra(path_length, coeffs, min_wavelength, max_wavelength, complexity): """ """ solution = random_solution(coeffs, complexity) return beers_law(solution, path_length, coeffs, min_wavelength, max_wavelength)
a82a0d638473d63cd768bfdc0318f5042a75ae12
6,410
def data_prep(data,unit_identifier,time_identifier,matching_period,treat_unit,control_units,outcome_variable, predictor_variables, normalize=False): """ Prepares the data by normalizing X for section 3.3. in order to replicate Becker and Klößner (2017) """ X = data.loc[data[time_ident...
6f13cc083973d5bd7ac7d2ca239741aaf067fede
6,411
def calculate_auroc_statistics(y_true, y_pred, confint_alpha=0.05): """ calculate AUROC and it's p-values and CI """ #TODO: small sample test #TODO: check when it crashes #TODO: confidence intervals predictions_group0 = y_pred[y_true==0, 1] predictions_group1 = y_pred[y_true==1, 1...
5413912892d833cbb448efb396bff0c015866c59
6,412
import numpy def kabsch_superpose(P, Q): # P,Q: vstack'ed matrix """ Usage: P = numpy.vstack([a2, b2, c2]) Q = numpy.vstack([a1, b1, c1]) m = kabsch_superpose(P, Q) newP = numpy.dot(m, P) """ A = numpy.dot(numpy.transpose(P), Q) U, s, V = numpy.linalg.svd(A) tmp = numpy.identi...
56b7b9c3168e644ad71bee2146af3e4ae455c648
6,413
def add(a_t, b_t): """ add operator a+b """ return add_op(a_t, b_t)
be4e5bad6deb651af8e8f084cbefd185c1f9781f
6,414
import os def download_pkg(): """第二步下载相关环境需要的第三方库 :return: bool """ print("正在下载安装必要的第三方库文件...") try: # 如果需要使用IT之家爬虫还需要下载selenium、BeautifulSoup4、requests。可添加到后面 os.system('pip install flask flask_cors flask_wtf flask_mail pymysql redis apscheduler xlwt psutil ') print("安装成功...
fed51c16d21cb0425c13d737a20b141e91eae2d6
6,415
def GetExtensionDescriptor(full_extension_name): """Searches for extension descriptor given a full field name.""" return _pool.FindExtensionByName(full_extension_name)
5e0088f785809e38d306d7416129114ac09a5135
6,416
import os import logging def upload_file(file_name, bucket, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_name is used :return: True if file was uploaded, else ...
171869ca015151ec8474a26198f6d50c615b15ff
6,417
from operator import sub def parse_args(): """ Parses command-line arguments and returns username, title of specified repository and its' branch. Returns: tuple (username, repo_name, branch). Used only once in `main` method. """ DESC = 'Automatic license detection of a Github repository.' ...
f7bf4b0cc27a87add8f65f82bebbabb6a4b9ca06
6,418
import argparse def get_parameters(): """ Parse script arguments """ parser = argparse.ArgumentParser(prog='compile.py') # config.h template parameters parser.add_argument('os', type=str, default="LINUX", choices=available_os) parser.add_argument('arch', type=str, default="X86", choices=av...
106e325dcea9835badaae33c8ac51e1ef56dbf7a
6,419
import itertools def collect_inventory_values(dataset, inventory_list, parameter_map): """ Collect inventories from a dataset. """ # Collect raw/unicode/clts for all relevant inventories to_collect = [] for catalog in inventory_list.keys(): to_collect += list( itertools.ch...
1c59e0784b6fc4db24f994440990e46a0ba2b1f0
6,420
import sys import copy import time import optparse import random import logging def Start(parser=None, argv=sys.argv, quiet=False, add_pipe_options=True, add_extract_options=False, add_group_dedup_options=True, add_sam_options=True, add_umi_groupin...
ee5f99a8f65735d2e7d3e53e358f352253a3e580
6,421
from spinup.env_wrappers.dynamic_skip_env import DynamicSkipEnv from spinup.env_wrappers.single_agent_env import SingleAgentEnv import time def sac(env_fn, actor_critic=core.mlp_actor_critic, ac_kwargs=dict(), seed=0, steps_per_epoch=10000, epochs=10000, replay_size=int(1e6), gamma=0.99, polyak=0.99...
e6cbaa93e6a05ad0d128f1e50a277bbd9bff72ea
6,422
def flatten_list(a_list, parent_list=None): """Given a list/tuple as entry point, return a flattened list version. EG: >>> flatten_list([1, 2, [3, 4]]) [1, 2, 3, 4] NB: The kwargs are only for internal use of the function and should not be used by the caller. """ if parent_list...
dd6c9c66a370e65744ede40dfdc295b0ec63379a
6,423
from typing import List def list_to_csv_str(input_list: List) -> Text: """ Concatenates the elements of the list, joining them by ",". Parameters ---------- input_list : list List with elements to be joined. Returns ------- str Returns a string, resulting from concate...
4c172b0ce3daba01f2d976bc60739846b852c459
6,424
def scheme_listp(x): """Return whether x is a well-formed list. Assumes no cycles.""" while x is not nil: if not isinstance(x, Pair): return False x = x.second return True
e5001695035d2d24e2914295e8ae2f86d8ead0b3
6,425
def list_to_dict(config): """ Convert list based beacon configuration into a dictionary. """ _config = {} list(map(_config.update, config)) return _config
3d7ace7612e67a0c406a2a400ad3147f99dbef0a
6,426
def get_model(model_name, in_channels = 3, input_size = 224, num_classes = 1000): """Get model Args : --model_name: model's name --in_channels: default is 3 --input_size: default is 224 --num_classes: default is 1000 for ImageNet return : --model: model instance "...
0380a19e2a063382920b7986d1087aaf70f05eda
6,427
def check_edge_heights( stack, shifts, height_resistance, shift_lines, height_arr, MIN_H, MAX_H, RESOLUTION ): """ Check all edges and output an array indicating which ones are 0 - okay at minimum pylon height, 2 - forbidden, 1 - to be computed NOTE: function not used here! only for test purpose...
f73c6fd0396967e2a5ecfa89d52f1468d2005967
6,428
def linear_int_ext(data_pts, p, scale=None, allow_extrap=False): """ Interpolate data points to find remaining unknown values absent from `p` with optionally scaled axes. If `p` is not in the range and `allow_extra` == True, a linear extrapolation is done using the two data points at the end corresp...
f69cc25d4610987a5f76f21e23df49efad5c6a7f
6,429
def eval_in_els_and_qp(expression, ig, iels, coors, fields, materials, variables, functions=None, mode='eval', term_mode=None, extra_args=None, verbose=True, kwargs=None): """ Evaluate an expression in given elements and points. Parameter...
b71a20f0806ac03f9f995ffa41f317bc2c029d1c
6,430
def tracks2Dataframe(tracks): """ Saves lsit of Track objects to pandas dataframe Input: tracks: List of Track objects Output: df: Pandas dataframe """ if(len(tracks) == 0): print("Error saving to CSV. List of tracks is empty") return #...
9d25e7f9535cfefc5b6faf791555b382edf12a07
6,431
def sift_point_to_best(target_point, point, sift_dist): """ Move a point to target point given a distance. Based on Jensen's inequality formula. Args: target_point: A ndarray or tensor, the target point of pca, point: A ndarray or tensor, point of pca, sift_dist: A float, distance w...
a14216998631f22d6c8d4e98112672608b8477e5
6,432
def jrandom_counts(sample, randoms, j_index, j_index_randoms, N_sub_vol, rp_bins, pi_bins, period, num_threads, do_DR, do_RR): """ Count jackknife random pairs: DR, RR """ if do_DR is True: DR = npairs_jackknife_xy_z(sample, randoms, rp_bins, pi_bins, period=period, jtags1=j...
dce697b11f1d66b61aef46982c40b0310a292a92
6,433
from typing import Any def process_not_inferred_array(ex: pa.ArrowInvalid, values: Any) -> pa.Array: """Infer `pyarrow.array` from PyArrow inference exception.""" dtype = process_not_inferred_dtype(ex=ex) if dtype == pa.string(): array: pa.Array = pa.array(obj=[str(x) for x in values], type=dtype,...
c2d84f436dbd1123e38e1468101f8910e928e9ba
6,434
def start_end(tf): """Find start and end indices of running streaks of True values""" n = len(tf) tf = np.insert(tf, [0, len(tf)], [False, False]) # 01 and 10 masks start_mask = (tf[:-1] == 0) & (tf[1:] == 1) end_mask = (tf[:-1] == 1) & (tf[1:] == 0) # Locations start_loc = np.whe...
592a55da0d1c02259676444d2dd640f759dfb62d
6,435
def remove_provinces(data, date_range): """ REMOVE PROVINCES :param data: The Data received from the API :param date_range: the date range of the data :return: data after removing provinces """ countries_with_provinces = [] names_of_countries_with_prov = [] # get countries with prov...
05e973254402fb2c9873fa065d45a6a5dd3da353
6,436
def plot_publish(families, targets=None, identifiers=None, keys=None): """Parse and plot all plugins by families and targets Args: families (list): List of interested instance family names targets (list, optional): List of target names identifiers (list, optional): List of interested di...
de2dc8cf3184fdd4d883e340256b55153346a3a9
6,437
from datetime import datetime import math def get_job_view(execution, prev_execution, stackstorm_url): """ Gets a job view from the specified execution and previous execution :param execution: dict :param prev_execution: dict :param stackstorm_url: string :return: dict """ current_tim...
88acb9a725bacb7a51518c3250001a607346ddba
6,438
import torch def mdetr_resnet101_refcocoplus(pretrained=False, return_postprocessor=False): """ MDETR R101 with 6 encoder and 6 decoder layers. Trained on refcoco+, achieves 79.52 val accuracy """ model = _make_detr("resnet101") if pretrained: checkpoint = torch.hub.load_state_dict_fro...
30f73654fbabccc35629c9adb3d7ac91c5fe368d
6,439
import sys import requests import json def launch_duo_report(related_genome_id, duo_relation, duo_affected, proband_genome_id, proband_sex, score_indels, accession_id): """Launch a family report. Return the JSON response. """ # Construct url and request url ...
58be6c1a80ce34539683862fcda0b10cfbed2de1
6,440
import re def readConfigFile(filePath): """ Read the config file and generate a dictionnary containing an entry for every modules of the installation. """ modules_attributes_list = [] confFile = open(filePath, "r") for i, line in enumerate(confFile.readlines()): # Remove everything that is written after "#...
fadaec4dd005d6337eb5950b8782d5db944fb4cc
6,441
def unpad_pkcs7(data): """ Strips PKCS#7 padding from data. Raises ValueError if padding is invalid. """ if len(data) == 0: raise ValueError("Error: Empty input.") pad_value = data[-1] if pad_value == 0 or pad_value > 16: raise ValueError("Error: Invalid padding.") for i ...
27e59b8a880c130997f19814135c09cb6e94354d
6,442
def create_output_channel( mgr: sl_tag.TagManager, group: str, name: str, data_type: sl_tag.DataType ) -> sl_tag.TagData: """Create a FlexLogger output channel.""" # "Import" the channel into FlexLogger. full_name = get_tag_prefix() + ".Import.Setpoint.{}.{}".format(group, name) mgr.open(full_name, ...
40bf2f6f555993deb4433d00768a3241dc8d72f6
6,443
import re def slugify(value, allow_unicode=False): """ adapted from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, underscores, or hyphe...
f87a54f124a06fde2163fec39ba41881032db569
6,444
import torch def data_process(raw_text_iter: dataset.IterableDataset) -> Tensor: """Converts raw text into a flat Tensor.""" data = [torch.tensor(vocab(tokenizer(item)), dtype=torch.long) for item in raw_text_iter] return torch.cat(tuple(filter(lambda t: t.numel() > 0, data)))
1c4bb8cf9997f6a6205c7c4f1122892b528f5c0e
6,445
def rna_view_redirect(request, upi, taxid): """Redirect from urs_taxid to urs/taxid.""" return redirect('unique-rna-sequence', upi=upi, taxid=taxid, permanent=True)
7a45b8b75e2cffb7573a7856c74d8e7b21e70543
6,446
from typing import AbstractSet def skip_for_variants(meta: MetaData, variant_keys: AbstractSet[str]) -> bool: """Check if the recipe uses any given variant keys Args: meta: Variant MetaData object Returns: True if any variant key from variant_keys is used """ # This is the same behav...
89bc8bf82431043cc4c6b42b6f8385df14c8d7d1
6,447
def _is_safe_url(url, request): """Override the Django `is_safe_url()` to pass a configured list of allowed hosts and enforce HTTPS.""" allowed_hosts = ( settings.DOMAIN, urlparse(settings.EXTERNAL_SITE_URL).netloc, ) require_https = request.is_secure() if request else False retu...
e1a8779c72b6d5adfa3fe01b478783d81ef515de
6,448
from typing import Union import asyncio import os def test_full_pipeline() -> None: """Test the full pipeline.""" # Define a class that can send messages and one that can receive them. class TestClassS: """Test class incorporating send functionality.""" msg = _TestMessageSenderBoth() ...
04baa2c69b183ee2eff762f08943969863bdb3d0
6,449
def _server(): """ Reconstitute the name of this Blueprint I/O Server. """ return urlparse.urlunparse((request.environ.get('wsgi.url_scheme', 'https'), request.environ.get('HTTP_HOST', ...
122457aa7f2a5e301299ccaaed4bba75cf273f5a
6,450
def get_range_api(spreadsheetToken, sheet_id, range, valueRenderOption=False): """ 该接口用于根据 spreadsheetToken 和 range 读取表格单个范围的值,返回数据限制为10M。 :return: """ range_fmt = sheet_id + '!' + range get_range_url = cfg.get_range_url.format(spreadsheetToken=spreadsheetToken, range=range_fmt) headers = { ...
0c226caaa64e1bab09ac9b3af6a839609d62d5a3
6,451
def rotate_rboxes90(rboxes: tf.Tensor, image_width: int, image_height: int, rotation_count: int = 1) -> tf.Tensor: """Rotate oriented rectangles counter-clockwise by multiples of 90 degrees.""" image_width = tf.cast(image_width, dtype=tf.float32) image_h...
7c21d6ea3bf8454af9aabd0f4408c9de593432ac
6,452
def get_wrong_user_credentials(): """ Monkeypatch GithubBackend.get_user_credentials to force the case where invalid credentias were provided """ return dict(username='invalid', password='invalid', token='invalid', remember=False, remem...
3598f00b05a53cdb13543642048fc8c333eebe52
6,453
def get_points(coords, m, b=None, diagonal=False): """Returns all discrete points on a line""" points = [] x1, y1, x2, y2 = coords[0], coords[1], coords[2], coords[3] # vertical line if m is np.nan: # bottom to top y = min(y1, y2) while y <= max(y1, y2): points.a...
23d6d4002c5625b8ea6011c26a0419c2a2710b53
6,454
def get_region_geo(region_id): """Get Geo/TopoJSON of a region. Args: region_id (str): Region ID (e.g. LK-1, LK-23) Returns: Geo-spatial data as GeoPandasFrame """ region_type = get_entity_type(region_id) region_to_geo = _get_region_to_geo(region_type) return region_to_geo...
0493aa9e521c6d27cad6e6be07662449b6768a20
6,455
def load_vocabulary(f): """ Load the vocabulary from file. :param f: Filename or file object. :type f: str or file :return: Vocabulary """ v = Vocabulary() if isinstance(f, str): file_ = open(f, 'r') else: file_ = f for line in file_: wordid, word, word...
7a7cdf44016eccd1ceefd4fcc9e19f8f50caece2
6,456
def populate_objects(phylodata_objects, project_name, path_to_species_trees, path_to_gene_trees, path_to_ranger_outputs): """ this function will try and associate each phylodata object with the correct species_besttree gene_bootstrap_trees and rangerDTL output files (if they exist) args: ...
5813981113be0513920fed0bc21bd6eedd6890f3
6,457
import copy def extract_peers_dataset( work_dict, scrub_mode='sort-by-date'): """extract_peers_dataset Fetch the IEX peers data for a ticker and return it as a pandas Dataframe :param work_dict: dictionary of args :param scrub_mode: type of scrubbing handler to run """ la...
d0aec2efe89a0a65010f2de4da686694c8906cbf
6,458
def xml_ind(content): """Translate a individual expression or variable to MathCAD XML. :param content: str, math expression or variable name. :return: str, formatted MathCAD XML. """ ns = ''' xmlns:ml="http://schemas.mathsoft.com/math30">''' # name space as initial head sub_statement = xml_sta...
67e82cbfd2796e31eaef7305e240fc9e3d93c08e
6,459
from typing import Any def read_slug(slug: str, db: Session = Depends(get_db)) -> Any: """ Get a post by slug """ db_slug = get_post(db, slug) if db_slug is None: raise HTTPException(status_code=404, detail="Post not found") return db_slug
347dfd32aa87417cecfbb5b192288fdc0585a071
6,460
from typing import List def left_join_predictions(anno_gold: pd.DataFrame, anno_predicted: pd.DataFrame, columns_keep_gold: List[str], columns_keep_system: List[str]) -> pd.DataFrame: """ Given gold mention annotations and predicted mention annotations, this method returns the gold a...
c34785e255940f69375ee64674186b0b7e8bdf1f
6,461
import json def get_users_data(filter): """ Returns users in db based on submitted filter :param filter: :return: """ # presets - filter must be in one of the lists filter_presets = {"RegistrationStatus": ["Pending", "Verified"], "userTypeName": ["Administrator", "Event Manager", "Alumni"]...
568dab028a30c9c6f88de83054b6a7b3e95662fc
6,462
def calAdjCCTTFromTrace(nt,dt,tStartIn,tEndIn,dataIn, synthIn): """ calculate the cross correlation traveltime adjoint sources for one seismogram IN: nt : number of timesteps in each seismogram dt : timestep of seismograms tStartIn : float starting time for trac...
7524d350c241ae07810b1e5c38bb3db869136804
6,463
def get_par_idx_update_pars_dict(pars_dict, cmd, params=None, rev_pars_dict=None): """Get par_idx representing index into pars tuples dict. This is used internally in updating the commands H5 and commands PARS_DICT pickle files. The ``pars_dict`` input is updated in place. This code was factored out v...
9be23a37884eb674b3faa67ac17342b830c123fd
6,464
import time import logging def profile(function, *args, **kwargs): """ Log the runtime of a function call. Args: function: The callable to profile. args: Additional positional arguments to ``function``. kwargs: Additional keyword arguments to ``function``. Returns: Th...
73369ea9e97e50e72100be5e6537d4ca39664a17
6,465
from argparse import ArgumentParser from argparse import RawTextHelpFormatter from .. import __version__ as _vstr from pathlib import Path def get_parser(): """Define the command line interface""" parser = ArgumentParser(description='SDC Workflows', formatter_class=RawTextHelpForm...
825f69340e1dce9c281f67768ff2559241bb1acc
6,466
def COSTR(LR, R, W, S): """ COSTR one value of cosine transform of two-sided function p. 90 """ COSNW = 1. SINNW = 0. COSW = COS(W) SINW = SIN(W) S = R[0] for I in range(1, LR): T = COSW * COSNW - SINW * SINNW COSNW = T S += 2 * R[I] * COSNW re...
c4a4ff69ac4bd2d22885fc5103e62b0d861d8ed6
6,467
def CV_SIGN(*args): """CV_SIGN(int a)""" return _cv.CV_SIGN(*args)
380758a917df6111c27e6072a72a483ac13513c9
6,468
def import_config_data(config_path): """ Parameters ---------- config_path : str path to the experimental configuration file Returns ------- config data : dict dict containing experimental metadata for a given session config file """ data = get_config(config_path) ...
c174272dfd56876f7e8dbd306248c81aa1f3bdb2
6,469
def sigmaLabel(ax, xlabel, ylabel, sigma=None): """Label the axes on a figure with some uncertainty.""" confStr = r'$\pm{} \sigma$'.format(sigma) if sigma is not None else '' ax.set_xlabel(xlabel + confStr) ax.set_ylabel(ylabel + confStr) return ax
8ecf5ae2defd0d67c545943ea48992906612282e
6,470
def startswith(x, prefix): """Determines if entries of x start with prefix Args: x: A vector of strings or a string prefix: The prefix to test against Returns: A bool vector for each element in x if element startswith the prefix """ x = regcall(as_character, x) return x...
2d41a61d5a569af1925e8df7e2218fdae2bcb7ec
6,471
def create_estimator(est_cls, const_kwargs, node, child_list): """ Creates an estimator. :param est_cls: Function that creates the estimator. :param const_kwargs: Keyword arguments which do not change during the evolution. :param child_list: List of converted child nodes - should me empty. :par...
306a948f11bc3f70a3c489d1740d7144bbaa4c5b
6,472
def exists(hub_id): """Check for existance of hub in local state. Args: hub_id(str): Id of hub to query. The id is a string of hexadecimal sections used internally to represent a hub. """ if 'Hubs.{0}'.format(hub_id) in config.state: return True else: return False
4b6d333e070e1dea9300db20bcd50b58c1b9b457
6,473
import logging def query_by_date_after(**kwargs): """ 根据发布的时间查询,之后的记录: 2020-06-03之后,即2020-06-03, 2020-06-04, ...... :param kwargs: {'date': date} :return: """ session = None try: date = kwargs['date'].strip() + config.BEGIN_DAY_TIME session = get_session() ret = ses...
b6bbf40441ae8c3f6db861e8bed025986b7373bd
6,474
import os def get_artifact_path(name): """Получение пути для сохранения артефакта. Side-эффект: Создание директории @param name: Название артефакта @return Путь для сохранения """ if not os.path.exists('../artifacts/'): os.makedirs('../artifacts/') path = f'../artifacts/{name}.png' ...
99c076c5803b418b27deeec0f65a5a42a24f3579
6,475
from skimage.feature import peak_local_max # Defer slow import from scipy.stats import iqr import math def _step_4_find_peaks( aligned_composite_bg_removed_im, aligned_roi_rect, raw_mask_rects, border_size, field_df, sigproc_params, ): """ Find peaks on the composite image TASK: ...
1439336369681569a85ee3e8a8566e4d02cc2999
6,476
import socket def get_reverse_host(): """Return the reverse hostname of the IP address to the calling function.""" try: return socket.gethostbyaddr(get_ipaddress())[0] except: return "Unable to resolve IP address to reverse hostname"
48911baf6507563470cb2d34af2392b52c58ac9a
6,477
def trans_stop(value) -> TransformerResult: """ A transformer that simply returns TransformerResult.RETURN. """ return TransformerResult.RETURN
c124c62a15bca1000ecdfaaa02433de405338e6c
6,478
def generator(n, mode): """ Returns a data generator object. Args: mode: One of 'training' or 'validation' """ flip_cams = False if FLAGS.regularization == 'GRU': flip_cams = True gen = ClusterGenerator(FLAGS.train_data_root, FLAGS.view_num, FLAGS.max_w, FLAGS.max_h, ...
1dc7950a4ae0f7c35a4ba788710327c2e63fae14
6,479
import re def remove_multispaces(text): """ Replace multiple spaces with only 1 space """ return [re.sub(r' +', " ",word) for word in text]
0b87f6a4b0d49931b3f4bec6f9c313be05d476f0
6,480
def empirical_ci(arr: np.ndarray, alpha: float = 95.0) -> np.ndarray: """Computes percentile range in an array of values. Args: arr: An array. alpha: Percentile confidence interval. Returns: A triple of the lower bound, median and upper bound of the confidence interval with...
8bb0ff5768c70d4e34174ea4187898513a4f841e
6,481
def euclidean(a,b): """Calculate GCD(a,b) with the Euclidean algorithm. Args: a (Integer): an integer > 0. b (Integer): an integer > 0. Returns: Integer: GCD(a,b) = m ∈ ℕ : (m|a ⋀ m|b) ⋀ (∄ n ∈ ℕ : (n|a ⋀ n|b) ⋀ n>m). """ if(a<b): a,b = b,a a, b = abs(a), abs(b) while a != 0: a, b = b % a, a return...
8af351e251e52336d7ef946a28bb6d666bff97c3
6,482
from typing import Union def check_reserved_pulse_id(pulse: OpInfo) -> Union[str, None]: """ Checks whether the function should be evaluated generically or has special treatment. Parameters ---------- pulse The pulse to check. Returns ------- : A str with a specia...
d4bd89da98612031fbcc7fcde9bcf40bb0843f70
6,483
def figure(*args, **kwargs): """ Returns a new SpectroFigure, a figure extended with features useful for analysis of spectrograms. Compare pyplot.figure. """ kw = { 'FigureClass': SpectroFigure, } kw.update(kwargs) return plt.figure(*args, **kw)
851b02773dc974691ba6e43477244aa8e4ba0760
6,484
import six def allow_ports(ports, proto="tcp", direction="in"): """ Fully replace the incoming or outgoing ports line in the csf.conf file - e.g. TCP_IN, TCP_OUT, UDP_IN, UDP_OUT, etc. CLI Example: .. code-block:: bash salt '*' csf.allow_ports ports="[22,80,443,4505,4506]" proto='tc...
3a14a9ea74daf4062e3bd970623284a152ffde08
6,485
def add(n1, n2, base=10): """Add two numbers represented as lower-endian digit lists.""" k = max(len(n1), len(n2)) + 1 d1 = n1 + [0 for _ in range(k - len(n1))] d2 = n2 + [0 for _ in range(k - len(n2))] res = [] carry = 0 for i in range(k): if d1[i] + d2[i] + carry < base: ...
098bfa9ebedf7f219a6f9910e98c4cf9cbf13aa8
6,486
from datetime import datetime import pytz def folder_datetime(foldername, time_infolder_fmt=TIME_INFOLDER_FMT): """Parse UTC datetime from foldername. Foldername e.g.: hive1_rpi1_day-190801/ """ # t_str = folder.name.split("Photos_of_Pi")[-1][2:] # heating!! t_str = foldername.split("day-")[-1]...
fbbd9d9749cba6807391009e1720ca35b9dd7c7b
6,487
def get_policy_profile_by_name(name, db_session=None): """ Retrieve policy profile by name. :param name: string representing the name of the policy profile :param db_session: database session :returns: policy profile object """ db_session = db_session or db.get_session() vsm_hosts = con...
36136be7e618490bcda58799285277982bc41f71
6,488
def ecg_hrv_assessment(hrv, age=None, sex=None, position=None): """ Correct HRV features based on normative data from Voss et al. (2015). Parameters ---------- hrv : dict HRV features obtained by :function:`neurokit.ecg_hrv`. age : float Subject's age. sex : str Subj...
fe3ab5e6f97920f44b7a32928785a19a6185e3d9
6,489
import warnings def declared_attr_roles(rw=None, call=None, read=None, write=None): """ Equivalent of :func:`with_roles` for use with ``@declared_attr``:: @declared_attr @declared_attr_roles(read={'all'}) def my_column(cls): return Column(Integer) While :func:`with_ro...
4128754046a18e332d5b6f8ba7e2c60d1d576c6b
6,490
def _in_iterating_context(node): """Check if the node is being used as an iterator. Definition is taken from lib2to3.fixer_util.in_special_context(). """ parent = node.parent # Since a call can't be the loop variant we only need to know if the node's # parent is a 'for' loop to know it's being ...
f1109b22842e3e9d6306a266b0654670a9f30ac8
6,491
def to_point(obj): """Convert `obj` to instance of Point.""" if obj is None or isinstance(obj, Point): return obj if isinstance(obj, str): obj = obj.split(",") return Point(*(int(i) for i in obj))
340182f054ebac39133edb09c9e1d049f9dde9d4
6,492
def issues(request, project_id): """问题栏""" if request.method == "GET": # 筛选条件 -- 通过get来实现参数筛选 allow_filter_name = ['issues_type', 'status', 'priority', 'assign', 'attention'] condition = {} # 条件 for name in allow_filter_name: value_list = request.GET.getlist(name) ...
099b292e8143f1559f3e78e96ad555eaa7328449
6,493
from operator import and_ def get_30mhz_rht_data(sensor_id): """ Produces a JSON with the 30MHz RH & T sensor data for a specified sensor. Args: sensor_id - Advanticsys sensor ID Returns: result - JSON string """ dt_from, dt_to = parse_date_range_argument(request.args.get("ra...
d688850720162c33ea9bdd84eaed9ecd83a49902
6,494
import requests def stock_em_gpzy_industry_data() -> pd.DataFrame: """ 东方财富网-数据中心-特色数据-股权质押-上市公司质押比例-行业数据 http://data.eastmoney.com/gpzy/industryData.aspx :return: pandas.DataFrame """ url = "http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get" page_num = _get_page_num_gpzy_indu...
4ac0de7bdbae197c9d89dc663dbef594e2010fc6
6,495
def to_float32(x: tf.Tensor) -> tf.Tensor: """Cast the given tensor to float32. Args: x: The tensor of any type. Returns: The tensor casts to float32. """ return tf.cast(x, tf.float32)
2c25ea5450e86139fa1c21041be73e21f01b1bff
6,496
def cli_usage(name=None): """ custom usage message to override `cli.py` """ return """ {logo} usage: signalyze [-h] [-o OUTPUT] [--show-name] [-b | -w | -all] [--show-graph | --show-extra-info] """.format(logo=get_logo())
f512be4404da92aff9a237cdece487a266cbf175
6,497
def unban_chat_member(chat_id, user_id, **kwargs): """ Use this method to unban a previously kicked user in a supergroup. The user will not return to the group automatically, but will be able to join via link, etc. The bot must be an administrator in the group for this to work :param chat_id: Unique id...
cc1558e1d49841e47ebf4f457e615319e47abae4
6,498
from typing import Optional import re def parse_progress_line(prefix: str, line: str) -> Optional[float]: """Extract time in seconds from a prefixed string.""" regexp = prefix + r"(?P<hours>\d+):(?P<minutes>\d{2}):(?P<seconds>\d{2}.\d{2})" match = re.search(regexp, line) if not match: return N...
690b2f0e48a5f584da646f9e4058ed75e654251e
6,499