content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def tf_box_3d_diagonal_length(boxes_3d):
"""Returns the diagonal length of box_3d
Args:
boxes_3d: An tensor of shape (N x 7) of boxes in box_3d format.
Returns:
Diagonal of all boxes, a tensor of (N,) shape.
"""
lengths_sqr = tf.square(boxes_3d[:, 3])
width_sqr = tf.square(box... | acf1788f8e035a3adf96f3b303f6344bcee0a1f1 | 3,641,500 |
async def employment_plot(current_city:City):
"""
Visualize employment information for city
- see industry breakdown and employment type
### Query Parameters
- city
### Response
JSON string to render with react-plotly.js
"""
city = validate_city(current_city)
city_data = CityDa... | 4db7f3f0973391c7294be486088a24c6ffa2770a | 3,641,501 |
def get_freesurfer_matrix_ras2vox():
"""
Get standard matrix to convert RAS coordinate to voxel index for Freesurfer conformed space volumes.
Get matrix to convert RAS coordinate to voxel index for Freesurfer conformed space volumes. See the documentation for get_freesurfer_matrix_vox2ras for background in... | 5d5ee8d7bec4f632e494f468f6ebc7ff20cdf85c | 3,641,502 |
def parse_create_table(string):
"""Parse the create table sql query and return metadata
Args:
string(sql): SQL string from a SQL Statement
Returns:
table_data(dict): table_data dictionary for instantiating a table
"""
# Parse the base table definitions
table_data = to_dict(get_... | e82875dfcc3cd052aeecac8c38277c26f0d15e8f | 3,641,503 |
def retrieve_context_connection_connection_by_id(uuid): # noqa: E501
"""Retrieve connection by ID
Retrieve operation of resource: connection # noqa: E501
:param uuid: ID of uuid
:type uuid: str
:rtype: Connection
"""
return 'do some magic!' | 4de55de3a799f7c41168fa9072b1a03345dd61de | 3,641,504 |
def read_filenames(path):
"""
Read all file names from `path` and match them against FILENAME_REGEX.
Arguments:
- path: path to the directory containing CSV data files.
Returns:
- list of tuples of every filename and regex match to the CSV filename
format in the specified dir... | 970b00dc5947426960110fa646c9c1c91114ef9f | 3,641,505 |
def _sp_sleep_for(t: int) -> str:
"""Return the subprocess cmd for sleeping for `t` seconds."""
return 'python -c "import time; time.sleep({})"'.format(t) | 20ac8022a2438ceb62123f534ba5911b7c560502 | 3,641,506 |
import re
def verify_show_environment(dut, verify_str_list):
"""
To get show environment.
Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com)
"""
command = "show environment"
output = utils.remove_last_line_from_string(st.show(dut, command, skip_tmpl=True))
result = True
for item in v... | 9334045f2b4ff2e33085398b871ff7a905b995ee | 3,641,507 |
def get_labelset_keys():
"""get labelset keys
Given DATA_CFG, return slideviewer labelsets
Args:
none
Returns:
list: a list of labelset names
"""
cfg = ConfigSet()
label_config = cfg.get_value(path=const.DATA_CFG+'::LABEL_SETS')
labelsets = [cfg.get_value(... | 824d15b529bccb576c359fb50614ed1e33aa561c | 3,641,508 |
from typing import List
def create_instrument_level_pattern(instrument_symbols: List[str]) -> str:
"""Creates a regular expression pattern to target all the instrument symbols in a list.
The function creates a regular expression pattern to target, within a specific DC
message, the portion of the message ... | 25e1e9cc52b009e8e4fa95f8502e5b10cad29209 | 3,641,509 |
def localtime(nist_lookup=0,
localtime=DateTime.localtime,utctime=utctime):
""" Returns the current local time as DateTime instance.
Same notes as for utctime().
"""
return localtime(utctime(nist_lookup).gmticks()) | 312bb973edd62b03d2d251e4d8e215cd00bd470d | 3,641,510 |
from datetime import datetime
def device_now():
"""Return datetime object constructed from 'now' on device."""
cmd = "adb shell date '+%Y:%m:%d:%H:%M:%S'"
lines = u.docmdlines(cmd)
line = lines.pop(0)
if line is None:
u.error("unable to interpret output from '%s'" % cmd)
d = line.split(":")
try:
... | 93e927194390e77fcc7b26cb22db2e5d1debd164 | 3,641,511 |
def copy_safe_request(request):
"""
Copy selected attributes from a request object into a new fake request object. This is needed in places where
thread safe pickling of the useful request data is needed.
"""
meta = {
k: request.META[k]
for k in HTTP_REQUEST_META_SAFE_COPY
if... | a0e2b670732a2d09ac51678059bac80d115b350b | 3,641,512 |
import hashlib
def sha256(firmware_filename, firmware_size=None):
"""Returns the sha256 hash of the firmware"""
hasher = hashlib.sha256()
# If firmware size is supplied, then we want a sha256 of the firmware with its header
if firmware_size is not None:
hasher.update(b"\x00" + firmware_size.to... | 62fabc35796b9fe21ca2489b317550f93f6774ca | 3,641,513 |
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN][entry.entry_id].stop()
return unload_ok | 38460ec92c350cdfcae0094039e834c3344369d8 | 3,641,514 |
def is_serial_increased(old, new):
""" Return true if serial number was increased using RFC 1982 logic. """
old, new = (int(n) for n in [old, new])
diff = (new - old) % 2**32
return 0 < diff < (2**31 - 1) | 44a33a1c7e8caebe3b74284002c7c4be6ac29b40 | 3,641,515 |
def svn_relpath_skip_ancestor(parent_relpath, child_relpath):
"""svn_relpath_skip_ancestor(char const * parent_relpath, char const * child_relpath) -> char const *"""
return _core.svn_relpath_skip_ancestor(parent_relpath, child_relpath) | 23ca0f2e91f0c69e7b410983603ef98e9dea4c13 | 3,641,516 |
def rnn_model(input_dim, units, activation, output_dim=29):
""" Build a recurrent network for speech
"""
# Main acoustic input
input_data = Input(name='the_input', shape=(None, input_dim))
# Add recurrent layer
simp_rnn = GRU(units, activation=activation,
return_sequences=True, implement... | 2b0c4614e0e80888db89fcc8e43ef0a6614400cb | 3,641,517 |
def _pad_statistic(arr, pad_width, stat_length, stat_op):
"""
pads the array with values calculated along the given axis, used in mode: "maximum",
"minimum", "mean"
"""
ndim = arr.ndim
shape = arr.shape
if stat_length is None:
stat_length = _make_stat_length(shape)
else:
... | 4976615e4d41f48d5063ed9af0719801dbe1f9db | 3,641,518 |
def register_do(mysql, json):
"""
helper function that registers data objects into MySQL DB
@param mysql: a mysql object for MySQL database
@param json: metadata that contains information for data source and device
"""
cnx = mysql.connect()
cursor = cnx.cursor()
dataSource = json... | bfb8aa83e91955691d1b3a15c73c5e36d5e3b6b8 | 3,641,519 |
import decimal
def split_amount(amount, splits, places=2):
"""Return list of ``splits`` amounts where sum of items equals ``amount``.
>>> from decimal import Decimal
>>> split_amount(Decimal('12'), 1)
Decimal('12.00')
>>> split_amount(Decimal('12'), 2)
[Decimal('6.00'), Decimal('6.00')]
... | 8c8a17ed9bbcab194550ea78a9b414f51ca5610d | 3,641,520 |
from datetime import timedelta
def shift_compare_date(df, date_field, smaller_eq_than_days=1, compare_with_next=False):
""" ATENTION: This Dataframe need to be sorted!!!
"""
if compare_with_next:
s = (
(df[date_field].shift(-1) - df[date_field]
) <= timedelta(days=smaller... | 56d4466f61cb6329ec1e365ad74f349d6043dd0a | 3,641,521 |
def format_alleles(variant):
"""Gets a string representation of the variant's alleles.
Args:
variant: nucleus.genomics.v1.Variant.
Returns:
A string ref_bases/alt1,alt2 etc.
"""
return '{}/{}'.format(variant.reference_bases, ','.join(
variant.alternate_bases)) | 775fe3e112ff0b7e73780600e0621a8695fa5ad0 | 3,641,522 |
import numbers
def _validate_inputs(input_list, input_names, method_name):
"""
This method will validate the inputs of other methods.
input_list is a list of the inputs passed to a method.
input_name is a list of the variable names associated with
input_list
method_name is the name of the m... | 25a72bd99639b4aab23459635fce116e08299bdc | 3,641,523 |
def server_base_url(environ):
"""
Using information in tiddlyweb.config, construct
the base URL of the server, sans the trailing /.
"""
return '%s%s' % (server_host_url(environ), _server_prefix(environ)) | 3919c9223039929530d6543c13e39b880c657d4f | 3,641,524 |
def calc_ctrlg_ratio(rpl: sc2reader.resources.Replay,
pid: int) -> dict[str, float]:
"""Calculates the ratio between `ControlGroupEvents` and the union of
the `CommandEvents`, `SelectionEvents` and `ControlGroupCommand` sets
to quantify the players' level of awareness and use of this ... | 74d79128bba3584a4966e0bb8f2ce0e4dfdf402e | 3,641,525 |
import os
def data_exists(date, hour=None):
"""
Checks if there is a directory with daily data files for given date and hour(s)
Parameters
----------
date: str
Expected date format is yyyy/mm/dd
hour: int or array-like, default None
Specific hour(s) to check, has to be in th... | b3a97f4bee234ea09c5c40ac1febe43c69f14a54 | 3,641,526 |
import matplotlib.pyplot as plt
def plot_single_roccurve(signals, bkgs, cut_function, cut_values, ax=None):
"""
Main routine for plotting a single roccurve
"""
# Get a default ax if none is given
if ax is None:
fig = plt.figure(figsize=(8,8))
ax = fig.gca()
# Plot the base line... | 13341d3742fa97784cf552a1a7b3a1a5b285180a | 3,641,527 |
import tqdm
def draw_normal_surface(pcd, scale, estimation_params=None):
"""Draw and return a mesh of arrows of normal vectors for each point
in the given cloud
Parameters
----------
pcd : o3d.geometry.PointCloud
Input point cloud
scale : float
Scale of the default arrow wh... | cb54f2a84febe82b03806b09af0a8c99fecc0669 | 3,641,528 |
def texture_from_clusters(clusters):
""" Compute the GLCM texture properties from image clusters.
:param clusters: clusters of pixels representing sections of the image
:returns: DataFrame -- of texture features for every cluster.
"""
thetas = np.arange(0, np.pi, np.pi/8)
props = ['contrast', ... | 353aa3bbc1fec765fd01e201bd769e00bbf8a1fa | 3,641,529 |
def parse_dict(input_data):
"""Return a rules dict of the format:
{
'light red': [(1, 'bright white'), (2, 'muted yellow')],
'dark orange': [(3, bright white), (4, muted yellow)],
'faded blue': [(0, 'bags')]
}
"""
bags = dict()
for line in input_data.split('\n'):
outer, ... | a1aad66a16e4754c35c9b3518d5641096e393530 | 3,641,530 |
def extract_vars(samples_file_name,n_burnin,v_names,debug,stride=1):
"""From a file with samples in ascii format, with
the first line containing the label for each column, extract
the columns with the labels in v_names and return them
in a numpy array. Remove n_burnin samples from the top.
Only read... | e964378501eb32191b2b390e4f9a84d41cef911f | 3,641,531 |
def distance_without_normalise(bin_image):
"""
Takes a binary image and returns a distance transform version of it.
"""
res = np.zeros_like(bin_image)
for j in range(1, bin_image.max() + 1):
one_cell = np.zeros_like(bin_image)
one_cell[bin_image == j] = 1
one_cell = distance_... | ed4cf85498a74e2f7d030daefceebf66e460e0fd | 3,641,532 |
def list_inventory():
""" Returns all of the Inventory """
app.logger.info('Request for inventory list')
inventory = []
category = request.args.get('category')
name = request.args.get('name')
condition = request.args.get('condition')
count = request.args.get('count')
available = request.... | 381de71a10d1626f44710643cd837523e9a930ed | 3,641,533 |
import argparse
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input-dir', help="Directory which contains the input data", required=True)
parser.add_argument('-o', '--output-dir', help="Directory which will hold the output data", re... | aeabf459569b5981eba66460ba0bbf15fb4c96f7 | 3,641,534 |
def is_instance_method(obj):
"""Checks if an object is a bound method on an instance."""
if not isinstance(obj, MethodType):
return False # Not a method
elif obj.__self__ is None:
return False # Method is not bound
elif (
issubclass(obj.__self__.__class__, type)
or hasa... | 82050391193388cdb6d9466442774e6b0fa6878c | 3,641,535 |
from typing import List
from typing import Dict
def _clean_empty_and_duplicate_authors_from_grobid_parse(authors: List[Dict]) -> List[Dict]:
"""
Within affiliation, `location` is a dict with fields <settlement>, <region>, <country>, <postCode>, etc.
Too much hassle, so just take the first one that's not e... | 5a02b877ee074270c544c7dbb06dd1ceab487e79 | 3,641,536 |
def get_distutils_display_options():
""" Returns a set of all the distutils display options in their long and
short forms. These are the setup.py arguments such as --name or --version
which print the project's metadata and then exit.
Returns
-------
opts : set
The long and short form d... | 86e87f22ea97db4a2642ef578999ad1f0cd67a66 | 3,641,537 |
def get_followers(api, user_id):
"""Returns list of followers"""
followers = []
next_max_id = ''
while next_max_id is not None:
_ = api.getUserFollowers(user_id, maxid=next_max_id)
followers.extend(api.LastJson.get('users', []))
next_max_id = api.LastJson.get('next_max_id', '')
... | debfb11fe0b8b22232b82e9a8ea360a4d2a8cdc1 | 3,641,538 |
def map(v, ds, de, ts, te):
"""\
Map the value v, in range [ds, de] to
the corresponding value in range [ts, te]
"""
d1 = de - ds
d2 = te - ts
v2 = v - ds
r = v2 / d1
return ts + d2 * r | 2c2ba49b2acc283ca25b07c10b7ad717ad6a280d | 3,641,539 |
def get_Q_body(hs_type, Theta_SW_hs):
"""温水暖房用熱源機の筐体放熱損失 (2)
Args:
hs_type(str): 温水暖房用熱源機の種類
Theta_SW_hs(ndarray): 温水暖房用熱源機の往き温水温度
Returns:
ndarray: 温水暖房用熱源機の筐体放熱損失
"""
if hs_type in ['石油従来型暖房機', '石油従来型温水暖房機', '石油従来型給湯温水暖房機', '不明']:
# (2a)
return [234 * 3600 * 10... | 60e35a31d9c9b2f5d77d3d6f1518b7a20484fad2 | 3,641,540 |
def softmax(inputs):
"""
Calculate the softmax for the give inputs (array)
:param inputs:
:return:
"""
return np.exp(inputs) / float(sum(np.exp(inputs))) | eb8e215e24fbc30e08e986d9b9498973a866cb9b | 3,641,541 |
def get_config_list(ranking, ckpt_path2is_3class):
"""Assemble a model list for a specific task based on the ranking.
In addition to bundling information about the ckpt_path and whether to
model_uncertainty, the config_list also lists the value of the metric to
aid debugging.
Args:
ranking... | 0c0819f2f4ea844468091fd395390be8038ef4a6 | 3,641,542 |
def _get_turn_angle(start_angle, target_angle):
"""
Difference in angle in the range -180 to +180 (where negative is counter clockwise)
Parameters
----------
start_angle, target_angle : float
Returns
-------
float
difference in angle.
"""
return _map_to_pm180(target_ang... | 7f41482ec69c4d3c4c4b3e1afb674ad46e7d607b | 3,641,543 |
import ctypes
def load(fname):
"""Load symbol from a JSON file.
You can also use pickle to do the job if you only work on python.
The advantage of load/save is the file is language agnostic.
This means the file saved using save can be loaded by other language binding of mxnet.
You also get the be... | bbeb4f5eb63a5ad656814d0ded27d7edbd9936d8 | 3,641,544 |
def filter_pairs(pairs):
"""returns pairs of with filter_pair()==True"""
return [pair for pair in pairs if filter_pair(pair)] | ce65a6ec84ea8b637771d75a5334af7d90bafa15 | 3,641,545 |
def merge(list_geo, npts=5):
"""
merge a list of cad_geometries and update internal/external faces and connectivities
Args:
list_geo: a list of cad_geometries
Returns:
a cad_geometries
"""
geo_f = list_geo[0]
for geo in list_geo[1:]:
geo_f = geo_f.merge(geo, npts=np... | 70db1b52be8ae70d21f689c8f12e051d9c41cd64 | 3,641,546 |
def imshow(image: Imagelike, module: str = None, **kwargs) -> None:
"""Show the given image.
FIXME[todo]:
Showing an image can be done in different ways:
- blocking=True: the execution of the main program is blocked.
The display will run an event loop to guarantee a responsive
GUI behaviour... | be56e4053269c7febd3a528af7e868d44717dcf8 | 3,641,547 |
from typing import Union
from typing import Sequence
from typing import Dict
import warnings
from pathlib import Path
import tqdm
import logging
def prepare_commonvoice(
corpus_dir: Pathlike,
output_dir: Pathlike,
languages: Union[str, Sequence[str]] = "auto",
splits: Union[str, Sequence[str]] = COMMO... | 1f2be866e9003224588a6e2cd4a29500854e9fb9 | 3,641,548 |
def plot_array_trans(pdata,a,copy=False):
"""
Warning!!!
----------
Latest Information: 22/05/2012 this is deprecated and plot_array_transg is used instead.
Purpose:
--------
Transform array according to speficication in list a. return a copy if copy is True.
Example:
--------
... | 0b885fba59fa34f567df5f6891ecdbe46d8a8be9 | 3,641,549 |
def process_generate_api_token_data(post_data):
"""
This expects the post_data to contain an array called ``user_to_form``.
Each item in this array is of the form:
.. code-block:: python
'<UserID>.<form_prefix>' (i.e. '1.form-0')
Each form then may add two form data key-value pairs:
... | 8da8c2566621bdc8710091daf604a292a30c602a | 3,641,550 |
from bpy import context as C
from bpy import data as D
def add_vcolor(hemis, mesh=None, name='color'):
"""Seems like `hemis` is color you wish to apply to currently selected mesh."""
if mesh is None:
mesh = C.scene.objects.active.data
elif isinstance(mesh, str):
mesh = D.meshes[mesh]
... | 9199411ab0265c8e16e4a8bb2dfa45f9550d5d1a | 3,641,551 |
import itertools
import pandas as pd
def gridSeach(model, parameters, features, response, train, test):
"""
This function performs a grid search over the parameter space.
It is simplistic and only allows certain range of values. If there
is a parameter in the models that needs to be a list it has to ... | 69d406cb16312d2777e7aa0562f77c77b20c44f7 | 3,641,552 |
def cvt_lambdef(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base:
"""lambdef: 'lambda' [varargslist] ':' test"""
assert ctx.is_REF, [node]
name = xcast(ast_cooked.NameBindsNode, cvt(node.children[0], ctx.to_BINDING()))
ctx_func = new_ctx_from(ctx)
if len(node.children) == 4:
parameters = xcas... | 42ee22a02c2d003afc808bc3e28f18a57e3153fe | 3,641,553 |
import re
def ischapter_name(text_str):
"""判断是否是章节名"""
if re.match(r'^第(.{1,9})([章节回卷集部篇])(\s*)(.*)', text_str):
return True
else:
return False | c89a34408def2c2f9026045925212c2dde88a41d | 3,641,554 |
def calc_mean_onbit_density(bitsets, number_of_bits):
"""Calculate the mean density of bits that are on in bitsets collection.
Args:
bitsets (list[pyroaring.BitMap]): List of fingerprints
number_of_bits: Number of bits for all fingerprints
Returns:
float: Mean on bit density
"... | 4d68ff5c280708d930d8e1525753804f831fc9da | 3,641,555 |
import os
import pickle
def logger_client():
"""Authentification and service delivery from gmail API
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens,
# and is created automatically when the authorization flow
# completes for the first time.
if os.path.e... | 7a0a80a719ea5d5cfea586ead586ed0e6286d0fd | 3,641,556 |
from typing import List
from typing import Dict
from typing import Any
from typing import Optional
def get_parameters(path: str) -> List[Dict[str, Any]]:
"""
Retrieve parameters from AWS SSM Parameter Store. Decrypts any encrypted parameters.
Relies on the appropriate environment variables to authenticat... | 0905e9e707dfa45b9dab8137676fac14e496e594 | 3,641,557 |
import re
def normalizeUrl(url):
"""
ParseResult(scheme='https', netloc='www.tWitch.tv', path='/ludwig/clip/MoldyNiceMarjoramCharlieBitMe-6EbApxzSGbjacptE', params='', query='a=b&c=d', fragment='')
Wish I could convert clips like this:
https://www.twitch.tv/ludwig/clip/MoldyNiceMarjoramCharlieBit... | c72572f07dd0755a1cef65ab328a5f6d5dcf774f | 3,641,558 |
import requests
def _getPVGIS(lat, lon):
"""
This function uses the non-interactive version of PVGIS to extract a
tmy dataset to be used to predict VRE yields for future periods.
------ inputs ------
Latitude, in decimal degrees, south is negative.
Longitude, in decimal degrees, wes... | e4d47cb3efab61bae1e5d38a87c642c687176ed3 | 3,641,559 |
def get_metric_key_samples(metricDict, metricNames, keyVal="means"):
"""
Returns a dictionary of samples for the given metric name, but only extracts
the samples for the given key
Args:
metricDict (dict): Dictionary of sampled metrics
metricNames (list): Names of the keys of the metric ... | f6b2bb32218654d90404812654623580ab4425df | 3,641,560 |
def apply_nonbonded(nodes, scaling=1.0, suffix=""):
""" Nonbonded in nodes. """
# TODO: should this be 9-6 or 12-6?
return {
"u%s"
% suffix: scaling
* esp.mm.nonbonded.lj_9_6(
x=nodes.data["x"],
sigma=nodes.data["sigma%s" % suffix],
epsilon=nodes.d... | e54f96168ea238ee6c799a428e7325063e527d93 | 3,641,561 |
import requests
def swapi_films(episode):
"""
Gets the films listed in the api.
:param episode:
:return: response json
"""
response = requests.get(SWAPI_API + 'films/' + str(episode))
return response | fab283eeb2c96db1e509d4262fed79f7f4652fca | 3,641,562 |
def prepare_qualifications(request, bids=[], lotId=None):
""" creates Qualification for each Bid
"""
new_qualifications = []
tender = request.validated["tender"]
if not bids:
bids = tender.bids
if tender.lots:
active_lots = [lot.id for lot in tender.lots if lot.status == "active"... | 53399716f029d4b7bebc45ddef8e6f39272e33d1 | 3,641,563 |
def int_format(x):
"""
Format an integer:
- upcast to a (u)int64
- determine buffer size
- use snprintf
"""
x = upcast(x)
buf = flypy.runtime.obj.core.newbuffer(flypy.types.char, ndigits(x) + 1)
formatting.sprintf(buf, getformat(x), x)
return flypy.types.String(buf) | 363b4998bca8c45eb6a5a3b825270ce48bbb237e | 3,641,564 |
import re
def pyccparser2cbmc(srcfile, libs):
"""
Transforms the result of a parsed file from pycparser to a valid cbmc
input.
"""
fd = open(srcfile, "r")
src = fd.read()
fd.close()
# Replace the definition of __VERIFIER_error with the one for CBMC
if "extern void __VERIFIER_error();" in src:
# print "__... | 499208680da71382d652d655a95c227d29129ee5 | 3,641,565 |
import dill
import base64
def check_finished(worker, exec_id):
"""
:param worker:
:param exec_id:
:return:
"""
result = worker.status(exec_id)
status = dill.loads(base64.b64decode(result.data))
if status["status"] == "FAILED":
raise Exception("Remote job execution failed")
... | 285090fd0fcdfce6964aa43f4af0fae836175ab1 | 3,641,566 |
def round_filters(filters, global_params):
""" Calculate and round number of filters based on depth multiplier. """
multiplier = global_params.width_coefficient
if not multiplier:
return filters
divisor = global_params.depth_divisor
min_depth = global_params.min_depth
filters *= multipli... | b39ca8a0b77ae1c134983e20725297fa6bccdac8 | 3,641,567 |
def admin_user_detail():
"""管理员信息编辑详情页"""
if not g.user.is_admin:
return redirect('/')
if request.method == 'GET':
# 获取参数
admin_id = request.args.get('admin_id')
if not admin_id:
abort(404)
try:
admin_id = int(admin_id)
except Excepti... | 2b8ec2201688d0e5fcc49e77fd1a238413d259e3 | 3,641,568 |
def splitBinNum(binNum):
"""Split an alternate block number into latitude and longitude parts.
Args:
binNum (int): Alternative block number
Returns:
:tuple Tuple:
1. (int) Latitude portion of the alternate block number.
Example: ``614123`` => ``614``
2.... | da9b9cc67d592e73da842f4b686c0d16985f3457 | 3,641,569 |
def load_model_from_params_file(model):
"""
case 0: CHECKPOINT.CONVERT_MODEL = True:
Convert the model
case 1: CHECKPOINT.RESUME = False and TRAIN.PARAMS_FILE is not none:
load params_file
case 2: CHECKPOINT.RESUME = True and TRAIN.PARAMS_FILE is not none:
case 2a: if checkpoin... | 4f7c862829135e8b01038c6c9a540aeb1f55e285 | 3,641,570 |
def getPool(pool_type='avg', gmp_lambda=1e3, lse_r=10):
"""
# NOTE: this function is not used in writer_ident, s. constructor of
# ResNet50Encoder
params
pool_type: the allowed pool types
gmp_lambda: the initial regularization parameter for GMP
lse_r: the initial regularization p... | 751bd851d57d37f7cf0749ba2183b67d59722c83 | 3,641,571 |
def draw_transperency(image, mask, color_f, color_b):
"""
image (np.uint8)
mask (np.float32) range from 0 to 1
"""
mask = mask.round()
alpha = np.zeros_like(image, dtype=np.uint8)
alpha[mask == 1, :] = color_f
alpha[mask == 0, :] = color_b
image_alpha = cv2.add(image, alpha)
ret... | 900269f7a36a4daa8c87cb2e2b5adc5b9be8728e | 3,641,572 |
def split_in_pairs(s, padding = "0"):
"""
Takes a string and splits into an iterable of strings of two characters each.
Made to break up a hex string into octets, so default is to pad an odd length
string with a 0 in front. An alternative character may be specified as the
second argument.
"""
... | 8807448bb8125c80fa78ba32f887a54ba9bab1dd | 3,641,573 |
def make_slicer_query_with_totals_and_references(
database,
table,
joins,
dimensions,
metrics,
operations,
filters,
references,
orders,
share_dimensions=(),
):
"""
:param dataset:
:param database:
:param table:
:param joins:
:param dimensions:
:param m... | ea77cf6729cc8b677758801d53338d96e67b167f | 3,641,574 |
def corr_na(array1, array2, corr_method: str = 'spearmanr', **addl_kws):
"""Correlation method that tolerates missing values. Can take pearsonr or spearmanr.
Args:
array1: Vector of values
array2: Vector of values
corr_method: Which method to use, pearsonr or spearmanr.
**addl_k... | b534898dee50b06488514de5b21d6ea7fcf025f6 | 3,641,575 |
from typing import Type
from typing import Callable
def analyze_member_access(name: str,
typ: Type,
node: Context,
is_lvalue: bool,
is_super: bool,
is_operator: bool,
... | d5fd897785bc857f075f0a50e3f4aef0082a2c84 | 3,641,576 |
def has_global(node, name):
"""
check whether node has name in its globals list
"""
return hasattr(node, "globals") and name in node.globals | 7a2ef301cb25cba242d8544e2c191a537f63bf19 | 3,641,577 |
def make_generator_model(input_dim=100) -> tf.keras.Model:
"""Generator モデルを生成する
Args:
input_dim (int, optional): 入力次元. Defaults to 100.
Returns:
tf.keras.Model: Generator モデル
"""
dense_size = (7, 7, 256)
conv2d1_channel = 128
conv2d2_channel = 64
conv2d3_channel = 1
... | 3214afc37153471dae0c599a93cb95def1da8971 | 3,641,578 |
from unittest.mock import call
def deploy_gradle(app, deltas={}):
"""Deploy a Java application using Gradle"""
java_path = join(ENV_ROOT, app)
build_path = join(APP_ROOT, app, 'build')
env_file = join(APP_ROOT, app, 'ENV')
env = {
'VIRTUAL_ENV': java_path,
"PATH": ':'.join([join(j... | d1be9ecd675389c05324d4e1f0e077414db814a5 | 3,641,579 |
from typing import Optional
def find_badge_by_slug(slug: str) -> Optional[Badge]:
"""Return the badge with that slug, or `None` if not found."""
badge = db.session \
.query(DbBadge) \
.filter_by(slug=slug) \
.one_or_none()
if badge is None:
return None
return _db_enti... | ec4102cf529b247c0b725e7c32d4b9de9c3a1e98 | 3,641,580 |
import os
import io
def extract_img_features(
input_path,
input_type,
output_path,
img=None,
img_meta=None,
feature_mask_shape="spot",
):
"""
Extract features from image. Works with IF or HE image from Visium tif files.
For block feature, a square will be drawn around each spot. Si... | bad225053293205940928d65ee0cdfadee67fd9a | 3,641,581 |
import logging
def validate_color(color,default,color_type):
"""Validate a color against known PIL values. Return the validated color if valid; otherwise return a default.
Keyword arguments:
color: color to test.
default: default color string value if color is invalid.
color_type: string name for color type,... | 2a91a9f5db2cbed3d530af12e8c383b65c5e2fa8 | 3,641,582 |
def d_xx_yy_tt(psi):
"""Return the second derivative of the field psi by fft
Parameters
--------------
psi : array of complex64 for the field
Returns
--------------
cxx psi_xx+ cyy psi_yy + ctt psi_tt : second derivatives with respect to x
"""
# this function is to remove
glob... | 12980ca705f5a1f3f3514d792cfc4e06529d0600 | 3,641,583 |
from typing import Iterable
def negate_objective(objective):
"""Take the negative of the given objective (converts a gain into a loss and vice versa)."""
if isinstance(objective, Iterable):
return (list)((map)(negate_objective, objective))
else:
return -objective | e24877d00b7c84e04c0cb38b5facdba85694890f | 3,641,584 |
from typing import Any
import json
def process_vm_size(file_name: str) -> Any:
"""
Extract VMs instance specification.
:file_name (str) File name
Return VMs specification object
"""
current_app.logger.info(f'Processing VM Size {file_name}...')
file = open(file_name,)
data = json.loa... | 7afe372fa82769ac6add9e473bce082f0e268318 | 3,641,585 |
def gen_key(password, salt, dkLen=BLOCKSIZE):
"""
Implement PBKDF2 to make short passwords match the BLOCKSIZE.
Parameters
---------
password str
salt str
dkLen int
Returns
-------
- str
"""
return KDF.PBKDF2(pas... | 134d6c7b17f2aea869bfb79f72a0126367d44b36 | 3,641,586 |
import six
def _bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto."""
if isinstance(value, six.string_types):
value = six.binary_type(value, encoding='utf-8')
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) | 85bdab9a6445ec224f8e5f54be5b775008582d48 | 3,641,587 |
def parse_plot_set(plot_set_string):
"""
Given one of the string arguments to the --plot-sets option, parse out a
data structure representing which conditions ought to be compared against
each other, and what those comparison plots/tables should be called.
The syntax of a plot set is [title:]c... | 1df83681aa3110dfd9302bd7918f15dfbfa497ab | 3,641,588 |
def check_types_excel(row: tuple) -> bool:
"""Returns true if row from excel file has correct types"""
if not isinstance(row[1], (pd.Timestamp, str)):
return False
if not ((isinstance(row[2], dt.time) and isinstance(row[3], dt.time)) or
(isinstance(row[2], str) and isinstance(row[3], str... | 80ac33feff968de076bd29f34350bcf518cd34d5 | 3,641,589 |
def add(num1, num2):
""" Adds two numbers
>>> add(2,4)
6
"""
return num1 + num2 | 932981ca91c01817242e57e1be55c35441337fc4 | 3,641,590 |
def is_palindrome1(str):
"""
Create slice with negative step and confirm equality with str.
"""
return str[::-1] == str | 39dbc19d0d73b956c9af24abc1babae18c816d73 | 3,641,591 |
from datetime import datetime
def number_generetor(view, form):
""" Генератор номера платежа (по умолчанию) """
if is_py2:
uuid_fields = uuid4().get_fields()
else:
uuid_fields = uuid4().fields
return u'{:%Y%m%d}-{:08x}'.format(datetime.now(), uuid_fields[0]) | 005cd8347b903be3adffe56d7c8c53ba79ebf2e8 | 3,641,592 |
def get_underlay_info():
"""
:return:
"""
return underlay_info | a48f2ede459a4ca8969e095e94ba09b99e59300d | 3,641,593 |
async def get_guild_roles(id_: int):
"""
Get the roles of a guild
:param id_: Guild ID
:return: List of roles
"""
guild = await router.bot.rest.fetch_guild(id_)
if guild is None:
return status.HTTP_404_NOT_FOUND
roles = await guild.fetch_roles()
return [to_dict(role) for role... | 4d5084f62f29a5038dc3111b047b1644a96a958a | 3,641,594 |
def prior_min_field(field_name, field_value):
"""
Creates prior min field with the
:param field_name: prior name (field name initial)
:param field_value: field initial properties
:return: name of the min field, updated field properties
"""
name = field_name
value = field_value.copy()
... | 9f331ee58e699318e678d881c0028486b746c05c | 3,641,595 |
def checkpoint_save_config():
"""Fixture to create a config for saving attributes of a detector."""
toolset = {
"test_id": "Dummy_test",
"saved_attributes": {
"FeatureExtraction": [
"dummy_dict",
"dummy_list",
"dummy_tuple",
... | 6cb7e05a5eb680f6915fc58f40e72403787eea8b | 3,641,596 |
def matrix_sum_power(A, T):
"""Take the sum of the powers of a matrix, i.e.,
sum_{t=1} ^T A^t.
:param A: Matrix to be powered
:type A: np.ndarray
:param T: Maximum order for the matrixpower
:type T: int
:return: Powered matrix
:rtype: np.ndarray
"""
At = np.eye(A.shape[0])
... | b590f0751c114bd7cfeaa39d3d03a3de49007c62 | 3,641,597 |
def mean_zero_unit_variance(arr, mean_vector=None, std_vector=None, samples_in='row'):
"""
Normalize input data to have zero mean and unit variance.
Return the normalized data, the mean, and the calculated standard
deviation which was used to normalize the data
[normalized, meanvec, stddev] = mean_... | 38a1ca262362b3f04aed06f3f0d21836eca8d5ad | 3,641,598 |
import torch
def soft_precision(scores: torch.FloatTensor,
mask: torch.FloatTensor) -> torch.FloatTensor:
"""
Helper function for computing soft precision in batch.
# Parameters
scores : torch.FloatTensor
Tensor of scores with shape: (num_refs, num_cands, max_ref_len, max_c... | e76552bde3ae58f5b976abbf58e5dac1d4995117 | 3,641,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.