content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def _parallel_blocks(out_image,
band_list,
ii,
jj,
y_offset,
x_offset,
nn_rows,
nn_cols,
left,
top,
... | 25fb7c51413ea4fd0cdad28a2031d61b147cf56a | 3,612,200 |
import tempfile
import os
def launch_tor_with_config(config, tor_cmd = 'tor', completion_percent = 100, init_msg_handler = None, timeout = DEFAULT_INIT_TIMEOUT, take_ownership = False, close_output = True):
"""
Initializes a tor process, like :func:`~stem.process.launch_tor`, but with a
customized configuration... | cb2a4ee6e1971f4023faddb58b5c7845323dcab4 | 3,612,201 |
def shell(command, input_text=None, stdin=PIPE, stdout=PIPE, stderr=PIPE):
"""
Creates and executes a new process using provided command.
Notes:
• if command's type is str then it will be executed using /bin/sh.
• if input_text was provided then it will be used as input for shell
command whic... | a551d2957e6deb9d0c817252e4c77c24d1ffae0b | 3,612,202 |
import torch
def val_net(net, dataloader):
"""Compute accuracy on validation set."""
net.eval()
correct = 0.0
total = 0.0
with torch.no_grad():
for i, data in enumerate(dataloader):
# Get the inputs, keeping batch size
x, y = data
... | b79245274569ae9768ceba60da3868a3ba92fb15 | 3,612,203 |
import os
def encode_game_log(year, log, dataset_dir, discard_dir, pon_dir, kan_dir,
kita_dir, riichi_dir, discard_count, pon_count, kan_count,
kita_count, riichi_count):
"""
:param year: String
:param log: Tenhou JSON game log object
:param dataset_dir: Dataset... | 92e1ed8192fe4e0de83c446facee0eabf9b0fb13 | 3,612,204 |
import sqlite3
def update_existing_stock(vol,vendor,part,vehicle):
"""
Update existing document data by document ID
:param document_id:
:param data:
:return:
"""
conn = sqlite3.connect(DATBASE_LOCATION)
cur = conn.cursor()
cur.execute('''UPDATE Stats
SET stock = stoc... | 80e84bacd26c9c7d2b5ff53f4f19e493cdf69084 | 3,612,205 |
def _get_presence_coconstraints(object_spec):
"""
Get presence co-constraint info from the given object specification.
This includes the groups and dependencies.
:param object_spec: The object specification
:return: A 2-tuple with (a) the group co-constraint mapping from group
name to const... | 2cd71fc7c6cb6d7813b806a31d51174675303e5a | 3,612,206 |
import csv
def tableToCSV(input_table, csv_filepath, fld_to_remove_override=[], keep_fields=[]):
"""Returns the file path of a csv containing the attributes table of a shapefile or other table"""
fld_list = arcpy.ListFields(input_table)
fld_names = [str(fld.name) for fld in fld_list]
# Either delete ... | c2680a4724f9f7283152680c1d7c1afcba441799 | 3,612,207 |
def sigmoid_derivative(x):
"""
Actual derivative: S'(x) = S(x)(1-S(x)) but the inputs have already gone
through the sigmoid function.
"""
return x * (1 - x) | 8ae624b16e324a8f68a7369c3798256e1296aa61 | 3,612,208 |
def get_lint_messages_by_level(raw_lint_feedback_str):
"""
Gets lists of lint messages grouped by message level (brief, main, extra).
Each message in a list is for a particular error / warning type e.g. E501.
A message might be consolidated (e.g. foo has prob; bar has prob etc) or be
a composite m... | 3aa8ee9be40810378dbeda47830e62ceb2633c85 | 3,612,209 |
def merge_again(other, script):
"""
Merge the two DataFrames for other and script together again,
but keeping distinct rows for the cumulated levenshtein distances
for each category (other and script).
Returns DataFrame.
"""
data = other.merge(script, how="left", on="line")
data.rename(c... | 204e716fce02765e2ba601f5d5a7f91efa792838 | 3,612,210 |
def _get_roi_id(db, offset, shape, exp_name=None):
"""Get database ROI ID for the given ROI position within the main image5d.
Args:
db (:obj:`sqlite.ClrDB`): Database object.
offset (List[int]): ROI offset in z,y,x.
shape (List[int]): ROI shape in z,y,x.
exp_name (str): Name... | 271764148d2cf43066ef5842af2675c0dc2cbcca | 3,612,211 |
def sdf2xyz(sdf_string):
"""Convert a sdf string to a xyz string."""
atoms = get_ind_from_sdfline(sdf_string.split('\n')[3])[0]
coord = [str(atoms)+('\n')]
for i in range(4, 4+atoms):
x = float(sdf_string.split('\n')[i].split()[0])
y = float(sdf_string.split('\n')[i].split()[1])
... | 1af2bbbe2deceb7fda5666f5c4612ce617a83108 | 3,612,212 |
import numpy as np
def iso(fabric_width, fabric_height):
"""
Calculate robot iso speed
:param fabric_width: float fabric width
:param fabric_height: float fabric height
:return: float quasi state robot speed, float transient state robot speed, float relevant speed
"""
# Import here for opt... | 634cf9f0dee798bee365fd03588ec0a50517323f | 3,612,213 |
from datetime import datetime
def parse_utc_timestamp(timestamp):
"""
解析服务器发回来的 UTC 时间戳
形如: 2017-07-28T08:28:47.776Z
Return:
- time datetime.datetime
"""
UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
utcTime = datetime.datetime.strptime(timestamp, UTC_FORMAT)
localTime = utcTime + ... | 0890c6f6cd1ee6dfc91ffcf1c5554e0e4a06d6eb | 3,612,214 |
def _parse_mapping_file(lines, strip_quotes=True, suppress_stripping=False):
"""Parser for map file that relates samples to metadata.
Format: header line with fields
optionally other comment lines starting with #
tab-delimited fields
Parameters
----------
lines : iterable o... | 889a3d84e0f6303368390e04406b7e77d6ae8a40 | 3,612,215 |
def laplacian_kernel(X, Y=None, gamma=None):
"""Compute the laplacian kernel between X and Y.
The laplacian kernel is defined as::
K(x, y) = exp(-gamma ||x-y||_1)
for each pair of rows x in X and y in Y.
Read more in the :ref:`User Guide <laplacian_kernel>`.
.. versionadded:: 0.17
Parame... | 9e92afb8de056c4a4e1b12f61fae2b907cabd441 | 3,612,216 |
def subset_dict(d, selected_keys):
"""Given a dict {key: int} and a list of keys, return subset dict {key: int} for only key in keys.
If a selected key is not in d, set its value to 0"""
return {key: (0 if key not in d else d[key]) for key in selected_keys} | e16e5ce7a9baa0fa9dbf8bb65eadd9101e188092 | 3,612,217 |
from malaya.transformers.babble import sequential_generation
def transformer(
string: str,
model,
generate_length: int = 30,
leed_out_len: int = 1,
temperature: float = 1.0,
top_k: int = 100,
burnin: int = 15,
batch_size: int = 5,
):
"""
Use pretrained transformer models to gen... | 3efa1ef65d94058e87c91fe932c8071e4cf60b57 | 3,612,218 |
from typing import Callable
from typing import Any
from typing import Optional
import logging
import traceback
def exception_handler(function: Callable) -> Callable:
"""
Wrapping function in try-except expression
Args:
function (Callable): Function, you want to wrap
Returns:
Callable... | 9d72c37d21b1e28d75f4812f8148d24a2c07353e | 3,612,219 |
def save_state(push, commit, agent_name, delta):
"""
Saves dialogflow.com agent's state (Intents/Entities) as json files
"""
return save_state_internal(push, commit, agent_name, delta=delta) | aa34676efe5a6e6678c278f513858831e3ecac45 | 3,612,220 |
def ccColor2(cc):
""" this function returns a different color depending on the type of
the CC-point. Useful for visualizing CL or CC points """
if cc.type==cam.CCType.FACET:
col = (1,0,1)
elif cc.type == cam.CCType.VERTEX:
col = (1,1,0)
elif cc.type == cam.CCType.EDGE:
co... | c3c90452db60cb9a4f9c13373975f3fd2176b5fa | 3,612,221 |
def _json_dumps_fallback(value):
# type: (Any) -> Any
"""
Fallback handler for json.dumps to handle objects json doesn't know how to
serialize.
"""
try:
# This is what structlog's json fallback does
return value.__structlog__()
except AttributeError:
return repr(value... | 7e441c743c033af4b8e0f35b2f4f2948af35bde2 | 3,612,222 |
def Floyd(graph, s, e):
"""弗洛伊德算法"""
end = len(graph[0])
for k in range(end):
for i in range(end):
for j in range(end):
# 更新经过i点的最短路径
if graph[i][j] > graph[i][k]+graph[k][j]:
graph[i][j] = graph[i][k]+graph[k][j]
# 查看最短路劲
print... | 23040a06b1849459b6b8807e96f47a06293537ab | 3,612,223 |
def Extrema_CurveTool_DN(*args):
"""
:param C:
:type C: Adaptor3d_Curve &
:param U:
:type U: float
:param N:
:type N: int
:rtype: gp_Vec
"""
return _Extrema.Extrema_CurveTool_DN(*args) | 28de6112518b7a02f6ae50528b0c63bf3b0a95ec | 3,612,224 |
def read_grey(filename, channel=0):
"""
Read an image file and return the red component (or component specified by channel)
of the image. This is used to get an nxm greyscale image from a file saved in rgb or rgba format.
Args:
filename: Name of image file to read
channel: Index of rgb... | 19ed9cea20aa257316fae220819ecfd81465d8c5 | 3,612,225 |
def convert_to_logit(param_value, pparam):
"""First convert any parameters that aren't probs to probs; then convert to logit"""
# Convert params to probs if they aren't already:
if pparam == "RAT_COEFF_TOM":
param_value = param_value/20
elif pparam == "LOOK_AHEAD_STEPS_TOM":
#TODO: Bett... | 9f65c89ebe6e3839b12ca415e06a238c73b98e03 | 3,612,226 |
def create_nodes(df):
"""Create the network nodes for the cleaned trains DataFrame."""
def _group_nodes(group):
assert (
len(group["countryCode"].unique()) == 1
), "station exists in multiple countries"
counts = group.shape[0]
type_freq = group["type"].value_counts(n... | e63e71153cdd11811b698aecaa9ee5d8e741fa86 | 3,612,227 |
def read_html():
"""Return simple HTML response."""
text = f'<html><body><h1>Hello! Today date is {date.today()}</h1></body></html>'
return HTMLResponse(text) | 3bad4c8acf948e9493bc3e356d579280fe90041b | 3,612,228 |
def _get_selected_arg(view, com_reg, pos):
"""
Retrieves the selected argument in a comma separated list,
returns None if there are several entries and no entry is selected
directly
"""
args = com_reg.group("args")
if "," not in args:
# only one arg => return it
return args
... | 8ab32ccaae2469c239aec60de0e8dcaaa4864023 | 3,612,229 |
def template_hook(name, silent=True, is_markup=True, **kwargs):
"""Calls the given template hook.
:param name: The name of the hook.
:param silent: If set to ``False``, it will raise an exception if a hook
doesn't exist. Defauls to ``True``.
:param is_markup: Determines if the hook s... | efaec987bd620bdad9a288fc3a284630d70f0c20 | 3,612,230 |
import sys
def create_google_sheet_export(username, id_string, export_id, **options):
"""
Google Sheets export task.
"""
# we re-query the db instead of passing model objects according to
# http://docs.celeryproject.org/en/latest/userguide/tasks.html#state
try:
export = _get_export_obj... | f82196532515897b5b5e92d90f6e449124b43d20 | 3,612,231 |
def eigenvalue_nonunitary_diamondnorm(a, b, mx_basis):
"""
Eigenvalue nonunitary diamond distance between a and b
Parameters
----------
a : numpy.ndarray
The first process (transfer) matrix.
b : numpy.ndarray
The second process (transfer) matrix.
mx_basis : Basis or {'pp',... | 83a368ffe36b9695599d00b00c356def44ef975f | 3,612,232 |
def compute_airfoil_aerodynamics(beta,c,r,R,B,Wa,Wt,a,nu,a_loc,a_geo,cl_sur,cd_sur,ctrl_pts,Nr,Na,tc,use_2d_analysis):
"""
Cl, Cdval = compute_airfoil_aerodynamics( beta,c,r,R,B,
Wa,Wt,a,nu,
a_loc,a_geo,cl_sur,cd_sur,
... | 9e960102a5ad45c4218595420c33ffc82eef961b | 3,612,233 |
def rescale_image(image, scale=0.5):
"""
Resize the frame is good to have an improvement
of the capability to read the image
"""
image_height = image.shape[0]
image_width = image.shape[1]
dimensions = int(image_width*scale), int(image_height*scale)
return cv2.resize(image, dimen... | fd2b8a05eafe457ee911370258e326c03d44fa96 | 3,612,234 |
def make_fwd_slice(shape, slices, reverse=None, cull_second=True):
"""Make sure slices go forward
This function returns two slices equivalent to `slices` such
that the first slice always goes forward. This is necessary because
h5py can't deal with reverse slices such as [::-1].
The optional `rever... | c029411f29c8c3d1eb3530cea42a7a76bba72ed2 | 3,612,235 |
from typing import Union
def _str2float(s: str) -> Union[float, str]:
"""
Convert string to a numeric type, if possible.
"""
try:
# if numpy is installed, use np.float64 instead of Python built-in
if USE_NUMPY:
return np.float64(s)
else:
return float(s)... | 848f8496fa44014fdb1afb302834af542d153e82 | 3,612,236 |
from typing import Optional
def get_prev_weekday(x: Optional[Date] = None) -> Date:
"""
Returns the previous week day as of given (optional) date.
:param x: Optional date in time.
:return: Previous business day.
>>> get_prev_weekday(Date(2020, 1, 1))
datetime.date(2019, 12, 31)
>>> get_p... | 4c0804179e0ba78078d50a3e07aff4e4ca351317 | 3,612,237 |
from typing import List
def get_student_teams(
platform_url: str, org_name: str = const.TARGET_ORG_NAME
) -> List[plug.StudentTeam]:
"""Like :py:func:`get_platform_teams`, but converts each team to a
:py:class:`~repobee_plug.StudentTeam`. for easier comparison.
Args:
platform_url: URL to the ... | 109d67c32aa0c374153044cc09b95bb14c64dc50 | 3,612,238 |
def openProcFile(proc_filename, read_proc0, bounds):
"""Open single proc*.hdf file and return its handler
Parameters
proc_filename - name of the input proc*hdf file
read_proc0 == list_read_proc[0], the bottom processor layer index. See below.
bounds - oordinates of the edg... | 442a897789b4ea1c933523c862c4afc1ba6c068e | 3,612,239 |
from typing import Tuple
def get_mern2_props(
m1: float,
m2: float,
m3: float,
n: int) -> Tuple[float, float, float]:
"""
Helper function to estimate Erlang distributions rates and
probabilities from the given moments and Erlang shape (n).
See theorem 3 in [1] for deta... | d672184dc4e8cd3a40b7cbb0bfda55f23afbb074 | 3,612,240 |
import os
def get_recursive_files(folder_path):
"""
Returns:
[], sub-files
"""
result = []
for root, dirs, files in os.walk(folder_path):
for f in files:
file_path = os.path.join(root, f)
result.append(file_path)
return result | b89c25ff4be54276627300d56c3b0b523d4c302d | 3,612,241 |
def get_record(oid):
"""
Handle get and push requests coming to metadata server
POST is an update of an existing record.
Access control is done here. An admin can modify anyone's records
but they must be an admin in the authenication database.
returns:
Response with newly created or e... | de46370c9e1d2b2517e39bfeeaf04af1ad308c15 | 3,612,242 |
import json
def delete_sessions(request):
"""
delete_sessions:
This view deletes the session based on the request_id in Session_info
if it runs without exception then it deletes and return the result : success
if not then it just returns the result : error
@param:
request - trivial
@variables:
... | 27f773a73067f1acd43d378b50684888b57802e9 | 3,612,243 |
def max_quantile_CI(X, q, m, alpha=0.05):
"""Calculate CI on `q` quantile of distribution on max of `m` iid samples using a data set `X`.
This uses nonparametric estimation from order statistics and will have alpha level of at most `alpha` due to the
discrete nature of order statistics.
Parameters
... | fbea566a703f04a8384c9ff0240dd7fccf713397 | 3,612,244 |
def df_to_graph(struct_df, label):
"""
struct_df: Dataframe
"""
lig_df = struct_df[struct_df.chain == 'L']
lig_graph = gr.prot_df_to_graph(lig_df)
prot_df = struct_df[struct_df.chain != 'L']
prot_graph = gr.prot_df_to_graph(prot_df)
node_feats, edge_index, edge_feats, pos = gr.combine_gr... | e47d249fe7529fdce0c7ca8694321b606e94bea8 | 3,612,245 |
def ctoa(character: str) -> int:
"""Find the ASCII value of character.
Uses the ord builtin function.
"""
code = ord(character)
return code | dbf3b01f331a976632ae2559e08488a3f6a7f15d | 3,612,246 |
def load_data(data_path,
sep=",",
header=None,
index_col=None) -> object:
"""Helper function to load train and test files
as well as optional param loading
Args:
data_path (str or list of str): path to csv file
sep (str):
index_col (str):
... | 34fac4e24715c2d8cbe79128aaa41757a1430f20 | 3,612,247 |
def relief(df, measures=ABE.measures.default):
"""
reference: sect 2.2 of hall et al. "Benchmarking Attribute Selection Techniques for Discrete Class Data Mining"
reference2: Kononenko et al. "Estimating Attributes: Analysis and Extensions of Relief"
requires: discretization. distance measure provided
... | 365702889c8949186088499181017edce294271d | 3,612,248 |
def resolve_translation(instance, _info, language_code):
"""Get translation object from instance based on language code."""
return instance.translations.filter(language_code=language_code).first() | aedd46bec3dc0d3a567718abf1fd69b460e69ba1 | 3,612,249 |
def get_conf_dict():
"""
获取标准、标签、业务、项目字典表
:return:
"""
# standard_version_id对应的字典
standard_dict = {}
standard_content_dict = {}
# online标准列表
standard_list = DataManageApi.standard_search({"is_online": 1})
# 标签字典
tag_dict = DataManageApi.tag_dict()
# 业务字典
all_biz_dict ... | afe8979a494bc584e1932439852d7229a16171e7 | 3,612,250 |
import logging
from datetime import datetime
def normalize_crunchtime(row):
"""Normalizes a single row of Crunchtime Baseball data
Args:
row: `dict`-ified row from Crunchtime Baseball spreadsheet
Returns:
Formatted model (`Model`)
"""
log = logging.getLogger(__name__)
model... | 3a94110653c2551498f45481cda3d2ad64ff1e4e | 3,612,251 |
import pandas
def screen_oligos(fasta_file, kmer_sizes, hairpin_tm_max = 35, homo_tm_max = 35,
tm_max = 65, tm_min = 50, min_occurrence = 5, no_3_T = True,
no_poly_3_GC = True, max_degen = 60, no_poly_run = True,
step = 3, primer_conc = 200, max_gap_prop = .1,
... | b1273d973b1f41da8debcd5f3c1429dd3dab68fc | 3,612,252 |
def vector3(draw, x=float64(), y=float64(), z=float64()):
"""
Generate value for ROS geometry message type "vector3".
Parameters
----------
x : hypothesis.strategies.floats()
Strategy to generate x value. (Default: Default hypothesis strategy.)
y : hypothesis.strategies.floats()
... | 21aacc179bbb767b255f6b00d7ce5aad2e64311f | 3,612,253 |
def build_worker(cfg: DictConfig) -> WorkerPool:
"""
Builds the worker.
:param cfg: DictConfig. Configuration that is used to run the experiment.
:return: Instance of WorkerPool.
"""
logger.info('Building WorkerPool...')
worker: WorkerPool = (
instantiate(cfg.worker, output_dir=cfg.o... | e619054cf313d493fa69ce4b0ea6e710d4f67e39 | 3,612,254 |
def rds_get_sensor_type(rd):
"""
For reference designator, determine sensor type to process.
"""
sensor_type = None
try:
for type in valid_sensor_types:
if '-' not in type:
check_type = '-' + type
else:
check_type = type
if ... | 9397ee93e34db3cc4fce3dd3d8c67069e953dd5b | 3,612,255 |
import os
import inspect
def create_repo_list_object(localized_resource_obj,
repo_list_p=None):
"""
Create a repo list object.
:param localized_resource_obj:
The localization object responsible for managing localized strings.
:param repo_list_p:
If ... | 2dec58b960fc856cdaa4e8cd38d7dcd59bb1634d | 3,612,256 |
def _reshape_into_tiled_square(data: np.array, n: int):
"""Manipulate the shape of the numpy arrays so it corresponds to one large square 3-channel image."""
data = data.reshape((n, n) + data.shape[1:])
data = data.transpose((0, 2, 1, 3, 4))
return data.reshape((n * data.shape[1], n * data.shape[3]) ... | 9958a0f9d0aafa5eeb94335f391650102757a2d9 | 3,612,257 |
from typing import Union
from datetime import datetime
def auto_regressive(start_date: Union[str, datetime.date],
end_date: Union[str, datetime.date],
frequency: str,
start_values: list,
cst: float,
order: int,
... | 1f52756f5f8b7cf644448cc6453a074abfbcb294 | 3,612,258 |
import dill
def load_estimators():
"""
Reads the ML fractional cover estimators
"""
with open('svmPipelines', 'rb') as input:
return dill.load(input) | aa1500185336a6624061da883838ac25187aae22 | 3,612,259 |
import inspect
import linecache
import ast
def getsource(obj):
"""Get the source code of an object."""
if inspect.isclass(obj):
# From Python 3.9 inspect library
obj = inspect.unwrap(obj)
file = inspect.getsourcefile(obj)
if file:
# Invalidate cache if needed.
... | bb85bedaf6117f0adcb5b2eeb6dab9d5f2b2a564 | 3,612,260 |
def read_stations(state):
"""Read the station table"""
rows = []
for line in open('ghcnd-stations.txt'):
if not line.startswith('USC') or line[38:40] != state:
continue
rows.append([line[:11], line[13:20], line[21:30], line[31:37],
line[38:40], line[41:76].st... | 53a0f3c77a8d4fb72ea8c7325484e9c75a461000 | 3,612,261 |
def _shared_ptr(name, nbytes):
""" Generate a shared pointer. """
return [
("std::shared_ptr<unsigned char> {name}("
"new unsigned char[{nbytes}], "
"[](unsigned char *d) {{ delete[] d; }});"
.format(name=name, nbytes=nbytes))
] | 1ab0779f2932c9225a1f579c958cfb290f935cfc | 3,612,262 |
def do_static_absolute(parser, token):
"""
'{% load url_toolkit %}'
"{% static_absolute 'test/fb.png' %}"
"""
return StaticFilesAbsoluteNode.handle_token(parser, token) | 79a49f69a1f0c6a4a5710b9fd5380a0d186785e2 | 3,612,263 |
def combine_dicts(dicts, keys):
"""
Turns list of dicts into dict of np arrays
"""
return {
key: np.array([d[key] for d in dicts])
for key in keys
} | 170dcd37c73555d5cae8debc2d325a581f2e9a6e | 3,612,264 |
def build_row_idx_filter_expr(row_idx, row_col):
"""Build calcite expression to filter rows by rowid.
Parameters
----------
row_idx
The row numeric indices to select
row_col
InputRefExpr referencing proper rowid column to filter by
Returns
-------
CalciteBaseExpr
... | 242dc307967f51a8c8a5d04aa243b51374c2c889 | 3,612,265 |
def html_escape(s):
"""Replace special characters "&", "<" and ">" to HTML-safe sequences.
If the optional flag quote is true, the quotation mark character (")
is also translated.
"""
s = s.replace("&", "&")
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace(" ", "&n... | 943c30ac00297d2e152638ff053497a5f06968e7 | 3,612,266 |
import torch
def k_smallest_elems(mags, k, noise):
"""Partial sort of tensor `mags` returning a list of the k smallest elements in order.
:param mags: tensor of magnitudes to partially sort
:param k: partition point
:param noise: probability
:return:
"""
mags *= e_greedy_normal_noise(mags... | b04c273ae1218193a65e8233d7b3d3d86cc80b61 | 3,612,267 |
import re
def render_docstring(def_elem, name, names):
"""
Render single docstring definition source.
"""
unregistered_tags = set()
# Handle brief and/or detailed description elements
value = "\n".join(filter(None, [
ElementRenderer.render(
def_elem.find("briefdescription"... | 45a2dea3957369502a10d7eb7993cf3d867dd633 | 3,612,268 |
def upload_to_es(nmap_result: dict, es_instance: Elasticsearch) -> bool:
"""
Uploads the nmap result to elasticsearch.
Input:
- nmap_result: a dictionary result of the nmap scan.
- es_instance: an Elasticsearch object used to index the nmap result.
"""
_doc = nmap_result
if not n... | 1d62d63674f802a6cf36f471f80d7846e1312e14 | 3,612,269 |
def decode_base64_str(
string: str,
urlsafe: bool = True,
encoding: str = DEFAULT_ENCODING,
errors: str = DEFAULT_ERRORS,
) -> str:
"""Decode Base64, correctly padding the string.
This is similar to :func:`~gd.crypto.decode_base64`,
except it operates on strings with their encoding.
Pa... | 12339aa267a3a04e6da0cd2284debfc72f36f5fa | 3,612,270 |
from typing import List
def _df_to_ner_items(
df: pd.DataFrame,
content_column: str = "Content",
annotations_column: str = "Annotations",
) -> List[LabeledTextItem]:
"""Converts pandas dataframe into a list of LabeledTextItem.
Parameters
----------
df: pd.DataFrame
The Pandas data... | 9ab740c89e81f575c2fc5641de68499d0868c5b7 | 3,612,271 |
def add_quads(grid, nids, eids_quads, nid_offset):
"""adds quad elements to the vtkUnstructuredGrid"""
nelements = 0
if eids_quads is not None:
nelements = eids_quads.shape[0]
eids = eids_quads[:, 0]
elem_nids = eids_quads[:, 1:]
#inids = np.searchsorted(nids, elem_nids)
... | f0fcf7baa4b36b85023031f0aa14f44830ba42f3 | 3,612,272 |
def approx_vertex_cover(g : Graph):
"""
顶点覆盖问题的近似算法
"""
C = []
edges = deepcopy(g.edges)
while len(edges) != 0:
u, v = g.getvertexfromedge(edges[0])
C += [u.key, v.key]
i = 0
while i < len(edges):
edge = edges[i]
if edge.vertex1.key == u.ke... | 1c12d6cd60988a284a392df98caeecdcc9743a83 | 3,612,273 |
def _IsZonalGroup(ref):
"""Checks if reference to instance group is zonal."""
return ref.Collection() == 'compute.instanceGroupManagers' | bf48f2c277fb03db2f0cc3ea42234781df9a2500 | 3,612,274 |
def plant(f, *, tag, **harvest_kwargs):
"""Injects tagged values into a function.
Transforms a function to one where tagged values can injected. In
implementation, returns a function that takes plants as an additional
initial argument.
Args:
f: a function to be transformed
tag: `str`, the harvest ta... | 1c3c36b0dbb31a5c83fcfcd22de403b62980ac0c | 3,612,275 |
def lex_ident(node_syn, pred_syn, gold_syn):
"""
1. check if the predicted synset's lexname equals to the gold synset's name
2. check if the predicted synset's lexname is in the set of its wordnet hypernyms' lexnames (including hypernyms/instance_hypernyms)
"""
pred_lex = pred_syn.lexname()
gold... | 487fe7c0772d9ecaf84a6f8fe349b0ec20fd3646 | 3,612,276 |
def get_word_count(blob, n=1):
"""
This method will build a word count DataFrame given a text blob.
Args:
blob (textblob.TextBlob): blob of all words from tweets
n (int): number of ngrams
Returns:
word count pandas.DataFrame
"""
# Get the count o... | c767566b8312708ab0e449bfa82f31052e2af90b | 3,612,277 |
def edges(cv_frame):
"""
Applies a Canny (edge-detection) filter
:param cv_frame: An OpenCV frame with RGB pattern
"""
# r, g, b = cv2.split(img) then cv2.merge([b,g,r])
gray = cv2.cvtColor(cv_frame, cv2.COLOR_RGB2GRAY)
edges = cv2.Canny(gray, 50, 150, apertureSize=3)
return edges | 1f0cd581c8814f06ec8b7b35a82586909007c9fa | 3,612,278 |
def remove_project_users(post_data=None, slug=None):
"""remove-project-users (Site admins/Site managers/Project managers only)
Usage: remove-project-users [-h] <slug> <users> ...
Arguments:
<slug> The slug of the project
<username> The username of the user to remove
Examples:
climesync remove-p... | a14e7dd7692f0118b2d29c958559a51352884a8e | 3,612,279 |
def avg_np_arr(data, area_cells=None, block_size=1, func=np.ma.mean):
"""
COARSENS: Takes data, and averages all positive (only numerical) numbers in blocks
E.g. with a block_size of 2, convert (720 x 1440) array into (360 x 720)
Args:
data: numpy array (2D)
area_cells:
block_siz... | 1fce6c6911f9d14741a19644c75819fb677be8fa | 3,612,280 |
def autoswitch(*args, **kwargs):
"""A decorator that exposes a function as a switch, "inferring" the name of the switch
from the function's name (converting to lower-case, and replacing underscores with hyphens).
The arguments are the same as for :func:`switch <plumbum.cli.switch>`."""
def deco(func):
... | 6221620fe437570b16f1b5bfccb9545c28810cba | 3,612,281 |
def normal_dist(x,mean,sigma):
"""
Function that computes a simple normal distribution (not the same as
the gaussian() function for emission line fitting).
"""
return 1.0/np.sqrt(2*np.pi*sigma**2)*np.exp(-(x-mean)**2/(2.0*sigma**2)) | 0217621386055318dc9a433f715e833463c6b5c0 | 3,612,282 |
def get_plugin_manager(namespace):
"""Fetch pluggy's plugin manager for our library."""
pm = pluggy.PluginManager(namespace)
log.info("Loading Hook Specifications..")
pm.add_hookspecs(specs)
log.info("Loading Hook Implemenations from entry points..")
pm.load_setuptools_entrypoints(namespace)
... | d09b59c55a7d25e2ccd5f4436eeb649bec440283 | 3,612,283 |
def _load(module):
"""Load a module from its name."""
return import_module("{}.{}".format(__name__, module)) | daa75b7ff06e9e31c6863525eb08e0389cefe337 | 3,612,284 |
from typing import OrderedDict
import re
def get_ops_from_graph(graph):
"""Get ops from graph and convert Node."""
ops = graph.get_operations()
merged_ops = OrderedDict()
for op in ops:
support_ops_name = None
scope_name = None
for _support_ops_name in Node.__support_ops__:
... | f641c81122f5e06c18bc734ae1d11a7ab5147019 | 3,612,285 |
import tqdm
import os
def train(cfg, train_dataset, features, model, tokenizer, continue_from_global_step=0):
""" Train the model """
if cfg.local_rank in [-1, 0]:
_dir_splits = cfg.output_dir.split('/')
_log_dir = '/'.join([_dir_splits[0], 'runs'] + _dir_splits[1:])
tb_writer = Summar... | 0e9cefc7e881898ed3e9a52d3cf1b0b6b5a94bf0 | 3,612,286 |
import os
def path_to_settings(ini_file):
"""
Find directory of ini-file relative to this directory (currently two directories up).
:param ini_file: name of ini-file, e.g. development.ini
:type: str
:return: path to directory containing ini-file
:rtype: str
"""
dir_name = os.path.absp... | 16cb765034c11fbbf038b474d04d571f59f4389b | 3,612,287 |
from typing import Sequence
from typing import Optional
from typing import Union
from pydantic import BaseModel # noqa: E0611
from typing import Dict
from typing import Any
import copy
def _create_models(
model: _input_model_type, obs: Sequence[str], lineages: Sequence[Optional[str]]
) -> _return_model_type:
... | 91de988c5ac6270aa8c9a0ab6884b3f6735acd87 | 3,612,288 |
import numbers
import collections
def _setup_put(chid, value, chtype=None, count=None):
"""
Setup the C value for ca put. This is used by both :func:`put` and :func:`sg_put`.
Return (chtype, count, c_value) tuple.
"""
if chtype is None:
chtype = field_type(chid)
native_count = element... | 0cf495ca570cc254c19a45a0e7a419c6fdb489e0 | 3,612,289 |
def perm_get_ssh_challenge_token(issuer, kwargs):
"""
Checks if an account can request a challenge token.
:param issuer: Account identifier which issues the command.
:returns: True if account is allowed to call the API call, otherwise False
"""
return True | 5002d9bb2b7d8aed44122926153396acc9fcfe18 | 3,612,290 |
def distrust(mac: str, *args, **kwargs) -> None:
"""Distrust a bluetooth device.
:param mac: MAC address of bluetooth device.
"""
with UsedEngine(*args, **kwargs) as engine:
return engine.distrust(mac) | 93c5ab277b84eafa7f6f95db86bbd47d1109f4f2 | 3,612,291 |
def masked_word_model_loss():
"""Computes the masked word language modeling loss"""
loss_fct = CrossEntropyLoss()
loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
return loss | 34485cb073ef3802944eeb9026fca2c6797fdc0c | 3,612,292 |
import copy
def log_to_file(file_out, protocol="json"):
"""Log the tuning records into file.
The rows of the log are stored in the format of autotvm.record.encode.
for lhs == rhs, we add an extra rhs = [] record
Parameters
----------
file_out : str
The file to log to.
protocol: st... | b5739a210a0233b909d9b1345123e9101b64f950 | 3,612,293 |
def periodify(f, T=2*np.pi, tinit=0.0):
""" Forces a piecewise periodic function
"""
def f_p(t):
return f(tinit + np.mod(t, T))
return f_p | 3c1209e2e71edb41c60a30c257345aba4c78c8f5 | 3,612,294 |
def circumference2(d):
"""Calculates the circumference of a cirle using the formula:
\u03C0 * diameter
Parameters
----------
d: int or float
The diameter in the equation.
Returns
-------
Float
\u03C0 * d
Raises
------
ValueError
If d::
... | 3af0b58132ec011cb70a36af70c08c2202192632 | 3,612,295 |
def namedict(name, requires=(), fields=None):
"""
Return a subclass of dict with named fields
:param fields: option fields
:param requires: requires fields
"""
return type(name, (NamedDict,), {
"__Fields__": fields or {},
"__Requires__": requires,
}) | 901582c44fce481f2985ef37122f78e2af52ad50 | 3,612,296 |
import os
def dir_empty_ne(path: str) -> Result[bool, Error]:
"""Check if directory is empty, do not raise exceptions.
Args:
path (str): path to a directory.
Returns:
Result[bool, Error]:
Ok (True): directory is empty.
Ok (False): directory is not empty.
... | e7b00934e15def82f974048d0646dd0a3ba25f06 | 3,612,297 |
def sumy_clean_lines(lines):
"""
Compared to regular clean lines, this one preserves heading and paragraph information.
"""
new_lines = []
for line in lines:
if line.startswith("="):
new_lines.append(line.strip("=").upper())
else:
new_lines.append(line)
... | 1e16514b71c3e11dd6c3b701a6a8dbab7d796b41 | 3,612,298 |
import traceback
def write_traceback(stream, err, test):
"""Converts a sys.exc_info()-style tuple of values into a string.
Copied from Python 2.7's unittest.TestResult._exc_info_to_string.
"""
def _is_relevant_tb_level(tb):
return '__unittest' in tb.tb_frame.f_globals
def _count_relevant... | cc8528fdb556359b67db4e9a95327d0c96fc16d3 | 3,612,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.