content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def distance_along_glacier(nx, map_dx):
"""Calculates the distance along the glacier in km.
Parameters
----------
nx : int
number of grid points
map_dx : int
grid point spacing
Returns
-------
ndarray
distance along the glacier in km.
"""
return np.linsp... | 5,342,800 |
def make_docs():
"""Create documentation"""
with lcd("docs"):
## generate Sphinx HTML documentation, including API docs
try:
remove("docs/fab_support.rst")
except FileNotFoundError:
pass
try:
remove("docs/modules.rst")
except FileNotFou... | 5,342,801 |
def p_entity_body_outer(p: YaccProduction) -> None:
"""entity_body_outer : mls entity_body END"""
p[0] = (p[1], p[2]) | 5,342,802 |
def make_postdict_to_fetch_token(token_endpoint: str, grant_type: str,
code: str, client_id: str,
client_secret: str,
redirect_uri: str) -> dict:
"""POST dictionary is the API of the requests library"""
return {'u... | 5,342,803 |
def _haxe_std_lib(ctx):
"""
_haxe_std_lib implementation.
Args:
ctx: Bazel context.
"""
toolchain = ctx.toolchains["@rules_haxe//:toolchain_type"]
build_source_file = ctx.actions.declare_file("StdBuild.hx")
toolchain.create_std_build(
ctx,
ctx.attr.t... | 5,342,804 |
def detect_vswhere_path():
"""
Attempt to detect the location of vswhere, which is used to query the installed visual studio tools (version 2017+)
:return: The validated path to vswhere
"""
# Find VS Where
path_program_files_x86 = os.environ['ProgramFiles(x86)']
if not path_program_files_x86... | 5,342,805 |
def spread_match_network(expr_df_in, node_names_in):
"""
Matches S (spreadsheet of gene expressions) and N (network)
The function returns expr_df_out which is formed by reshuffling columns of
expr_df_in. Also, node_names_out is formed by reshuffling node_names_in. The
intersection of node_names... | 5,342,806 |
def _InstallNanny():
"""Installs the nanny program."""
# We need to copy the nanny sections to the registry to ensure the
# service is correctly configured.
new_config = config.CONFIG.MakeNewConfig()
new_config.SetWriteBack(config.CONFIG["Config.writeback"])
for option in _NANNY_OPTIONS:
new_config.Set... | 5,342,807 |
def top_level(url, data):
"""Read top level names from compressed file."""
sb = io.BytesIO(data)
txt = None
with Archive(url, sb) as archive:
file = None
for name in archive.names:
if name.lower().endswith('top_level.txt'):
file = name
break
... | 5,342,808 |
def get_timeseries_data(request):
"""
AJAX Controller for getting time series data.
"""
return_obj = {}
# -------------------- #
# VERIFIES REQUEST #
# -------------------- #
if not (request.is_ajax() and request.method == "POST"):
return_obj["error"] = "Unable to establis... | 5,342,809 |
def line_col(lbreaks: List[int], pos: int) -> Tuple[int, int]:
"""
Returns the position within a text as (line, column)-tuple based
on a list of all line breaks, including -1 and EOF.
"""
if not lbreaks and pos >= 0:
return 0, pos
if pos < 0 or pos > lbreaks[-1]: # one character behind ... | 5,342,810 |
def show_img_augmentation(X, Y, sess):
"""This function is to visulize the result of data augmentation for testing"""
i = 0 # show the i-th image
img_ori, img_aug, hm_ori, hm_aug = sess.run([x_in, x_batch, y_in, hm_target_batch], feed_dict={x_in: X, y_in: Y})
img_aug = reshape_img(img_aug, i)
img_o... | 5,342,811 |
def init_setup(dbhost, dbname, dbusername, dbpassword, projectpath):
"""
This function will check/create the config.json in project root.
then it'll check/create the revision table in database
"""
cwd = get_cwd()
json_dict = { "host": dbhost, "database": dbname, "user": dbusername, "pass... | 5,342,812 |
def add_scrollbars_with_tags(outer, InnerType, *inner_args, **inner_kw):
""" Wrapper around `add_scrollbars`. Returns tuple of InnerType instance
and scroll tag. Scroll tag should be added to all `inner` child widgets that
affect scrolling.
"""
scrolltag = "tag_" + str(next(tags_count))
inner = add_sc... | 5,342,813 |
def sample_from_script(script_path, num_lines, chars_per_line):
"""Sample num_lines from a script.
Parameters
----------
script_path : str
Path to the script
num_lines : int
Number of lines to sample.
chars_per_line : int
Numer of consecutive characters... | 5,342,814 |
def is_valid_uuid(x):
"""Determine whether this is a valid hex-encoded uuid."""
if not x or len(x) != 36:
return False
return (parse_uuid(x) != None) | 5,342,815 |
def wait_for_needle_list(
loops: int,
needle_list: list[tuple[str, tuple[int, int, int, int]]],
sleep_range: tuple[int, int],
):
"""
Works like vision.wait_for_needle(), except multiple needles can be
searched for simultaneously.
Args:
loops: The number of tries to look for each nee... | 5,342,816 |
def get_word():
"""Returns random word."""
words = ['Charlie', 'Woodstock', 'Snoopy', 'Lucy', 'Linus',
'Schroeder', 'Patty', 'Sally', 'Marcie']
return random.choice(words).upper() | 5,342,817 |
def write_out_tf_examples(objects, path):
"""Writes out list of objects out as a single tf_example
Args:
objects (list): list of objects to put into the tf_example
path (Path): directory to write this tf_example to, encompassing the name
"""
num_shards = (len(objects) // 1000) + 1
... | 5,342,818 |
async def test_get_scm(client):
"""Test case for get_scm
"""
headers = {
'Accept': 'application/json',
'Authorization': 'BasicZm9vOmJhcg==',
}
response = await client.request(
method='GET',
path='/blue/rest/organizations/{organization}/scm/{scm}'.format(organiz... | 5,342,819 |
def is_admin(user):
"""Check if the user is administrator"""
admin_user = current_app.config['ADMIN_USER']
if user.email == admin_user or user.email.replace('@cern.ch', '') == admin_user:
current_app.logger.debug('User {user} is admin'.format(user=user.email))
return True
return False | 5,342,820 |
def test_task_to_data_relationship(dbsession):
"""Test data integrity across relationship between tables."""
get_id = uuid4()
g = GetTickerTask(
id=get_id, ticker='AUD_JPY', price='M', granularity='M15',
_from=d.strptime('2018-02-01 13:00:00', '%Y-%m-%d %H:%M:%S'),
to=d.strptime('201... | 5,342,821 |
def test_get_port_from_range(port_range):
"""Test getting random port from given range."""
assert get_port(port_range) in list(range(2000, 3000 + 1)) | 5,342,822 |
def parsed_json_to_dict(parsed):
"""
Convert parsed dict into dict with python built-in type
param:
parsed parsed dict by json decoder
"""
new_bangumi = {}
new_bangumi['name'] = parsed['name']
new_bangumi['start_date'] = datetime.strptime(
parsed['start_date'], '%Y-%m-%d').... | 5,342,823 |
def download_osmnx_graph(): # pragma: no cover
"""Load a simple street map from Open Street Map.
Generated from:
.. code:: python
>>> import osmnx as ox # doctest:+SKIP
>>> address = 'Holzgerlingen DE' # doctest:+SKIP
>>> graph = ox.graph_from_address(address, dist=500, network... | 5,342,824 |
def plot_shift_type_by_frequency(tidy_schedule: pandas.DataFrame) -> tuple:
"""
Plots a bar graph of shift type frequencies.
:param tidy_schedule: A pandas data frame containing a schedule,
as loaded by load_tidy_schedule().
:type tidy_schedule: pandas.DataFrame
:return: A tuple with a figure a... | 5,342,825 |
def main(args):
"""Main function.
Parses the raw uri file and generates a new file without
length number at the beginning of the line
If the line is empty a warning log will be shown
:param args: command-line retrieved arguments
:type args: ArgumentParser.parse_args()
:raises FileNo... | 5,342,826 |
def experiment(variant):
"""
This is a job script for running NPG/DAPG on hand tasks and other gym envs.
Note that DAPG generalizes PG and BC init + PG finetuning.
With appropriate settings of parameters, we can recover the full family.
"""
import mj_envs
job_data = default_job_data.copy()
... | 5,342,827 |
def load_image(path, size=None):
"""
Load the image from the given file-path and resize it to the given size if not None.
Eg: size = (width, height)
"""
img = Image.open(path)
if (size != None) and (size != ''):
img = img.resize(size=size, resample=Image.LANCZOS)
img = np.array(img... | 5,342,828 |
def test_indexer():
"""
Test Indexer class
"""
assert dataclasses.asdict(IdrDex) == {
'Ed25519_Sig': 'A',
'ECDSA_256k1_Sig': 'B',
'Ed448_Sig': '0A',
'Label': '0B'
}
assert IdrDex.Ed25519_Sig == 'A' # Ed25519 signature.
assert IdrDex.ECDSA_256k1_Sig == 'B' #... | 5,342,829 |
def train_linkpred(model,
optimizer,
train_loader_generator,
validation_loader_generator
):
"""
:param model:
:param optimizer:
:param train_loader_generator:
:param validation_loader_generator:
:return:
"""
for... | 5,342,830 |
def call_wifi(label):
"""Wifi connect function
Parameters
----------
label : str
Output label
Returns
-------
None
"""
try:
# Setup wifi and connection
print(wifi.radio.connect(secrets['ssid'], secrets['password']))
print('ip', wifi.radio.ipv4_addre... | 5,342,831 |
def load_normalized_face_landmarks():
"""
Loads the locations of each of the 68 landmarks
:return:
"""
normalized_face_landmarks = np.float32([
(0.0792396913815, 0.339223741112), (0.0829219487236, 0.456955367943),
(0.0967927109165, 0.575648016728), (0.122141515615, 0.691921601066),
... | 5,342,832 |
def vacuum_vessel(shot):
"""
Get the coordinates of the Tore Supra / WEST vacuum vessel
R_wall, Z_wall = vacuum_vessel(shot)
Arguments:
- shot: Tore Supra or WEST shot number
Returns:
- R_wall: radius of the vacuum chamber walls [m]
- Z_wall: height of the vacuum chamber w... | 5,342,833 |
def backup_file(file):
"""Create timestamp'd backup of a file
Args:
file (str): filepath
Returns:
backupfile(str)
"""
current_time = datetime.now()
time_stamp = current_time.strftime("%b-%d-%y-%H.%M.%S")
backupfile = file +'.bkp_'+ time_stamp
copyfile(file, backupfil... | 5,342,834 |
def svn_client_mergeinfo_log_eligible(*args):
"""
svn_client_mergeinfo_log_eligible(char path_or_url, svn_opt_revision_t peg_revision,
char merge_source_path_or_url, svn_opt_revision_t src_peg_revision,
svn_log_entry_receiver_t receiver,
svn_boolean_t discover_changed_paths,
ap... | 5,342,835 |
def share_nodes_sockets():
"""
Create a shared node layout where the simulation and analysis ranks share
compute nodes. Furthermore, they share sockets of the node.
"""
shared_sockets = SummitNode()
for i in range(10):
shared_sockets.cpu[i] = "simulation:{}".format(i)
shared_soc... | 5,342,836 |
def imlist(img_dir, valid_exts=None, if_recursive=False):
"""
List images under directory
:param img_dir:
:param valid_exts:
:param if_recursive:
:return:
"""
from glob import glob
if is_str(valid_exts):
valid_exts = [valid_exts.strip(".")]
valid_exts = list(valid_exts) i... | 5,342,837 |
def add_assignment_to_db(db, assignment):
"""
Adds an assignment to the database
:param db: (string) The database to connect to
:param assignment: (Feature) The assignment to add
:return:
"""
conn = sqlite3.connect(db)
c = conn.cursor()
params = (
assignment.global_id,
)
... | 5,342,838 |
def _rle_decode(data):
"""
Decodes run-length-encoded `data`.
"""
if not data:
return data
new = b''
last = b''
for cur in data:
if last == b'\0':
new += last * cur
last = b''
else:
new += last
last = bytes([cur])
... | 5,342,839 |
def blend_and_save(freq_dict, filename, colormap='viridis', dots=600):
"""Plot a heatmap, upscale it to the keyboard and save a blended image."""
# Clear the heatmap plot and axes
plt.clf()
plt.xticks([])
plt.yticks([])
plt.axis('off')
# Display the data on the heatmap
heatmap_data = get... | 5,342,840 |
def flatten(lst):
"""Helper function used to massage the raw tweet data."""
for el in lst:
if (isinstance(el, collections.Iterable) and
not isinstance(el, str)):
for sub in flatten(el):
yield sub
else:
yield el | 5,342,841 |
def setup(app):
"""
Set up the sphinx extension.
"""
app.add_role('f', f_role)
app.add_role('ipa', ipa_role) | 5,342,842 |
def find_shift_between_two_models(model_1,model_2,shift_range=5,number_of_evaluations=10,rotation_angles=[0.,0.,0.],
cropping_model=0,initial_guess=[0.,0.,0.], method='brute_force',full_output=False):
"""
Find the correct shift alignment in 3D by using a different optimization... | 5,342,843 |
def read_cmd(frame, data):
"""Get the return of the cmd sent to the MicroPython card
:param data: The commande sent
:type data: str
:return: the return of the command sent
:rtype: str
"""
b = frame.serial.read(frame.serial.in_waiting)
frame.is_data = False
if b:
frame.is_d... | 5,342,844 |
def get_url(
url: str,
stream: bool = False,
session: Optional[requests.Session] = None
) -> requests.Response:
"""Call requests.get() on a url and return the requests.Response."""
if not session:
session = retry_session()
resp = session.get(url, stream=stream)
resp.raise_for_status(... | 5,342,845 |
def uploadFromPath(localFilePath: str,
resource,
bucketName: str,
fileID: str,
headerArgs: Optional[dict] = None,
partSize: int = 50 << 20):
"""
Uploads a file to s3, using multipart uploading if applicable
:para... | 5,342,846 |
def scale_log2lin(value):
"""
Scale value from log10 to linear scale: 10**(value/10)
Parameters
----------
value : float or array-like
Value or array to be scaled
Returns
-------
float or array-like
Scaled value
"""
return 10**(value/10) | 5,342,847 |
async def test_key_error(opp):
"""Test Connect returning empty string."""
flow = config_flow.SomaFlowHandler()
flow.opp = opp
with patch.object(SomaApi, "list_devices", return_value={}):
result = await flow.async_step_import({"host": MOCK_HOST, "port": MOCK_PORT})
assert result["type"] == da... | 5,342,848 |
def _cal_tgt_match_pct_worker(in_queue, out_queue, mapped_intervals, tgt_data, src_data, src_samples, ref_match_pct, sample_size, query_ref_match_pct, mapped_len_esp, len_esp, var_esp, sfs_esp):
"""
Description:
Worker function to calculate match percents in target populations.
Arguments:
i... | 5,342,849 |
def train(
train_length:Union[int, TrainLength], model:nn.Module, dls:DataLoaders, loss_func:LossFunction,
opt:torch.optim.Optimizer, sched=None, metric:Optional[Metric]=None,
device=None, clip_grad:ClipGradOptions=None, callbacks:List[TrainingCallback]=None
) -> TrainingStats:
"""
Train `model` w... | 5,342,850 |
def _error_to_level(error):
"""Convert a boolean error field to 'Error' or 'Info' """
if error:
return 'Error'
else:
return 'Info' | 5,342,851 |
def add_review(status):
"""
Adds the flags on the tracker document.
Input: tracker document.
Output: sum of the switches.
"""
cluster = status['cluster_switch']
classify = status['classify_switch']
replace = status['replace_switch']
final = status['final_switch']
finished = statu... | 5,342,852 |
def test_pyramid_conv_encoder_forward_invalid_mask(config, images, masks):
"""Test PyramidConvEncoder.forward handles some invalid masks."""
encoder = encoders.PyramidConvEncoder(config=config, pretrained=False)
masks[-2:] = 0
actual = encoder(images, masks)
assert actual.shape == (BATCH_SIZE, *enco... | 5,342,853 |
def n_floordiv(a, b):
"""safe floordiv"""
return np.where(b != 0, o.floordiv(a, b), 1) | 5,342,854 |
def load_encoder_inputs(encoder_np_vecs='train_body_vecs.npy'):
"""
Load variables & data that are inputs to encoder.
Parameters
----------
encoder_np_vecs : str
filename of serialized numpy.array of encoder input (issue title)
Returns
-------
encoder_input_data : numpy.array
The issue body
... | 5,342,855 |
def test_parse_args():
"""Test argument parser of cli."""
argv = ['hourly', '--startyear', '2008',
'--variables', 'total_precipitation', '--statistics',
'--endyear', '2008', '--ensemble', '--land']
args = cli._parse_args(argv)
assert args.command == 'hourly'
assert args.days ... | 5,342,856 |
def save_groups(portal, groups, path, f='json', cls=None, **kw):
""" Save groups in the portal to disk. """
serializer = _select_serializer(f, cls, **kw)
serializer.serialize_groups(groups, path, portal) | 5,342,857 |
def parse_row(row):
"""Create an Event object from a data row
Args:
row: Tuple of input data.
Returns:
Event object.
"""
# Ignore either 1 or 2 columns that preceed year
if len(row) > 6:
row = row[2:]
else:
row = row[1:]
# Remove occasional 'r' or 'x' character prefix from year,
# I... | 5,342,858 |
def vertical_log_binning(p, data):
"""Create vertical log_binning. Used for peak sale."""
import math
import operator
index, value = zip(*sorted(data.items(), key=operator.itemgetter(1)))
bin_result = []
value = list(value)
bin_edge = [min(value)]
i = 1
while len(value) > 0:
... | 5,342,859 |
def get_main_name(ext="", prefix=""):
"""Returns the base name of the main script. Can optionally add an
extension or prefix."""
return prefix + op.splitext(op.basename(__main__.__file__))[0] + ext | 5,342,860 |
def _grad_block_to_band(op, grad):
"""
Gradient associated to the ``block_to_band`` operator.
"""
grad_block = banded_ops.band_to_block(
grad, op.get_attr("block_size"), symmetric=op.get_attr("symmetric"), gradient=True
)
return grad_block | 5,342,861 |
def LSTM(nO, nI):
"""Create an LSTM layer. Args: number out, number in"""
weights = LSTM_weights(nO, nI)
gates = LSTM_gates(weights.ops)
return Recurrent(RNN_step(weights, gates)) | 5,342,862 |
def test_setup_polynomial_wrong_weight_shape(small_data):
"""Ensures that an exception is raised if input weights and data are different shapes."""
weights = np.ones(small_data.shape[0] + 1)
with pytest.raises(ValueError):
_algorithm_setup._setup_polynomial(small_data, weights=weights) | 5,342,863 |
def test_mse_multiple_hidden_units():
"""Test the MSE loss w/ 2 hidden units."""
_check_ae(MSE_MAX_SCORE, hidden_units=(2,)) | 5,342,864 |
def get_token(host, port, headers, auth_data):
"""Return token for a user.
"""
url = api_url(host, port, '/Users/AuthenticateByName')
r = requests.post(url, headers=headers, data=auth_data)
return r.json().get('AccessToken') | 5,342,865 |
def generateDateTime(s):
"""生成时间"""
dt = datetime.fromtimestamp(float(s)/1e3)
time = dt.strftime("%H:%M:%S.%f")
date = dt.strftime("%Y%m%d")
return date, time | 5,342,866 |
def get_activation_function():
"""
Returns tf.nn activation function
"""
return ACTIVATION_FUNCTION | 5,342,867 |
def doi_and_title_from_citation(citation):
"""
Gets the DOI from
a plaintext citation.
Uses a search to CrossRef.org to retrive paper DOI.
Parameters
----------
citation : str
Full journal article citation.
Example: Senís, Elena, et al. "CRISPR/Cas9‐mediated genome
... | 5,342,868 |
def prep_ciphertext(ciphertext):
"""Remove whitespace."""
message = "".join(ciphertext.split())
print("\nciphertext = {}".format(ciphertext))
return message | 5,342,869 |
def setup_sample_file(base_filename, args, num_threads=1):
"""
Return a sample data file, the ancestors file, a corresponding recombination rate
(a single number or a RateMap), a prefix to use for files, and None
"""
gmap = args.genetic_map
sd = tsinfer.load(base_filename + ".samples")
anc ... | 5,342,870 |
def main():
"""Runs dir()."""
call = PROCESS_POOL.submit(call_dir)
while True:
if call.done():
result = call.result().decode()
print("Results: \n\n{}".format(result))
return result | 5,342,871 |
def bacthing_predict_SVGPVAE_rotated_mnist(test_data_batch, vae, svgp,
qnet_mu, qnet_var, aux_data_train):
"""
Get predictions for test data. See chapter 3.3 in Casale's paper.
This version supports batching in prediction pipeline (contrary to function predict_SVGP... | 5,342,872 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""
Set up Strava Home Assistant config entry initiated through the HASS-UI.
"""
hass.data.setdefault(DOMAIN, {})
# OAuth Stuff
try:
implementation = await config_entry_oauth2_flow.async_get_config_entry_implementati... | 5,342,873 |
def normalize_boxes(boxes: List[Tuple], img_shape: Union[Tuple, List]) -> List[Tuple]:
"""
Transform bounding boxes back to yolo format
"""
img_height = img_shape[1]
img_width = img_shape[2]
boxes_ = []
for i in range(len(boxes)):
x1, y1, x2, y2 = boxes[i]
width = x2 - x1
... | 5,342,874 |
def _make_reference_filters(filters, ref_dimension, offset_func):
"""
Copies and replaces the reference dimension's definition in all of the filters applied to a dataset query.
This is used to shift the dimension filters to fit the reference window.
:param filters:
:param ref_dimension:
:param... | 5,342,875 |
def test_division():
"""
Divide two units.
"""
pc_cgs = cm_per_pc
km_cgs = cm_per_km
# Create symbols
pc_sym = Symbol("pc", positive=True)
km_sym = Symbol("km", positive=True)
s_sym = Symbol("s", positive=True)
# Create units
u1 = Unit("pc")
u2 = Unit("km * s")
u3... | 5,342,876 |
def detect():
"""
Detects the shell the user is currently using. The logic is picked from
Docker Machine
https://github.com/docker/machine/blob/master/libmachine/shell/shell.go#L13
"""
shell = os.getenv("SHELL")
if not shell:
return None
if os.getenv("__fish_bin_dir"):
re... | 5,342,877 |
def test_sanity_pass_declarative(ini_settings, dbsession):
"""See database sanity check understands about relationships and don't deem them as missing column."""
engine = engine_from_config(ini_settings, 'sqlalchemy.')
conn = engine.connect()
trans = conn.begin()
Session = sessionmaker(bind=engine... | 5,342,878 |
def load_plane_dataset(name, num_points, flip_axes=False):
"""Loads and returns a plane dataset.
Args:
name: string, the name of the dataset.
num_points: int, the number of points the dataset should have,
flip_axes: bool, flip x and y axes if True.
Returns:
A Dataset object... | 5,342,879 |
def get_toxic(annotated_utterance, probs=True, default_probs=None, default_labels=None):
"""Function to get toxic classifier annotations from annotated utterance.
Args:
annotated_utterance: dictionary with annotated utterance, or annotations
probs: return probabilities or not
default: d... | 5,342,880 |
def compute_energy_lapkmode(X,C,l,W,sigma,bound_lambda):
"""
compute Laplacian K-modes energy in discrete form
"""
e_dist = ecdist(X,C,squared =True)
g_dist = np.exp(-e_dist/(2*sigma**2))
pairwise = 0
Index_list = np.arange(X.shape[0])
for k in range(C.shape[0]):
tmp=np.asa... | 5,342,881 |
def set_openid_cookie(response, openid):
"""Utility method to consistently set the openid cookie."""
print 'SETTING openid cookie to: %s' % openid
response.set_cookie('openid', openid,
expires=(datetime.datetime.now() + datetime.timedelta(days=3650)), # expires in 10 year... | 5,342,882 |
def calc_2d_wave_map(wave_grid, x_dms, y_dms, tilt, oversample=2, padding=10, maxiter=5, dtol=1e-2):
"""Compute the 2D wavelength map on the detector.
:param wave_grid: The wavelength corresponding to the x_dms, y_dms, and tilt values.
:param x_dms: the trace x position on the detector in DMS coordinates.
... | 5,342,883 |
def is_pipeline_variable(var: object) -> bool:
"""Check if the variable is a pipeline variable
Args:
var (object): The variable to be verified.
Returns:
bool: True if it is, False otherwise.
"""
# Currently Expression is on top of all kinds of pipeline variables
# as well as P... | 5,342,884 |
def scan(infile: str = 'scanner_domains.txt', outfile: str = 'scanner_log.txt', signature: str = 'None'):
"""Scans an input list for metadata and, optionally, for the presence of a given signature and sends the results to
be written to a file.
:param infile: An optional string containing the path to the in... | 5,342,885 |
def export_data():
"""Exports data to a file"""
data = {}
data['adgroup_name'] = request.args.get('name')
if data['adgroup_name']:
data['sitelist'] = c['adgroups'].find_one({'name':data['adgroup_name']}, {'sites':1})['sites']
return render_template("export.html", data=data) | 5,342,886 |
def thresh_bin(img, thresh_limit=60):
""" Threshold using blue channel """
b, g, r = cv2.split(img)
# mask = get_salient(r)
mask = cv2.threshold(b, 50, 255, cv2.THRESH_BINARY_INV)[1]
return mask | 5,342,887 |
def get_aux():
"""Get the entire auxiliary stack. Not commonly used."""
@parser
def g(c: Cursor, a: Any):
return a, c, a
return g | 5,342,888 |
def _destupidize_dict(mylist):
"""The opposite of _stupidize_dict()"""
output = {}
for item in mylist:
output[item['key']] = item['value']
return output | 5,342,889 |
def test_J5(i):
""" Test a property of J from result 2 of the paper with a log base """
d = SD([1 / i] * i)
d.set_base('e')
assert J(d) == pytest.approx((i - 1) * (np.log(i) - np.log(i - 1))) | 5,342,890 |
def print_on_stderr(msg, *param):
"""Print msg on stderr"""
print(msg.format(*param), file=sys.stderr) | 5,342,891 |
def equipment_add(request, type_, id_=None):
"""Adds an equipment."""
template = {}
if request.method == 'POST':
form = EquipmentForm(request.POST)
if form.is_valid():
form.save(request.user, id_)
return redirect('settings_equipment')
template['form'] = fo... | 5,342,892 |
def sync_app(search_app, batch_size=None, post_batch_callback=None):
"""Syncs objects for an app to ElasticSearch in batches of batch_size."""
model_name = search_app.es_model.__name__
batch_size = batch_size or search_app.bulk_batch_size
logger.info(f'Processing {model_name} records, using batch size {... | 5,342,893 |
def _parse_text(val, **options):
"""
:return: Parsed value or value itself depends on 'ac_parse_value'
"""
if val and options.get('ac_parse_value', False):
return parse_single(val)
return val | 5,342,894 |
async def test_zeroconf_host_already_exists(hass: HomeAssistant) -> None:
"""Test hosts already exists from zeroconf."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
"host": "1.1.1.1",
"name": "Envoy",
"username": "test-username",
"passwo... | 5,342,895 |
def test_get_networkx_graph(dummy_project):
"""test_get_networkx_graph."""
dummy_project.get_networkx_graph()
# TODO
# assert... | 5,342,896 |
def output_path(model, model_set):
"""Return path to model output directory
Parameters
----------
model : str
model_set : str
"""
path = model_path(model, model_set=model_set)
return os.path.join(path, 'output') | 5,342,897 |
def create_balcony_ungrouped(bm, faces, prop):
"""Make a balcony on each face selection"""
for f in faces:
f.select = False
if not valid_ngon(f):
ngon_to_quad(bm, f)
normal = f.normal.copy()
split_faces = create_balcony_split(bm, f, prop)
for f in sp... | 5,342,898 |
def get_rotation_matrix(rotation_angles):
"""Get the rotation matrix from euler's angles
Parameters
-----
rotation_angles: array-like or list
Three euler angles in the order [sai, theta, phi] where
sai = rotation along the x-axis
theta = rotation along the y-axis
phi = r... | 5,342,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.