content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time def get_ntp_time(ntp_server_url): """ 通过ntp server获取网络时间 :param ntp_server_url: 传入的服务器的地址 :return: time.strftime()格式化后的时间和日期 """ ntp_client = ntplib.NTPClient() ntp_stats = ntp_client.request(ntp_server_url) fmt_time = time.strftime('%X', time.localtime(ntp_stats.tx_time))...
17881970361994e329e1154478c8abb8171461f9
16,100
def read_data(path, names, verbose=False): """ Read time-series from MATLAB .mat file. Parameters ---------- path : str Path (relative or absolute) to the time series file. names : list Names of the requested time series incl. the time array itself verbose : bool, optional ...
978870d4517b5e5ab66186747c326794d6d43814
16,101
async def search(q: str, person_type: str = 'student') -> list: """ Search by query. :param q: `str` query to search for :param person_type: 'student', 'lecturer', 'group', 'auditorium' :return: list of results """ url = '/'.join((BASE_URL, SEARCH_INDPOINT)) params = {'term': q, ...
83913866f45a44202ccddbc9352fef9799caf751
16,102
def format_data_hex(data): """Convert the bytes array to an hex representation.""" # Bytes are separated by spaces. return ' '.join('%02X' % byte for byte in data)
27239052d9ca0b12c19977e79d512e0cab04182e
16,103
import glob import os def eval_test(test_path, gt_path, test_prefix='', gt_prefix='', test_format='png', gt_format='png', exigence=2, desync=0): """ Evaluates some test results against a given ground truth :param test_path: (str) relative or absolute path to the test results images :par...
b71475bf3c51e5a69e8498e60b8131a00fcd3d6f
16,104
from datetime import datetime import requests import dateutil def get_installation_token(installation): """ Get access token for installation """ now = datetime.datetime.now().timestamp() if installation_token_expiry[installation] is None or now + 60 > installation_token_expiry[installation]: ...
e5bf43f601ca9e155dcf296179d778b78b2cc67a
16,105
def disp(cog_x, cog_y, src_x, src_y): """ Compute the disp parameters Parameters ---------- cog_x: `numpy.ndarray` or float cog_y: `numpy.ndarray` or float src_x: `numpy.ndarray` or float src_y: `numpy.ndarray` or float Returns ------- (disp_dx, disp_dy, disp_norm, disp_ang...
e9d8166827e86a8e2180ba357a450aca817fdff4
16,106
def get_landmark_from_prob(prob, thres=0.5, mode="mean", binary_mask=False): """Compute landmark location from the model probablity maps Inputs: prob : [RO, E1], the model produced probablity map for a landmark thres : if np.max(prob)<thres, determine there is no landmark detected m...
fad614088e587e389f15b0700bf442a956d498b0
16,107
import socket def request( url, timeout: float, method="GET", data=None, response_encoding="utf-8", headers=None, ): """ Helper function to perform HTTP requests """ req = Request(url, data=data, method=method, headers=headers or {}) try: return urlopen(req, timeout...
80f130101290442d538fa3f416f5650800547c6b
16,108
from typing import Any from typing import Optional from typing import get_args from typing import get_origin def get_annotation_affiliation(annotation: Any, default: Any) -> Optional[Any]: """Helper for classifying affiliation of parameter :param annotation: annotation record :returns: classified value o...
db6efd7dfb0ed0272e7491547669de8f235b2b35
16,109
import os import glob def find_config_files( path=['~/.vcspull'], match=['*'], filetype=['json', 'yaml'], include_home=False ): """Return repos from a directory and match. Not recursive. Parameters ---------- path : list list of paths to search match : list list of globs to se...
3138839e8914451a4138c3e24d375089c5c866b0
16,110
def sort_dict(original): """Recursively sorts dictionary keys and dictionary values in alphabetical order""" if isinstance(original, dict): res = ( dict() ) # Make a new "ordered" dictionary. No need for Collections in Python 3.7+ for k, v in sorted(original.items()): ...
8c194af76160b0e4d3bad135720e051a4d4622b0
16,111
import requests def playonyt(topic): """Will play video on following topic, takes about 10 to 15 seconds to load""" url = 'https://www.youtube.com/results?q=' + topic count = 0 cont = requests.get(url) data = str(cont.content) lst = data.split('"') for i in lst: count+=1 if...
49f4285dc0e0086d30776fc0668bac0e4c19dbc5
16,112
def train_classifier(classifier, features, labels): """This function must concern itself with training the classifier on the specified data.""" return classifier.fit(features, labels)
ef74548aeb6e245d8728caf3205163c249046aae
16,113
def work_on_disk(dev, root_mb, swap_mb, image_path): """Creates partitions and write an image to the root partition.""" root_part = "%s-part1" % dev swap_part = "%s-part2" % dev if not is_block_device(dev): LOG.warn(_("parent device '%s' not found"), dev) return make_partitions(dev,...
195ded6deae958b7efa41bcfdda1d3d68cabb23d
16,114
def get_annotation_names(viewer): """Detect the names of nodes and edges layers""" layer_nodes_name = None layer_edges_name = None for layer in viewer.layers: if isinstance(layer, napari.layers.points.points.Points): layer_nodes_name = layer.name elif isinstance(layer, napar...
20e64a6719b945eceda341d5a42da178818cb1a1
16,115
def remap(kx,ky,lx,ly,qomt,datai): """ remap the k-space variable back to shearing periodic frame to reflect the time dependent Eulerian wave number """ ndim = datai.ndim dim = np.array(datai.shape)# datai[nz,ny,nx] sh_data = np.empty([dim[0],dim[1],dim[2]]) tp_data = np.empty([dim[0],dim[2]]) sh...
6ea415df88c0db2ba26ef0fc8daa35b12a101ef8
16,116
def fips_disable(): """ Disables FIPS on RH/CentOS system. Note that you must reboot the system in order for FIPS to be disabled. This routine prepares the system to disable FIPS. CLI Example: .. code-block:: bash salt '*' ash.fips_disable """ installed_fips_pkgs = _get_install...
d31cc5ad6dd71ec0f3d238051a7b2a64b311c0fd
16,117
import java.lang import sys def get_os_platform(): """return platform name, but for Jython it uses os.name Java property""" ver = sys.platform.lower() if ver.startswith('java'): ver = java.lang.System.getProperty("os.name").lower() print('platform: %s' % (ver)) return ver
df717ae12fadf0ced75f4f1148ceed11701a7f25
16,118
from datetime import datetime def buy_sell_fun_mp_org(datam, S1=1.0, S2=0.8): """ 斜率指标交易策略标准分策略 """ start_t = datetime.datetime.now() print("begin-buy_sell_fun_mp:", start_t) dataR = pd.DataFrame() for code in datam.index.levels[1]: # data = price.copy() # price = datam.que...
8d3b78b9d266c3c39b8491677caa0f4dfb9f839a
16,119
import collections import abc def marshall_namedtuple(obj): """ This method takes any atomic value, list, dictionary or namedtuple, and recursively it tries translating namedtuples into dictionaries """ recurse = lambda x: map(marshall_namedtuple, x) obj_is = partial(isinstance, obj) if ha...
87d24fe1b273bfcf481679a96710be757baf08a5
16,120
import torch def prep_image(img, inp_dim): """ Prepare image for inputting to the neural network. Returns a Variable """ # print("prepping images") img = cv2.resize(img, (inp_dim, inp_dim)) img = img[:,:,::-1].transpose((2,0,1)).copy() img = torch.from_numpy(img).float().div(255...
02ebc73a32a24d59c53da9bfb99485f3a4f6dee2
16,121
from typing import Dict from typing import List import math def best_broaders(supers_for_all_entities: Dict, per_candidate_links_and_supers: List[Dict], num_best: int = 5, super_counts_field: str = "broader_counts", doprint=False, ...
9aa9826c43e67a28eeca463b107296e093709246
16,122
def clump_list_sort(clump_list): """Returns a copy of clump_list, sorted by ascending minimum density. This eliminates overlap when passing to yt.visualization.plot_modification.ClumpContourCallback""" minDensity = [c['Density'].min() for c in clump_list] args = np.argsort(minDensity) list...
732e747e36c37f9d65ef44b6aa060d5c9d04e3d1
16,123
from typing import Dict from typing import Any from typing import Type import types from typing import Optional def _prepare_artifact( metadata_handler: metadata.Metadata, uri: Text, properties: Dict[Text, Any], custom_properties: Dict[Text, Any], reimport: bool, output_artifact_class: Type[types....
d30dcd579c73c71173f10207ab80d05c761c7185
16,124
import re def ParseCLILines(lines, skipStartLines=0, lastSkipLineRe=None, skipEndLines=0): """Delete first few and last few lines in an array""" if skipStartLines > 0: if lastSkipLineRe != None: # sanity check. Make sure last line to skip matches the given regexp if None == re....
dc445765f42df25b8d046e3f2303d85109a3d419
16,125
def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) ...
785985b79b9284ba8c6058c8e9c4018955407cf8
16,126
import os def _NormalizedSource(source): """Normalize the path. But not if that gets rid of a variable, as this may expand to something larger than one directory. Arguments: source: The path to be normalize.d Returns: The normalized path. """ normalized = os.path.normpath(source) if sou...
5ecaeddf2c3941bbfb0d89ee902a961f7aeab838
16,127
from datetime import datetime def get_df_from_sampled_trips(step_trip_list, show_service_data=False, earliest_datetime=None): """Get dataframe from sampled trip list. Parameters ---------- step_trip_list : list of lists List of trip lists occuring in the same step. show_service_data: bool...
36bba80f0c46862df0390cf4e4279eeb33002e86
16,128
def compute_v_y(transporter, particles): """ Compute values of V y on grid specified in bunch configuration :param transporter: transport function :param particles: BunchConfiguration object, specification of grid :return: matrix with columns: x, theta_x, y, theta_y, pt, V y """ return __com...
4a17e0c0e4612534483187b6779bcf5c179c0fcc
16,129
def gabor_kernel_nodc(frequency, theta=0, bandwidth=1, gamma=1, n_stds=3, offset=0): """ Return complex 2D Gabor filter kernel with no DC offset. This function is a modification of the gabor_kernel function of scikit-image Gabor kernel is a Gaussian kernel modulated by a ...
f725561a1eb56b6e23c1046c33b0abec49201122
16,130
def run_fn(fn_args: TrainerFnArgs): """Train the model based on given args. Args: fn_args: Holds args used to train the model as name/value pairs. """ # get transform component output tf_transform_output = tft.TFTransformOutput(fn_args.transform_output) # read input data train_dataset...
15c8202ad6955052bbd1da2984aedb9887c390af
16,131
def log_likelihood(X, Y, Z, data, boolean=True, **kwargs): """ Log likelihood ratio test for conditional independence. Also commonly known as G-test, G-squared test or maximum likelihood statistical significance test. Tests the null hypothesis that X is independent of Y given Zs. Parameters --...
00493131d78506c5a6cbb9e04bda51b69f1a04ca
16,132
def conjugada_matriz_vec(mat:list): """ Funcion que realiza la conjugada de una matriz o vector complejo. :param mat: Lista que representa la matriz o vector complejo. :return: lista que representa la matriz o vector resultante. """ fila = len(mat) columnas = len(mat[0]) resul = [] f...
ad883dae9161f4e60f933caf93703544e16bfb4d
16,133
def features2matrix(feature_list): """ Args: feature_list (list of Feature): Returns: (np.ndarray, list of str): matrix and list of key of features """ matrix = np.array([feature.values for feature in feature_list], dtype=float) key_lst = [feature.key for feature in feature_li...
f60cdb904489cca3ab926dbc8d396804367e4a7a
16,134
import os def GenDataFrameFromPath(path, pattern='*.png', fs=False): """ generate a dataframe for all file in a dir with the specific pattern of file name. use: GenDataFrameFromPath(path, pattern='*.png') """ fnpaths = list(path.glob(pattern)) df = pd.DataFrame(dict(zip(['fnpath'], [fnpaths]))...
899026131fe8eb18a2c5c6cf0df6a4ebfa287986
16,135
import re def is_heading(line): """Determine whether a given line is a section header that describes subsequent lines of a report. """ has_cattle = re.search(r'steer?|hfrs?|calves|cows?|bulls?', line, re.IGNORECASE) has_price = re.search(r'\$[0-9]+\.[0-9]{2}', line) return bool(has_cattle) a...
ccbc80f7db61f7ba82aa88e54112d1995d457764
16,136
def get_channel_messages(channel_id): """ Holt fuer einen bestimmten Kanal die Nachrichten aus der Datenbank""" session = get_cassandra_session() future = session.execute_async("SELECT * FROM messages WHERE channel_id=%s", (channel_id,)) try: rows = future.result() except Exception: ...
7a3821dd8e93c4d49dfeecea200a881fdcb3f1a4
16,137
def train(traj, pol, targ_pol, qf, targ_qf, optim_pol, optim_qf, epoch, batch_size, # optimization hypers tau, gamma, # advantage estimation sampling, ): """ Train function for deep deterministic policy gradient Parameters ---------- tra...
14c09f3ce1f30366be3b8d0e0b965bdc1c677834
16,138
import os def upsample_gtiff(files: list, scale: float) -> list: """ Performs array math to artificially increase the resolution of a geotiff. No interpolation of values. A scale factor of X means that the length of a horizontal and vertical grid cell decreases by X. Be careful, increasing the resolut...
93e158d4beae9d4d179e9908e6dce639de1770d3
16,139
def merge_dicts(dict1, dict2): """ _merge_dicts Merges two dictionaries into one. INPUTS @dict1 [dict]: First dictionary to merge. @dict2 [dict]: Second dictionary to merge. RETURNS @merged [dict]: Merged dictionary """ merged = {**dict1, **dict2} return merged
67e96ba9c9831e6e2aa4bbd6cd8b8d1d5edb93c4
16,140
import pagure.api import pagure.lib.query def check_api_acls(acls, optional=False): """Checks if the user provided an API token with its request and if this token allows the user to access the endpoint desired. :arg acls: A list of access control :arg optional: Only check the API token is valid. Skip...
81d658036c5b31e3471e48ef44f4eb26e571c49a
16,141
import os def get_data(): """ Return data files :return: """ data = {} for df in get_manifest(): d, f = os.path.split(df) if d not in data: data[d] = [df] else: data[d].append(df) return list(data.items())
3add894e03e153dc82aebcaca3a0099ac98b0a1c
16,142
def china_province_head_fifteen(): """ 各省前15数据 :return: """ return db_request_service.get_china_province_head_fifteen(ChinaTotal, ChinaProvince)
18dc3f22c05b3580bcd983361efc03bd3cdae43b
16,143
import tempfile import os from datetime import datetime import glob import shutil def exec_sedml_docs_in_archive(sed_doc_executer, archive_filename, out_dir, apply_xml_model_changes=False, sed_doc_executer_supported_features=(Task, Report, DataSet, Plot2D, Curve, Plot3D, Surface), ...
508ac3f83e7365c58f830081bf16470e0ad43e43
16,144
def pipeline(x_train, y_train, x_test, y_test, param_dict=None, problem='classification'): """Trains and evaluates a DNN classifier. Args: x_train: np.array or scipy.sparse.*matrix array of features of training data y_train: np.array 1-D arra...
f01e20851c91dd9f6b3db889fdf713edc1eb37b9
16,145
def model_selection(modelname, num_out_classes, dropout=None): """ :param modelname: :return: model, image size, pretraining<yes/no>, input_list """ if modelname == 'xception': return TransferModel(modelchoice='xception', num_out_classes=num_o...
67ba26ab4f7cbe8f4540eb10f2ef6e598b49ea2f
16,146
def Packet_computeBinaryPacketLength(startOfPossibleBinaryPacket): """Packet_computeBinaryPacketLength(char const * startOfPossibleBinaryPacket) -> size_t""" return _libvncxx.Packet_computeBinaryPacketLength(startOfPossibleBinaryPacket)
58139b8d874d9292e63b6eb6afdbd9c5c2fa6f9d
16,147
def build_check_query(check_action: Action) -> str: """Builds check query from action item Parameters ---------- check_action : action check action to build query from Returns ------- str query to execute """ return f""" UPDATE todos SET completed = ...
a6b8f5b328e3bb9eedf61a325e54d6cae9704a55
16,148
import itertools def gen_positions(n, n_boulders): """Generates state codes for boulders. Includes empty rows Parameters: n: number of rows/columns n_boulders: number of boulders per row return value: Possible boulder and alien states """ boulder_positions=[]; b_p=[] a...
0a20594f2e021bf8e190f6c7c726159fde0b8367
16,149
def analysis_linear_correlation(data1:np.array, data2:np.array, alpha:float = .05, return_corr:bool = True, verbose:bool = False)->bool: """ ## Linear correlation analysis to test i...
6eaf34a12281949236d28143399024ed30e834ad
16,150
def sha256(buffer=None): """Secure Hash Algorithm 2 (SHA-2) with 256 bits hash value.""" return Hash("sha256", buffer)
2e33c38c0f7b9dd019104a18e6842243773686ca
16,151
import math import torch def nmc_eig(model, design, observation_labels, target_labels=None, N=100, M=10, M_prime=None, independent_priors=False): """ Nested Monte Carlo estimate of the expected information gain (EIG). The estimate is, when there are not any random effects, .. math:: ...
8de69e87677a4a74fd04ce4cf302221121d00b2d
16,152
import scipy def _orient_eigs(eigvecs, phasing_track, corr_metric=None): """ Orient each eigenvector deterministically according to the orientation that correlates better with the phasing track. Parameters ---------- eigvecs : 2D array (n, k) `k` eigenvectors (as columns). phasing...
d6feebbd7b7748549ebc494bf8b00f0d9e313f7c
16,153
def test_CreativeProject_auto_multivariate_functional(max_iter, max_response, error_lim, model_type): """ test that auto method works for a particular multivariate (bivariate) function """ # define data covars = [(0.5, 0, 1), (0.5, 0, 1)] # covariates come as a list of tuples (one per covariate: (...
ee0cc1d34a1836c8ea9ec2b23de175f4b6d8ca75
16,154
def crossValidate(x, y, cv=5, K=None): """ :param y: N*L ranking vectors :return: """ results = {"perf": []} ## cross validation ## np.random.seed(1100) kf = KFold(n_splits=cv, shuffle=True, random_state=0) for train, test in kf.split(x): x_train = x[train, :] y_trai...
820f5b53a38d2a64a3a1ee740d0fded020000bb7
16,155
def make_word_groups(vocab_words): """ :param vocab_words: list of vocabulary words with a prefix. :return: str of prefix followed by vocabulary words with prefix applied, separated by ' :: '. This function takes a `vocab_words` list and returns a string with the prefix and the words...
f940c602939ca3a9bab013f5847918f7ba4536ae
16,156
def gpi_g10s40(rescale=False): """ Multiply by the 'rescale' factor to adjust hole sizes and centers in entrance pupil (PM) (Magnify the physical mask coordinates up to the primary mirror size) """ demag = gpi_mag_asdesigned() if rescale: demag = demag/rescale # rescale 1.1 gives a bigge...
4be151f7e99332be0f67d00619fe75def90c2b5d
16,157
import inspect def test_close_sections(): """Parse sections without blank lines in between.""" def f(x, y, z): """ Parameters ---------- x : X y : Y z : Z Raises ------ Error2 error. ...
793d92d989f3caa020c06ea798f7f34703abd747
16,158
import sys def get_good_contours(proc_image, image, bb, savedir, max_num_add=None): """ Adapted from `click_and_crop_v3.py`, except that we have to make the contours. Here, we're going to inspect and check that the contours are reasonable. Returns a list of processed contours that I'll then use for l...
4437c44c249b1bd4bf6bcef90d38defdcbe9bc48
16,159
def _int_converter(value): """Convert string value to int. We do not use the int converter default exception since we want to make sure the exact http response code. Raises: exception_handler.BadRequest if value can not be parsed to int. Examples: /<request_path>?count=10 parsed to {'count':...
6b5c99635211bf8ce2e3c2adc784f2a4e9ee355f
16,160
from typing import List def split_rule(rules, rule_name, symbols_to_extract: List[str], subrule_name: str): """ Let only options which are starting with symbols from symbols_to_extract. Put the rest to a subrule. """ r = rule_by_name(rules, rule_name) assert isinstance(r.body, Antlr4Selection...
aa4d2aac62c488e3cd8d002556edea3aaef7185b
16,161
def ESS(works_prev, works_incremental): """ compute the effective sample size (ESS) as given in Eq 3.15 in https://arxiv.org/abs/1303.3123. Parameters ---------- works_prev: np.array np.array of floats representing the accumulated works at t-1 (unnormalized) works_incremental: np.array ...
514ca2462708a4c163f45e92854159d50eb5f3a8
16,162
def new_line_over(): """Creates a new line over the cursor. The cursor is also moved to the beginning of the new line. It is not possible to create more than one new line over the cursor at a time for now. Usage: `In a config file:` .. code-block:: yaml - new_line_over: `Usi...
41da4d301240a8ea3d9108dd1d957a30cff1097b
16,163
import json def lambda_handler(event, context): """Calls custom job waiter developed by user Arguments: event {dict} -- Dictionary with details on previous processing step context {dict} -- Dictionary with details on Lambda context Returns: {dict} -- Dictionary with Processed Buc...
e5a4055a39d0df1fabd3ad5f70a2859524378f44
16,164
def put_path(components, value): """Recursive function to put value in component""" if len(components) > 1: new = components.pop(0) value = put_path(components, value) else: new = components[0] return {new: value}
77db4064a77cf1cdcde1d74d901410525722b66e
16,165
def con_orthogonal_checkboard(X,c_v1,c_v2,c_v3,c_v4,num,N): """for principal / isothermic / developable mesh / aux_diamond / aux_cmc (v1-v3)*(v2-v4)=0 """ col = np.r_[c_v1,c_v2,c_v3,c_v4] row = np.tile(np.arange(num),12) d1 = X[c_v2]-X[c_v4] d2 = X[c_v1]-X[c_v3] d3 = X[c_v4]-X[c_v2] ...
f05228d6caa49f60a2a9f515ce5590e6f13127e0
16,166
def _PropertyGridInterface_GetPropertyValues(self, dict_=None, as_strings=False, inc_attributes=False): """ Returns all property values in the grid. :param `dict_`: A to fill with the property values. If not given, then a new one is created. The dict_ can be an object as well, in which ...
06974bec88351d5e8743b43e7c0495bb40545ef0
16,167
def get_pipelines(exp_type, cal_ver=None, context=None): """Given `exp_type` and `cal_ver` and `context`, locate the appropriate SYSTEM CRDSCFG reference file and determine the sequence of pipeline .cfgs required to process that exp_type. """ context = _get_missing_context(context) cal_ver = _g...
7fb4a02ffe7598df4621b2fd4a6863094616fd41
16,168
def distance_to_line(p,a,b): """ Computes the perpendicular distance from a point to an infinite line. Parameters ---------- p : (x,y) Coordinates of a point. a : (x,y) Coordinates of a point on a line. b : (x,y) Coordinates of another point on a line. Return...
1b1d0ef37587cd8cb0f5730ac78c39ec8b42faec
16,169
def pearsonr(A, B): """ A broadcasting method to compute pearson r and p ----------------------------------------------- Parameters: A: matrix A, (i*k) B: matrix B, (j*k) Return: rcorr: matrix correlation, (i*j) pcorr: matrix correlation p, (i*j) Example: ...
f66ca9eb6c6367580043ab9d512400c826d30d39
16,170
def inst_bench(dt, gt, bOpts, tp=None, fp=None, score=None, numInst=None): """ ap, rec, prec, npos, details = inst_bench(dt, gt, bOpts, tp = None, fp = None, sc = None, numInst = None) dt - a list with a dict for each image and with following fields .boxInfo - info that will be used to cpmpute the ...
9f8e12863205c24247003a4c95cf52f99086a6a6
16,171
from typing import Tuple from typing import List def _tee( cmd: str, executable: str, abort_on_error: bool ) -> Tuple[int, List[str]]: """ Execute command "cmd", capturing its output and removing empty lines. :return: list of strings """ _LOG.debug("cmd=%s executable=%s", cmd, executable) ...
4aafdac48b9deb4810b96f99ffc178464b79372a
16,172
def normalized_str(token): """ Return as-is text for tokens that are proper nouns or acronyms, lemmatized text for everything else. Args: token (``spacy.Token`` or ``spacy.Span``) Returns: str """ if isinstance(token, SpacyToken): return token.text if preserve_case(...
c5e30b48716fa99bfbcf8252b3ecd018cc921cbe
16,173
def scatter_nd(*args, **kwargs): """ See https://www.tensorflow.org/api_docs/python/tf/scatter_nd . """ return tensorflow.scatter_nd(*args, **kwargs)
5b5d457c91df73314de6d81c105132d6b69eb1aa
16,174
from typing import Union from typing import Tuple def concatenate_sequences(X: Union[list, np.ndarray], y: Union[list, np.ndarray], sequence_to_value: bool = False) \ -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Concatenate multiple sequences to scikit-learn compatible n...
b4b2489eeb601ce5378f6cf7b2cce7daf68bdf1d
16,175
def get_export_table_operator(table_name, dag=None): """Get templated BigQueryToCloudStorageOperator. Args: table_name (string): Name of the table to export. dag (airflow.models.DAG): DAG used by context_manager. e.g. `with get_dag() as dag: get_export_table_operator(..., dag=dag)`. Defaults to...
b1fd75caf10bc5fefbba4b5702bf05ab1ec6be6c
16,176
def run_command_with_code(cmd, redirect_output=True, check_exit_code=True): """Runs a command in an out-of-process shell. Returns the output of that command. Working directory is self.root. """ if redirect_output: stdout = sp.PIPE else: stdout = None p...
45e8592def8290f45458a183bed410072cc15000
16,177
import logging async def delete_project( delete_project_request: DeleteProject, token: str = Depends(oauth2_scheme) ): """[API router to delete project on AWS Rekognition] Args: delete_project_request (DeleteProject): [AWS Rekognition create project request] token (str, optional): [Bearer...
5711adf3ee9177952561d825a733ee169b6f97b0
16,178
from typing import Union import ast def _create_element_invocation(span_: span.Span, callee: Union[ast.NameRef, ast.ModRef], arg_array: ast.Expr) -> ast.Invocation: """Creates a function invocation on the first element of ...
0449c27fc6e7f16054bddfd99bd9e64109b9ee0e
16,179
import os import logging def _CreateClassToFileNameDict(test_apk): """Creates a dict mapping classes to file names from size-info apk.""" constants.CheckOutputDirectory() test_apk_size_info = os.path.join(constants.GetOutDirectory(), 'size-info', os.path.basename(test_apk) + ...
96ba6c74217d212ee50d454225f334528919292c
16,180
import time def train_deeper_better(train_data, train_labels, test_data, test_labels, params): """Same as 'train_deeper', but now with tf.contrib.data.Dataset input pipeline.""" default_params = { 'regularization_coeff': 0.00001, 'keep_prob': 0.5, 'batch_size': 128, 'fc1_size':...
c2d2c56ac7dbb52d072f2397540d4d793ac0d0c4
16,181
def redirect_return(): """Redirects back from page with url generated by url_return.""" return redirect(str(Url.get_return()))
f1ce09afef02651e0331a930e53211f9eb4f2a54
16,182
def setup(coresys: CoreSys) -> EvaluateBase: """Initialize evaluation-setup function.""" return EvaluateOperatingSystem(coresys)
daf3bd3ddca0085d6305535b27c28d70ac240dac
16,183
def _weight_initializers(seed=42): """Function returns initilializers to be used in the model.""" kernel_initializer = tf.keras.initializers.TruncatedNormal( mean=0.0, stddev=0.02, seed=seed ) bias_initializer = tf.keras.initializers.Zeros() return kernel_initializer, bias_initializer
1c7652b787d4a69d3a43983c2c291c09337d06d0
16,184
import os def inputs(eval_data, data_dir, batch_size): """Construct input for eye evaluation using the Reader ops. Args: eval_data: bool, indicating if one should use the train or eval data set. data_dir: Path to the eye data directory. batch_size: Number of images per batch. Returns: ...
e5b8457bcc370df37e995db100ac5d0470df2fa8
16,185
def get_non_ready_rs_pod_names(namespace): """ get names of rs pods that are not ready """ pod_names = [] rs_pods = get_pods(namespace, selector='redis.io/role=node') if not rs_pods: logger.info("Namespace '%s': cannot find redis enterprise pods", namespace) return [] fo...
167922c4fa03127a3371f2c5b7516bb6462c6253
16,186
def lookup_material_probase(information_extractor, query, num): """Lookup material in Probase""" material_params = { 'instance': query, 'topK': num } result = information_extractor.lookup_probase(material_params) rank = information_extractor.rank_probase_result_material(result) r...
9cecf99e3a9689f85788df21ef01d4e86c9a392d
16,187
def get_unexpected_exit_events(op): """Return all unexpected exit status events.""" events = get_events(op) if not events: return None return [e for e in events if is_unexpected_exit_status_event(e)]
171158d16c34e2764bc8c91f4888863c162043c4
16,188
async def delete_user(username: str) -> GenericResponse: """Delete concrete user by username""" try: await MongoDbWrapper().remove_user(username) except Exception as exception_message: raise DatabaseException(error=exception_message) return GenericResponse(detail="Deleted user")
8b2756922ab79d058097105fa8cd000396350a3b
16,189
def get_changelog(): """download ChangeLog.txt from github, extract latest version number, return a tuple of (latest_version, contents) """ # url will be chosen depend on frozen state of the application source_code_url = 'https://github.com/pyIDM/pyIDM/raw/master/ChangeLog.txt' new_release_url = 'h...
7c8df0cbc5fa85642e4e23106006445f59539a1f
16,190
def get_train_tags(force=False): """ Download (if needed) and read the training tags. Keyword Arguments ----------------- force : bool If true, overwrite existing data if it already exists. """ download_train_tags(force=force) return read_tags(train_tags_file_path)
5d67422a275011a719c0121206397fb99e6e4f70
16,191
def select_own(ligands, decoys, scores): """Select ligand ids and decoy ids from full ranked ids.""" #scores format is full OUTDOCK line selected = set(ligands) selected.update(decoys) results = [] for scoreline in scores: #id = scoreline[extract_all.zincCol] #refer to correct column alw...
444555a30571e61fad7eac36389e2dd638313744
16,192
def create_app(): """ 生成FatAPI对象 :return: """ app = FastAPI( debug=settings.DEBUG, title=settings.PROJECT_NAME, # 项目名称 description=settings.DESCRIPTION, # 项目简介 docs_url=f"{settings.API_V1}/docs", # 自定义 docs文档的访问路径 redoc_url=f"{settings.API_V1}/redocs", # 禁...
10e106e9968344cf8382ecbd24b1029b3548be79
16,193
def cmp_text_file(text, file): """returns True when text and file content are identical """ fh = open(file) ftext = fh.read() fh.close() return cmp(ftext, text)
ecf10004cd3fa230d0e794c4c89e45ca91e7e40e
16,194
def get_alignment_summary(seq_info): """ Determine the consensus sequence of an alignment, and create position matrix Definition of consensus: most common base represented at that position. """ consensus_sequence = [] position_matrix = [] for position in seq_info: #Ignore any ambi...
f91e4dcea2f4570a194524970fdbc95eacc455b2
16,195
def calculate_pcx_chord_emission(impact_factor, Ti, w0, mu, Lnu, Vouter, rmax=40.0, nr=101, nlambda=2000, Lne=2.5, R_outer=35): """Calculates PCX emission with only the outer boundary spinning for a given impact factor Args: impact_factor (float): impact factor for chor...
611d80973d3767b16fbd26c7ccebee8fc5390c95
16,196
def _get_variables(exp:Experiment, config: dict) -> dict: """Process the configuration's variables before rendering it""" return {key: value.format(exp=exp) for key, value in config.get("variables", {}).items()}
1b819c93ef079557908c216dc5c9fa75d55fe0f3
16,197
def func_calc_M(S): """ Use molecules structure/symbol to calculate molecular weight Parameter: S : structrue in a format: (atomType number) separated by '-' or blank space number of '-' and spaces does not matter precendent: '-' > blank space Examp...
ed8e3d5ccd5305caccfac64cb0ecb200fde650eb
16,198
def find_NN(ngbrof, ngbrin, distance_ULIM=NP.inf, flatten=False, parallel=False, nproc=None): """ ----------------------------------------------------------------------------- Find all nearest neighbours of one set of locations in another set of locations within a specified distance. ...
131d136ad92900f3ee624982f70234070d0d76a6
16,199