INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Show an image. | 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) |
Draw bboxes on an image. | 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... |
Draw bboxes and class labels ( with scores ) on an image. | def imshow_det_bboxes(img,
bboxes,
labels,
class_names=None,
score_thr=0,
bbox_color='green',
text_color='green',
thickness=1,
font_scale=0.5,
... |
Read an optical flow map. | 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... |
Write optical flow to file. | 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... |
Quantize flow to [ 0 255 ]. | def quantize_flow(flow, max_val=0.02, norm=True):
"""Quantize flow to [0, 255].
After this step, the size of flow will be much smaller, and can be
dumped as jpeg images.
Args:
flow (ndarray): (h, w, 2) array of optical flow.
max_val (float): Maximum value of flow, values beyond
... |
Recover from quantized flow. | 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... |
Load state_dict to a module. | 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:... |
Load checkpoint from a file or URI. | 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... |
Copy a model state_dict to cpu. | 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()
... |
Save checkpoint to file. | 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.
... |
Init the optimizer. | 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.
... |
Init the logger. | 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... |
Get current learning rates. | 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']... |
Register a hook into the hook list. | 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... |
Start running. | 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... |
Register default hooks for training. | def register_training_hooks(self,
lr_config,
optimizer_config=None,
checkpoint_config=None,
log_config=None):
"""Register default hooks for training.
Default hooks include:
... |
Convert a video with ffmpeg. | 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... |
Resize a video. | 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.
... |
Cut a clip from a video. | 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... |
Concatenate multiple videos into a single one. | 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... |
Load a text file and parse the content as a list of strings. | 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... |
Load a text file and parse the content as a dict. | 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:
... |
3x3 convolution with padding | 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) |
Initialize an object from dict. | 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.
... |
Read an image. | 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,
... |
Read an image from bytes. | 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... |
Write image to file | 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... |
Convert a BGR image to grayscale image. | 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.
... |
Convert a grayscale image to BGR image. | 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 |
Cast elements of an iterable object into some type. | 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... |
Check whether it is a sequence of some type. | 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... |
Slice a list into several sub lists by a list of given length. | 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):
... |
A decorator factory to check if prerequisites are satisfied. | 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... |
Average latest n values or all values | 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... |
Scatters tensor across multiple GPUs. | 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... |
Convert various input to color tuples. | 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... |
Add check points in a single line. | 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... |
Start the timer. | def start(self):
"""Start the timer."""
if not self._is_running:
self._t_start = time()
self._is_running = True
self._t_last = time() |
Total time since the timer is started. | 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 |
Time since the last checking. | 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 =... |
Show optical flow. | 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... |
Convert flow map to RGB image. | 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... |
Build a color wheel. | 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. [... |
Computes the precision | 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... |
Scatter inputs to target gpus. | 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... |
Scatter with support for kwargs dictionary | 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... |
Fetch all the information by using aiohttp | 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... |
Define a Decorate to be called before a request. eg: | def request(self, *args, **kwargs):
"""
Define a Decorate to be called before a request.
eg: @middleware.request
"""
middleware = args[0]
@wraps(middleware)
def register_middleware(*args, **kwargs):
self.request_middleware.append(middleware)
... |
Define a Decorate to be called after a response. eg: | def response(self, *args, **kwargs):
"""
Define a Decorate to be called after a response.
eg: @middleware.response
"""
middleware = args[0]
@wraps(middleware)
def register_middleware(*args, **kwargs):
self.response_middleware.appendleft(middleware)
... |
Read and decodes JSON response. | 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... |
Read response payload and decode. | 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) |
Run hook before/ after spider start crawling: param hook_func: aws function: return: | async def _run_spider_hook(self, hook_func):
"""
Run hook before/after spider start crawling
:param hook_func: aws function
:return:
"""
if callable(hook_func):
try:
aws_hook_func = hook_func(weakref.proxy(self))
if isawaitable(... |
Corresponding processing for the invalid callback result: param item:: return: | async def process_callback_result(self, callback_result):
"""
Corresponding processing for the invalid callback result
:param item:
:return:
"""
callback_result_name = type(callback_result).__name__
process_func_name = self.callback_result_map.get(
cal... |
Start an async spider: param middleware: customize middleware or a list of middleware: param loop:: param after_start: hook: param before_stop: hook: return: | async def async_start(
cls,
middleware: typing.Union[typing.Iterable, Middleware] = None,
loop=None,
after_start=None,
before_stop=None,
**kwargs):
"""
Start an async spider
:param middleware: customize middleware or a list ... |
Start a spider: param after_start: hook: param before_stop: hook: param middleware: customize middleware or a list of middleware: param loop: event loop: param close_event_loop: bool: return: | def start(cls,
middleware: typing.Union[typing.Iterable, Middleware] = None,
loop=None,
after_start=None,
before_stop=None,
close_event_loop=True,
**kwargs):
"""
Start a spider
:param after_start: hook
:p... |
Process coroutine callback function | 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()}>')
... |
Wrap request with middleware.: param request:: return: | async def handle_request(self, request: Request
) -> typing.Tuple[AsyncGeneratorType, Response]:
"""
Wrap request with middleware.
:param request:
:return:
"""
callback_result, response = None, None
await self._run_request_middleware(... |
For crawling multiple urls | 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
... |
Init a Request class for crawling html | 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,
... |
Actually start crawling. | 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 = [
... |
Finish all running tasks cancel remaining tasks then stop loop.: param _signal:: return: | async def stop(self, _signal):
"""
Finish all running tasks, cancel remaining tasks, then stop loop.
:param _signal:
:return:
"""
self.logger.info(f'Stopping spider: {self.name}')
await self._cancel_tasks()
self.loop.stop() |
If there is a group dict return the dict ; even if there s only one value in the dict return a dictionary ; If there is a group in match return the group ; if there is only one value in the group return the value ; if there has no group return the whole matched string ; if there are many groups return a tuple ;: param ... | def _parse_match(self, match):
"""
If there is a group dict, return the dict;
even if there's only one value in the dict, return a dictionary;
If there is a group in match, return the group;
if there is only one value in the group, return the value;
if there has n... |
Get a db instance: param db: database name: return: the motor db instance | def get_db(self, db='test'):
"""
Get a db instance
:param db: database name
:return: the motor db instance
"""
if db not in self._db:
self._db[db] = self.client(db)[db]
return self._db[db] |
Ensures tasks have an action key and strings are converted to python objects | 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:
... |
Parses yaml as ansible. utils. parse_yaml but with linenumbers. | 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... |
Uses ruamel. yaml to parse comments then adds a skipped_rules list to the task ( or meta yaml block ) | def append_skipped_rules(pyyaml_data, file_text, file_type):
""" Uses ruamel.yaml to parse comments then adds a
skipped_rules list to the task (or meta yaml block)
"""
yaml = ruamel.yaml.YAML()
ruamel_data = yaml.load(file_text)
if file_type in ('tasks', 'handlers'):
ruamel_tasks = ... |
Helper method that compares two StoreItems and their e_tags and returns True if the new_value should overwrite the old_value. Otherwise returns False.: param old_value:: param new_value:: return: | def __should_write_changes(self, old_value: StoreItem, new_value: StoreItem) -> bool:
"""
Helper method that compares two StoreItems and their e_tags and returns True if the new_value should overwrite
the old_value. Otherwise returns False.
:param old_value:
:param new_value:
... |
Called by the parent class to run the adapters middleware set and calls the passed in callback () handler at the end of the chain.: param context:: param callback:: return: | async def run_middleware(self, context: TurnContext, callback: Callable=None):
"""
Called by the parent class to run the adapters middleware set and calls the passed in `callback()` handler at
the end of the chain.
:param context:
:param callback:
:return:
"""
... |
Registers middleware plugin ( s ) with the bot or set.: param middleware:: return: | def use(self, *middleware: Middleware):
"""
Registers middleware plugin(s) with the bot or set.
:param middleware :
:return:
"""
for (idx, m) in enumerate(middleware):
if hasattr(m, 'on_process_request') and callable(m.on_process_request):
self... |
Send information about the page viewed in the application ( a web page for instance ).: param name: the name of the page that was viewed.: param url: the URL of the page that was viewed.: param duration: the duration of the page view in milliseconds. ( defaults to: 0 ): param properties: the set of custom properties th... | def track_pageview(self, name: str, url:str, duration: int = 0, properties : Dict[str, object]=None,
measurements: Dict[str, object]=None) -> None:
"""
Send information about the page viewed in the application (a web page for instance).
:param name: the name of the page ... |
Send information about a single exception that occurred in the application.: param type_exception: the type of the exception that was thrown.: param value: the exception that the client wants to send.: param tb: the traceback information as returned by: func: sys. exc_info.: param properties: the set of custom properti... | def track_exception(self, type_exception: type = None, value : Exception =None, tb : traceback =None,
properties: Dict[str, object]=None, measurements: Dict[str, object]=None) -> None:
"""
Send information about a single exception that occurred in the application.
:para... |
Send information about a single event that has occurred in the context of the application.: param name: the data to associate to this event.: param properties: the set of custom properties the client wants attached to this data item. ( defaults to: None ): param measurements: the set of custom measurements the client w... | def track_event(self, name: str, properties: Dict[str, object] = None,
measurements: Dict[str, object] = None) -> None:
"""
Send information about a single event that has occurred in the context of the application.
:param name: the data to associate to this event.
:... |
Send information about a single metric data point that was captured for the application.: param name: The name of the metric that was captured.: param value: The value of the metric that was captured.: param type: The type of the metric. ( defaults to: TelemetryDataPointType. aggregation ): param count: the number of m... | def track_metric(self, name: str, value: float, type: TelemetryDataPointType =None,
count: int =None, min: float=None, max: float=None, std_dev: float=None,
properties: Dict[str, object]=None) -> NotImplemented:
"""
Send information about a single metric data poi... |
Sends a single trace statement.: param name: the trace statement. \ n: param properties: the set of custom properties the client wants attached to this data item. ( defaults to: None ) \ n: param severity: the severity level of this trace one of DEBUG INFO WARNING ERROR CRITICAL | def track_trace(self, name: str, properties: Dict[str, object]=None, severity=None):
"""
Sends a single trace statement.
:param name: the trace statement.\n
:param properties: the set of custom properties the client wants attached to this data item. (defaults to: None)\n
:param s... |
Sends a single request that was captured for the application.: param name: The name for this request. All requests with the same name will be grouped together.: param url: The actual URL for this request ( to show in individual request instances ).: param success: True if the request ended in success False otherwise.: ... | def track_request(self, name: str, url: str, success: bool, start_time: str=None,
duration: int=None, response_code: str =None, http_method: str=None,
properties: Dict[str, object]=None, measurements: Dict[str, object]=None,
request_id: str=None):
"... |
Sends a single dependency telemetry that was captured for the application.: param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.: param data: the command initiated by this dependency call. Examples are SQL statement and... | def track_dependency(self, name:str, data:str, type:str=None, target:str=None, duration:int=None,
success:bool=None, result_code:str=None, properties:Dict[str, object]=None,
measurements:Dict[str, object]=None, dependency_id:str=None):
"""
Sends a single... |
Create a property definition and register it with this BotState.: param name: The name of the property.: param force:: return: If successful the state property accessor created. | def create_property(self, name:str) -> StatePropertyAccessor:
"""
Create a property definition and register it with this BotState.
:param name: The name of the property.
:param force:
:return: If successful, the state property accessor created.
"""
if not name:
... |
Reads in the current state object and caches it in the context object for this turm.: param turn_context: The context object for this turn.: param force: Optional. True to bypass the cache. | async def load(self, turn_context: TurnContext, force: bool = False) -> None:
"""
Reads in the current state object and caches it in the context object for this turm.
:param turn_context: The context object for this turn.
:param force: Optional. True to bypass the cache.
"""
... |
If it has changed writes to storage the state object that is cached in the current context object for this turn.: param turn_context: The context object for this turn.: param force: Optional. True to save state to storage whether or not there are changes. | async def save_changes(self, turn_context: TurnContext, force: bool = False) -> None:
"""
If it has changed, writes to storage the state object that is cached in the current context object for this turn.
:param turn_context: The context object for this turn.
:param force: Optional. True ... |
Clears any state currently stored in this state scope. NOTE: that save_changes must be called in order for the cleared state to be persisted to the underlying store.: param turn_context: The context object for this turn.: return: None | async def clear_state(self, turn_context: TurnContext):
"""
Clears any state currently stored in this state scope.
NOTE: that save_changes must be called in order for the cleared state to be persisted to the underlying store.
:param turn_context: The context object for this turn... |
Delete any state currently stored in this state scope.: param turn_context: The context object for this turn.: return: None | async def delete(self, turn_context: TurnContext) -> None:
"""
Delete any state currently stored in this state scope.
:param turn_context: The context object for this turn.
:return: None
"""
if turn_context == None:
raise TypeError('BotState.delete():... |
Deletes a property from the state cache in the turn context.: param turn_context: The context object for this turn.: param property_name: The value to set on the property.: return: None | async def set_property_value(self, turn_context: TurnContext, property_name: str, value: object) -> None:
"""
Deletes a property from the state cache in the turn context.
:param turn_context: The context object for this turn.
:param property_name: The value to set on the propert... |
Continues a conversation with a user. This is often referred to as the bots Proactive Messaging flow as its lets the bot proactively send messages to a conversation or user that its already communicated with. Scenarios like sending notifications or coupons to a user are enabled by this method.: param reference:: param ... | async def continue_conversation(self, reference: ConversationReference, logic):
"""
Continues a conversation with a user. This is often referred to as the bots "Proactive Messaging"
flow as its lets the bot proactively send messages to a conversation or user that its already
communicated... |
Starts a new conversation with a user. This is typically used to Direct Message ( DM ) a member of a group.: param reference:: param logic:: return: | async def create_conversation(self, reference: ConversationReference, logic):
"""
Starts a new conversation with a user. This is typically used to Direct Message (DM) a member
of a group.
:param reference:
:param logic:
:return:
"""
try:
if ref... |
Processes an activity received by the bots web server. This includes any messages sent from a user and is the method that drives what s often referred to as the bots Reactive Messaging flow.: param req:: param auth_header:: param logic:: return: | async def process_activity(self, req, auth_header: str, logic: Callable):
"""
Processes an activity received by the bots web server. This includes any messages sent from a
user and is the method that drives what's often referred to as the bots "Reactive Messaging"
flow.
:param re... |
Allows for the overriding of authentication in unit tests.: param request:: param auth_header:: return: | async def authenticate_request(self, request: Activity, auth_header: str):
"""
Allows for the overriding of authentication in unit tests.
:param request:
:param auth_header:
:return:
"""
await JwtTokenValidation.authenticate_request(request, auth_header, self._cre... |
Parses and validates request: param req:: return: | async def parse_request(req):
"""
Parses and validates request
:param req:
:return:
"""
async def validate_activity(activity: Activity):
if not isinstance(activity.type, str):
raise TypeError('BotFrameworkAdapter.parse_request(): invalid or mi... |
Replaces an activity that was previously sent to a channel. It should be noted that not all channels support this feature.: param context:: param activity:: return: | async def update_activity(self, context: TurnContext, activity: Activity):
"""
Replaces an activity that was previously sent to a channel. It should be noted that not all
channels support this feature.
:param context:
:param activity:
:return:
"""
try:
... |
Deletes an activity that was previously sent to a channel. It should be noted that not all channels support this feature.: param context:: param conversation_reference:: return: | async def delete_activity(self, context: TurnContext, conversation_reference: ConversationReference):
"""
Deletes an activity that was previously sent to a channel. It should be noted that not all
channels support this feature.
:param context:
:param conversation_reference:
... |
Deletes a member from the current conversation.: param context:: param member_id:: return: | async def delete_conversation_member(self, context: TurnContext, member_id: str) -> None:
"""
Deletes a member from the current conversation.
:param context:
:param member_id:
:return:
"""
try:
if not context.activity.service_url:
raise... |
Lists the members of a given activity.: param context:: param activity_id:: return: | async def get_activity_members(self, context: TurnContext, activity_id: str):
"""
Lists the members of a given activity.
:param context:
:param activity_id:
:return:
"""
try:
if not activity_id:
activity_id = context.activity.id
... |
Lists the members of a current conversation.: param context:: return: | async def get_conversation_members(self, context: TurnContext):
"""
Lists the members of a current conversation.
:param context:
:return:
"""
try:
if not context.activity.service_url:
raise TypeError('BotFrameworkAdapter.get_conversation_member... |
Lists the Conversations in which this bot has participated for a given channel server. The channel server returns results in pages and each page will include a continuationToken that can be used to fetch the next page of results from the server.: param service_url:: param continuation_token:: return: | async def get_conversations(self, service_url: str, continuation_token: str=None):
"""
Lists the Conversations in which this bot has participated for a given channel server. The channel server
returns results in pages and each page will include a `continuationToken` that can be used to fetch the... |
Allows for mocking of the connector client in unit tests.: param service_url:: return: | def create_connector_client(self, service_url: str) -> ConnectorClient:
"""
Allows for mocking of the connector client in unit tests.
:param service_url:
:return:
"""
client = ConnectorClient(self._credentials, base_url=service_url)
client.config.add_user_agent(US... |
Adds a dialog to the component dialog. Adding a new dialog will inherit the BotTelemetryClient of the ComponentDialog.: param dialog: The dialog to add.: return: The updated ComponentDialog | def add_dialog(self, dialog: Dialog) -> object:
"""
Adds a dialog to the component dialog.
Adding a new dialog will inherit the BotTelemetryClient of the ComponentDialog.
:param dialog: The dialog to add.
:return: The updated ComponentDialog
"""
self._dialogs.add(... |
Authenticates the request and sets the service url in the set of trusted urls.: param activity: The incoming Activity from the Bot Framework or the Emulator: type activity: ~botframework. connector. models. Activity: param auth_header: The Bearer token included as part of the request: type auth_header: str: param crede... | async def authenticate_request(activity: Activity, auth_header: str, credentials: CredentialProvider) -> ClaimsIdentity:
"""Authenticates the request and sets the service url in the set of trusted urls.
:param activity: The incoming Activity from the Bot Framework or the Emulator
:type ... |
Return distribution full name with - replaced with _ | 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()))) |
Return archive name without extension | 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 |
Generate requirements from setup. cfg as ( Requires - Dist requirement ; qualifier ) tuples. From a metadata section in setup. cfg: | def setupcfg_requirements(self):
"""Generate requirements from setup.cfg as
('Requires-Dist', 'requirement; qualifier') tuples. From a metadata
section in setup.cfg:
[metadata]
provides-extra = extra1
extra2
requires-dist = requirement; qualifier
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.