_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q268000 | __beat_track_dp | test | def __beat_track_dp(localscore, period, tightness):
"""Core dynamic program for beat tracking"""
backlink = np.zeros_like(localscore, dtype=int)
cumscore = np.zeros_like(localscore)
# Search range for previous beat
window = np.arange(-2 * period, -np.round(period / 2) + 1, dtype=int)
# Make a... | python | {
"resource": ""
} |
q268001 | __last_beat | test | def __last_beat(cumscore):
"""Get the last beat from the cumulative score array"""
maxes = util.localmax(cumscore)
med_score = np.median(cumscore[np.argwhere(maxes)])
# The last of these is the last beat (since score generally increases)
return np.argwhere((cumscore * maxes * 2 > med_score)).max() | python | {
"resource": ""
} |
q268002 | recurrence_to_lag | test | def recurrence_to_lag(rec, pad=True, axis=-1):
'''Convert a recurrence matrix into a lag matrix.
`lag[i, j] == rec[i+j, j]`
Parameters
----------
rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)]
A (binary) recurrence matrix, as returned by `recurrence_matrix`
pad : bool
... | python | {
"resource": ""
} |
q268003 | lag_to_recurrence | test | def lag_to_recurrence(lag, axis=-1):
'''Convert a lag matrix into a recurrence matrix.
Parameters
----------
lag : np.ndarray or scipy.sparse.spmatrix
A lag matrix, as produced by `recurrence_to_lag`
axis : int
The axis corresponding to the time dimension.
The alternate axi... | python | {
"resource": ""
} |
q268004 | timelag_filter | test | def timelag_filter(function, pad=True, index=0):
'''Filtering in the time-lag domain.
This is primarily useful for adapting image filters to operate on
`recurrence_to_lag` output.
Using `timelag_filter` is equivalent to the following sequence of
operations:
>>> data_tl = librosa.segment.recur... | python | {
"resource": ""
} |
q268005 | subsegment | test | def subsegment(data, frames, n_segments=4, axis=-1):
'''Sub-divide a segmentation by feature clustering.
Given a set of frame boundaries (`frames`), and a data matrix (`data`),
each successive interval defined by `frames` is partitioned into
`n_segments` by constrained agglomerative clustering.
..... | python | {
"resource": ""
} |
q268006 | agglomerative | test | def agglomerative(data, k, clusterer=None, axis=-1):
"""Bottom-up temporal segmentation.
Use a temporally-constrained agglomerative clustering routine to partition
`data` into `k` contiguous segments.
Parameters
----------
data : np.ndarray
data to cluster
k : int > 0 [... | python | {
"resource": ""
} |
q268007 | path_enhance | test | def path_enhance(R, n, window='hann', max_ratio=2.0, min_ratio=None, n_filters=7,
zero_mean=False, clip=True, **kwargs):
'''Multi-angle path enhancement for self- and cross-similarity matrices.
This function convolves multiple diagonal smoothing filters with a self-similarity (or
recurrenc... | python | {
"resource": ""
} |
q268008 | onset_detect | test | def onset_detect(input_file, output_csv):
'''Onset detection function
:parameters:
- input_file : str
Path to input audio file (wav, mp3, m4a, flac, etc.)
- output_file : str
Path to save onset timestamps as a CSV file
'''
# 1. load the wav file and resample to 22.050 ... | python | {
"resource": ""
} |
q268009 | frame | test | def frame(y, frame_length=2048, hop_length=512):
'''Slice a time series into overlapping frames.
This implementation uses low-level stride manipulation to avoid
redundant copies of the time series data.
Parameters
----------
y : np.ndarray [shape=(n,)]
Time series to frame. Must be one... | python | {
"resource": ""
} |
q268010 | valid_audio | test | def valid_audio(y, mono=True):
'''Validate whether a variable contains valid, mono audio data.
Parameters
----------
y : np.ndarray
The input data to validate
mono : bool
Whether or not to force monophonic audio
Returns
-------
valid : bool
True if all tests pass
... | python | {
"resource": ""
} |
q268011 | valid_int | test | def valid_int(x, cast=None):
'''Ensure that an input value is integer-typed.
This is primarily useful for ensuring integrable-valued
array indices.
Parameters
----------
x : number
A scalar value to be cast to int
cast : function [optional]
A function to modify `x` before c... | python | {
"resource": ""
} |
q268012 | fix_length | test | def fix_length(data, size, axis=-1, **kwargs):
'''Fix the length an array `data` to exactly `size`.
If `data.shape[axis] < n`, pad according to the provided kwargs.
By default, `data` is padded with trailing zeros.
Examples
--------
>>> y = np.arange(7)
>>> # Default: pad with zeros
>>... | python | {
"resource": ""
} |
q268013 | axis_sort | test | def axis_sort(S, axis=-1, index=False, value=None):
'''Sort an array along its rows or columns.
Examples
--------
Visualize NMF output for a spectrogram S
>>> # Sort the columns of W by peak frequency bin
>>> y, sr = librosa.load(librosa.util.example_audio_file())
>>> S = np.abs(librosa.st... | python | {
"resource": ""
} |
q268014 | normalize | test | def normalize(S, norm=np.inf, axis=0, threshold=None, fill=None):
'''Normalize an array along a chosen axis.
Given a norm (described below) and a target axis, the input
array is scaled so that
`norm(S, axis=axis) == 1`
For example, `axis=0` normalizes each column of a 2-d array
by aggrega... | python | {
"resource": ""
} |
q268015 | localmax | test | def localmax(x, axis=0):
"""Find local maxima in an array `x`.
An element `x[i]` is considered a local maximum if the following
conditions are met:
- `x[i] > x[i-1]`
- `x[i] >= x[i+1]`
Note that the first condition is strict, and that the first element
`x[0]` will never be considered as a... | python | {
"resource": ""
} |
q268016 | peak_pick | test | def peak_pick(x, pre_max, post_max, pre_avg, post_avg, delta, wait):
'''Uses a flexible heuristic to pick peaks in a signal.
A sample n is selected as an peak if the corresponding x[n]
fulfills the following three conditions:
1. `x[n] == max(x[n - pre_max:n + post_max])`
2. `x[n] >= mean(x[n - pre... | python | {
"resource": ""
} |
q268017 | sparsify_rows | test | def sparsify_rows(x, quantile=0.01):
'''
Return a row-sparse matrix approximating the input `x`.
Parameters
----------
x : np.ndarray [ndim <= 2]
The input matrix to sparsify.
quantile : float in [0, 1.0)
Percentage of magnitude to discard in each row of `x`
Returns
--... | python | {
"resource": ""
} |
q268018 | roll_sparse | test | def roll_sparse(x, shift, axis=0):
'''Sparse matrix roll
This operation is equivalent to ``numpy.roll``, but operates on sparse matrices.
Parameters
----------
x : scipy.sparse.spmatrix or np.ndarray
The sparse matrix input
shift : int
The number of positions to roll the speci... | python | {
"resource": ""
} |
q268019 | buf_to_float | test | def buf_to_float(x, n_bytes=2, dtype=np.float32):
"""Convert an integer buffer to floating point values.
This is primarily useful when loading integer-valued wav data
into numpy arrays.
See Also
--------
buf_to_float
Parameters
----------
x : np.ndarray [dtype=int]
The inte... | python | {
"resource": ""
} |
q268020 | index_to_slice | test | def index_to_slice(idx, idx_min=None, idx_max=None, step=None, pad=True):
'''Generate a slice array from an index array.
Parameters
----------
idx : list-like
Array of index boundaries
idx_min : None or int
idx_max : None or int
Minimum and maximum allowed indices
step : N... | python | {
"resource": ""
} |
q268021 | sync | test | def sync(data, idx, aggregate=None, pad=True, axis=-1):
"""Synchronous aggregation of a multi-dimensional array between boundaries
.. note::
In order to ensure total coverage, boundary points may be added
to `idx`.
If synchronizing a feature matrix against beat tracker output, ensure
... | python | {
"resource": ""
} |
q268022 | softmask | test | def softmask(X, X_ref, power=1, split_zeros=False):
'''Robustly compute a softmask operation.
`M = X**power / (X**power + X_ref**power)`
Parameters
----------
X : np.ndarray
The (non-negative) input array corresponding to the positive mask elements
X_ref : np.ndarray
The ... | python | {
"resource": ""
} |
q268023 | tiny | test | def tiny(x):
'''Compute the tiny-value corresponding to an input's data type.
This is the smallest "usable" number representable in `x`'s
data type (e.g., float32).
This is primarily useful for determining a threshold for
numerical underflow in division or multiplication operations.
Parameter... | python | {
"resource": ""
} |
q268024 | frames2video | test | def frames2video(frame_dir,
video_file,
fps=30,
fourcc='XVID',
filename_tmpl='{:06d}.jpg',
start=0,
end=0,
show_progress=True):
"""Read the frame images from a directory and join them as a video
... | python | {
"resource": ""
} |
q268025 | VideoReader.read | test | def read(self):
"""Read the next frame.
If the next frame have been decoded before and in the cache, then
return it directly, otherwise decode, cache and return it.
Returns:
ndarray or None: Return the frame if successful, otherwise None.
"""
# pos = self._p... | python | {
"resource": ""
} |
q268026 | VideoReader.get_frame | test | def get_frame(self, frame_id):
"""Get frame by index.
Args:
frame_id (int): Index of the expected frame, 0-based.
Returns:
ndarray or None: Return the frame if successful, otherwise None.
"""
if frame_id < 0 or frame_id >= self._frame_cnt:
ra... | python | {
"resource": ""
} |
q268027 | VideoReader.cvt2frames | test | def cvt2frames(self,
frame_dir,
file_start=0,
filename_tmpl='{:06d}.jpg',
start=0,
max_num=0,
show_progress=True):
"""Convert a video to frame images
Args:
frame_dir (str): Outp... | python | {
"resource": ""
} |
q268028 | track_progress | test | def track_progress(func, tasks, bar_width=50, **kwargs):
"""Track the progress of tasks execution with a progress bar.
Tasks are done with a simple for-loop.
Args:
func (callable): The function to be applied to each task.
tasks (list or tuple[Iterable, int]): A list of tasks or
... | python | {
"resource": ""
} |
q268029 | track_parallel_progress | test | def track_parallel_progress(func,
tasks,
nproc,
initializer=None,
initargs=None,
bar_width=50,
chunksize=1,
skip_first=False... | python | {
"resource": ""
} |
q268030 | imflip | test | def imflip(img, direction='horizontal'):
"""Flip an image horizontally or vertically.
Args:
img (ndarray): Image to be flipped.
direction (str): The flip direction, either "horizontal" or "vertical".
Returns:
ndarray: The flipped image.
"""
assert direction in ['horizontal'... | python | {
"resource": ""
} |
q268031 | imrotate | test | def imrotate(img,
angle,
center=None,
scale=1.0,
border_value=0,
auto_bound=False):
"""Rotate an image.
Args:
img (ndarray): Image to be rotated.
angle (float): Rotation angle in degrees, positive values mean
clockwise... | python | {
"resource": ""
} |
q268032 | bbox_clip | test | def bbox_clip(bboxes, img_shape):
"""Clip bboxes to fit the image shape.
Args:
bboxes (ndarray): Shape (..., 4*k)
img_shape (tuple): (height, width) of the image.
Returns:
ndarray: Clipped bboxes.
"""
assert bboxes.shape[-1] % 4 == 0
clipped_bboxes = np.empty_like(bboxe... | python | {
"resource": ""
} |
q268033 | bbox_scaling | test | def bbox_scaling(bboxes, scale, clip_shape=None):
"""Scaling bboxes w.r.t the box center.
Args:
bboxes (ndarray): Shape(..., 4).
scale (float): Scaling factor.
clip_shape (tuple, optional): If specified, bboxes that exceed the
boundary will be clipped according to the given ... | python | {
"resource": ""
} |
q268034 | imcrop | test | def imcrop(img, bboxes, scale=1.0, pad_fill=None):
"""Crop image patches.
3 steps: scale the bboxes -> clip bboxes -> crop and pad.
Args:
img (ndarray): Image to be cropped.
bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes.
scale (float, optional): Scale ratio of... | python | {
"resource": ""
} |
q268035 | impad | test | def impad(img, shape, pad_val=0):
"""Pad an image to a certain shape.
Args:
img (ndarray): Image to be padded.
shape (tuple): Expected padding shape.
pad_val (number or sequence): Values to be filled in padding areas.
Returns:
ndarray: The padded image.
"""
if not i... | python | {
"resource": ""
} |
q268036 | impad_to_multiple | test | def impad_to_multiple(img, divisor, pad_val=0):
"""Pad an image to ensure each edge to be multiple to some number.
Args:
img (ndarray): Image to be padded.
divisor (int): Padded image edges will be multiple to divisor.
pad_val (number or sequence): Same as :func:`impad`.
Returns:
... | python | {
"resource": ""
} |
q268037 | _scale_size | test | def _scale_size(size, scale):
"""Rescale a size by a ratio.
Args:
size (tuple): w, h.
scale (float): Scaling factor.
Returns:
tuple[int]: scaled size.
"""
w, h = size
return int(w * float(scale) + 0.5), int(h * float(scale) + 0.5) | python | {
"resource": ""
} |
q268038 | imresize | test | def imresize(img, size, return_scale=False, interpolation='bilinear'):
"""Resize image to a given size.
Args:
img (ndarray): The input image.
size (tuple): Target (w, h).
return_scale (bool): Whether to return `w_scale` and `h_scale`.
interpolation (str): Interpolation method, a... | python | {
"resource": ""
} |
q268039 | imresize_like | test | def imresize_like(img, dst_img, return_scale=False, interpolation='bilinear'):
"""Resize image to the same size of a given image.
Args:
img (ndarray): The input image.
dst_img (ndarray): The target image.
return_scale (bool): Whether to return `w_scale` and `h_scale`.
interpolat... | python | {
"resource": ""
} |
q268040 | imrescale | test | def imrescale(img, scale, return_scale=False, interpolation='bilinear'):
"""Resize image while keeping the aspect ratio.
Args:
img (ndarray): The input image.
scale (float or tuple[int]): The scaling factor or maximum size.
If it is a float number, then the image will be rescaled by... | python | {
"resource": ""
} |
q268041 | _register_handler | test | def _register_handler(handler, file_formats):
"""Register a handler for some file extensions.
Args:
handler (:obj:`BaseFileHandler`): Handler to be registered.
file_formats (str or list[str]): File formats to be handled by this
handler.
"""
if not isinstance(handler, BaseFil... | python | {
"resource": ""
} |
q268042 | get_priority | test | def get_priority(priority):
"""Get priority value.
Args:
priority (int or str or :obj:`Priority`): Priority.
Returns:
int: The priority value.
"""
if isinstance(priority, int):
if priority < 0 or priority > 100:
raise ValueError('priority must be between 0 and 1... | python | {
"resource": ""
} |
q268043 | dequantize | test | def dequantize(arr, min_val, max_val, levels, dtype=np.float64):
"""Dequantize an array.
Args:
arr (ndarray): Input array.
min_val (scalar): Minimum value to be clipped.
max_val (scalar): Maximum value to be clipped.
levels (int): Quantization levels.
dtype (np.type): Th... | python | {
"resource": ""
} |
q268044 | imshow | test | def imshow(img, win_name='', wait_time=0):
"""Show an image.
Args:
img (str or ndarray): The image to be displayed.
win_name (str): The window name.
wait_time (int): Value of waitKey param.
"""
cv2.imshow(win_name, imread(img))
cv2.waitKey(wait_time) | python | {
"resource": ""
} |
q268045 | imshow_bboxes | test | def imshow_bboxes(img,
bboxes,
colors='green',
top_k=-1,
thickness=1,
show=True,
win_name='',
wait_time=0,
out_file=None):
"""Draw bboxes on an image.
Args:
im... | python | {
"resource": ""
} |
q268046 | flowread | test | def flowread(flow_or_path, quantize=False, concat_axis=0, *args, **kwargs):
"""Read an optical flow map.
Args:
flow_or_path (ndarray or str): A flow map or filepath.
quantize (bool): whether to read quantized pair, if set to True,
remaining args will be passed to :func:`dequantize_f... | python | {
"resource": ""
} |
q268047 | flowwrite | test | def flowwrite(flow, filename, quantize=False, concat_axis=0, *args, **kwargs):
"""Write optical flow to file.
If the flow is not quantized, it will be saved as a .flo file losslessly,
otherwise a jpeg image which is lossy but of much smaller size. (dx and dy
will be concatenated horizontally into a sin... | python | {
"resource": ""
} |
q268048 | dequantize_flow | test | def dequantize_flow(dx, dy, max_val=0.02, denorm=True):
"""Recover from quantized flow.
Args:
dx (ndarray): Quantized dx.
dy (ndarray): Quantized dy.
max_val (float): Maximum value used when quantizing.
denorm (bool): Whether to multiply flow values with width/height.
Retur... | python | {
"resource": ""
} |
q268049 | load_state_dict | test | def load_state_dict(module, state_dict, strict=False, logger=None):
"""Load state_dict to a module.
This method is modified from :meth:`torch.nn.Module.load_state_dict`.
Default value for ``strict`` is set to ``False`` and the message for
param mismatch will be shown even if strict is False.
Args:... | python | {
"resource": ""
} |
q268050 | load_checkpoint | test | def load_checkpoint(model,
filename,
map_location=None,
strict=False,
logger=None):
"""Load checkpoint from a file or URI.
Args:
model (Module): Module to load checkpoint.
filename (str): Either a filepath or URL or... | python | {
"resource": ""
} |
q268051 | weights_to_cpu | test | def weights_to_cpu(state_dict):
"""Copy a model state_dict to cpu.
Args:
state_dict (OrderedDict): Model weights on GPU.
Returns:
OrderedDict: Model weights on GPU.
"""
state_dict_cpu = OrderedDict()
for key, val in state_dict.items():
state_dict_cpu[key] = val.cpu()
... | python | {
"resource": ""
} |
q268052 | save_checkpoint | test | def save_checkpoint(model, filename, optimizer=None, meta=None):
"""Save checkpoint to file.
The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.
Args:
model (Module): Module whose params are to be saved.
... | python | {
"resource": ""
} |
q268053 | Runner.init_optimizer | test | def init_optimizer(self, optimizer):
"""Init the optimizer.
Args:
optimizer (dict or :obj:`~torch.optim.Optimizer`): Either an
optimizer object or a dict used for constructing the optimizer.
Returns:
:obj:`~torch.optim.Optimizer`: An optimizer object.
... | python | {
"resource": ""
} |
q268054 | Runner.init_logger | test | def init_logger(self, log_dir=None, level=logging.INFO):
"""Init the logger.
Args:
log_dir(str, optional): Log file directory. If not specified, no
log file will be used.
level (int or str): See the built-in python logging module.
Returns:
:o... | python | {
"resource": ""
} |
q268055 | Runner.current_lr | test | def current_lr(self):
"""Get current learning rates.
Returns:
list: Current learning rate of all param groups.
"""
if self.optimizer is None:
raise RuntimeError(
'lr is not applicable because optimizer does not exist.')
return [group['lr']... | python | {
"resource": ""
} |
q268056 | Runner.register_hook | test | def register_hook(self, hook, priority='NORMAL'):
"""Register a hook into the hook list.
Args:
hook (:obj:`Hook`): The hook to be registered.
priority (int or str or :obj:`Priority`): Hook priority.
Lower value means higher priority.
"""
assert is... | python | {
"resource": ""
} |
q268057 | Runner.run | test | def run(self, data_loaders, workflow, max_epochs, **kwargs):
"""Start running.
Args:
data_loaders (list[:obj:`DataLoader`]): Dataloaders for training
and validation.
workflow (list[tuple]): A list of (phase, epochs) to specify the
running order an... | python | {
"resource": ""
} |
q268058 | Runner.register_training_hooks | test | def register_training_hooks(self,
lr_config,
optimizer_config=None,
checkpoint_config=None,
log_config=None):
"""Register default hooks for training.
Default hooks include:
... | python | {
"resource": ""
} |
q268059 | convert_video | test | def convert_video(in_file, out_file, print_cmd=False, pre_options='',
**kwargs):
"""Convert a video with ffmpeg.
This provides a general api to ffmpeg, the executed command is::
`ffmpeg -y <pre_options> -i <in_file> <options> <out_file>`
Options(kwargs) are mapped to ffmpeg comm... | python | {
"resource": ""
} |
q268060 | resize_video | test | def resize_video(in_file,
out_file,
size=None,
ratio=None,
keep_ar=False,
log_level='info',
print_cmd=False,
**kwargs):
"""Resize a video.
Args:
in_file (str): Input video filename.
... | python | {
"resource": ""
} |
q268061 | cut_video | test | def cut_video(in_file,
out_file,
start=None,
end=None,
vcodec=None,
acodec=None,
log_level='info',
print_cmd=False,
**kwargs):
"""Cut a clip from a video.
Args:
in_file (str): Input video fil... | python | {
"resource": ""
} |
q268062 | concat_video | test | def concat_video(video_list,
out_file,
vcodec=None,
acodec=None,
log_level='info',
print_cmd=False,
**kwargs):
"""Concatenate multiple videos into a single one.
Args:
video_list (list): A list of video... | python | {
"resource": ""
} |
q268063 | list_from_file | test | def list_from_file(filename, prefix='', offset=0, max_num=0):
"""Load a text file and parse the content as a list of strings.
Args:
filename (str): Filename.
prefix (str): The prefix to be inserted to the begining of each item.
offset (int): The offset of lines.
max_num (int): T... | python | {
"resource": ""
} |
q268064 | dict_from_file | test | def dict_from_file(filename, key_type=str):
"""Load a text file and parse the content as a dict.
Each line of the text file will be two or more columns splited by
whitespaces or tabs. The first column will be parsed as dict keys, and
the following columns will be parsed as dict values.
Args:
... | python | {
"resource": ""
} |
q268065 | conv3x3 | test | def conv3x3(in_planes, out_planes, dilation=1):
"3x3 convolution with padding"
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=3,
padding=dilation,
dilation=dilation) | python | {
"resource": ""
} |
q268066 | obj_from_dict | test | def obj_from_dict(info, parent=None, default_args=None):
"""Initialize an object from dict.
The dict must contain the key "type", which indicates the object type, it
can be either a string or type, such as "list" or ``list``. Remaining
fields are treated as the arguments for constructing the object.
... | python | {
"resource": ""
} |
q268067 | imread | test | def imread(img_or_path, flag='color'):
"""Read an image.
Args:
img_or_path (ndarray or str): Either a numpy array or image path.
If it is a numpy array (loaded image), then it will be returned
as is.
flag (str): Flags specifying the color type of a loaded image,
... | python | {
"resource": ""
} |
q268068 | imfrombytes | test | def imfrombytes(content, flag='color'):
"""Read an image from bytes.
Args:
content (bytes): Image bytes got from files or other streams.
flag (str): Same as :func:`imread`.
Returns:
ndarray: Loaded image array.
"""
img_np = np.frombuffer(content, np.uint8)
flag = imread... | python | {
"resource": ""
} |
q268069 | imwrite | test | def imwrite(img, file_path, params=None, auto_mkdir=True):
"""Write image to file
Args:
img (ndarray): Image array to be written.
file_path (str): Image file path.
params (None or list): Same as opencv's :func:`imwrite` interface.
auto_mkdir (bool): If the parent folder of `file... | python | {
"resource": ""
} |
q268070 | bgr2gray | test | def bgr2gray(img, keepdim=False):
"""Convert a BGR image to grayscale image.
Args:
img (ndarray): The input image.
keepdim (bool): If False (by default), then return the grayscale image
with 2 dims, otherwise 3 dims.
Returns:
ndarray: The converted grayscale image.
... | python | {
"resource": ""
} |
q268071 | gray2bgr | test | def gray2bgr(img):
"""Convert a grayscale image to BGR image.
Args:
img (ndarray or str): The input image.
Returns:
ndarray: The converted BGR image.
"""
img = img[..., None] if img.ndim == 2 else img
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
return out_img | python | {
"resource": ""
} |
q268072 | iter_cast | test | def iter_cast(inputs, dst_type, return_type=None):
"""Cast elements of an iterable object into some type.
Args:
inputs (Iterable): The input object.
dst_type (type): Destination type.
return_type (type, optional): If specified, the output object will be
converted to this typ... | python | {
"resource": ""
} |
q268073 | is_seq_of | test | def is_seq_of(seq, expected_type, seq_type=None):
"""Check whether it is a sequence of some type.
Args:
seq (Sequence): The sequence to be checked.
expected_type (type): Expected type of sequence items.
seq_type (type, optional): Expected sequence type.
Returns:
bool: Wheth... | python | {
"resource": ""
} |
q268074 | slice_list | test | def slice_list(in_list, lens):
"""Slice a list into several sub lists by a list of given length.
Args:
in_list (list): The list to be sliced.
lens(int or list): The expected length of each out list.
Returns:
list: A list of sliced list.
"""
if not isinstance(lens, list):
... | python | {
"resource": ""
} |
q268075 | check_prerequisites | test | def check_prerequisites(
prerequisites,
checker,
msg_tmpl='Prerequisites "{}" are required in method "{}" but not '
'found, please install them first.'):
"""A decorator factory to check if prerequisites are satisfied.
Args:
prerequisites (str of list[str]): Prerequisites... | python | {
"resource": ""
} |
q268076 | LogBuffer.average | test | def average(self, n=0):
"""Average latest n values or all values"""
assert n >= 0
for key in self.val_history:
values = np.array(self.val_history[key][-n:])
nums = np.array(self.n_history[key][-n:])
avg = np.sum(values * nums) / np.sum(nums)
self.o... | python | {
"resource": ""
} |
q268077 | scatter | test | def scatter(input, devices, streams=None):
"""Scatters tensor across multiple GPUs.
"""
if streams is None:
streams = [None] * len(devices)
if isinstance(input, list):
chunk_size = (len(input) - 1) // len(devices) + 1
outputs = [
scatter(input[i], [devices[i // chunk... | python | {
"resource": ""
} |
q268078 | color_val | test | def color_val(color):
"""Convert various input to color tuples.
Args:
color (:obj:`Color`/str/tuple/int/ndarray): Color inputs
Returns:
tuple[int]: A tuple of 3 integers indicating BGR channels.
"""
if is_str(color):
return Color[color].value
elif isinstance(color, Colo... | python | {
"resource": ""
} |
q268079 | check_time | test | def check_time(timer_id):
"""Add check points in a single line.
This method is suitable for running a task on a list of items. A timer will
be registered when the method is called for the first time.
:Example:
>>> import time
>>> import mmcv
>>> for i in range(1, 6):
>>> # simulat... | python | {
"resource": ""
} |
q268080 | Timer.start | test | def start(self):
"""Start the timer."""
if not self._is_running:
self._t_start = time()
self._is_running = True
self._t_last = time() | python | {
"resource": ""
} |
q268081 | Timer.since_start | test | def since_start(self):
"""Total time since the timer is started.
Returns (float): Time in seconds.
"""
if not self._is_running:
raise TimerError('timer is not running')
self._t_last = time()
return self._t_last - self._t_start | python | {
"resource": ""
} |
q268082 | Timer.since_last_check | test | def since_last_check(self):
"""Time since the last checking.
Either :func:`since_start` or :func:`since_last_check` is a checking
operation.
Returns (float): Time in seconds.
"""
if not self._is_running:
raise TimerError('timer is not running')
dur =... | python | {
"resource": ""
} |
q268083 | flowshow | test | def flowshow(flow, win_name='', wait_time=0):
"""Show optical flow.
Args:
flow (ndarray or str): The optical flow to be displayed.
win_name (str): The window name.
wait_time (int): Value of waitKey param.
"""
flow = flowread(flow)
flow_img = flow2rgb(flow)
imshow(rgb2bgr... | python | {
"resource": ""
} |
q268084 | flow2rgb | test | def flow2rgb(flow, color_wheel=None, unknown_thr=1e6):
"""Convert flow map to RGB image.
Args:
flow (ndarray): Array of optical flow.
color_wheel (ndarray or None): Color wheel used to map flow field to
RGB colorspace. Default color wheel will be used if not specified.
unkno... | python | {
"resource": ""
} |
q268085 | make_color_wheel | test | def make_color_wheel(bins=None):
"""Build a color wheel.
Args:
bins(list or tuple, optional): Specify the number of bins for each
color range, corresponding to six ranges: red -> yellow,
yellow -> green, green -> cyan, cyan -> blue, blue -> magenta,
magenta -> red. [... | python | {
"resource": ""
} |
q268086 | accuracy | test | def accuracy(output, target, topk=(1, )):
"""Computes the precision@k for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expan... | python | {
"resource": ""
} |
q268087 | scatter | test | def scatter(inputs, target_gpus, dim=0):
"""Scatter inputs to target gpus.
The only difference from original :func:`scatter` is to add support for
:type:`~mmcv.parallel.DataContainer`.
"""
def scatter_map(obj):
if isinstance(obj, torch.Tensor):
return OrigScatter.apply(target_g... | python | {
"resource": ""
} |
q268088 | scatter_kwargs | test | def scatter_kwargs(inputs, kwargs, target_gpus, dim=0):
"""Scatter with support for kwargs dictionary"""
inputs = scatter(inputs, target_gpus, dim) if inputs else []
kwargs = scatter(kwargs, target_gpus, dim) if kwargs else []
if len(inputs) < len(kwargs):
inputs.extend([() for _ in range(len(kw... | python | {
"resource": ""
} |
q268089 | Request.fetch | test | async def fetch(self) -> Response:
"""Fetch all the information by using aiohttp"""
if self.request_config.get('DELAY', 0) > 0:
await asyncio.sleep(self.request_config['DELAY'])
timeout = self.request_config.get('TIMEOUT', 10)
try:
async with async_timeout.timeou... | python | {
"resource": ""
} |
q268090 | Response.json | test | async def json(self,
*,
encoding: str = None,
loads: JSONDecoder = DEFAULT_JSON_DECODER,
content_type: Optional[str] = 'application/json') -> Any:
"""Read and decodes JSON response."""
return await self._aws_json(
en... | python | {
"resource": ""
} |
q268091 | Response.text | test | async def text(self,
*,
encoding: Optional[str] = None,
errors: str = 'strict') -> str:
"""Read response payload and decode."""
return await self._aws_text(encoding=encoding, errors=errors) | python | {
"resource": ""
} |
q268092 | Spider.handle_callback | test | async def handle_callback(self, aws_callback: typing.Coroutine, response):
"""Process coroutine callback function"""
callback_result = None
try:
callback_result = await aws_callback
except NothingMatchedError as e:
self.logger.error(f'<Item: {str(e).lower()}>')
... | python | {
"resource": ""
} |
q268093 | Spider.multiple_request | test | async def multiple_request(self, urls, is_gather=False, **kwargs):
"""For crawling multiple urls"""
if is_gather:
resp_results = await asyncio.gather(
*[
self.handle_request(self.request(url=url, **kwargs))
for url in urls
... | python | {
"resource": ""
} |
q268094 | Spider.request | test | def request(self,
url: str,
method: str = 'GET',
*,
callback=None,
encoding: typing.Optional[str] = None,
headers: dict = None,
metadata: dict = None,
request_config: dict = None,
... | python | {
"resource": ""
} |
q268095 | Spider.start_master | test | async def start_master(self):
"""Actually start crawling."""
for url in self.start_urls:
request_ins = self.request(
url=url, callback=self.parse, metadata=self.metadata)
self.request_queue.put_nowait(self.handle_request(request_ins))
workers = [
... | python | {
"resource": ""
} |
q268096 | normalize_task_v2 | test | def normalize_task_v2(task):
'''Ensures tasks have an action key and strings are converted to python objects'''
result = dict()
mod_arg_parser = ModuleArgsParser(task)
try:
action, arguments, result['delegate_to'] = mod_arg_parser.parse()
except AnsibleParserError as e:
try:
... | python | {
"resource": ""
} |
q268097 | parse_yaml_linenumbers | test | def parse_yaml_linenumbers(data, filename):
"""Parses yaml as ansible.utils.parse_yaml but with linenumbers.
The line numbers are stored in each node's LINE_NUMBER_KEY key.
"""
def compose_node(parent, index):
# the line number where the previous token has ended (plus empty lines)
line... | python | {
"resource": ""
} |
q268098 | bdist_wheel.wheel_dist_name | test | def wheel_dist_name(self):
"""Return distribution full name with - replaced with _"""
return '-'.join((safer_name(self.distribution.get_name()),
safer_version(self.distribution.get_version()))) | python | {
"resource": ""
} |
q268099 | bdist_wheel.get_archive_basename | test | def get_archive_basename(self):
"""Return archive name without extension"""
impl_tag, abi_tag, plat_tag = self.get_tag()
archive_basename = "%s-%s-%s-%s" % (
self.wheel_dist_name,
impl_tag,
abi_tag,
plat_tag)
return archive_basename | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.