content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_package_environment():
"""Loads templates from the current Python package"""
templates_dir = os.path.dirname(templates.__file__)
template_loader = jinja2.FileSystemLoader(searchpath=templates_dir)
return jinja2.Environment(loader=template_loader) | 47,600 |
def import_token():
"""
Attempts to to get the discord token from auth file then env variable
Returns:
(string)
"""
try:
import auth
return auth.DISCORD_HACKSPACE_TOKEN
except ImportError:
try:
import os
return os.environ["DISCORD_HACK... | 47,601 |
def _evolve_angles_forwards(
mass_1, mass_2, a_1, a_2, tilt_1, tilt_2, phi_12, f_start, final_velocity,
tolerance, dt, evolution_approximant
):
"""Wrapper function for the SimInspiralSpinTaylorPNEvolveOrbit function
Parameters
----------
mass_1: float
primary mass of the binary
mass... | 47,602 |
def get_execution(execution):
"""Get an execution"""
logging.info('[ROUTER]: Getting execution: '+execution)
include = request.args.get('include')
include = include.split(',') if include else []
exclude = request.args.get('exclude')
exclude = exclude.split(',') if exclude else []
try:
... | 47,603 |
def fz_Kd_singlesite(K: float, p: np.ndarray, x: np.ndarray) -> np.ndarray:
"""Fit function for Cl titration."""
return (p[0] + p[1] * x / K) / (1 + x / K) | 47,604 |
def test_reverse_string():
"""Solution to exercise C-4.16.
Write a short recursive Python function that takes a character string s and
outputs its reverse. For example, the reverse of "pots&pans" would be
"snap&stop".
"""
string1 = "pots&pans"
string2 = "abc"
assert chap4.reverse_string... | 47,605 |
def show_exam_result(request, course_id, submission_id):
""" Returns exam result template """
course_obj = get_object_or_404(Course, pk=course_id)
submission_obj = get_object_or_404(Submission, pk=submission_id)
submission_choices = submission_obj.choices.all()
choice_ids = [choice_obj.id for choic... | 47,606 |
def createInvoiceObject(account_data: dict, invoice_data: dict) -> dict:
"""
example: https://wiki.wayforpay.com/view/852498
param: account_data: dict
merchant_account: str
merchant_password: str
param: invoice_data
reqularMode -> one of [
... | 47,607 |
def get_un_vn(p):
"""
Gets all values of u and v for the n'th eigenstate, as a function of the variable that e.g. the eigenenergy is a function of, named lambda_.
Notes
-----
- lambda_ is e.g. mu or Ez, and has the unit of meV.
"""
pass | 47,608 |
def _kmeans_seed_points(points, D, d, C, K, trial=0):
"""A seed point generation function that puts the seed points at customer
node point cluster centers using k-Means clustering."""
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=K, random_state=trial).fit(points[1:])
return kme... | 47,609 |
def site_geolocation(site):
""" Obtain lat-lng coordinate of active trials in the Cancer NCI API"""
try:
latitude = site['org_coordinates']['lat']
longitude = site['org_coordinates']['lon']
lat_lng = tuple((latitude, longitude))
return lat_lng
except KeyError: # key ['org... | 47,610 |
def get_scaling_desired_nodes(sg):
"""
Returns the numb of desired nodes the scaling group will have in the future
"""
return sg.get_state()["desired_capacity"] | 47,611 |
def _BitmapFromBufferRGBA(*args, **kwargs):
"""_BitmapFromBufferRGBA(int width, int height, buffer data) -> Bitmap"""
return _gdi_._BitmapFromBufferRGBA(*args, **kwargs) | 47,612 |
def bing_to_s3(ctx, prefix, bucket):
"""Moves Bing reports to S3"""
server = ctx.obj['server']
processor = bing.BingReportsToS3(bucket=bucket, prefix=prefix)
server.register_processor(ctx.obj['username'], processor)
server.run() | 47,613 |
def get_user_analysis_choice():
"""
Function gets the user input to determine what kind of data
quality metrics s/he wants to investigate.
:return:
analytics_type (str): the data quality metric the user wants to
investigate
percent_bool (bool): determines whether the data will be seen
... | 47,614 |
def points_to_segments(points):
"""Convert a list of points, given in clockwise order compared to the inside of the system to a list of segments.
The last point being linked to the first one.
Args:
points (list): list of lists of size 2
Returns:
[np.ndarray]: 2D-array of segments - ea... | 47,615 |
def main() -> None:
"""Main function"""
arguments = [
Argument("-c", "--cluster", "API server IP:port details")]
args = parse_args(
"Demonstrates Snapshot Operations using REST API.", arguments,
)
setup_logging()
headers = setup_connection(args.api_user, args.api_pass)
snap... | 47,616 |
def neighbors(
adata: AnnData,
n_neighbors: int = 15,
n_pcs: Optional[int] = None,
use_rep: Optional[str] = None,
knn: bool = True,
random_state: Optional[Union[int, RandomState]] = 0,
method: Optional[_Method] = "umap",
metric: Union[_Metric, _MetricFn] = "euclidean",
metric_kwds: M... | 47,617 |
def trial_10_detect_plaintext_type_with_shift_short_changing_key():
"""
Trial 10
-------
Testing ability to recognize the type of text when the cipher shift with short key length
The task of the ML is to recognize the difference between english text and binary data
ML model - FC NN
... | 47,618 |
def resnet_v1_34(inputs,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
spatial_squeeze=True,
reuse=None,
scope='resnet_v1_34', **kwargs):
"""ResNet-34 model of [1]. See ... | 47,619 |
def test_wordle_guesses_letters():
"""WordleGuesses.wordle_letters is set appropriately."""
wordle_letters = get_wordle_letters("beats", "bybbb")
guesses = WordleGuesses(wordle_letters)
assert guesses.wordle_letters == wordle_letters | 47,620 |
def from_dlpack(x: Union[ivy.Array, ivy.NativeArray]) -> ivy.Array:
"""Returns a new array containing the data from another (array) object with a
``__dlpack__`` method.
Parameters
----------
x object
input (array) object.
Returns
-------
ret
an array containing the dat... | 47,621 |
def render_webpage_string(vegalite_spec: str) -> str:
"""
Renders the given Vega-lite specification into a string of an HTML webpage
that displays the specified plots.
:param vegalite_spec str: The Vega-lite plot specification to create a
webpage for.
:returns: A string of a webpage with th... | 47,622 |
def _parse_blog(element):
"""
Parse and return genral blog data (title, tagline etc).
"""
title = element.find("./title").text
tagline = element.find("./description").text
language = element.find("./language").text
site_url = element.find("./{%s}base_site_url" % WP_NAMESPACE).text
blog_... | 47,623 |
def summarize_block(block):
"""
Return the sentence that best summarizes block.
"""
sents = nltk.sent_tokenize(block)
word_sents = map(nltk.word_tokenize, sents)
d = dict((compute_score(word_sent, word_sents), sent)
for sent, word_sent in zip(sents, word_sents))
return d[max(d.k... | 47,624 |
def weekend_subsets_3_2_rule(M, i, t, w, e, d1, d2):
"""
TODO: Write me
:param M: Model
:param i:
:param t:
:param w:
:param e:
:param d1:
:param d2:
:return:
"""
days_subset = [d1, d2]
return sum(M.TourTypeDay[i, t, d, w] for d in days_subset) <= \
sum(M... | 47,625 |
def get_club_result() -> list:
""" Returns the club's page. """
d = api_call("ion", "activities")
while "next" in d and d["next"] is not None:
for result in d["results"]:
if "cube" in result["name"].lower():
return result
d = api_call("ion", d["next"], False) | 47,626 |
def DiffuserConst_get_decorator_type_name():
"""DiffuserConst_get_decorator_type_name() -> std::string"""
return _RMF.DiffuserConst_get_decorator_type_name() | 47,627 |
def lemmatizer():
"""
Substitutes words by their lemma
"""
lemmatizer = WordNetLemmatizer()
preprocessor = lambda text: [lemmatizer.lemmatize(w) for w in \
text.split(" ")]
def preprocess(name, dataset):
description = " Running NLTK Lemmatizer - preprocessing dataset "
description += "{}...".format(name)
... | 47,628 |
def convert_numpy_array(numpy_array: np.ndarray):
"""
Converts a numpy array into compressed bytes
:param numpy_array: An array that is going to be converted into bytes
:return: A BytesIO object that contains compressed bytes
"""
compressed_array = io.BytesIO() # np.savez_compressed() requires ... | 47,629 |
def notas(* valores, sit=False):
"""
-> Função para analisar notas e situações de vários alunos.
:param valores: uma ou mais notas dos alunos (aceita várias)
:param sit: valor opcional, indicando se deve ou não adicionar a situação
:return: dicionário com várias informações sobre a situação da turma... | 47,630 |
def append_OrbitSection(df):
"""Use OrbitDirection flags to identify 4 sections in each orbit."""
df["OrbitSection"] = 0
ascending = (df["OrbitDirection"] == 1) & (df["QDOrbitDirection"] == 1)
descending = (df["OrbitDirection"] == -1) & (df["QDOrbitDirection"] == -1)
df["OrbitSection"].mask(
... | 47,631 |
def _get_old_time(request):
"""
Get's the alarm time the user wants to change
Args:
request (Request): contains info about the conversation up to this point
(e.g. domain, intent, entities, etc)
Returns:
string: resolved 24-hour time in XX:XX:XX format
"""
old_time_entit... | 47,632 |
def sxxxxx(p, nss):
"""
Defines a scalar wavefunction. Input momenta have shape (num events, 4).
Parameters
----------
p: tf.Tensor, scalar boson four-momenta of shape=(None,4)
nss: tf.Tensor, final|initial state of shape=(), values=(+1|-1)
Returns
-------
phi: tf.Tenso... | 47,633 |
def main():
""" Enable preload options
"""
# Enable preload options
util.set_environment('WINEDLLOVERRIDES','dxgi=n') | 47,634 |
def get_user_directories_directory():
"""
Determines the directory where user directories are stored. This is actually
not that easy, and different systems have different ways of doing it. So,
we try adding a user called '_chaptest_' just to see where the directory goes,
and use that.
"""
... | 47,635 |
def target_risk_contributions(target_risk, cov):
"""
Returns the weights of the portfolio that gives you the weights such
that the contributions to portfolio risk are as close as possible to
the target_risk, given the covariance matrix
"""
n = cov.shape[0]
init_guess = np.repeat(1 / n... | 47,636 |
def check_petpvc(version_requirements=None):
"""Check PETPVC software."""
from colorama import Fore
from clinica.utils.exceptions import ClinicaMissingDependencyError
list_binaries = ['petpvc', 'pvc_diy', 'pvc_gtm', 'pvc_iy', 'pvc_labbe', 'pvc_make4d', 'pvc_mg',
'pvc_mtc', 'pvc_rbv... | 47,637 |
def read_monthly_indices_from_CLIMEXP(name_of_index):
"""
Try reading various monthly indices from KNMI's Climate Explorer
"""
import urllib, datetime
import xarray as xr
import numpy as np
name_to_url = {
'M1i': 'http://climexp.knmi.nl/data/iM1.dat', # 1910 ->
'M2i': 'h... | 47,638 |
def generate_xdataEMX(parm):
"""
Generate the x data from the parameters dictionary
Parameters:
parm: [dict] parameters
Returns:
xdata = nd.array[XNbPoints]
"""
# Extracts the x axis data from the parameter file
try:
xpoints = parm['SSX']
except KeyError:
... | 47,639 |
def csv_2d_cartesian(filename, polar=False, scan=False):
"""extract 2d cartesian coordinates from a file"""
x_values = []
y_values = []
with open(filename) as data_file:
odom_data = csv.reader(data_file)
for row in odom_data:
# if scan:
# row[1] = pi/2 + float... | 47,640 |
def create_num_bucket_backup_files_with_duplicates(
context,
num,
bucket,
file_type):
""" Creates a specified number of files, and duplicates of those files. """
for suffix in ["orig", "dup"]:
create_num_bucket_files(context, num, bucket, file_type, suffix) | 47,641 |
def get_edge_similarity(node_pos,neighbor_positions):
"""
useful for finding approximate colinear neighbors.
"""
displacements = get_displacement_to_neighbors(node_pos,neighbor_positions)
n_neighbors = neighbor_positions.shape[0]
# Quick and dirty, can reduce computation by factor 2.
similar... | 47,642 |
def high_pass_filter(x_vals, y_vals, cutoff, inspectPlots=True):
"""
Replicate origin directy
http://www.originlab.com/doc/Origin-Help/Smooth-Algorithm
"rotate" the data set so it ends at 0,
enforcing a periodicity in the data. Otherwise
oscillatory artifacts result at the ends
This uses a ... | 47,643 |
def crontab_task_switch():
"""
关闭配置开关
"""
import datetime
from apps.console.tools.tasks import ToolsTaskFinishRecord, ToolsTaskConf
conf = ToolsTaskConf.select().where(ToolsTaskConf.task_switch == ToolsTaskConf.TASK_SWITCH_ON)
now = datetime.datetime.now()
for c in conf:
if c.end... | 47,644 |
def encode_data_cartoon(path_to_local='D:\Experiments',data_dir='cartoonset10k', size_shape=(128,128), attribute="hair_color"):
"""
Load images from .png or .npz files into numpy vectors
"""
images = list()
labels = list()
for filename in os.listdir(data_dir):
if(filename.endswith('.png'... | 47,645 |
def hyetograph(dataframe, col="precipitation", freq="hourly", ax=None, downward=True):
"""Plot showing rainfall depth over time.
Parameters
----------
dataframe : pandas.DataFrame
Must have a datetime index.
col : string, optional (default = 'precip')
The name of the column in *data... | 47,646 |
def objective(z, x):
""" Objective. """
return park2_3_mf(z, x) | 47,647 |
def main() -> None:
"""
Main entry point
"""
# parse command line arguments
_parse_args() | 47,648 |
def p_command_save(p):
"""command : save ID in ID"""
p[0] = ('save', p[2], p[4]) | 47,649 |
def test_graph__is_dag():
"""Validates that a graph is directed and acyclic (i.e. a DAG)."""
dag_parser = DbtDagParser(manifest_path=MANIFEST_PATH)
assert nx.is_directed_acyclic_graph(dag_parser.graph) is True | 47,650 |
def validate_config(crawler_path):
"""
Validates config
"""
with open(crawler_path) as file:
config = json.load(file)
if 'total_articles_to_find_and_parse' not in config:
raise IncorrectNumberOfArticlesError
if 'seed_urls' not in config:
raise IncorrectURLError
ur... | 47,651 |
def parse_FORCE_SETS(natom=None, filename="FORCE_SETS", to_type2=False):
"""Parse FORCE_SETS from file.
to_type2 : bool
dataset of type2 is returned when True.
Returns
-------
dataset : dict
Displacement dataset. See Phonopy.dataset.
"""
with open(filename, "r") as f:
... | 47,652 |
def DeserializeFileAttributesFromObjectMetadata(obj_metadata, url_str):
"""Parses the POSIX attributes from the supplied metadata.
Args:
obj_metadata: The metadata for an object.
url_str: File/object path that provides context if a warning is thrown.
Returns:
A POSIXAttribute object with the retriev... | 47,653 |
def hex_to_64(hexstr):
"""Convert a hex string to a base64 string.
Keyword arguments:
hexstr -- the hex string we wish to convert
"""
B64CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
## internals
# bits contains the bits read off so far that don't make enou... | 47,654 |
def get_frozen_graph(graph_file):
"""Read Frozen Graph file from disk."""
with tf.gfile.FastGFile(graph_file, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
return graph_def | 47,655 |
def test_parse_connack():
"""
A CONNACK for a successful connect is successfuly parsed.
"""
data = bytearray()
data.extend(
binascii.unhexlify(b'20020000')
)
msgs = []
c = _parsing.parse(data, msgs)
assert len(data) == c
assert msgs[0].return_code == 0
assert msgs[0].... | 47,656 |
def wrap_functional_unit(dct):
"""Transform functional units for effective logging.
Turns ``Activity`` objects into their keys."""
data = []
for key, amount in dct.items():
if isinstance(key, int):
data.append({"id": key, "amount": amount})
else:
try:
... | 47,657 |
def load_dataset_class(name):
"""dynamically load a class object from a dataset file.
Return: dataset class object
"""
base_dir = os.path.join("lmnet", "datasets")
dataset_class = _load_class_from_name(name, base_dir)
return dataset_class | 47,658 |
def full_fuel_requirement(mass: int) -> int:
"""Complete fuel requirements for a single module."""
base_fuel = fuel_requirement(mass)
return base_fuel + sum(additional_fuel_requirements(base_fuel)) | 47,659 |
def is_private(name):
"""Check whether a Python object is private based on its name."""
return name.startswith("_") | 47,660 |
def get_suitable_output_file_name_for_current_output_format(output_file, output_format):
""" renames the name given for the output_file if the results for current_output format are returned compressed by default
and the name selected by the user does not contain the correct extension.
output_file : str, op... | 47,661 |
def efficientnet_b1(
num_classes: int = 1000,
class_type: str = "single",
dropout: float = 0.2,
se_mod: bool = False,
) -> EfficientNet:
"""
EfficientNet B1 implementation; expected input shape is (B, 3, 240, 240)
:param num_classes: the number of classes to classify
:param class_type: ... | 47,662 |
def importdb(cmdobj, **opt):
"""
导入Decipher Syndrome
"""
register_connection("cmd-import", opt['db'], opt['host'])
selectchr = []
try:
for i in opt['chr']:
selectchr.append(positions[i-1])
except TypeError,e:
selectchr = positions
except Exception,e:
p... | 47,663 |
def mark_user_authenticated(user, login):
"""
Modify a User so it knows it is logged in - checked via user.is_authenticated()
"""
setattr(user, ACTIVATED_LOGIN_KEY, login)
return user | 47,664 |
def handle_adminlistlog(bot, event):
""" lists log filters. """
from jsb.utils.log import logplugs, logfilter
event.reply("plugs: %s filter: %s" % (str(logplugs), str(logfilter))) | 47,665 |
def remove_list_from_all_contacts(user, list_key):
""" Removes the list from all contacts. """
contacts = get_contacts_for_user(user)
for contact in contacts:
if list_key in contact.list_keys:
contact.list_keys.remove(list_key)
contact.put() | 47,666 |
def assignments(bmat, order=1, ntry=10):
"""Make assignments between rows and columns.
The objective is to have assigments following the following conditions:
- all association are allowed in bmat,
- each row is associated with a unique column,
- each column is associated with a unique row,
... | 47,667 |
def save_game():
"""Save a game from file."""
print('ERROR: saving a game not currently supported')
return
file_name = raw_input("Filename: ")
print("Saving game to file {0}".format(file_name))
with open(file_name, 'w') as f:
dump(game, f) | 47,668 |
def test_pset_field_default_non_optional():
"""
By default ``pset_field`` is non-optional, i.e. does not allow
``None``.
"""
class Record(PRecord):
value = pset_field(int)
with pytest.raises(TypeError):
Record(value=None) | 47,669 |
def _tracemin_fiedler(L, X, normalized, tol, method):
"""Compute the Fiedler vector of L using the TraceMIN-Fiedler algorithm.
"""
n = X.shape[0]
if normalized:
# Form the normalized Laplacian matrix and determine the eigenvector of
# its nullspace.
e = sqrt(L.diagonal())
... | 47,670 |
def default_char_class_join_with():
""" default join for char_class and combine types """
return '' | 47,671 |
def infer_orf(pos1, pos2, corr_coeff=np.zeros(7)):
"""
Approximation of spatial correlations at seven angles, with borders at
30 degrees.
"""
if np.all(pos1 == pos2):
return 1.
else:
eta = np.arccos(np.dot(pos1, pos2))
idx = np.round( eta / np.pi * 180/30.).astype(int)
... | 47,672 |
def load_all_metamaps(dirname, number_cap=None):
"""Loads all the metamaps in the given directory, returning a giant numpy array"""
map_names = os.listdir(dirname)
if isinstance(number_cap, numbers.Integral) and number_cap > 0:
map_names = map_names[:number_cap]
all_maps = np.zeros((len(map_name... | 47,673 |
def help():
"""It prints that how user can query."""
print("querying format")
print("Get all endpoints:- show endpoints")
print("Get all class_endpoints:- show classEndpoints")
print("Get all collection_endpoints:- show collectionEndpoints")
print("Get all members of collection_endpoint:-",
... | 47,674 |
def draw_bs_reps_ind(data, func, size=1):
"""Draw bootstrap replicates, resampling indices"""
# Set up array of indices
inds = np.arange(len(data))
# Initialize replicates
bs_reps = np.empty(size)
# Generate replicates
for i in range(size):
bs_inds = np.random.choice(inds, size=le... | 47,675 |
def insercion(lista):
"""
Ordena una lista de elementos según el método de inserción.
Pre: los elementos de la lista deben ser comparables.
Post: la lista está ordenada.
"""
for i in range(1, len(lista)):
insertar_ordenado(lista, i) | 47,676 |
def test_return_net_list():
"""
test transforming matrix as np.array to list of edges
"""
_make_tmp_dir()
conmat = np.load(conmat_file)
list_conmat = return_net_list(conmat, int_factor=1000)
assert list_conmat.shape[1] == 3 | 47,677 |
def get_committee_assignment(
state: BeaconState,
config: Eth2Config,
epoch: Epoch,
validator_index: ValidatorIndex,
) -> CommitteeAssignment:
"""
Return the ``CommitteeAssignment`` in the ``epoch`` for ``validator_index``.
``CommitteeAssignment.committee`` is the tuple array of validators i... | 47,678 |
def from_tfp(posterior, var_names=None, *, coords=None, dims=None):
"""Convert tfp data into an InferenceData object."""
return TfpConverter(
posterior=posterior, var_names=var_names, coords=coords, dims=dims
).to_inference_data() | 47,679 |
def collection_file_fixture(config, filesystem):
"""Return a test CollectionFile instance"""
collection_name = 'test-collection'
file_name = 'index'
collection_file = CollectionFile(config, filesystem, collection_name, file_name)
collection_file.get_collection().get_path().mkdir(parents=True)
r... | 47,680 |
def test_django_settings_installed_apps_has_app_data():
"""Test that get settings info has installed apps as value."""
info = get_settings_info()
assert info['INSTALLED_APPS'] == ['django.contrib.admin',
'django.contrib.auth',
'djan... | 47,681 |
def get_array_of_data():
"""Function helps to collect all filtered data in one array and it returns that"""
array_of_data = []
array_of_messages = gmail_get.get_bodies_of_messages()
for msg in array_of_messages:
if 'новый сотрудник' in msg:
message = get_data_from_text(msg)
... | 47,682 |
def call_blade_functions (calls):
"""
Call a set of system functions for each blade in the rack. The results of the calls will be
aggregated together for each blade.
:param calls: A list of tuples containing the functions to call, the name of the parameter that
contains the blade ID, and a lis... | 47,683 |
def interaction_distances(pairs, ppis):
"""
For every pair in pairs, calculate the distance between their interaction
patterns.
"""
allps = pu.unique_items(pairs)
dpartners = partner_scores_dict(ppis, allps)
dists = []
for a,b in pairs:
dists.append(distance_partners(a, b, dpartn... | 47,684 |
def seglearn_wrapper(func: Callable, func_name: Optional[str] = None) -> FuncWrapper:
"""Wrapper enabling compatibility with seglearn functions.
As [seglearn feature-functions](https://github.com/dmbee/seglearn/blob/master/seglearn/feature_functions.py)
are vectorized along the first axis (axis=0), we... | 47,685 |
def spline_fit(output_wave,input_wave,input_flux,required_resolution,input_ivar=None,order=3,max_resolution=None):
"""Performs spline fit of input_flux vs. input_wave and resamples at output_wave
Args:
output_wave : 1D array of output wavelength samples
input_wave : 1D array of input wavelength... | 47,686 |
def add_point_key_to_heatmap_collection(db, quantized_coords, precision, label, count):
""" Adds a new point key to database_schema.COLLECTION_HEATMAP_SUBCOLLECTION_WEIGHTED_POINTS.
The point key will be added to the relevant precision document.
"""
precision_string_id = 'precision{precision_number}'.f... | 47,687 |
def park2_3_mf(z, x):
""" Computes the Park2_3 function. """
f = [z[0][0]/5000.0, z[1]/10.0]
return park2_3_z_x(f, x) | 47,688 |
def make_batch_sql(
table, datas, auto_update=False, update_columns=(), update_columns_value=()
):
"""
@summary: 生产批量的sql
---------
@param table:
@param datas: 表数据 [{...}]
@param auto_update: 使用的是replace into, 为完全覆盖已存在的数据
@param update_columns: 需要更新的列 默认全部,当指定值时,auto_update设置无效,当dupl... | 47,689 |
def get_dimensions():
"""Returns bot_config.py's get_attributes() dict."""
# Importing this administrator provided script could have side-effects on
# startup. That is why it is imported late.
try:
if _in_load_test_mode():
# Returns a minimal set of dimensions so it doesn't run tasks by error.
d... | 47,690 |
def find_project_root(srcs):
"""Return a directory containing .git, .robocop or pyproject.toml.
That directory will be a common parent of all files and directories
passed in `srcs`.
If no directory in the tree contains a marker that would specify it's the
project root, the root of the file system is... | 47,691 |
def use(name):
"""
Set the name of the GUI toolkit we should use.
"""
global toolkit, family
name = name.lower()
if name.startswith('choose'):
pass
elif name.startswith('qt') or name.startswith('pyside'):
family = 'qt'
if name == 'qt':
name = 'qt4'
... | 47,692 |
def test_scenario24(kiali_client, openshift_client, browser):
""" DestinationRule: DISABLED at mesh-level
"""
tests = ValidationsTest(
kiali_client=kiali_client, openshift_client=openshift_client, browser=browser,
objects_path=istio_objects_mtls_path.strpath)
tests.test_istio_ob... | 47,693 |
def __virtual__():
"""
Return virtual name of the module.
:return: The virtual name of the module.
"""
if HAS_SQLI:
return __virtualname__
return False, "sqlite3 module is missing" | 47,694 |
def filter_contours(flist, contours, dist):
""" Filter out all visual cues with a eucl_dist(P/A ratio) smaller than .05
"""
n, fltr_cnts, bad_cnts = [], [], []
# loop over each frame to verify condition
for i in range(len(flist)):
fltr_areas = list(np.array(contours[i])[np.where(np.array(dis... | 47,695 |
def count_ents(phrase):
"""
Counts the number of Named Entities in a spaCy Doc/Span object.
:param phrase: the Doc/Span object from which to remove Named Entities.
:return: The number of Named Entities identified in the input object.
"""
named_entities = list(phrase.ents)
return len(named_en... | 47,696 |
def test_SearchQuery_has_source_clause_for_fields_constraint():
"""If there's a "fields" query param, there's a "_source" property in the
Elasticsearch query."""
params = types.ItemsQueryType({'fields': 'id'})
sq = search_query.SearchQuery(params)
assert '_source' in sq.query | 47,697 |
def reset():
"""
Reset all global variables for use in future passes
"""
global blur_step, bird_step, birdbb_step
global dir_path, des_path, num_files
global first_pass, index, files
global comp, std, std_hash, count
global images, boxes, canvas
blur_step = bird_step = birdbb_step =... | 47,698 |
def version_command(argv) -> CommandResult:
"""Show FlakeHell version.
"""
print('FlakeHell', colored(flakehell_version, 'green'))
print('Flake8 ', colored(flake8_version, 'green'))
print('For plugins versions use', colored('flakehell plugins', 'green'))
return ExitCode.OK, '' | 47,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.