text
stringlengths 5
22M
| id
stringlengths 12
177
| metadata
dict | __index_level_0__
int64 0
1.37k
|
---|---|---|---|
import pytest
from random import Random
from archai.discrete_search.search_spaces.config import (
ArchConfig, ArchParamTree, ConfigSearchSpace, DiscreteChoice,
repeat_config
)
@pytest.fixture
def rng():
return Random(1)
@pytest.fixture
def tree_c1():
s = DiscreteChoice(['a', 'b', 'c'])
c = {
'param1': s,
'param2': DiscreteChoice(['d', 'e', 'f']),
'param1_clone': s,
'sub1': {
'sub2':{
'param1_clone': s
}
},
'param_list': repeat_config({
'param3': DiscreteChoice(['g', 'h', 'i']),
'param4': repeat_config({
'constant': 'a',
'param5': DiscreteChoice(['j', 'k', 'l'])
}, repeat_times=[3, 4], share_arch=True)
}, repeat_times=[0, 1, 2], share_arch=False)
}
return c
@pytest.fixture
def tree_c2():
c = {
'p1': DiscreteChoice(list([False, True])),
'p2': DiscreteChoice(list([False, True]))
}
return c
def test_param_sharing(rng, tree_c1):
tree = ArchParamTree(tree_c1)
for _ in range(10):
config = tree.sample_config(rng)
p1 = config.pick('param1')
assert config.get_used_params()['param1']
p1_c = config.pick('param1_clone')
assert p1 == p1_c
p1_c2 = config.pick('sub1').pick('sub2').pick('param1_clone')
assert p1 == p1_c2
def test_repeat_config_share(rng, tree_c1):
tree = ArchParamTree(tree_c1)
for _ in range(10):
config = tree.sample_config(rng)
for param_block in config.pick('param_list'):
par4 = param_block.pick('param4')
assert len(set(
p.pick('constant') for p in par4
)) == 1
assert len(set(
p.pick('param5') for p in par4
)) == 1
def test_default_value():
a = ArchConfig({
'p': 2
})
assert a.pick('c', default=2) == a.pick('p')
def test_ss(rng, tree_c2, tmp_path_factory):
tmp_path = tmp_path_factory.mktemp('test_ss')
tree = ArchParamTree(tree_c2)
def use_arch(c):
if c.pick('p1'):
return
if c.pick('p2'):
return
cache = []
for _ in range(2):
ids = []
ss = ConfigSearchSpace(use_arch, tree, seed=1)
m = ss.random_sample()
ids += [m.archid]
ss.save_arch(m, tmp_path / 'arch.json')
m2 = ss.load_arch(tmp_path / 'arch.json')
assert m.archid == m2.archid
m3 = ss.mutate(m)
ids += [m3.archid]
m4 = ss.crossover([m3, m2])
ids += [m4.archid]
cache += [ids]
# make sure the archid's returned are repeatable so that search jobs can be restartable.
assert cache[0] == cache[1]
def test_ss_archid(rng, tree_c2):
tree = ArchParamTree(tree_c2)
def use_arch(c):
if c.pick('p1'):
return
if c.pick('p2'):
return
ss = ConfigSearchSpace(use_arch, tree, seed=1)
archids = set()
for _ in range(100):
config = ss.random_sample()
archids.add(config.archid)
assert len(archids) == 3 # Will fail with probability approx 1/2^100
|
archai/tests/discrete_search/search_spaces/config/test_config_ss.py/0
|
{
"file_path": "archai/tests/discrete_search/search_spaces/config/test_config_ss.py",
"repo_id": "archai",
"token_count": 1607
}
| 361 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import pytest
from onnxruntime import InferenceSession
from transformers import GPT2Config, GPT2LMHeadModel
from archai.onnx.export import export_to_onnx
from archai.onnx.onnx_loader import load_from_onnx
from archai.onnx.optimization import optimize_onnx
@pytest.fixture
def onnx_model_path():
model = GPT2LMHeadModel(config=GPT2Config(vocab_size=1, n_layer=1))
onnx_model_path = "temp_model.onnx"
onnx_config = export_to_onnx(model, onnx_model_path)
ort_model_path = optimize_onnx(onnx_model_path, onnx_config)
yield ort_model_path
os.remove(onnx_model_path)
os.remove(ort_model_path)
def test_load_from_onnx(onnx_model_path):
# Assert that the `session` can be loaded from the `onnx_model_path`
session = load_from_onnx(onnx_model_path)
assert isinstance(session, InferenceSession)
|
archai/tests/onnx/test_onnx_loader.py/0
|
{
"file_path": "archai/tests/onnx/test_onnx_loader.py",
"repo_id": "archai",
"token_count": 365
}
| 362 |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import pytest
if os.name == "nt":
pytest.skip(allow_module_level=True)
from archai.common.file_utils import get_full_path
from archai.trainers.nlp.ds_training_args import DsTrainingArguments
def test_ds_training_arguments():
# Assert that the default values are correct
args = DsTrainingArguments("logdir")
assert args.output_dir == get_full_path("logdir")
assert args.ds_config == {}
assert args.do_eval == True
assert args.max_steps == 1
assert args.logging_steps == 10
assert args.save_steps == 500
assert args.seed == 42
assert args.local_rank == os.getenv("LOCAL_RANK", -1)
assert args.backend == "nccl"
assert args.eval_steps == 500
assert args.eval_max_steps == None
assert args.pipe_parallel_size == 1
assert args.pipe_parallel_loss_fn == None
assert args.pipe_parallel_partition_method == "parameters"
assert args.pipe_parallel_activation_checkpoint_steps == 0
assert args.dataloader_pin_memory == True
assert args.dataloader_num_workers == 0
|
archai/tests/trainers/nlp/test_ds_training_args.py/0
|
{
"file_path": "archai/tests/trainers/nlp/test_ds_training_args.py",
"repo_id": "archai",
"token_count": 394
}
| 363 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from __future__ import print_function
import logging
import os
import re
import uuid
from msrest import Deserializer, Serializer
from msrest.exceptions import DeserializationError, SerializationError
from msrest.universal_http import ClientRequest
from msrest.service_client import ServiceClient
from .exceptions import AzureDevOpsAuthenticationError, AzureDevOpsClientRequestError, AzureDevOpsServiceError
from .client_configuration import ClientConfiguration
from . import _models
from ._file_cache import OPTIONS_CACHE as OPTIONS_FILE_CACHE
logger = logging.getLogger(__name__)
class Client(object):
"""Client.
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
self.config = ClientConfiguration(base_url)
self.config.credentials = creds
self._client = ServiceClient(creds, config=self.config)
_base_client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)}
self._base_deserialize = Deserializer(_base_client_models)
self._base_serialize = Serializer(_base_client_models)
self._all_host_types_locations = {}
self._locations = {}
self._suppress_fedauth_redirect = True
self._force_msa_pass_through = True
self.normalized_url = Client._normalize_url(base_url)
def add_user_agent(self, user_agent):
if user_agent is not None:
self.config.add_user_agent(user_agent)
def _send_request(self, request, headers=None, content=None, media_type=None, **operation_config):
"""Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to add to the request.
:param config: Any specific config overrides
"""
if (TRACE_ENV_VAR in os.environ and os.environ[TRACE_ENV_VAR] == 'true')\
or (TRACE_ENV_VAR_COMPAT in os.environ and os.environ[TRACE_ENV_VAR_COMPAT] == 'true'):
print(request.method + ' ' + request.url)
logger.debug('%s %s', request.method, request.url)
if media_type is not None and media_type == 'application/json':
logger.debug('Request content: %s', content)
response = self._client.send(request=request, headers=headers,
content=content, **operation_config)
if ('Content-Type' in response.headers
and response.headers['Content-Type'].startswith('application/json')):
logger.debug('Response content: %s', response.content)
if response.status_code < 200 or response.status_code >= 300:
self._handle_error(request, response)
return response
def _send(self, http_method, location_id, version, route_values=None,
query_parameters=None, content=None, media_type='application/json', accept_media_type='application/json',
additional_headers=None):
request = self._create_request_message(http_method=http_method,
location_id=location_id,
route_values=route_values,
query_parameters=query_parameters)
negotiated_version = self._negotiate_request_version(
self._get_resource_location(self.normalized_url, location_id),
version)
if version != negotiated_version:
logger.info("Negotiated api version from '%s' down to '%s'. This means the client is newer than the server.",
version,
negotiated_version)
else:
logger.debug("Api version '%s'", negotiated_version)
# Construct headers
headers = {'Content-Type': media_type + '; charset=utf-8',
'Accept': accept_media_type + ';api-version=' + negotiated_version}
if additional_headers is not None:
for key in additional_headers:
headers[key] = str(additional_headers[key])
if self.config.additional_headers is not None:
for key in self.config.additional_headers:
headers[key] = self.config.additional_headers[key]
if self._suppress_fedauth_redirect:
headers['X-TFS-FedAuthRedirect'] = 'Suppress'
if self._force_msa_pass_through:
headers['X-VSS-ForceMsaPassThrough'] = 'true'
if Client._session_header_key in Client._session_data and Client._session_header_key not in headers:
headers[Client._session_header_key] = Client._session_data[Client._session_header_key]
response = self._send_request(request=request, headers=headers, content=content, media_type=media_type)
if Client._session_header_key in response.headers:
Client._session_data[Client._session_header_key] = response.headers[Client._session_header_key]
return response
def _unwrap_collection(self, response):
if response.headers.get("transfer-encoding") == 'chunked':
wrapper = self._base_deserialize.deserialize_data(response.json(), 'VssJsonCollectionWrapper')
else:
wrapper = self._base_deserialize('VssJsonCollectionWrapper', response)
collection = wrapper.value
return collection
def _create_request_message(self, http_method, location_id, route_values=None,
query_parameters=None):
location = self._get_organization_resource_location(location_id)
deployment_level = False
deployment_url = None
if location is None:
logger.debug('API resource location ' + location_id + ' is not registered on ' + self.config.base_url + '.')
deployment_url = self._get_deployment_url()
if deployment_url is not None:
logger.debug('Checking for location at deployment level: ' + deployment_url)
location = self._get_resource_location(deployment_url, location_id)
deployment_level = True
if location is None:
raise ValueError('API resource location ' + location_id + ' is not registered on '
+ self.config.base_url + '.')
if route_values is None:
route_values = {}
route_values['area'] = location.area
route_values['resource'] = location.resource_name
route_template = self._remove_optional_route_parameters(location.route_template,
route_values)
logger.debug('Route template: %s', location.route_template)
if not deployment_level:
url = self._client.format_url(route_template, **route_values)
else:
url = self._client.format_url(deployment_url + route_template, **route_values)
request = ClientRequest(method=http_method, url=url)
if query_parameters:
request.format_parameters(query_parameters)
return request
@staticmethod
def _remove_optional_route_parameters(route_template, route_values):
new_template = ''
route_template = route_template.replace('{*', '{')
for path_segment in route_template.split('/'):
if (len(path_segment) <= 2 or not path_segment[0] == '{'
or not path_segment[len(path_segment) - 1] == '}'
or path_segment[1:len(path_segment) - 1] in route_values):
new_template = new_template + '/' + path_segment
return new_template
def _get_organization_resource_location(self, location_id):
return self._get_resource_location(self.normalized_url, location_id)
def _get_deployment_url(self):
pos = self.normalized_url.rfind('/')
if pos > 0:
deployment_url = self.normalized_url[:pos]
if deployment_url.find('://') > 0:
return deployment_url
return None
def _get_resource_location(self, url, location_id):
if url not in Client._locations_cache:
Client._locations_cache[url] = self._get_resource_locations(url, all_host_types=False)
for location in Client._locations_cache[url]:
if location.id == location_id:
return location
def _get_resource_locations(self, url, all_host_types):
# Check local client's cached Options first
if all_host_types:
if url in self._all_host_types_locations:
return self._all_host_types_locations[url]
elif url in self._locations:
return self._locations[url]
# Next check for options cached on disk
if not all_host_types and OPTIONS_FILE_CACHE[url]:
try:
logger.debug('File cache hit for options on: %s', url)
self._locations[url] = self._base_deserialize.deserialize_data(OPTIONS_FILE_CACHE[url],
'[ApiResourceLocation]')
return self._locations[url]
except DeserializationError as ex:
logger.debug(ex, exc_info=True)
else:
logger.debug('File cache miss for options on: %s', url)
# Last resort, make the call to the server
options_uri = self._combine_url(url, '_apis')
request = ClientRequest(method='OPTIONS', url=self._client.format_url(options_uri))
if all_host_types:
query_parameters = {'allHostTypes': True}
request.format_parameters(query_parameters)
headers = {'Accept': 'application/json'}
if self._suppress_fedauth_redirect:
headers['X-TFS-FedAuthRedirect'] = 'Suppress'
if self._force_msa_pass_through:
headers['X-VSS-ForceMsaPassThrough'] = 'true'
response = self._send_request(request, headers=headers)
wrapper = self._base_deserialize('VssJsonCollectionWrapper', response)
if wrapper is None:
raise AzureDevOpsClientRequestError("Failed to retrieve resource locations from: {}".format(options_uri))
collection = wrapper.value
returned_locations = self._base_deserialize('[ApiResourceLocation]',
collection)
if all_host_types:
self._all_host_types_locations[url] = returned_locations
else:
self._locations[url] = returned_locations
try:
OPTIONS_FILE_CACHE[url] = wrapper.value
except SerializationError as ex:
logger.debug(ex, exc_info=True)
return returned_locations
@staticmethod
def _negotiate_request_version(location, version):
if location is None or version is None:
return version
pattern = r'(\d+(\.\d)?)(-preview(.(\d+))?)?'
match = re.match(pattern, version)
requested_api_version = match.group(1)
if requested_api_version is not None:
requested_api_version = float(requested_api_version)
if location.min_version > requested_api_version:
# Client is older than the server. The server no longer supports this
# resource (deprecated).
return
elif location.max_version < requested_api_version:
# Client is newer than the server. Negotiate down to the latest version
# on the server
negotiated_version = str(location.max_version)
if float(location.released_version) < location.max_version:
negotiated_version += '-preview'
return negotiated_version
else:
# We can send at the requested api version. Make sure the resource version
# is not bigger than what the server supports
negotiated_version = match.group(1)
is_preview = match.group(3) is not None
if is_preview:
negotiated_version += '-preview'
if match.group(5) is not None:
if location.resource_version < int(match.group(5)):
negotiated_version += '.' + str(location.resource_version)
else:
negotiated_version += '.' + match.group(5)
return negotiated_version
@staticmethod
def _combine_url(part1, part2):
return part1.rstrip('/') + '/' + part2.strip('/')
def _handle_error(self, request, response):
content_type = response.headers.get('Content-Type')
error_message = ''
if content_type is None or content_type.find('text/plain') < 0:
try:
wrapped_exception = self._base_deserialize('WrappedException', response)
if wrapped_exception is not None and wrapped_exception.message is not None:
raise AzureDevOpsServiceError(wrapped_exception)
else:
# System exceptions from controllers are not returning wrapped exceptions.
# Following code is to handle this unusual exception json case.
# TODO: dig into this.
collection_wrapper = self._base_deserialize('VssJsonCollectionWrapper', response)
if collection_wrapper is not None and collection_wrapper.value is not None:
wrapped_exception = self._base_deserialize('ImproperException', collection_wrapper.value)
if wrapped_exception is not None and wrapped_exception.message is not None:
raise AzureDevOpsClientRequestError(wrapped_exception.message)
# if we get here we still have not raised an exception, try to deserialize as a System Exception
system_exception = self._base_deserialize('SystemException', response)
if system_exception is not None and system_exception.message is not None:
raise AzureDevOpsClientRequestError(system_exception.message)
except DeserializationError:
pass
elif response.content is not None:
error_message = response.content.decode("utf-8") + ' '
if response.status_code == 401:
full_message_format = '{error_message}The requested resource requires user authentication: {url}'
raise AzureDevOpsAuthenticationError(full_message_format.format(error_message=error_message,
url=request.url))
else:
full_message_format = '{error_message}Operation returned a {status_code} status code.'
raise AzureDevOpsClientRequestError(full_message_format.format(error_message=error_message,
status_code=response.status_code))
def _get_continuation_token(self, response):
if self._continuation_token_header_key in response.headers:
return response.headers[self._continuation_token_header_key]
else:
return None
@staticmethod
def _normalize_url(url):
return url.rstrip('/').lower()
_locations_cache = {}
_continuation_token_header_key = 'X-MS-ContinuationToken'
_session_header_key = 'X-TFS-Session'
_session_data = {_session_header_key: str(uuid.uuid4())}
TRACE_ENV_VAR_COMPAT = 'vsts_python_print_urls'
TRACE_ENV_VAR = 'azure_devops_python_print_urls'
|
azure-devops-python-api/azure-devops/azure/devops/client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/client.py",
"repo_id": "azure-devops-python-api",
"token_count": 6845
}
| 364 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from ...v7_0.search.models import *
from .search_client import SearchClient
__all__ = [
'BoardResult',
'BoardSearchRequest',
'BoardSearchResponse',
'BranchInfo',
'CodeResult',
'CodeSearchRequest',
'CodeSearchResponse',
'Collection',
'CustomRepositoryBranchStatusResponse',
'CustomRepositoryStatusResponse',
'DepotInfo',
'EntitySearchRequest',
'EntitySearchRequestBase',
'EntitySearchResponse',
'FeedInfo',
'Filter',
'Hit',
'PackageHit',
'PackageResult',
'PackageSearchRequest',
'PackageSearchResponse',
'PackageSearchResponseContent',
'Project',
'ProjectReference',
'Repository',
'RepositoryStatusResponse',
'ScrollSearchRequest',
'SettingResult',
'SettingSearchRequest',
'SettingSearchResponse',
'SortOption',
'Team',
'TfvcRepositoryStatusResponse',
'Version',
'Wiki',
'WikiHit',
'WikiResult',
'WikiSearchRequest',
'WikiSearchResponse',
'WorkItemHit',
'WorkItemResult',
'WorkItemSearchRequest',
'WorkItemSearchResponse',
'SearchClient'
]
|
azure-devops-python-api/azure-devops/azure/devops/released/search/__init__.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/released/search/__init__.py",
"repo_id": "azure-devops-python-api",
"token_count": 495
}
| 365 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from .models import *
from .contributions_client import ContributionsClient
__all__ = [
'ClientContribution',
'ClientContributionNode',
'ClientContributionProviderDetails',
'ClientDataProviderQuery',
'Contribution',
'ContributionBase',
'ContributionConstraint',
'ContributionNodeQuery',
'ContributionNodeQueryResult',
'ContributionPropertyDescription',
'ContributionType',
'DataProviderContext',
'DataProviderExceptionDetails',
'DataProviderQuery',
'DataProviderResult',
'ExtensionEventCallback',
'ExtensionEventCallbackCollection',
'ExtensionFile',
'ExtensionLicensing',
'ExtensionManifest',
'InstalledExtension',
'InstalledExtensionState',
'InstalledExtensionStateIssue',
'LicensingOverride',
'ResolvedDataProvider',
'ContributionsClient'
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/contributions/__init__.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/contributions/__init__.py",
"repo_id": "azure-devops-python-api",
"token_count": 361
}
| 366 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class ExtensionManagementClient(Client):
"""ExtensionManagement
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(ExtensionManagementClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = '6c2b0933-3600-42ae-bf8b-93d4f7e83594'
def get_installed_extensions(self, include_disabled_extensions=None, include_errors=None, asset_types=None, include_installation_issues=None):
"""GetInstalledExtensions.
[Preview API] List the installed extensions in the account / project collection.
:param bool include_disabled_extensions: If true (the default), include disabled extensions in the results.
:param bool include_errors: If true, include installed extensions with errors.
:param [str] asset_types: Determines which files are returned in the files array. Provide the wildcard '*' to return all files, or a colon separated list to retrieve files with specific asset types.
:param bool include_installation_issues:
:rtype: [InstalledExtension]
"""
query_parameters = {}
if include_disabled_extensions is not None:
query_parameters['includeDisabledExtensions'] = self._serialize.query('include_disabled_extensions', include_disabled_extensions, 'bool')
if include_errors is not None:
query_parameters['includeErrors'] = self._serialize.query('include_errors', include_errors, 'bool')
if asset_types is not None:
asset_types = ":".join(asset_types)
query_parameters['assetTypes'] = self._serialize.query('asset_types', asset_types, 'str')
if include_installation_issues is not None:
query_parameters['includeInstallationIssues'] = self._serialize.query('include_installation_issues', include_installation_issues, 'bool')
response = self._send(http_method='GET',
location_id='275424d0-c844-4fe2-bda6-04933a1357d8',
version='7.1-preview.1',
query_parameters=query_parameters)
return self._deserialize('[InstalledExtension]', self._unwrap_collection(response))
def update_installed_extension(self, extension):
"""UpdateInstalledExtension.
[Preview API] Update an installed extension. Typically this API is used to enable or disable an extension.
:param :class:`<InstalledExtension> <azure.devops.v7_1.extension_management.models.InstalledExtension>` extension:
:rtype: :class:`<InstalledExtension> <azure.devops.v7_1.extension_management.models.InstalledExtension>`
"""
content = self._serialize.body(extension, 'InstalledExtension')
response = self._send(http_method='PATCH',
location_id='275424d0-c844-4fe2-bda6-04933a1357d8',
version='7.1-preview.1',
content=content)
return self._deserialize('InstalledExtension', response)
def get_installed_extension_by_name(self, publisher_name, extension_name, asset_types=None):
"""GetInstalledExtensionByName.
[Preview API] Get an installed extension by its publisher and extension name.
:param str publisher_name: Name of the publisher. Example: "fabrikam".
:param str extension_name: Name of the extension. Example: "ops-tools".
:param [str] asset_types: Determines which files are returned in the files array. Provide the wildcard '*' to return all files, or a colon separated list to retrieve files with specific asset types.
:rtype: :class:`<InstalledExtension> <azure.devops.v7_1.extension_management.models.InstalledExtension>`
"""
route_values = {}
if publisher_name is not None:
route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str')
if extension_name is not None:
route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str')
query_parameters = {}
if asset_types is not None:
asset_types = ":".join(asset_types)
query_parameters['assetTypes'] = self._serialize.query('asset_types', asset_types, 'str')
response = self._send(http_method='GET',
location_id='fb0da285-f23e-4b56-8b53-3ef5f9f6de66',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('InstalledExtension', response)
def install_extension_by_name(self, publisher_name, extension_name, version=None):
"""InstallExtensionByName.
[Preview API] Install the specified extension into the account / project collection.
:param str publisher_name: Name of the publisher. Example: "fabrikam".
:param str extension_name: Name of the extension. Example: "ops-tools".
:param str version:
:rtype: :class:`<InstalledExtension> <azure.devops.v7_1.extension_management.models.InstalledExtension>`
"""
route_values = {}
if publisher_name is not None:
route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str')
if extension_name is not None:
route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str')
if version is not None:
route_values['version'] = self._serialize.url('version', version, 'str')
response = self._send(http_method='POST',
location_id='fb0da285-f23e-4b56-8b53-3ef5f9f6de66',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('InstalledExtension', response)
def uninstall_extension_by_name(self, publisher_name, extension_name, reason=None, reason_code=None):
"""UninstallExtensionByName.
[Preview API] Uninstall the specified extension from the account / project collection.
:param str publisher_name: Name of the publisher. Example: "fabrikam".
:param str extension_name: Name of the extension. Example: "ops-tools".
:param str reason:
:param str reason_code:
"""
route_values = {}
if publisher_name is not None:
route_values['publisherName'] = self._serialize.url('publisher_name', publisher_name, 'str')
if extension_name is not None:
route_values['extensionName'] = self._serialize.url('extension_name', extension_name, 'str')
query_parameters = {}
if reason is not None:
query_parameters['reason'] = self._serialize.query('reason', reason, 'str')
if reason_code is not None:
query_parameters['reasonCode'] = self._serialize.query('reason_code', reason_code, 'str')
self._send(http_method='DELETE',
location_id='fb0da285-f23e-4b56-8b53-3ef5f9f6de66',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/extension_management/extension_management_client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/extension_management/extension_management_client.py",
"repo_id": "azure-devops-python-api",
"token_count": 3187
}
| 367 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class AcquisitionOperation(Model):
"""
:param operation_state: State of the AcquisitionOperation for the current user
:type operation_state: object
:param operation_type: AcquisitionOperationType: install, request, buy, etc...
:type operation_type: object
:param reason: Optional reason to justify current state. Typically used with Disallow state.
:type reason: str
"""
_attribute_map = {
'operation_state': {'key': 'operationState', 'type': 'object'},
'operation_type': {'key': 'operationType', 'type': 'object'},
'reason': {'key': 'reason', 'type': 'str'}
}
def __init__(self, operation_state=None, operation_type=None, reason=None):
super(AcquisitionOperation, self).__init__()
self.operation_state = operation_state
self.operation_type = operation_type
self.reason = reason
class AcquisitionOptions(Model):
"""
Market item acquisition options (install, buy, etc) for an installation target.
:param default_operation: Default Operation for the ItemId in this target
:type default_operation: :class:`AcquisitionOperation <azure.devops.v7_1.gallery.models.AcquisitionOperation>`
:param item_id: The item id that this options refer to
:type item_id: str
:param operations: Operations allowed for the ItemId in this target
:type operations: list of :class:`AcquisitionOperation <azure.devops.v7_1.gallery.models.AcquisitionOperation>`
:param target: The target that this options refer to
:type target: str
"""
_attribute_map = {
'default_operation': {'key': 'defaultOperation', 'type': 'AcquisitionOperation'},
'item_id': {'key': 'itemId', 'type': 'str'},
'operations': {'key': 'operations', 'type': '[AcquisitionOperation]'},
'target': {'key': 'target', 'type': 'str'}
}
def __init__(self, default_operation=None, item_id=None, operations=None, target=None):
super(AcquisitionOptions, self).__init__()
self.default_operation = default_operation
self.item_id = item_id
self.operations = operations
self.target = target
class Answers(Model):
"""
:param vs_marketplace_extension_name: Gets or sets the vs marketplace extension name
:type vs_marketplace_extension_name: str
:param vs_marketplace_publisher_name: Gets or sets the vs marketplace publisher name
:type vs_marketplace_publisher_name: str
"""
_attribute_map = {
'vs_marketplace_extension_name': {'key': 'vsMarketplaceExtensionName', 'type': 'str'},
'vs_marketplace_publisher_name': {'key': 'vsMarketplacePublisherName', 'type': 'str'}
}
def __init__(self, vs_marketplace_extension_name=None, vs_marketplace_publisher_name=None):
super(Answers, self).__init__()
self.vs_marketplace_extension_name = vs_marketplace_extension_name
self.vs_marketplace_publisher_name = vs_marketplace_publisher_name
class AssetDetails(Model):
"""
:param answers: Gets or sets the Answers, which contains vs marketplace extension name and publisher name
:type answers: :class:`Answers <azure.devops.v7_1.gallery.models.Answers>`
:param publisher_natural_identifier: Gets or sets the VS publisher Id
:type publisher_natural_identifier: str
"""
_attribute_map = {
'answers': {'key': 'answers', 'type': 'Answers'},
'publisher_natural_identifier': {'key': 'publisherNaturalIdentifier', 'type': 'str'}
}
def __init__(self, answers=None, publisher_natural_identifier=None):
super(AssetDetails, self).__init__()
self.answers = answers
self.publisher_natural_identifier = publisher_natural_identifier
class AzurePublisher(Model):
"""
:param azure_publisher_id:
:type azure_publisher_id: str
:param publisher_name:
:type publisher_name: str
"""
_attribute_map = {
'azure_publisher_id': {'key': 'azurePublisherId', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'}
}
def __init__(self, azure_publisher_id=None, publisher_name=None):
super(AzurePublisher, self).__init__()
self.azure_publisher_id = azure_publisher_id
self.publisher_name = publisher_name
class AzureRestApiRequestModel(Model):
"""
:param asset_details: Gets or sets the Asset details
:type asset_details: :class:`AssetDetails <azure.devops.v7_1.gallery.models.AssetDetails>`
:param asset_id: Gets or sets the asset id
:type asset_id: str
:param asset_version: Gets or sets the asset version
:type asset_version: long
:param customer_support_email: Gets or sets the customer support email
:type customer_support_email: str
:param integration_contact_email: Gets or sets the integration contact email
:type integration_contact_email: str
:param operation: Gets or sets the asset version
:type operation: str
:param plan_id: Gets or sets the plan identifier if any.
:type plan_id: str
:param publisher_id: Gets or sets the publisher id
:type publisher_id: str
:param type: Gets or sets the resource type
:type type: str
"""
_attribute_map = {
'asset_details': {'key': 'assetDetails', 'type': 'AssetDetails'},
'asset_id': {'key': 'assetId', 'type': 'str'},
'asset_version': {'key': 'assetVersion', 'type': 'long'},
'customer_support_email': {'key': 'customerSupportEmail', 'type': 'str'},
'integration_contact_email': {'key': 'integrationContactEmail', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'str'},
'plan_id': {'key': 'planId', 'type': 'str'},
'publisher_id': {'key': 'publisherId', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'}
}
def __init__(self, asset_details=None, asset_id=None, asset_version=None, customer_support_email=None, integration_contact_email=None, operation=None, plan_id=None, publisher_id=None, type=None):
super(AzureRestApiRequestModel, self).__init__()
self.asset_details = asset_details
self.asset_id = asset_id
self.asset_version = asset_version
self.customer_support_email = customer_support_email
self.integration_contact_email = integration_contact_email
self.operation = operation
self.plan_id = plan_id
self.publisher_id = publisher_id
self.type = type
class CategoriesResult(Model):
"""
This is the set of categories in response to the get category query
:param categories:
:type categories: list of :class:`ExtensionCategory <azure.devops.v7_1.gallery.models.ExtensionCategory>`
"""
_attribute_map = {
'categories': {'key': 'categories', 'type': '[ExtensionCategory]'}
}
def __init__(self, categories=None):
super(CategoriesResult, self).__init__()
self.categories = categories
class CategoryLanguageTitle(Model):
"""
Definition of one title of a category
:param lang: The language for which the title is applicable
:type lang: str
:param lcid: The language culture id of the lang parameter
:type lcid: int
:param title: Actual title to be shown on the UI
:type title: str
"""
_attribute_map = {
'lang': {'key': 'lang', 'type': 'str'},
'lcid': {'key': 'lcid', 'type': 'int'},
'title': {'key': 'title', 'type': 'str'}
}
def __init__(self, lang=None, lcid=None, title=None):
super(CategoryLanguageTitle, self).__init__()
self.lang = lang
self.lcid = lcid
self.title = title
class CustomerSupportRequest(Model):
"""
An entity representing the data required to create a Customer Support Request.
:param display_name: Display name of extension in concern
:type display_name: str
:param email_id: Email of user making the support request
:type email_id: str
:param extension_name: Extension name
:type extension_name: str
:param extension_uRL: Link to the extension details page
:type extension_uRL: str
:param message: User-provided support request message.
:type message: str
:param publisher_name: Publisher name
:type publisher_name: str
:param reason: Reason for support request
:type reason: str
:param re_captcha_token:
:type re_captcha_token: str
:param reporter_vSID: VSID of the user making the support request
:type reporter_vSID: str
:param review: Review under concern
:type review: :class:`Review <azure.devops.v7_1.gallery.models.Review>`
:param source_link: The UI source through which the request was made
:type source_link: str
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'email_id': {'key': 'emailId', 'type': 'str'},
'extension_name': {'key': 'extensionName', 'type': 'str'},
'extension_uRL': {'key': 'extensionURL', 'type': 'str'},
'message': {'key': 'message', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'reason': {'key': 'reason', 'type': 'str'},
're_captcha_token': {'key': 'reCaptchaToken', 'type': 'str'},
'reporter_vSID': {'key': 'reporterVSID', 'type': 'str'},
'review': {'key': 'review', 'type': 'Review'},
'source_link': {'key': 'sourceLink', 'type': 'str'}
}
def __init__(self, display_name=None, email_id=None, extension_name=None, extension_uRL=None, message=None, publisher_name=None, reason=None, re_captcha_token=None, reporter_vSID=None, review=None, source_link=None):
super(CustomerSupportRequest, self).__init__()
self.display_name = display_name
self.email_id = email_id
self.extension_name = extension_name
self.extension_uRL = extension_uRL
self.message = message
self.publisher_name = publisher_name
self.reason = reason
self.re_captcha_token = re_captcha_token
self.reporter_vSID = reporter_vSID
self.review = review
self.source_link = source_link
class EventCounts(Model):
"""
:param average_rating: Average rating on the day for extension
:type average_rating: float
:param buy_count: Number of times the extension was bought in hosted scenario (applies only to VSTS extensions)
:type buy_count: int
:param connected_buy_count: Number of times the extension was bought in connected scenario (applies only to VSTS extensions)
:type connected_buy_count: int
:param connected_install_count: Number of times the extension was installed in connected scenario (applies only to VSTS extensions)
:type connected_install_count: int
:param install_count: Number of times the extension was installed
:type install_count: long
:param try_count: Number of times the extension was installed as a trial (applies only to VSTS extensions)
:type try_count: int
:param uninstall_count: Number of times the extension was uninstalled (applies only to VSTS extensions)
:type uninstall_count: int
:param web_download_count: Number of times the extension was downloaded (applies to VSTS extensions and VSCode marketplace click installs)
:type web_download_count: long
:param web_page_views: Number of detail page views
:type web_page_views: long
"""
_attribute_map = {
'average_rating': {'key': 'averageRating', 'type': 'float'},
'buy_count': {'key': 'buyCount', 'type': 'int'},
'connected_buy_count': {'key': 'connectedBuyCount', 'type': 'int'},
'connected_install_count': {'key': 'connectedInstallCount', 'type': 'int'},
'install_count': {'key': 'installCount', 'type': 'long'},
'try_count': {'key': 'tryCount', 'type': 'int'},
'uninstall_count': {'key': 'uninstallCount', 'type': 'int'},
'web_download_count': {'key': 'webDownloadCount', 'type': 'long'},
'web_page_views': {'key': 'webPageViews', 'type': 'long'}
}
def __init__(self, average_rating=None, buy_count=None, connected_buy_count=None, connected_install_count=None, install_count=None, try_count=None, uninstall_count=None, web_download_count=None, web_page_views=None):
super(EventCounts, self).__init__()
self.average_rating = average_rating
self.buy_count = buy_count
self.connected_buy_count = connected_buy_count
self.connected_install_count = connected_install_count
self.install_count = install_count
self.try_count = try_count
self.uninstall_count = uninstall_count
self.web_download_count = web_download_count
self.web_page_views = web_page_views
class ExtensionAcquisitionRequest(Model):
"""
Contract for handling the extension acquisition process
:param assignment_type: How the item is being assigned
:type assignment_type: object
:param billing_id: The id of the subscription used for purchase
:type billing_id: str
:param item_id: The marketplace id (publisherName.extensionName) for the item
:type item_id: str
:param operation_type: The type of operation, such as install, request, purchase
:type operation_type: object
:param properties: Additional properties which can be added to the request.
:type properties: :class:`object <azure.devops.v7_1.gallery.models.object>`
:param quantity: How many licenses should be purchased
:type quantity: int
:param targets: A list of target guids where the item should be acquired (installed, requested, etc.), such as account id
:type targets: list of str
"""
_attribute_map = {
'assignment_type': {'key': 'assignmentType', 'type': 'object'},
'billing_id': {'key': 'billingId', 'type': 'str'},
'item_id': {'key': 'itemId', 'type': 'str'},
'operation_type': {'key': 'operationType', 'type': 'object'},
'properties': {'key': 'properties', 'type': 'object'},
'quantity': {'key': 'quantity', 'type': 'int'},
'targets': {'key': 'targets', 'type': '[str]'}
}
def __init__(self, assignment_type=None, billing_id=None, item_id=None, operation_type=None, properties=None, quantity=None, targets=None):
super(ExtensionAcquisitionRequest, self).__init__()
self.assignment_type = assignment_type
self.billing_id = billing_id
self.item_id = item_id
self.operation_type = operation_type
self.properties = properties
self.quantity = quantity
self.targets = targets
class ExtensionBadge(Model):
"""
:param description:
:type description: str
:param img_uri:
:type img_uri: str
:param link:
:type link: str
"""
_attribute_map = {
'description': {'key': 'description', 'type': 'str'},
'img_uri': {'key': 'imgUri', 'type': 'str'},
'link': {'key': 'link', 'type': 'str'}
}
def __init__(self, description=None, img_uri=None, link=None):
super(ExtensionBadge, self).__init__()
self.description = description
self.img_uri = img_uri
self.link = link
class ExtensionCategory(Model):
"""
:param associated_products: The name of the products with which this category is associated to.
:type associated_products: list of str
:param category_id:
:type category_id: int
:param category_name: This is the internal name for a category
:type category_name: str
:param language: This parameter is obsolete. Refer to LanguageTitles for language specific titles
:type language: str
:param language_titles: The list of all the titles of this category in various languages
:type language_titles: list of :class:`CategoryLanguageTitle <azure.devops.v7_1.gallery.models.CategoryLanguageTitle>`
:param parent_category_name: This is the internal name of the parent if this is associated with a parent
:type parent_category_name: str
"""
_attribute_map = {
'associated_products': {'key': 'associatedProducts', 'type': '[str]'},
'category_id': {'key': 'categoryId', 'type': 'int'},
'category_name': {'key': 'categoryName', 'type': 'str'},
'language': {'key': 'language', 'type': 'str'},
'language_titles': {'key': 'languageTitles', 'type': '[CategoryLanguageTitle]'},
'parent_category_name': {'key': 'parentCategoryName', 'type': 'str'}
}
def __init__(self, associated_products=None, category_id=None, category_name=None, language=None, language_titles=None, parent_category_name=None):
super(ExtensionCategory, self).__init__()
self.associated_products = associated_products
self.category_id = category_id
self.category_name = category_name
self.language = language
self.language_titles = language_titles
self.parent_category_name = parent_category_name
class ExtensionDailyStat(Model):
"""
:param counts: Stores the event counts
:type counts: :class:`EventCounts <azure.devops.v7_1.gallery.models.EventCounts>`
:param extended_stats: Generic key/value pair to store extended statistics. Used for sending paid extension stats like Upgrade, Downgrade, Cancel trend etc.
:type extended_stats: dict
:param statistic_date: Timestamp of this data point
:type statistic_date: datetime
:param version: Version of the extension
:type version: str
"""
_attribute_map = {
'counts': {'key': 'counts', 'type': 'EventCounts'},
'extended_stats': {'key': 'extendedStats', 'type': '{object}'},
'statistic_date': {'key': 'statisticDate', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'str'}
}
def __init__(self, counts=None, extended_stats=None, statistic_date=None, version=None):
super(ExtensionDailyStat, self).__init__()
self.counts = counts
self.extended_stats = extended_stats
self.statistic_date = statistic_date
self.version = version
class ExtensionDailyStats(Model):
"""
:param daily_stats: List of extension statistics data points
:type daily_stats: list of :class:`ExtensionDailyStat <azure.devops.v7_1.gallery.models.ExtensionDailyStat>`
:param extension_id: Id of the extension, this will never be sent back to the client. For internal use only.
:type extension_id: str
:param extension_name: Name of the extension
:type extension_name: str
:param publisher_name: Name of the publisher
:type publisher_name: str
:param stat_count: Count of stats
:type stat_count: int
"""
_attribute_map = {
'daily_stats': {'key': 'dailyStats', 'type': '[ExtensionDailyStat]'},
'extension_id': {'key': 'extensionId', 'type': 'str'},
'extension_name': {'key': 'extensionName', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'stat_count': {'key': 'statCount', 'type': 'int'}
}
def __init__(self, daily_stats=None, extension_id=None, extension_name=None, publisher_name=None, stat_count=None):
super(ExtensionDailyStats, self).__init__()
self.daily_stats = daily_stats
self.extension_id = extension_id
self.extension_name = extension_name
self.publisher_name = publisher_name
self.stat_count = stat_count
class ExtensionDraft(Model):
"""
:param assets:
:type assets: list of :class:`ExtensionDraftAsset <azure.devops.v7_1.gallery.models.ExtensionDraftAsset>`
:param created_date:
:type created_date: datetime
:param draft_state:
:type draft_state: object
:param extension_name:
:type extension_name: str
:param id:
:type id: str
:param last_updated:
:type last_updated: datetime
:param payload:
:type payload: :class:`ExtensionPayload <azure.devops.v7_1.gallery.models.ExtensionPayload>`
:param product:
:type product: str
:param publisher_name:
:type publisher_name: str
:param validation_errors:
:type validation_errors: list of { key: str; value: str }
:param validation_warnings:
:type validation_warnings: list of { key: str; value: str }
"""
_attribute_map = {
'assets': {'key': 'assets', 'type': '[ExtensionDraftAsset]'},
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'draft_state': {'key': 'draftState', 'type': 'object'},
'extension_name': {'key': 'extensionName', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'last_updated': {'key': 'lastUpdated', 'type': 'iso-8601'},
'payload': {'key': 'payload', 'type': 'ExtensionPayload'},
'product': {'key': 'product', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'validation_errors': {'key': 'validationErrors', 'type': '[{ key: str; value: str }]'},
'validation_warnings': {'key': 'validationWarnings', 'type': '[{ key: str; value: str }]'}
}
def __init__(self, assets=None, created_date=None, draft_state=None, extension_name=None, id=None, last_updated=None, payload=None, product=None, publisher_name=None, validation_errors=None, validation_warnings=None):
super(ExtensionDraft, self).__init__()
self.assets = assets
self.created_date = created_date
self.draft_state = draft_state
self.extension_name = extension_name
self.id = id
self.last_updated = last_updated
self.payload = payload
self.product = product
self.publisher_name = publisher_name
self.validation_errors = validation_errors
self.validation_warnings = validation_warnings
class ExtensionDraftPatch(Model):
"""
:param extension_data:
:type extension_data: :class:`UnpackagedExtensionData <azure.devops.v7_1.gallery.models.UnpackagedExtensionData>`
:param operation:
:type operation: object
:param re_captcha_token:
:type re_captcha_token: str
"""
_attribute_map = {
'extension_data': {'key': 'extensionData', 'type': 'UnpackagedExtensionData'},
'operation': {'key': 'operation', 'type': 'object'},
're_captcha_token': {'key': 'reCaptchaToken', 'type': 'str'}
}
def __init__(self, extension_data=None, operation=None, re_captcha_token=None):
super(ExtensionDraftPatch, self).__init__()
self.extension_data = extension_data
self.operation = operation
self.re_captcha_token = re_captcha_token
class ExtensionEvent(Model):
"""
Stores details of each event
:param id: Id which identifies each data point uniquely
:type id: long
:param properties:
:type properties: :class:`object <azure.devops.v7_1.gallery.models.object>`
:param statistic_date: Timestamp of when the event occurred
:type statistic_date: datetime
:param version: Version of the extension
:type version: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'long'},
'properties': {'key': 'properties', 'type': 'object'},
'statistic_date': {'key': 'statisticDate', 'type': 'iso-8601'},
'version': {'key': 'version', 'type': 'str'}
}
def __init__(self, id=None, properties=None, statistic_date=None, version=None):
super(ExtensionEvent, self).__init__()
self.id = id
self.properties = properties
self.statistic_date = statistic_date
self.version = version
class ExtensionEvents(Model):
"""
Container object for all extension events. Stores all install and uninstall events related to an extension. The events container is generic so can store data of any type of event. New event types can be added without altering the contract.
:param events: Generic container for events data. The dictionary key denotes the type of event and the list contains properties related to that event
:type events: dict
:param extension_id: Id of the extension, this will never be sent back to the client. This field will mainly be used when EMS calls into Gallery REST API to update install/uninstall events for various extensions in one go.
:type extension_id: str
:param extension_name: Name of the extension
:type extension_name: str
:param publisher_name: Name of the publisher
:type publisher_name: str
"""
_attribute_map = {
'events': {'key': 'events', 'type': '{[ExtensionEvent]}'},
'extension_id': {'key': 'extensionId', 'type': 'str'},
'extension_name': {'key': 'extensionName', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'}
}
def __init__(self, events=None, extension_id=None, extension_name=None, publisher_name=None):
super(ExtensionEvents, self).__init__()
self.events = events
self.extension_id = extension_id
self.extension_name = extension_name
self.publisher_name = publisher_name
class ExtensionFile(Model):
"""
:param asset_type:
:type asset_type: str
:param language:
:type language: str
:param source:
:type source: str
"""
_attribute_map = {
'asset_type': {'key': 'assetType', 'type': 'str'},
'language': {'key': 'language', 'type': 'str'},
'source': {'key': 'source', 'type': 'str'}
}
def __init__(self, asset_type=None, language=None, source=None):
super(ExtensionFile, self).__init__()
self.asset_type = asset_type
self.language = language
self.source = source
class ExtensionFilterResult(Model):
"""
The FilterResult is the set of extensions that matched a particular query filter.
:param extensions: This is the set of applications that matched the query filter supplied.
:type extensions: list of :class:`PublishedExtension <azure.devops.v7_1.gallery.models.PublishedExtension>`
:param paging_token: The PagingToken is returned from a request when more records exist that match the result than were requested or could be returned. A follow-up query with this paging token can be used to retrieve more results.
:type paging_token: str
:param result_metadata: This is the additional optional metadata for the given result. E.g. Total count of results which is useful in case of paged results
:type result_metadata: list of :class:`ExtensionFilterResultMetadata <azure.devops.v7_1.gallery.models.ExtensionFilterResultMetadata>`
"""
_attribute_map = {
'extensions': {'key': 'extensions', 'type': '[PublishedExtension]'},
'paging_token': {'key': 'pagingToken', 'type': 'str'},
'result_metadata': {'key': 'resultMetadata', 'type': '[ExtensionFilterResultMetadata]'}
}
def __init__(self, extensions=None, paging_token=None, result_metadata=None):
super(ExtensionFilterResult, self).__init__()
self.extensions = extensions
self.paging_token = paging_token
self.result_metadata = result_metadata
class ExtensionFilterResultMetadata(Model):
"""
ExtensionFilterResultMetadata is one set of metadata for the result e.g. Total count. There can be multiple metadata items for one metadata.
:param metadata_items: The metadata items for the category
:type metadata_items: list of :class:`MetadataItem <azure.devops.v7_1.gallery.models.MetadataItem>`
:param metadata_type: Defines the category of metadata items
:type metadata_type: str
"""
_attribute_map = {
'metadata_items': {'key': 'metadataItems', 'type': '[MetadataItem]'},
'metadata_type': {'key': 'metadataType', 'type': 'str'}
}
def __init__(self, metadata_items=None, metadata_type=None):
super(ExtensionFilterResultMetadata, self).__init__()
self.metadata_items = metadata_items
self.metadata_type = metadata_type
class ExtensionPackage(Model):
"""
Package that will be used to create or update a published extension
:param extension_manifest: Base 64 encoded extension package
:type extension_manifest: str
"""
_attribute_map = {
'extension_manifest': {'key': 'extensionManifest', 'type': 'str'}
}
def __init__(self, extension_manifest=None):
super(ExtensionPackage, self).__init__()
self.extension_manifest = extension_manifest
class ExtensionPayload(Model):
"""
:param description:
:type description: str
:param display_name:
:type display_name: str
:param file_name:
:type file_name: str
:param installation_targets:
:type installation_targets: list of :class:`InstallationTarget <azure.devops.v7_1.gallery.models.InstallationTarget>`
:param is_preview:
:type is_preview: bool
:param is_signed_by_microsoft:
:type is_signed_by_microsoft: bool
:param is_valid:
:type is_valid: bool
:param metadata:
:type metadata: list of { key: str; value: str }
:param type:
:type type: object
"""
_attribute_map = {
'description': {'key': 'description', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'file_name': {'key': 'fileName', 'type': 'str'},
'installation_targets': {'key': 'installationTargets', 'type': '[InstallationTarget]'},
'is_preview': {'key': 'isPreview', 'type': 'bool'},
'is_signed_by_microsoft': {'key': 'isSignedByMicrosoft', 'type': 'bool'},
'is_valid': {'key': 'isValid', 'type': 'bool'},
'metadata': {'key': 'metadata', 'type': '[{ key: str; value: str }]'},
'type': {'key': 'type', 'type': 'object'}
}
def __init__(self, description=None, display_name=None, file_name=None, installation_targets=None, is_preview=None, is_signed_by_microsoft=None, is_valid=None, metadata=None, type=None):
super(ExtensionPayload, self).__init__()
self.description = description
self.display_name = display_name
self.file_name = file_name
self.installation_targets = installation_targets
self.is_preview = is_preview
self.is_signed_by_microsoft = is_signed_by_microsoft
self.is_valid = is_valid
self.metadata = metadata
self.type = type
class ExtensionQuery(Model):
"""
An ExtensionQuery is used to search the gallery for a set of extensions that match one of many filter values.
:param asset_types: When retrieving extensions with a query; frequently the caller only needs a small subset of the assets. The caller may specify a list of asset types that should be returned if the extension contains it. All other assets will not be returned.
:type asset_types: list of str
:param filters: Each filter is a unique query and will have matching set of extensions returned from the request. Each result will have the same index in the resulting array that the filter had in the incoming query.
:type filters: list of :class:`QueryFilter <azure.devops.v7_1.gallery.models.QueryFilter>`
:param flags: The Flags are used to determine which set of information the caller would like returned for the matched extensions.
:type flags: object
"""
_attribute_map = {
'asset_types': {'key': 'assetTypes', 'type': '[str]'},
'filters': {'key': 'filters', 'type': '[QueryFilter]'},
'flags': {'key': 'flags', 'type': 'object'}
}
def __init__(self, asset_types=None, filters=None, flags=None):
super(ExtensionQuery, self).__init__()
self.asset_types = asset_types
self.filters = filters
self.flags = flags
class ExtensionQueryResult(Model):
"""
This is the set of extensions that matched a supplied query through the filters given.
:param results: For each filter supplied in the query, a filter result will be returned in the query result.
:type results: list of :class:`ExtensionFilterResult <azure.devops.v7_1.gallery.models.ExtensionFilterResult>`
"""
_attribute_map = {
'results': {'key': 'results', 'type': '[ExtensionFilterResult]'}
}
def __init__(self, results=None):
super(ExtensionQueryResult, self).__init__()
self.results = results
class ExtensionShare(Model):
"""
:param id:
:type id: str
:param is_org:
:type is_org: bool
:param name:
:type name: str
:param type:
:type type: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'is_org': {'key': 'isOrg', 'type': 'bool'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'}
}
def __init__(self, id=None, is_org=None, name=None, type=None):
super(ExtensionShare, self).__init__()
self.id = id
self.is_org = is_org
self.name = name
self.type = type
class ExtensionStatistic(Model):
"""
:param statistic_name:
:type statistic_name: str
:param value:
:type value: float
"""
_attribute_map = {
'statistic_name': {'key': 'statisticName', 'type': 'str'},
'value': {'key': 'value', 'type': 'float'}
}
def __init__(self, statistic_name=None, value=None):
super(ExtensionStatistic, self).__init__()
self.statistic_name = statistic_name
self.value = value
class ExtensionStatisticUpdate(Model):
"""
:param extension_name:
:type extension_name: str
:param operation:
:type operation: object
:param publisher_name:
:type publisher_name: str
:param statistic:
:type statistic: :class:`ExtensionStatistic <azure.devops.v7_1.gallery.models.ExtensionStatistic>`
"""
_attribute_map = {
'extension_name': {'key': 'extensionName', 'type': 'str'},
'operation': {'key': 'operation', 'type': 'object'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'statistic': {'key': 'statistic', 'type': 'ExtensionStatistic'}
}
def __init__(self, extension_name=None, operation=None, publisher_name=None, statistic=None):
super(ExtensionStatisticUpdate, self).__init__()
self.extension_name = extension_name
self.operation = operation
self.publisher_name = publisher_name
self.statistic = statistic
class ExtensionVersion(Model):
"""
:param asset_uri:
:type asset_uri: str
:param badges:
:type badges: list of :class:`ExtensionBadge <azure.devops.v7_1.gallery.models.ExtensionBadge>`
:param fallback_asset_uri:
:type fallback_asset_uri: str
:param files:
:type files: list of :class:`ExtensionFile <azure.devops.v7_1.gallery.models.ExtensionFile>`
:param flags:
:type flags: object
:param last_updated:
:type last_updated: datetime
:param properties:
:type properties: list of { key: str; value: str }
:param target_platform:
:type target_platform: str
:param validation_result_message:
:type validation_result_message: str
:param version:
:type version: str
:param version_description:
:type version_description: str
"""
_attribute_map = {
'asset_uri': {'key': 'assetUri', 'type': 'str'},
'badges': {'key': 'badges', 'type': '[ExtensionBadge]'},
'fallback_asset_uri': {'key': 'fallbackAssetUri', 'type': 'str'},
'files': {'key': 'files', 'type': '[ExtensionFile]'},
'flags': {'key': 'flags', 'type': 'object'},
'last_updated': {'key': 'lastUpdated', 'type': 'iso-8601'},
'properties': {'key': 'properties', 'type': '[{ key: str; value: str }]'},
'target_platform': {'key': 'targetPlatform', 'type': 'str'},
'validation_result_message': {'key': 'validationResultMessage', 'type': 'str'},
'version': {'key': 'version', 'type': 'str'},
'version_description': {'key': 'versionDescription', 'type': 'str'}
}
def __init__(self, asset_uri=None, badges=None, fallback_asset_uri=None, files=None, flags=None, last_updated=None, properties=None, target_platform=None, validation_result_message=None, version=None, version_description=None):
super(ExtensionVersion, self).__init__()
self.asset_uri = asset_uri
self.badges = badges
self.fallback_asset_uri = fallback_asset_uri
self.files = files
self.flags = flags
self.last_updated = last_updated
self.properties = properties
self.target_platform = target_platform
self.validation_result_message = validation_result_message
self.version = version
self.version_description = version_description
class FilterCriteria(Model):
"""
One condition in a QueryFilter.
:param filter_type:
:type filter_type: int
:param value: The value used in the match based on the filter type.
:type value: str
"""
_attribute_map = {
'filter_type': {'key': 'filterType', 'type': 'int'},
'value': {'key': 'value', 'type': 'str'}
}
def __init__(self, filter_type=None, value=None):
super(FilterCriteria, self).__init__()
self.filter_type = filter_type
self.value = value
class GraphSubjectBase(Model):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None):
super(GraphSubjectBase, self).__init__()
self._links = _links
self.descriptor = descriptor
self.display_name = display_name
self.url = url
class IdentityRef(GraphSubjectBase):
"""
:param _links: This field contains zero or more interesting links about the graph subject. These links may be invoked to obtain additional relationships or more detailed information about this graph subject.
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.microsoft._visual_studio._services._web_api.models.ReferenceLinks>`
:param descriptor: The descriptor is the primary way to reference the graph subject while the system is running. This field will uniquely identify the same graph subject across both Accounts and Organizations.
:type descriptor: str
:param display_name: This is the non-unique display name of the graph subject. To change this field, you must alter its value in the source provider.
:type display_name: str
:param url: This url is the full route to the source resource of this graph subject.
:type url: str
:param directory_alias: Deprecated - Can be retrieved by querying the Graph user referenced in the "self" entry of the IdentityRef "_links" dictionary
:type directory_alias: str
:param id:
:type id: str
:param image_url: Deprecated - Available in the "avatar" entry of the IdentityRef "_links" dictionary
:type image_url: str
:param inactive: Deprecated - Can be retrieved by querying the Graph membership state referenced in the "membershipState" entry of the GraphUser "_links" dictionary
:type inactive: bool
:param is_aad_identity: Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsAadUserType/Descriptor.IsAadGroupType)
:type is_aad_identity: bool
:param is_container: Deprecated - Can be inferred from the subject type of the descriptor (Descriptor.IsGroupType)
:type is_container: bool
:param is_deleted_in_origin:
:type is_deleted_in_origin: bool
:param profile_url: Deprecated - not in use in most preexisting implementations of ToIdentityRef
:type profile_url: str
:param unique_name: Deprecated - use Domain+PrincipalName instead
:type unique_name: str
"""
_attribute_map = {
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'descriptor': {'key': 'descriptor', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'directory_alias': {'key': 'directoryAlias', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'image_url': {'key': 'imageUrl', 'type': 'str'},
'inactive': {'key': 'inactive', 'type': 'bool'},
'is_aad_identity': {'key': 'isAadIdentity', 'type': 'bool'},
'is_container': {'key': 'isContainer', 'type': 'bool'},
'is_deleted_in_origin': {'key': 'isDeletedInOrigin', 'type': 'bool'},
'profile_url': {'key': 'profileUrl', 'type': 'str'},
'unique_name': {'key': 'uniqueName', 'type': 'str'}
}
def __init__(self, _links=None, descriptor=None, display_name=None, url=None, directory_alias=None, id=None, image_url=None, inactive=None, is_aad_identity=None, is_container=None, is_deleted_in_origin=None, profile_url=None, unique_name=None):
super(IdentityRef, self).__init__(_links=_links, descriptor=descriptor, display_name=display_name, url=url)
self.directory_alias = directory_alias
self.id = id
self.image_url = image_url
self.inactive = inactive
self.is_aad_identity = is_aad_identity
self.is_container = is_container
self.is_deleted_in_origin = is_deleted_in_origin
self.profile_url = profile_url
self.unique_name = unique_name
class InstallationTarget(Model):
"""
:param extension_version:
:type extension_version: str
:param product_architecture:
:type product_architecture: str
:param target:
:type target: str
:param target_platform:
:type target_platform: str
:param target_version:
:type target_version: str
"""
_attribute_map = {
'extension_version': {'key': 'extensionVersion', 'type': 'str'},
'product_architecture': {'key': 'productArchitecture', 'type': 'str'},
'target': {'key': 'target', 'type': 'str'},
'target_platform': {'key': 'targetPlatform', 'type': 'str'},
'target_version': {'key': 'targetVersion', 'type': 'str'}
}
def __init__(self, extension_version=None, product_architecture=None, target=None, target_platform=None, target_version=None):
super(InstallationTarget, self).__init__()
self.extension_version = extension_version
self.product_architecture = product_architecture
self.target = target
self.target_platform = target_platform
self.target_version = target_version
class MetadataItem(Model):
"""
MetadataItem is one value of metadata under a given category of metadata
:param count: The count of the metadata item
:type count: int
:param name: The name of the metadata item
:type name: str
"""
_attribute_map = {
'count': {'key': 'count', 'type': 'int'},
'name': {'key': 'name', 'type': 'str'}
}
def __init__(self, count=None, name=None):
super(MetadataItem, self).__init__()
self.count = count
self.name = name
class NotificationsData(Model):
"""
Information needed for sending mail notification
:param data: Notification data needed
:type data: dict
:param identities: List of users who should get the notification
:type identities: dict
:param type: Type of Mail Notification.Can be Qna , review or CustomerContact
:type type: object
"""
_attribute_map = {
'data': {'key': 'data', 'type': '{object}'},
'identities': {'key': 'identities', 'type': '{object}'},
'type': {'key': 'type', 'type': 'object'}
}
def __init__(self, data=None, identities=None, type=None):
super(NotificationsData, self).__init__()
self.data = data
self.identities = identities
self.type = type
class ProductCategoriesResult(Model):
"""
This is the set of categories in response to the get category query
:param categories:
:type categories: list of :class:`ProductCategory <azure.devops.v7_1.gallery.models.ProductCategory>`
"""
_attribute_map = {
'categories': {'key': 'categories', 'type': '[ProductCategory]'}
}
def __init__(self, categories=None):
super(ProductCategoriesResult, self).__init__()
self.categories = categories
class ProductCategory(Model):
"""
This is the interface object to be used by Root Categories and Category Tree APIs for Visual Studio Ide.
:param has_children: Indicator whether this is a leaf or there are children under this category
:type has_children: bool
:param children:
:type children: list of :class:`ProductCategory <azure.devops.v7_1.gallery.models.ProductCategory>`
:param id: Individual Guid of the Category
:type id: str
:param title: Category Title in the requested language
:type title: str
"""
_attribute_map = {
'has_children': {'key': 'hasChildren', 'type': 'bool'},
'children': {'key': 'children', 'type': '[ProductCategory]'},
'id': {'key': 'id', 'type': 'str'},
'title': {'key': 'title', 'type': 'str'}
}
def __init__(self, has_children=None, children=None, id=None, title=None):
super(ProductCategory, self).__init__()
self.has_children = has_children
self.children = children
self.id = id
self.title = title
class PublishedExtension(Model):
"""
:param categories:
:type categories: list of str
:param deployment_type:
:type deployment_type: object
:param display_name:
:type display_name: str
:param extension_id:
:type extension_id: str
:param extension_name:
:type extension_name: str
:param flags:
:type flags: object
:param installation_targets:
:type installation_targets: list of :class:`InstallationTarget <azure.devops.v7_1.gallery.models.InstallationTarget>`
:param last_updated:
:type last_updated: datetime
:param long_description:
:type long_description: str
:param present_in_conflict_list: Check if Extension is in conflict list or not. Taking as String and not as boolean because we don't want end customer to see this flag and by making it Boolean it is coming as false for all the cases.
:type present_in_conflict_list: str
:param published_date: Date on which the extension was first uploaded.
:type published_date: datetime
:param publisher:
:type publisher: :class:`PublisherFacts <azure.devops.v7_1.gallery.models.PublisherFacts>`
:param release_date: Date on which the extension first went public.
:type release_date: datetime
:param shared_with:
:type shared_with: list of :class:`ExtensionShare <azure.devops.v7_1.gallery.models.ExtensionShare>`
:param short_description:
:type short_description: str
:param statistics:
:type statistics: list of :class:`ExtensionStatistic <azure.devops.v7_1.gallery.models.ExtensionStatistic>`
:param tags:
:type tags: list of str
:param versions:
:type versions: list of :class:`ExtensionVersion <azure.devops.v7_1.gallery.models.ExtensionVersion>`
"""
_attribute_map = {
'categories': {'key': 'categories', 'type': '[str]'},
'deployment_type': {'key': 'deploymentType', 'type': 'object'},
'display_name': {'key': 'displayName', 'type': 'str'},
'extension_id': {'key': 'extensionId', 'type': 'str'},
'extension_name': {'key': 'extensionName', 'type': 'str'},
'flags': {'key': 'flags', 'type': 'object'},
'installation_targets': {'key': 'installationTargets', 'type': '[InstallationTarget]'},
'last_updated': {'key': 'lastUpdated', 'type': 'iso-8601'},
'long_description': {'key': 'longDescription', 'type': 'str'},
'present_in_conflict_list': {'key': 'presentInConflictList', 'type': 'str'},
'published_date': {'key': 'publishedDate', 'type': 'iso-8601'},
'publisher': {'key': 'publisher', 'type': 'PublisherFacts'},
'release_date': {'key': 'releaseDate', 'type': 'iso-8601'},
'shared_with': {'key': 'sharedWith', 'type': '[ExtensionShare]'},
'short_description': {'key': 'shortDescription', 'type': 'str'},
'statistics': {'key': 'statistics', 'type': '[ExtensionStatistic]'},
'tags': {'key': 'tags', 'type': '[str]'},
'versions': {'key': 'versions', 'type': '[ExtensionVersion]'}
}
def __init__(self, categories=None, deployment_type=None, display_name=None, extension_id=None, extension_name=None, flags=None, installation_targets=None, last_updated=None, long_description=None, present_in_conflict_list=None, published_date=None, publisher=None, release_date=None, shared_with=None, short_description=None, statistics=None, tags=None, versions=None):
super(PublishedExtension, self).__init__()
self.categories = categories
self.deployment_type = deployment_type
self.display_name = display_name
self.extension_id = extension_id
self.extension_name = extension_name
self.flags = flags
self.installation_targets = installation_targets
self.last_updated = last_updated
self.long_description = long_description
self.present_in_conflict_list = present_in_conflict_list
self.published_date = published_date
self.publisher = publisher
self.release_date = release_date
self.shared_with = shared_with
self.short_description = short_description
self.statistics = statistics
self.tags = tags
self.versions = versions
class PublisherBase(Model):
"""
Keeping base class separate since publisher DB model class and publisher contract class share these common properties
:param display_name:
:type display_name: str
:param email_address:
:type email_address: list of str
:param extensions:
:type extensions: list of :class:`PublishedExtension <azure.devops.v7_1.gallery.models.PublishedExtension>`
:param flags:
:type flags: object
:param last_updated:
:type last_updated: datetime
:param long_description:
:type long_description: str
:param publisher_id:
:type publisher_id: str
:param publisher_name:
:type publisher_name: str
:param short_description:
:type short_description: str
:param state:
:type state: object
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'email_address': {'key': 'emailAddress', 'type': '[str]'},
'extensions': {'key': 'extensions', 'type': '[PublishedExtension]'},
'flags': {'key': 'flags', 'type': 'object'},
'last_updated': {'key': 'lastUpdated', 'type': 'iso-8601'},
'long_description': {'key': 'longDescription', 'type': 'str'},
'publisher_id': {'key': 'publisherId', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'short_description': {'key': 'shortDescription', 'type': 'str'},
'state': {'key': 'state', 'type': 'object'}
}
def __init__(self, display_name=None, email_address=None, extensions=None, flags=None, last_updated=None, long_description=None, publisher_id=None, publisher_name=None, short_description=None, state=None):
super(PublisherBase, self).__init__()
self.display_name = display_name
self.email_address = email_address
self.extensions = extensions
self.flags = flags
self.last_updated = last_updated
self.long_description = long_description
self.publisher_id = publisher_id
self.publisher_name = publisher_name
self.short_description = short_description
self.state = state
class PublisherFacts(Model):
"""
High-level information about the publisher, like id's and names
:param display_name:
:type display_name: str
:param domain:
:type domain: str
:param flags:
:type flags: object
:param is_domain_verified:
:type is_domain_verified: bool
:param publisher_id:
:type publisher_id: str
:param publisher_name:
:type publisher_name: str
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'domain': {'key': 'domain', 'type': 'str'},
'flags': {'key': 'flags', 'type': 'object'},
'is_domain_verified': {'key': 'isDomainVerified', 'type': 'bool'},
'publisher_id': {'key': 'publisherId', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'}
}
def __init__(self, display_name=None, domain=None, flags=None, is_domain_verified=None, publisher_id=None, publisher_name=None):
super(PublisherFacts, self).__init__()
self.display_name = display_name
self.domain = domain
self.flags = flags
self.is_domain_verified = is_domain_verified
self.publisher_id = publisher_id
self.publisher_name = publisher_name
class PublisherFilterResult(Model):
"""
The FilterResult is the set of publishers that matched a particular query filter.
:param publishers: This is the set of applications that matched the query filter supplied.
:type publishers: list of :class:`Publisher <azure.devops.v7_1.gallery.models.Publisher>`
"""
_attribute_map = {
'publishers': {'key': 'publishers', 'type': '[Publisher]'}
}
def __init__(self, publishers=None):
super(PublisherFilterResult, self).__init__()
self.publishers = publishers
class PublisherQuery(Model):
"""
An PublisherQuery is used to search the gallery for a set of publishers that match one of many filter values.
:param filters: Each filter is a unique query and will have matching set of publishers returned from the request. Each result will have the same index in the resulting array that the filter had in the incoming query.
:type filters: list of :class:`QueryFilter <azure.devops.v7_1.gallery.models.QueryFilter>`
:param flags: The Flags are used to determine which set of information the caller would like returned for the matched publishers.
:type flags: object
"""
_attribute_map = {
'filters': {'key': 'filters', 'type': '[QueryFilter]'},
'flags': {'key': 'flags', 'type': 'object'}
}
def __init__(self, filters=None, flags=None):
super(PublisherQuery, self).__init__()
self.filters = filters
self.flags = flags
class PublisherQueryResult(Model):
"""
This is the set of publishers that matched a supplied query through the filters given.
:param results: For each filter supplied in the query, a filter result will be returned in the query result.
:type results: list of :class:`PublisherFilterResult <azure.devops.v7_1.gallery.models.PublisherFilterResult>`
"""
_attribute_map = {
'results': {'key': 'results', 'type': '[PublisherFilterResult]'}
}
def __init__(self, results=None):
super(PublisherQueryResult, self).__init__()
self.results = results
class PublisherRoleAssignment(Model):
"""
:param access: Designates the role as explicitly assigned or inherited.
:type access: object
:param access_display_name: User friendly description of access assignment.
:type access_display_name: str
:param identity: The user to whom the role is assigned.
:type identity: :class:`IdentityRef <azure.devops.v7_1.gallery.models.IdentityRef>`
:param role: The role assigned to the user.
:type role: :class:`PublisherSecurityRole <azure.devops.v7_1.gallery.models.PublisherSecurityRole>`
"""
_attribute_map = {
'access': {'key': 'access', 'type': 'object'},
'access_display_name': {'key': 'accessDisplayName', 'type': 'str'},
'identity': {'key': 'identity', 'type': 'IdentityRef'},
'role': {'key': 'role', 'type': 'PublisherSecurityRole'}
}
def __init__(self, access=None, access_display_name=None, identity=None, role=None):
super(PublisherRoleAssignment, self).__init__()
self.access = access
self.access_display_name = access_display_name
self.identity = identity
self.role = role
class PublisherSecurityRole(Model):
"""
:param allow_permissions: Permissions the role is allowed.
:type allow_permissions: int
:param deny_permissions: Permissions the role is denied.
:type deny_permissions: int
:param description: Description of user access defined by the role
:type description: str
:param display_name: User friendly name of the role.
:type display_name: str
:param identifier: Globally unique identifier for the role.
:type identifier: str
:param name: Unique name of the role in the scope.
:type name: str
:param scope: Returns the id of the ParentScope.
:type scope: str
"""
_attribute_map = {
'allow_permissions': {'key': 'allowPermissions', 'type': 'int'},
'deny_permissions': {'key': 'denyPermissions', 'type': 'int'},
'description': {'key': 'description', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'identifier': {'key': 'identifier', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'scope': {'key': 'scope', 'type': 'str'}
}
def __init__(self, allow_permissions=None, deny_permissions=None, description=None, display_name=None, identifier=None, name=None, scope=None):
super(PublisherSecurityRole, self).__init__()
self.allow_permissions = allow_permissions
self.deny_permissions = deny_permissions
self.description = description
self.display_name = display_name
self.identifier = identifier
self.name = name
self.scope = scope
class PublisherUserRoleAssignmentRef(Model):
"""
:param role_name: The name of the role assigned.
:type role_name: str
:param unique_name: Identifier of the user given the role assignment.
:type unique_name: str
:param user_id: Unique id of the user given the role assignment.
:type user_id: str
"""
_attribute_map = {
'role_name': {'key': 'roleName', 'type': 'str'},
'unique_name': {'key': 'uniqueName', 'type': 'str'},
'user_id': {'key': 'userId', 'type': 'str'}
}
def __init__(self, role_name=None, unique_name=None, user_id=None):
super(PublisherUserRoleAssignmentRef, self).__init__()
self.role_name = role_name
self.unique_name = unique_name
self.user_id = user_id
class QnAItem(Model):
"""
The core structure of a QnA item
:param created_date: Time when the review was first created
:type created_date: datetime
:param id: Unique identifier of a QnA item
:type id: long
:param status: Get status of item
:type status: object
:param text: Text description of the QnA item
:type text: str
:param updated_date: Time when the review was edited/updated
:type updated_date: datetime
:param user: User details for the item.
:type user: :class:`UserIdentityRef <azure.devops.v7_1.gallery.models.UserIdentityRef>`
"""
_attribute_map = {
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'long'},
'status': {'key': 'status', 'type': 'object'},
'text': {'key': 'text', 'type': 'str'},
'updated_date': {'key': 'updatedDate', 'type': 'iso-8601'},
'user': {'key': 'user', 'type': 'UserIdentityRef'}
}
def __init__(self, created_date=None, id=None, status=None, text=None, updated_date=None, user=None):
super(QnAItem, self).__init__()
self.created_date = created_date
self.id = id
self.status = status
self.text = text
self.updated_date = updated_date
self.user = user
class QueryFilter(Model):
"""
A filter used to define a set of extensions to return during a query.
:param criteria: The filter values define the set of values in this query. They are applied based on the QueryFilterType.
:type criteria: list of :class:`FilterCriteria <azure.devops.v7_1.gallery.models.FilterCriteria>`
:param direction: The PagingDirection is applied to a paging token if one exists. If not the direction is ignored, and Forward from the start of the resultset is used. Direction should be left out of the request unless a paging token is used to help prevent future issues.
:type direction: object
:param page_number: The page number requested by the user. If not provided 1 is assumed by default.
:type page_number: int
:param page_size: The page size defines the number of results the caller wants for this filter. The count can't exceed the overall query size limits.
:type page_size: int
:param paging_token: The paging token is a distinct type of filter and the other filter fields are ignored. The paging token represents the continuation of a previously executed query. The information about where in the result and what fields are being filtered are embedded in the token.
:type paging_token: str
:param sort_by: Defines the type of sorting to be applied on the results. The page slice is cut of the sorted results only.
:type sort_by: int
:param sort_order: Defines the order of sorting, 1 for Ascending, 2 for Descending, else default ordering based on the SortBy value
:type sort_order: int
"""
_attribute_map = {
'criteria': {'key': 'criteria', 'type': '[FilterCriteria]'},
'direction': {'key': 'direction', 'type': 'object'},
'page_number': {'key': 'pageNumber', 'type': 'int'},
'page_size': {'key': 'pageSize', 'type': 'int'},
'paging_token': {'key': 'pagingToken', 'type': 'str'},
'sort_by': {'key': 'sortBy', 'type': 'int'},
'sort_order': {'key': 'sortOrder', 'type': 'int'}
}
def __init__(self, criteria=None, direction=None, page_number=None, page_size=None, paging_token=None, sort_by=None, sort_order=None):
super(QueryFilter, self).__init__()
self.criteria = criteria
self.direction = direction
self.page_number = page_number
self.page_size = page_size
self.paging_token = paging_token
self.sort_by = sort_by
self.sort_order = sort_order
class Question(QnAItem):
"""
The structure of the question / thread
:param created_date: Time when the review was first created
:type created_date: datetime
:param id: Unique identifier of a QnA item
:type id: long
:param status: Get status of item
:type status: object
:param text: Text description of the QnA item
:type text: str
:param updated_date: Time when the review was edited/updated
:type updated_date: datetime
:param user: User details for the item.
:type user: :class:`UserIdentityRef <azure.devops.v7_1.gallery.models.UserIdentityRef>`
:param re_captcha_token:
:type re_captcha_token: str
:param responses: List of answers in for the question / thread
:type responses: list of :class:`Response <azure.devops.v7_1.gallery.models.Response>`
"""
_attribute_map = {
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'long'},
'status': {'key': 'status', 'type': 'object'},
'text': {'key': 'text', 'type': 'str'},
'updated_date': {'key': 'updatedDate', 'type': 'iso-8601'},
'user': {'key': 'user', 'type': 'UserIdentityRef'},
're_captcha_token': {'key': 'reCaptchaToken', 'type': 'str'},
'responses': {'key': 'responses', 'type': '[Response]'}
}
def __init__(self, created_date=None, id=None, status=None, text=None, updated_date=None, user=None, re_captcha_token=None, responses=None):
super(Question, self).__init__(created_date=created_date, id=id, status=status, text=text, updated_date=updated_date, user=user)
self.re_captcha_token = re_captcha_token
self.responses = responses
class QuestionsResult(Model):
"""
:param has_more_questions: Flag indicating if there are more QnA threads to be shown (for paging)
:type has_more_questions: bool
:param questions: List of the QnA threads
:type questions: list of :class:`Question <azure.devops.v7_1.gallery.models.Question>`
"""
_attribute_map = {
'has_more_questions': {'key': 'hasMoreQuestions', 'type': 'bool'},
'questions': {'key': 'questions', 'type': '[Question]'}
}
def __init__(self, has_more_questions=None, questions=None):
super(QuestionsResult, self).__init__()
self.has_more_questions = has_more_questions
self.questions = questions
class RatingCountPerRating(Model):
"""
:param rating: Rating value
:type rating: str
:param rating_count: Count of total ratings
:type rating_count: long
"""
_attribute_map = {
'rating': {'key': 'rating', 'type': 'str'},
'rating_count': {'key': 'ratingCount', 'type': 'long'}
}
def __init__(self, rating=None, rating_count=None):
super(RatingCountPerRating, self).__init__()
self.rating = rating
self.rating_count = rating_count
class ReferenceLinks(Model):
"""
The class to represent a collection of REST reference links.
:param links: The readonly view of the links. Because Reference links are readonly, we only want to expose them as read only.
:type links: dict
"""
_attribute_map = {
'links': {'key': 'links', 'type': '{object}'}
}
def __init__(self, links=None):
super(ReferenceLinks, self).__init__()
self.links = links
class Response(QnAItem):
"""
The structure of a response
:param created_date: Time when the review was first created
:type created_date: datetime
:param id: Unique identifier of a QnA item
:type id: long
:param status: Get status of item
:type status: object
:param text: Text description of the QnA item
:type text: str
:param updated_date: Time when the review was edited/updated
:type updated_date: datetime
:param user: User details for the item.
:type user: :class:`UserIdentityRef <azure.devops.v7_1.gallery.models.UserIdentityRef>`
:param re_captcha_token:
:type re_captcha_token: str
"""
_attribute_map = {
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'long'},
'status': {'key': 'status', 'type': 'object'},
'text': {'key': 'text', 'type': 'str'},
'updated_date': {'key': 'updatedDate', 'type': 'iso-8601'},
'user': {'key': 'user', 'type': 'UserIdentityRef'},
're_captcha_token': {'key': 'reCaptchaToken', 'type': 'str'}
}
def __init__(self, created_date=None, id=None, status=None, text=None, updated_date=None, user=None, re_captcha_token=None):
super(Response, self).__init__(created_date=created_date, id=id, status=status, text=text, updated_date=updated_date, user=user)
self.re_captcha_token = re_captcha_token
class Review(Model):
"""
:param admin_reply: Admin Reply, if any, for this review
:type admin_reply: :class:`ReviewReply <azure.devops.v7_1.gallery.models.ReviewReply>`
:param id: Unique identifier of a review item
:type id: long
:param is_deleted: Flag for soft deletion
:type is_deleted: bool
:param is_ignored:
:type is_ignored: bool
:param product_version: Version of the product for which review was submitted
:type product_version: str
:param rating: Rating provided by the user
:type rating: str
:param re_captcha_token:
:type re_captcha_token: str
:param reply: Reply, if any, for this review
:type reply: :class:`ReviewReply <azure.devops.v7_1.gallery.models.ReviewReply>`
:param text: Text description of the review
:type text: str
:param title: Title of the review
:type title: str
:param updated_date: Time when the review was edited/updated
:type updated_date: datetime
:param user_display_name: Name of the user
:type user_display_name: str
:param user_id: Id of the user who submitted the review
:type user_id: str
"""
_attribute_map = {
'admin_reply': {'key': 'adminReply', 'type': 'ReviewReply'},
'id': {'key': 'id', 'type': 'long'},
'is_deleted': {'key': 'isDeleted', 'type': 'bool'},
'is_ignored': {'key': 'isIgnored', 'type': 'bool'},
'product_version': {'key': 'productVersion', 'type': 'str'},
'rating': {'key': 'rating', 'type': 'str'},
're_captcha_token': {'key': 'reCaptchaToken', 'type': 'str'},
'reply': {'key': 'reply', 'type': 'ReviewReply'},
'text': {'key': 'text', 'type': 'str'},
'title': {'key': 'title', 'type': 'str'},
'updated_date': {'key': 'updatedDate', 'type': 'iso-8601'},
'user_display_name': {'key': 'userDisplayName', 'type': 'str'},
'user_id': {'key': 'userId', 'type': 'str'}
}
def __init__(self, admin_reply=None, id=None, is_deleted=None, is_ignored=None, product_version=None, rating=None, re_captcha_token=None, reply=None, text=None, title=None, updated_date=None, user_display_name=None, user_id=None):
super(Review, self).__init__()
self.admin_reply = admin_reply
self.id = id
self.is_deleted = is_deleted
self.is_ignored = is_ignored
self.product_version = product_version
self.rating = rating
self.re_captcha_token = re_captcha_token
self.reply = reply
self.text = text
self.title = title
self.updated_date = updated_date
self.user_display_name = user_display_name
self.user_id = user_id
class ReviewPatch(Model):
"""
:param operation: Denotes the patch operation type
:type operation: object
:param reported_concern: Use when patch operation is FlagReview
:type reported_concern: :class:`UserReportedConcern <azure.devops.v7_1.gallery.models.UserReportedConcern>`
:param review_item: Use when patch operation is EditReview
:type review_item: :class:`Review <azure.devops.v7_1.gallery.models.Review>`
"""
_attribute_map = {
'operation': {'key': 'operation', 'type': 'object'},
'reported_concern': {'key': 'reportedConcern', 'type': 'UserReportedConcern'},
'review_item': {'key': 'reviewItem', 'type': 'Review'}
}
def __init__(self, operation=None, reported_concern=None, review_item=None):
super(ReviewPatch, self).__init__()
self.operation = operation
self.reported_concern = reported_concern
self.review_item = review_item
class ReviewReply(Model):
"""
:param id: Id of the reply
:type id: long
:param is_deleted: Flag for soft deletion
:type is_deleted: bool
:param product_version: Version of the product when the reply was submitted or updated
:type product_version: str
:param reply_text: Content of the reply
:type reply_text: str
:param review_id: Id of the review, to which this reply belongs
:type review_id: long
:param title: Title of the reply
:type title: str
:param updated_date: Date the reply was submitted or updated
:type updated_date: datetime
:param user_id: Id of the user who left the reply
:type user_id: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'long'},
'is_deleted': {'key': 'isDeleted', 'type': 'bool'},
'product_version': {'key': 'productVersion', 'type': 'str'},
'reply_text': {'key': 'replyText', 'type': 'str'},
'review_id': {'key': 'reviewId', 'type': 'long'},
'title': {'key': 'title', 'type': 'str'},
'updated_date': {'key': 'updatedDate', 'type': 'iso-8601'},
'user_id': {'key': 'userId', 'type': 'str'}
}
def __init__(self, id=None, is_deleted=None, product_version=None, reply_text=None, review_id=None, title=None, updated_date=None, user_id=None):
super(ReviewReply, self).__init__()
self.id = id
self.is_deleted = is_deleted
self.product_version = product_version
self.reply_text = reply_text
self.review_id = review_id
self.title = title
self.updated_date = updated_date
self.user_id = user_id
class ReviewsResult(Model):
"""
:param has_more_reviews: Flag indicating if there are more reviews to be shown (for paging)
:type has_more_reviews: bool
:param reviews: List of reviews
:type reviews: list of :class:`Review <azure.devops.v7_1.gallery.models.Review>`
:param total_review_count: Count of total review items
:type total_review_count: long
"""
_attribute_map = {
'has_more_reviews': {'key': 'hasMoreReviews', 'type': 'bool'},
'reviews': {'key': 'reviews', 'type': '[Review]'},
'total_review_count': {'key': 'totalReviewCount', 'type': 'long'}
}
def __init__(self, has_more_reviews=None, reviews=None, total_review_count=None):
super(ReviewsResult, self).__init__()
self.has_more_reviews = has_more_reviews
self.reviews = reviews
self.total_review_count = total_review_count
class ReviewSummary(Model):
"""
:param average_rating: Average Rating
:type average_rating: float
:param rating_count: Count of total ratings
:type rating_count: long
:param rating_split: Split of count across rating
:type rating_split: list of :class:`RatingCountPerRating <azure.devops.v7_1.gallery.models.RatingCountPerRating>`
"""
_attribute_map = {
'average_rating': {'key': 'averageRating', 'type': 'float'},
'rating_count': {'key': 'ratingCount', 'type': 'long'},
'rating_split': {'key': 'ratingSplit', 'type': '[RatingCountPerRating]'}
}
def __init__(self, average_rating=None, rating_count=None, rating_split=None):
super(ReviewSummary, self).__init__()
self.average_rating = average_rating
self.rating_count = rating_count
self.rating_split = rating_split
class UnpackagedExtensionData(Model):
"""
:param categories:
:type categories: list of str
:param description:
:type description: str
:param display_name:
:type display_name: str
:param draft_id:
:type draft_id: str
:param extension_name:
:type extension_name: str
:param installation_targets:
:type installation_targets: list of :class:`InstallationTarget <azure.devops.v7_1.gallery.models.InstallationTarget>`
:param is_converted_to_markdown:
:type is_converted_to_markdown: bool
:param is_preview:
:type is_preview: bool
:param pricing_category:
:type pricing_category: str
:param product:
:type product: str
:param publisher_name:
:type publisher_name: str
:param qn_aEnabled:
:type qn_aEnabled: bool
:param referral_url:
:type referral_url: str
:param repository_url:
:type repository_url: str
:param tags:
:type tags: list of str
:param version:
:type version: str
:param vsix_id:
:type vsix_id: str
"""
_attribute_map = {
'categories': {'key': 'categories', 'type': '[str]'},
'description': {'key': 'description', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'draft_id': {'key': 'draftId', 'type': 'str'},
'extension_name': {'key': 'extensionName', 'type': 'str'},
'installation_targets': {'key': 'installationTargets', 'type': '[InstallationTarget]'},
'is_converted_to_markdown': {'key': 'isConvertedToMarkdown', 'type': 'bool'},
'is_preview': {'key': 'isPreview', 'type': 'bool'},
'pricing_category': {'key': 'pricingCategory', 'type': 'str'},
'product': {'key': 'product', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'qn_aEnabled': {'key': 'qnAEnabled', 'type': 'bool'},
'referral_url': {'key': 'referralUrl', 'type': 'str'},
'repository_url': {'key': 'repositoryUrl', 'type': 'str'},
'tags': {'key': 'tags', 'type': '[str]'},
'version': {'key': 'version', 'type': 'str'},
'vsix_id': {'key': 'vsixId', 'type': 'str'}
}
def __init__(self, categories=None, description=None, display_name=None, draft_id=None, extension_name=None, installation_targets=None, is_converted_to_markdown=None, is_preview=None, pricing_category=None, product=None, publisher_name=None, qn_aEnabled=None, referral_url=None, repository_url=None, tags=None, version=None, vsix_id=None):
super(UnpackagedExtensionData, self).__init__()
self.categories = categories
self.description = description
self.display_name = display_name
self.draft_id = draft_id
self.extension_name = extension_name
self.installation_targets = installation_targets
self.is_converted_to_markdown = is_converted_to_markdown
self.is_preview = is_preview
self.pricing_category = pricing_category
self.product = product
self.publisher_name = publisher_name
self.qn_aEnabled = qn_aEnabled
self.referral_url = referral_url
self.repository_url = repository_url
self.tags = tags
self.version = version
self.vsix_id = vsix_id
class UserIdentityRef(Model):
"""
Identity reference with name and guid
:param display_name: User display name
:type display_name: str
:param id: User VSID
:type id: str
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'}
}
def __init__(self, display_name=None, id=None):
super(UserIdentityRef, self).__init__()
self.display_name = display_name
self.id = id
class UserReportedConcern(Model):
"""
:param category: Category of the concern
:type category: object
:param concern_text: User comment associated with the report
:type concern_text: str
:param review_id: Id of the review which was reported
:type review_id: long
:param submitted_date: Date the report was submitted
:type submitted_date: datetime
:param user_id: Id of the user who reported a review
:type user_id: str
"""
_attribute_map = {
'category': {'key': 'category', 'type': 'object'},
'concern_text': {'key': 'concernText', 'type': 'str'},
'review_id': {'key': 'reviewId', 'type': 'long'},
'submitted_date': {'key': 'submittedDate', 'type': 'iso-8601'},
'user_id': {'key': 'userId', 'type': 'str'}
}
def __init__(self, category=None, concern_text=None, review_id=None, submitted_date=None, user_id=None):
super(UserReportedConcern, self).__init__()
self.category = category
self.concern_text = concern_text
self.review_id = review_id
self.submitted_date = submitted_date
self.user_id = user_id
class Concern(QnAItem):
"""
The structure of a Concern Rather than defining a separate data structure having same fields as QnAItem, we are inheriting from the QnAItem.
:param created_date: Time when the review was first created
:type created_date: datetime
:param id: Unique identifier of a QnA item
:type id: long
:param status: Get status of item
:type status: object
:param text: Text description of the QnA item
:type text: str
:param updated_date: Time when the review was edited/updated
:type updated_date: datetime
:param user: User details for the item.
:type user: :class:`UserIdentityRef <azure.devops.v7_1.gallery.models.UserIdentityRef>`
:param category: Category of the concern
:type category: object
"""
_attribute_map = {
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'long'},
'status': {'key': 'status', 'type': 'object'},
'text': {'key': 'text', 'type': 'str'},
'updated_date': {'key': 'updatedDate', 'type': 'iso-8601'},
'user': {'key': 'user', 'type': 'UserIdentityRef'},
'category': {'key': 'category', 'type': 'object'}
}
def __init__(self, created_date=None, id=None, status=None, text=None, updated_date=None, user=None, category=None):
super(Concern, self).__init__(created_date=created_date, id=id, status=status, text=text, updated_date=updated_date, user=user)
self.category = category
class ExtensionDraftAsset(ExtensionFile):
"""
:param asset_type:
:type asset_type: str
:param language:
:type language: str
:param source:
:type source: str
"""
_attribute_map = {
'asset_type': {'key': 'assetType', 'type': 'str'},
'language': {'key': 'language', 'type': 'str'},
'source': {'key': 'source', 'type': 'str'},
}
def __init__(self, asset_type=None, language=None, source=None):
super(ExtensionDraftAsset, self).__init__(asset_type=asset_type, language=language, source=source)
class Publisher(PublisherBase):
"""
:param display_name:
:type display_name: str
:param email_address:
:type email_address: list of str
:param extensions:
:type extensions: list of :class:`PublishedExtension <azure.devops.v7_1.gallery.models.PublishedExtension>`
:param flags:
:type flags: object
:param last_updated:
:type last_updated: datetime
:param long_description:
:type long_description: str
:param publisher_id:
:type publisher_id: str
:param publisher_name:
:type publisher_name: str
:param short_description:
:type short_description: str
:param state:
:type state: object
:param _links:
:type _links: :class:`ReferenceLinks <azure.devops.v7_1.gallery.models.ReferenceLinks>`
:param domain:
:type domain: str
:param is_dns_token_verified:
:type is_dns_token_verified: bool
:param is_domain_verified:
:type is_domain_verified: bool
:param re_captcha_token:
:type re_captcha_token: str
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'email_address': {'key': 'emailAddress', 'type': '[str]'},
'extensions': {'key': 'extensions', 'type': '[PublishedExtension]'},
'flags': {'key': 'flags', 'type': 'object'},
'last_updated': {'key': 'lastUpdated', 'type': 'iso-8601'},
'long_description': {'key': 'longDescription', 'type': 'str'},
'publisher_id': {'key': 'publisherId', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'short_description': {'key': 'shortDescription', 'type': 'str'},
'state': {'key': 'state', 'type': 'object'},
'_links': {'key': '_links', 'type': 'ReferenceLinks'},
'domain': {'key': 'domain', 'type': 'str'},
'is_dns_token_verified': {'key': 'isDnsTokenVerified', 'type': 'bool'},
'is_domain_verified': {'key': 'isDomainVerified', 'type': 'bool'},
're_captcha_token': {'key': 'reCaptchaToken', 'type': 'str'}
}
def __init__(self, display_name=None, email_address=None, extensions=None, flags=None, last_updated=None, long_description=None, publisher_id=None, publisher_name=None, short_description=None, state=None, _links=None, domain=None, is_dns_token_verified=None, is_domain_verified=None, re_captcha_token=None):
super(Publisher, self).__init__(display_name=display_name, email_address=email_address, extensions=extensions, flags=flags, last_updated=last_updated, long_description=long_description, publisher_id=publisher_id, publisher_name=publisher_name, short_description=short_description, state=state)
self._links = _links
self.domain = domain
self.is_dns_token_verified = is_dns_token_verified
self.is_domain_verified = is_domain_verified
self.re_captcha_token = re_captcha_token
__all__ = [
'AcquisitionOperation',
'AcquisitionOptions',
'Answers',
'AssetDetails',
'AzurePublisher',
'AzureRestApiRequestModel',
'CategoriesResult',
'CategoryLanguageTitle',
'CustomerSupportRequest',
'EventCounts',
'ExtensionAcquisitionRequest',
'ExtensionBadge',
'ExtensionCategory',
'ExtensionDailyStat',
'ExtensionDailyStats',
'ExtensionDraft',
'ExtensionDraftPatch',
'ExtensionEvent',
'ExtensionEvents',
'ExtensionFile',
'ExtensionFilterResult',
'ExtensionFilterResultMetadata',
'ExtensionPackage',
'ExtensionPayload',
'ExtensionQuery',
'ExtensionQueryResult',
'ExtensionShare',
'ExtensionStatistic',
'ExtensionStatisticUpdate',
'ExtensionVersion',
'FilterCriteria',
'GraphSubjectBase',
'IdentityRef',
'InstallationTarget',
'MetadataItem',
'NotificationsData',
'ProductCategoriesResult',
'ProductCategory',
'PublishedExtension',
'PublisherBase',
'PublisherFacts',
'PublisherFilterResult',
'PublisherQuery',
'PublisherQueryResult',
'PublisherRoleAssignment',
'PublisherSecurityRole',
'PublisherUserRoleAssignmentRef',
'QnAItem',
'QueryFilter',
'Question',
'QuestionsResult',
'RatingCountPerRating',
'ReferenceLinks',
'Response',
'Review',
'ReviewPatch',
'ReviewReply',
'ReviewsResult',
'ReviewSummary',
'UnpackagedExtensionData',
'UserIdentityRef',
'UserReportedConcern',
'Concern',
'ExtensionDraftAsset',
'Publisher',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/gallery/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/gallery/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 32725
}
| 368 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from .models import *
from .pipeline_permissions_client import PipelinePermissionsClient
__all__ = [
'GraphSubjectBase',
'IdentityRef',
'Permission',
'PipelinePermission',
'ReferenceLinks',
'Resource',
'ResourcePipelinePermissions',
'PipelinePermissionsClient'
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/pipeline_permissions/__init__.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/pipeline_permissions/__init__.py",
"repo_id": "azure-devops-python-api",
"token_count": 186
}
| 369 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class GeoRegion(Model):
"""
:param region_code:
:type region_code: str
"""
_attribute_map = {
'region_code': {'key': 'regionCode', 'type': 'str'}
}
def __init__(self, region_code=None):
super(GeoRegion, self).__init__()
self.region_code = region_code
class ProfileRegion(Model):
"""
Country/region information
:param code: The two-letter code defined in ISO 3166 for the country/region.
:type code: str
:param name: Localized country/region name
:type name: str
"""
_attribute_map = {
'code': {'key': 'code', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'}
}
def __init__(self, code=None, name=None):
super(ProfileRegion, self).__init__()
self.code = code
self.name = name
class ProfileRegions(Model):
"""
Container of country/region information
:param notice_contact_consent_requirement_regions: List of country/region code with contact consent requirement type of notice
:type notice_contact_consent_requirement_regions: list of str
:param opt_out_contact_consent_requirement_regions: List of country/region code with contact consent requirement type of opt-out
:type opt_out_contact_consent_requirement_regions: list of str
:param regions: List of country/regions
:type regions: list of :class:`ProfileRegion <azure.devops.v7_1.profile.models.ProfileRegion>`
"""
_attribute_map = {
'notice_contact_consent_requirement_regions': {'key': 'noticeContactConsentRequirementRegions', 'type': '[str]'},
'opt_out_contact_consent_requirement_regions': {'key': 'optOutContactConsentRequirementRegions', 'type': '[str]'},
'regions': {'key': 'regions', 'type': '[ProfileRegion]'}
}
def __init__(self, notice_contact_consent_requirement_regions=None, opt_out_contact_consent_requirement_regions=None, regions=None):
super(ProfileRegions, self).__init__()
self.notice_contact_consent_requirement_regions = notice_contact_consent_requirement_regions
self.opt_out_contact_consent_requirement_regions = opt_out_contact_consent_requirement_regions
self.regions = regions
__all__ = [
'GeoRegion',
'ProfileRegion',
'ProfileRegions',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/profile_regions/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/profile_regions/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 950
}
| 370 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class DebugEntryCreateBatch(Model):
"""
A batch of debug entry to create.
:param create_behavior: Defines what to do when a debug entry in the batch already exists.
:type create_behavior: object
:param debug_entries: The debug entries.
:type debug_entries: list of :class:`DebugEntry <azure.devops.v7_1.symbol.models.DebugEntry>`
:param proof_nodes: Serialized Proof nodes, used to verify uploads on server side for Chunk Dedup DebugEntry
:type proof_nodes: list of str
"""
_attribute_map = {
'create_behavior': {'key': 'createBehavior', 'type': 'object'},
'debug_entries': {'key': 'debugEntries', 'type': '[DebugEntry]'},
'proof_nodes': {'key': 'proofNodes', 'type': '[str]'}
}
def __init__(self, create_behavior=None, debug_entries=None, proof_nodes=None):
super(DebugEntryCreateBatch, self).__init__()
self.create_behavior = create_behavior
self.debug_entries = debug_entries
self.proof_nodes = proof_nodes
class IDomainId(Model):
"""
"""
_attribute_map = {
}
def __init__(self):
super(IDomainId, self).__init__()
class JsonBlobBlockHash(Model):
"""
BlobBlock hash formatted to be deserialized for symbol service.
:param hash_bytes: Array of hash bytes.
:type hash_bytes: str
"""
_attribute_map = {
'hash_bytes': {'key': 'hashBytes', 'type': 'str'}
}
def __init__(self, hash_bytes=None):
super(JsonBlobBlockHash, self).__init__()
self.hash_bytes = hash_bytes
class JsonBlobIdentifier(Model):
"""
:param identifier_value:
:type identifier_value: str
"""
_attribute_map = {
'identifier_value': {'key': 'identifierValue', 'type': 'str'}
}
def __init__(self, identifier_value=None):
super(JsonBlobIdentifier, self).__init__()
self.identifier_value = identifier_value
class JsonBlobIdentifierWithBlocks(Model):
"""
BlobIdentifier with block hashes formatted to be deserialzied for symbol service.
:param block_hashes: List of blob block hashes.
:type block_hashes: list of :class:`JsonBlobBlockHash <azure.devops.v7_1.symbol.models.JsonBlobBlockHash>`
:param identifier_value: Array of blobId bytes.
:type identifier_value: str
"""
_attribute_map = {
'block_hashes': {'key': 'blockHashes', 'type': '[JsonBlobBlockHash]'},
'identifier_value': {'key': 'identifierValue', 'type': 'str'}
}
def __init__(self, block_hashes=None, identifier_value=None):
super(JsonBlobIdentifierWithBlocks, self).__init__()
self.block_hashes = block_hashes
self.identifier_value = identifier_value
class ResourceBase(Model):
"""
:param created_by: The ID of user who created this item. Optional.
:type created_by: str
:param created_date: The date time when this item is created. Optional.
:type created_date: datetime
:param id: An identifier for this item. Optional.
:type id: str
:param storage_eTag: An opaque ETag used to synchronize with the version stored at server end. Optional.
:type storage_eTag: str
:param url: A URI which can be used to retrieve this item in its raw format. Optional. Note this is distinguished from other URIs that are present in a derived resource.
:type url: str
"""
_attribute_map = {
'created_by': {'key': 'createdBy', 'type': 'str'},
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'str'},
'storage_eTag': {'key': 'storageETag', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, created_by=None, created_date=None, id=None, storage_eTag=None, url=None):
super(ResourceBase, self).__init__()
self.created_by = created_by
self.created_date = created_date
self.id = id
self.storage_eTag = storage_eTag
self.url = url
class DebugEntry(ResourceBase):
"""
A dual-purpose data object, the debug entry is used by the client to publish the symbol file (with file's blob identifier, which can be calculated from VSTS hashing algorithm) or query the file (with a client key). Since the symbol server tries to return a matched symbol file with the richest information level, it may not always point to the same symbol file for different queries with same client key.
:param created_by: The ID of user who created this item. Optional.
:type created_by: str
:param created_date: The date time when this item is created. Optional.
:type created_date: datetime
:param id: An identifier for this item. Optional.
:type id: str
:param storage_eTag: An opaque ETag used to synchronize with the version stored at server end. Optional.
:type storage_eTag: str
:param url: A URI which can be used to retrieve this item in its raw format. Optional. Note this is distinguished from other URIs that are present in a derived resource.
:type url: str
:param blob_details: Details of the blob formatted to be deserialized for symbol service.
:type blob_details: :class:`JsonBlobIdentifierWithBlocks <azure.devops.v7_1.symbol.models.JsonBlobIdentifierWithBlocks>`
:param blob_identifier: A blob identifier of the symbol file to upload to this debug entry. This property is mostly used during creation of debug entry (a.k.a. symbol publishing) to allow the server to query the existence of the blob.
:type blob_identifier: :class:`JsonBlobIdentifier <azure.devops.v7_1.symbol.models.JsonBlobIdentifier>`
:param blob_uri: The URI to get the symbol file. Provided by the server, the URI contains authentication information and is readily accessible by plain HTTP GET request. The client is recommended to retrieve the file as soon as it can since the URI will expire in a short period.
:type blob_uri: str
:param client_key: A key the client (debugger, for example) uses to find the debug entry. Note it is not unique for each different symbol file as it does not distinguish between those which only differ by information level.
:type client_key: str
:param domain_id: The Domain Id where this debugEntry lives. This property should not be null.
:type domain_id: :class:`IDomainId <azure.devops.v7_1.symbol.models.IDomainId>`
:param information_level: The information level this debug entry contains.
:type information_level: object
:param request_id: The identifier of symbol request to which this debug entry belongs.
:type request_id: str
:param size: The size for the debug entry.
:type size: long
:param status: The status of debug entry.
:type status: object
"""
_attribute_map = {
'created_by': {'key': 'createdBy', 'type': 'str'},
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'str'},
'storage_eTag': {'key': 'storageETag', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'blob_details': {'key': 'blobDetails', 'type': 'JsonBlobIdentifierWithBlocks'},
'blob_identifier': {'key': 'blobIdentifier', 'type': 'JsonBlobIdentifier'},
'blob_uri': {'key': 'blobUri', 'type': 'str'},
'client_key': {'key': 'clientKey', 'type': 'str'},
'domain_id': {'key': 'domainId', 'type': 'IDomainId'},
'information_level': {'key': 'informationLevel', 'type': 'object'},
'request_id': {'key': 'requestId', 'type': 'str'},
'size': {'key': 'size', 'type': 'long'},
'status': {'key': 'status', 'type': 'object'}
}
def __init__(self, created_by=None, created_date=None, id=None, storage_eTag=None, url=None, blob_details=None, blob_identifier=None, blob_uri=None, client_key=None, domain_id=None, information_level=None, request_id=None, size=None, status=None):
super(DebugEntry, self).__init__(created_by=created_by, created_date=created_date, id=id, storage_eTag=storage_eTag, url=url)
self.blob_details = blob_details
self.blob_identifier = blob_identifier
self.blob_uri = blob_uri
self.client_key = client_key
self.domain_id = domain_id
self.information_level = information_level
self.request_id = request_id
self.size = size
self.status = status
class Request(ResourceBase):
"""
Symbol request.
:param created_by: The ID of user who created this item. Optional.
:type created_by: str
:param created_date: The date time when this item is created. Optional.
:type created_date: datetime
:param id: An identifier for this item. Optional.
:type id: str
:param storage_eTag: An opaque ETag used to synchronize with the version stored at server end. Optional.
:type storage_eTag: str
:param url: A URI which can be used to retrieve this item in its raw format. Optional. Note this is distinguished from other URIs that are present in a derived resource.
:type url: str
:param description: An optional human-facing description.
:type description: str
:param domain_id: The Domain Id where this request lives. This property should not be null.
:type domain_id: :class:`IDomainId <azure.devops.v7_1.symbol.models.IDomainId>`
:param expiration_date: An optional expiration date for the request. The request will become inaccessible and get deleted after the date, regardless of its status. On an HTTP POST, if expiration date is null/missing, the server will assign a default expiration data (30 days unless overwridden in the registry at the account level). On PATCH, if expiration date is null/missing, the behavior is to not change whatever the request's current expiration date is.
:type expiration_date: datetime
:param is_chunked: Indicates if request should be chunk dedup
:type is_chunked: bool
:param name: A human-facing name for the request. Required on POST, ignored on PATCH.
:type name: str
:param size: The total Size for this request.
:type size: long
:param status: The status for this request.
:type status: object
"""
_attribute_map = {
'created_by': {'key': 'createdBy', 'type': 'str'},
'created_date': {'key': 'createdDate', 'type': 'iso-8601'},
'id': {'key': 'id', 'type': 'str'},
'storage_eTag': {'key': 'storageETag', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'},
'description': {'key': 'description', 'type': 'str'},
'domain_id': {'key': 'domainId', 'type': 'IDomainId'},
'expiration_date': {'key': 'expirationDate', 'type': 'iso-8601'},
'is_chunked': {'key': 'isChunked', 'type': 'bool'},
'name': {'key': 'name', 'type': 'str'},
'size': {'key': 'size', 'type': 'long'},
'status': {'key': 'status', 'type': 'object'}
}
def __init__(self, created_by=None, created_date=None, id=None, storage_eTag=None, url=None, description=None, domain_id=None, expiration_date=None, is_chunked=None, name=None, size=None, status=None):
super(Request, self).__init__(created_by=created_by, created_date=created_date, id=id, storage_eTag=storage_eTag, url=url)
self.description = description
self.domain_id = domain_id
self.expiration_date = expiration_date
self.is_chunked = is_chunked
self.name = name
self.size = size
self.status = status
__all__ = [
'DebugEntryCreateBatch',
'IDomainId',
'JsonBlobBlockHash',
'JsonBlobIdentifier',
'JsonBlobIdentifierWithBlocks',
'ResourceBase',
'DebugEntry',
'Request',
]
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/symbol/models.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/symbol/models.py",
"repo_id": "azure-devops-python-api",
"token_count": 4329
}
| 371 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class TestResultsClient(Client):
"""TestResults
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(TestResultsClient, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = 'c83eaf52-edf3-4034-ae11-17d38f25404c'
def query_test_results_meta_data(self, test_case_reference_ids, project, details_to_include=None):
"""QueryTestResultsMetaData.
[Preview API] Get list of test Result meta data details for corresponding testcasereferenceId
:param [str] test_case_reference_ids: TestCaseReference Ids of the test Result to be queried, comma separated list of valid ids (limit no. of ids 200).
:param str project: Project ID or project name
:param str details_to_include: Details to include with test results metadata. Default is None. Other values are FlakyIdentifiers.
:rtype: [TestResultMetaData]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if details_to_include is not None:
query_parameters['detailsToInclude'] = self._serialize.query('details_to_include', details_to_include, 'str')
content = self._serialize.body(test_case_reference_ids, '[str]')
response = self._send(http_method='POST',
location_id='b72ff4c0-4341-4213-ba27-f517cf341c95',
version='7.1-preview.4',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('[TestResultMetaData]', self._unwrap_collection(response))
def update_test_results_meta_data(self, test_result_meta_data_update_input, project, test_case_reference_id):
"""UpdateTestResultsMetaData.
[Preview API] Update properties of test result meta data
:param :class:`<TestResultMetaDataUpdateInput> <azure.devops.v7_1.test_results.models.TestResultMetaDataUpdateInput>` test_result_meta_data_update_input: TestResultMetaData update input TestResultMetaDataUpdateInput
:param str project: Project ID or project name
:param int test_case_reference_id: TestCaseReference Id of Test Result to be updated.
:rtype: :class:`<TestResultMetaData> <azure.devops.v7_1.test_results.models.TestResultMetaData>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if test_case_reference_id is not None:
route_values['testCaseReferenceId'] = self._serialize.url('test_case_reference_id', test_case_reference_id, 'int')
content = self._serialize.body(test_result_meta_data_update_input, 'TestResultMetaDataUpdateInput')
response = self._send(http_method='PATCH',
location_id='b72ff4c0-4341-4213-ba27-f517cf341c95',
version='7.1-preview.4',
route_values=route_values,
content=content)
return self._deserialize('TestResultMetaData', response)
def create_build_attachment_in_log_store(self, attachment_request_model, project, build_id):
"""CreateBuildAttachmentInLogStore.
[Preview API] Creates an attachment in the LogStore for the specified buildId.
:param :class:`<TestAttachmentRequestModel> <azure.devops.v7_1.test_results.models.TestAttachmentRequestModel>` attachment_request_model: Contains attachment info like stream, filename, comment, attachmentType
:param str project: Project ID or project name
:param int build_id: BuildId
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if build_id is not None:
route_values['buildId'] = self._serialize.url('build_id', build_id, 'int')
content = self._serialize.body(attachment_request_model, 'TestAttachmentRequestModel')
self._send(http_method='POST',
location_id='6f747e16-18c2-435a-b4fb-fa05d6845fee',
version='7.1-preview.1',
route_values=route_values,
content=content)
def create_test_run_log_store_attachment(self, attachment_request_model, project, run_id):
"""CreateTestRunLogStoreAttachment.
[Preview API] Creates an attachment in the LogStore for the specified runId.
:param :class:`<TestAttachmentRequestModel> <azure.devops.v7_1.test_results.models.TestAttachmentRequestModel>` attachment_request_model: Contains attachment info like stream, filename, comment, attachmentType
:param str project: Project ID or project name
:param int run_id: Test RunId
:rtype: :class:`<TestLogStoreAttachmentReference> <azure.devops.v7_1.test_results.models.TestLogStoreAttachmentReference>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
content = self._serialize.body(attachment_request_model, 'TestAttachmentRequestModel')
response = self._send(http_method='POST',
location_id='1026d5de-4b0b-46ae-a31f-7c59b6af51ef',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('TestLogStoreAttachmentReference', response)
def delete_test_run_log_store_attachment(self, project, run_id, filename):
"""DeleteTestRunLogStoreAttachment.
[Preview API] Deletes the attachment with the specified filename for the specified runId from the LogStore.
:param str project: Project ID or project name
:param int run_id: Test RunId
:param str filename: Attachment FileName
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if filename is not None:
query_parameters['filename'] = self._serialize.query('filename', filename, 'str')
self._send(http_method='DELETE',
location_id='1026d5de-4b0b-46ae-a31f-7c59b6af51ef',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
def get_test_run_log_store_attachment_content(self, project, run_id, filename, **kwargs):
"""GetTestRunLogStoreAttachmentContent.
[Preview API] Returns the attachment with the specified filename for the specified runId from the LogStore.
:param str project: Project ID or project name
:param int run_id: Test RunId
:param str filename: Attachment FileName
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if filename is not None:
query_parameters['filename'] = self._serialize.query('filename', filename, 'str')
response = self._send(http_method='GET',
location_id='1026d5de-4b0b-46ae-a31f-7c59b6af51ef',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_test_run_log_store_attachments(self, project, run_id):
"""GetTestRunLogStoreAttachments.
[Preview API] Returns a list of attachments for the specified runId from the LogStore.
:param str project: Project ID or project name
:param int run_id: Test RunId
:rtype: [TestLogStoreAttachment]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
response = self._send(http_method='GET',
location_id='1026d5de-4b0b-46ae-a31f-7c59b6af51ef',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[TestLogStoreAttachment]', self._unwrap_collection(response))
def get_test_run_log_store_attachment_zip(self, project, run_id, filename, **kwargs):
"""GetTestRunLogStoreAttachmentZip.
[Preview API] Returns the attachment with the specified filename for the specified runId from the LogStore.
:param str project: Project ID or project name
:param int run_id: Test RunId
:param str filename: Attachment FileName
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if filename is not None:
query_parameters['filename'] = self._serialize.query('filename', filename, 'str')
response = self._send(http_method='GET',
location_id='1026d5de-4b0b-46ae-a31f-7c59b6af51ef',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def create_failure_type(self, test_result_failure_type, project):
"""CreateFailureType.
[Preview API] Creates a new test failure type
:param :class:`<TestFailureType> <azure.devops.v7_1.test_results.models.TestFailureType>` test_result_failure_type:
:param str project: Project ID or project name
:rtype: :class:`<TestFailureType> <azure.devops.v7_1.test_results.models.TestFailureType>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
content = self._serialize.body(test_result_failure_type, 'TestFailureType')
response = self._send(http_method='POST',
location_id='c4ac0486-830c-4a2a-9ef9-e8a1791a70fd',
version='7.1-preview.1',
route_values=route_values,
content=content)
return self._deserialize('TestFailureType', response)
def delete_failure_type(self, project, failure_type_id):
"""DeleteFailureType.
[Preview API] Deletes a test failure type with specified failureTypeId
:param str project: Project ID or project name
:param int failure_type_id:
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if failure_type_id is not None:
route_values['failureTypeId'] = self._serialize.url('failure_type_id', failure_type_id, 'int')
self._send(http_method='DELETE',
location_id='c4ac0486-830c-4a2a-9ef9-e8a1791a70fd',
version='7.1-preview.1',
route_values=route_values)
def get_failure_types(self, project):
"""GetFailureTypes.
[Preview API] Returns the list of test failure types.
:param str project: Project ID or project name
:rtype: [TestFailureType]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
response = self._send(http_method='GET',
location_id='c4ac0486-830c-4a2a-9ef9-e8a1791a70fd',
version='7.1-preview.1',
route_values=route_values)
return self._deserialize('[TestFailureType]', self._unwrap_collection(response))
def get_test_result_logs(self, project, run_id, result_id, type, directory_path=None, file_name_prefix=None, fetch_meta_data=None, top=None, continuation_token=None):
"""GetTestResultLogs.
[Preview API] Get list of test result attachments reference
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains the result
:param int result_id: Id of the test result
:param str type: type of attachments to get
:param str directory_path: directory path of attachments to get
:param str file_name_prefix: file name prefix to filter the list of attachment
:param bool fetch_meta_data: Default is false, set if metadata is needed
:param int top: Numbe of attachments reference to return
:param String continuation_token: Header to pass the continuationToken
:rtype: :class:`<[TestLog]> <azure.devops.v7_1.test_results.models.[TestLog]>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if directory_path is not None:
query_parameters['directoryPath'] = self._serialize.query('directory_path', directory_path, 'str')
if file_name_prefix is not None:
query_parameters['fileNamePrefix'] = self._serialize.query('file_name_prefix', file_name_prefix, 'str')
if fetch_meta_data is not None:
query_parameters['fetchMetaData'] = self._serialize.query('fetch_meta_data', fetch_meta_data, 'bool')
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
additional_headers = {}
if continuation_token is not None:
additional_headers['x-ms-continuationtoken'] = continuation_token
response = self._send(http_method='GET',
location_id='714caaac-ae1e-4869-8323-9bc0f5120dbf',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
additional_headers=additional_headers)
return self._deserialize('[TestLog]', self._unwrap_collection(response))
def get_test_sub_result_logs(self, project, run_id, result_id, sub_result_id, type, directory_path=None, file_name_prefix=None, fetch_meta_data=None, top=None, continuation_token=None):
"""GetTestSubResultLogs.
[Preview API] Get list of test subresult attachments reference
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains the results
:param int result_id: Id of the test result that contains subresult
:param int sub_result_id: Id of the test subresult
:param str type: type of the attachments to get
:param str directory_path: directory path of the attachment to get
:param str file_name_prefix: file name prefix to filter the list of attachments
:param bool fetch_meta_data: Default is false, set if metadata is needed
:param int top: Number of attachments reference to return
:param String continuation_token: Header to pass the continuationToken
:rtype: :class:`<[TestLog]> <azure.devops.v7_1.test_results.models.[TestLog]>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if sub_result_id is not None:
query_parameters['subResultId'] = self._serialize.query('sub_result_id', sub_result_id, 'int')
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if directory_path is not None:
query_parameters['directoryPath'] = self._serialize.query('directory_path', directory_path, 'str')
if file_name_prefix is not None:
query_parameters['fileNamePrefix'] = self._serialize.query('file_name_prefix', file_name_prefix, 'str')
if fetch_meta_data is not None:
query_parameters['fetchMetaData'] = self._serialize.query('fetch_meta_data', fetch_meta_data, 'bool')
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
additional_headers = {}
if continuation_token is not None:
additional_headers['x-ms-continuationtoken'] = continuation_token
response = self._send(http_method='GET',
location_id='714caaac-ae1e-4869-8323-9bc0f5120dbf',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
additional_headers=additional_headers)
return self._deserialize('[TestLog]', self._unwrap_collection(response))
def get_test_run_logs(self, project, run_id, type, directory_path=None, file_name_prefix=None, fetch_meta_data=None, top=None, continuation_token=None):
"""GetTestRunLogs.
[Preview API] Get list of test run attachments reference
:param str project: Project ID or project name
:param int run_id: Id of the test run
:param str type: type of the attachments to get
:param str directory_path: directory path for which attachments are needed
:param str file_name_prefix: file name prefix to filter the list of attachment
:param bool fetch_meta_data: Default is false, set if metadata is needed
:param int top: Number of attachments reference to return
:param String continuation_token: Header to pass the continuationToken
:rtype: :class:`<[TestLog]> <azure.devops.v7_1.test_results.models.[TestLog]>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if directory_path is not None:
query_parameters['directoryPath'] = self._serialize.query('directory_path', directory_path, 'str')
if file_name_prefix is not None:
query_parameters['fileNamePrefix'] = self._serialize.query('file_name_prefix', file_name_prefix, 'str')
if fetch_meta_data is not None:
query_parameters['fetchMetaData'] = self._serialize.query('fetch_meta_data', fetch_meta_data, 'bool')
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
additional_headers = {}
if continuation_token is not None:
additional_headers['x-ms-continuationtoken'] = continuation_token
response = self._send(http_method='GET',
location_id='5b47b946-e875-4c9a-acdc-2a20996caebe',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters,
additional_headers=additional_headers)
return self._deserialize('[TestLog]', self._unwrap_collection(response))
def get_test_log_store_endpoint_details_for_result_log(self, project, run_id, result_id, type, file_path):
"""GetTestLogStoreEndpointDetailsForResultLog.
[Preview API] Get SAS Uri of a test results attachment
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains result
:param int result_id: Id of the test result whose files need to be downloaded
:param str type: type of the file
:param str file_path: filePath for which sas uri is needed
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_1.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
response = self._send(http_method='GET',
location_id='da630b37-1236-45b5-945e-1d7bdb673850',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
def get_test_log_store_endpoint_details_for_sub_result_log(self, project, run_id, result_id, sub_result_id, type, file_path):
"""GetTestLogStoreEndpointDetailsForSubResultLog.
[Preview API] Get SAS Uri of a test subresults attachment
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains result
:param int result_id: Id of the test result that contains subresult
:param int sub_result_id: Id of the test subresult whose file sas uri is needed
:param str type: type of the file
:param str file_path: filePath for which sas uri is needed
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_1.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if sub_result_id is not None:
query_parameters['subResultId'] = self._serialize.query('sub_result_id', sub_result_id, 'int')
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
response = self._send(http_method='GET',
location_id='da630b37-1236-45b5-945e-1d7bdb673850',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
def test_log_store_endpoint_details_for_result(self, project, run_id, result_id, sub_result_id, file_path, type):
"""TestLogStoreEndpointDetailsForResult.
[Preview API] Create empty file for a result and Get Sas uri for the file
:param str project: Project ID or project name
:param int run_id: Id of the test run that contains the result
:param int result_id: Id of the test results that contains sub result
:param int sub_result_id: Id of the test sub result whose file sas uri is needed
:param str file_path: file path inside the sub result for which sas uri is needed
:param str type: Type of the file for download
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_1.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
if result_id is not None:
route_values['resultId'] = self._serialize.url('result_id', result_id, 'int')
query_parameters = {}
if sub_result_id is not None:
query_parameters['subResultId'] = self._serialize.query('sub_result_id', sub_result_id, 'int')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
response = self._send(http_method='POST',
location_id='da630b37-1236-45b5-945e-1d7bdb673850',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
def get_test_log_store_endpoint_details_for_run_log(self, project, run_id, type, file_path):
"""GetTestLogStoreEndpointDetailsForRunLog.
[Preview API] Get SAS Uri of a test run attachment
:param str project: Project ID or project name
:param int run_id: Id of the test run whose file has to be downloaded
:param str type: type of the file
:param str file_path: filePath for which sas uri is needed
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_1.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
response = self._send(http_method='GET',
location_id='67eb3f92-6c97-4fd9-8b63-6cbdc7e526ea',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
def test_log_store_endpoint_details_for_run(self, project, run_id, test_log_store_operation_type, file_path=None, type=None):
"""TestLogStoreEndpointDetailsForRun.
[Preview API] Create empty file for a run and Get Sas uri for the file
:param str project: Project ID or project name
:param int run_id: Id of the run to get endpoint details
:param str test_log_store_operation_type: Type of operation to perform using sas uri
:param str file_path: file path to create an empty file
:param str type: Default is GeneralAttachment, type of empty file to be created
:rtype: :class:`<TestLogStoreEndpointDetails> <azure.devops.v7_1.test_results.models.TestLogStoreEndpointDetails>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if run_id is not None:
route_values['runId'] = self._serialize.url('run_id', run_id, 'int')
query_parameters = {}
if test_log_store_operation_type is not None:
query_parameters['testLogStoreOperationType'] = self._serialize.query('test_log_store_operation_type', test_log_store_operation_type, 'str')
if file_path is not None:
query_parameters['filePath'] = self._serialize.query('file_path', file_path, 'str')
if type is not None:
query_parameters['type'] = self._serialize.query('type', type, 'str')
response = self._send(http_method='POST',
location_id='67eb3f92-6c97-4fd9-8b63-6cbdc7e526ea',
version='7.1-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('TestLogStoreEndpointDetails', response)
|
azure-devops-python-api/azure-devops/azure/devops/v7_1/test_results/test_results_client.py/0
|
{
"file_path": "azure-devops-python-api/azure-devops/azure/devops/v7_1/test_results/test_results_client.py",
"repo_id": "azure-devops-python-api",
"token_count": 13401
}
| 372 |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from __future__ import print_function
import sys
import glob
import os
from subprocess import check_call, CalledProcessError
def exec_command(command):
try:
print('Executing: ' + command)
check_call(command.split(), cwd=root_dir)
print()
except CalledProcessError as err:
print(err, file=sys.stderr)
sys.exit(1)
print('Running dev setup...')
root_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), '..', '..'))
print('Root directory \'{}\'\n'.format(root_dir))
exec_command('python -m pip install --upgrade pip')
exec_command('python -m pip install --upgrade wheel')
# install general requirements
if os.path.isfile('./requirements.txt'):
exec_command('pip install -r requirements.txt')
# install dev packages
exec_command('pip install -e azure-devops')
# install packaging requirements
if os.path.isfile('./scripts/packaging_requirements.txt'):
exec_command('pip install -r scripts/packaging_requirements.txt')
|
azure-devops-python-api/scripts/dev_setup.py/0
|
{
"file_path": "azure-devops-python-api/scripts/dev_setup.py",
"repo_id": "azure-devops-python-api",
"token_count": 395
}
| 373 |
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
"""Azure Quantum Cirq Service"""
from .service import AzureQuantumService
from .job import Job
__all__ = ["AzureQuantumService", "Job"]
|
azure-quantum-python/azure-quantum/azure/quantum/cirq/__init__.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/cirq/__init__.py",
"repo_id": "azure-quantum-python",
"token_count": 62
}
| 374 |
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
"""Defines set of backends for interacting with Azure Quantum"""
from azure.quantum.qiskit.backends.ionq import (
IonQBackend,
IonQQPUBackend,
IonQAriaBackend,
IonQSimulatorBackend,
IonQQPUQirBackend,
IonQAriaQirBackend,
IonQForteBackend,
IonQForteQirBackend,
IonQSimulatorQirBackend,
)
from azure.quantum.qiskit.backends.quantinuum import (
QuantinuumBackend,
QuantinuumQPUBackend,
QuantinuumSyntaxCheckerBackend,
QuantinuumEmulatorBackend,
QuantinuumQPUQirBackend,
QuantinuumSyntaxCheckerQirBackend,
QuantinuumEmulatorQirBackend,
)
from azure.quantum.qiskit.backends.rigetti import (
RigettiBackend,
RigettiQPUBackend,
RigettiSimulatorBackend,
)
from azure.quantum.qiskit.backends.qci import (
QCIBackend,
QCISimulatorBackend,
QCIQPUBackend,
)
from azure.quantum.qiskit.backends.microsoft import (
MicrosoftBackend,
MicrosoftResourceEstimationBackend,
)
from .backend import AzureBackendBase
__all__ = [
"AzureBackendBase"
]
|
azure-quantum-python/azure-quantum/azure/quantum/qiskit/backends/__init__.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/qiskit/backends/__init__.py",
"repo_id": "azure-quantum-python",
"token_count": 454
}
| 375 |
"""Defines classes for interacting with Microsoft Elements DFT service"""
from .target import MicrosoftElementsDft
from .job import MicrosoftElementsDftJob
__all__ = ["MicrosoftElementsDft", "MicrosoftElementsDftJob"]
|
azure-quantum-python/azure-quantum/azure/quantum/target/microsoft/elements/dft/__init__.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/target/microsoft/elements/dft/__init__.py",
"repo_id": "azure-quantum-python",
"token_count": 56
}
| 376 |
##
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
##
"""
Module providing the Workspace class, used to connect to
an Azure Quantum Workspace.
"""
from __future__ import annotations
from datetime import datetime
import logging
from typing import (
Any,
Dict,
Iterable,
List,
Optional,
TYPE_CHECKING,
Tuple,
Union,
)
from azure.quantum._client import QuantumClient
from azure.quantum._client.operations import (
JobsOperations,
StorageOperations,
QuotasOperations,
SessionsOperations,
TopLevelItemsOperations
)
from azure.quantum._client.models import (
BlobDetails,
JobStatus,
TargetStatus,
)
from azure.quantum import Job, Session
from azure.quantum.job.workspace_item_factory import WorkspaceItemFactory
from azure.quantum._workspace_connection_params import (
WorkspaceConnectionParams
)
from azure.quantum._constants import (
ConnectionConstants,
)
from azure.quantum.storage import (
create_container_using_client,
get_container_uri,
ContainerClient
)
if TYPE_CHECKING:
from azure.quantum.target import Target
logger = logging.getLogger(__name__)
__all__ = ["Workspace"]
# pylint: disable=line-too-long
# pylint: disable=too-many-public-methods
class Workspace:
"""
Represents an Azure Quantum workspace.
When creating a Workspace object, callers have two options for
identifying the Azure Quantum workspace (in order of precedence):
1. specify a valid location and resource ID; or
2. specify a valid location, subscription ID, resource group, and workspace name.
You can also use a connection string to specify the connection parameters
to an Azure Quantum Workspace by calling
:obj:`~ Workspace.from_connection_string() <Workspace.from_connection_string>`.
If the Azure Quantum workspace does not have linked storage, the caller
must also pass a valid Azure storage account connection string.
:param subscription_id:
The Azure subscription ID.
Ignored if resource_id is specified.
:param resource_group:
The Azure resource group name.
Ignored if resource_id is specified.
:param name:
The Azure Quantum workspace name.
Ignored if resource_id is specified.
:param storage:
The Azure storage account connection string.
Required only if the specified Azure Quantum
workspace does not have linked storage.
:param resource_id:
The resource ID of the Azure Quantum workspace.
:param location:
The Azure region where the Azure Quantum workspace is provisioned.
This may be specified as a region name such as
\"East US\" or a location name such as \"eastus\".
:param credential:
The credential to use to connect to Azure services.
Normally one of the credential types from [Azure.Identity](https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes).
Defaults to \"DefaultAzureCredential\", which will attempt multiple
forms of authentication.
:param user_agent:
Add the specified value as a prefix to the HTTP User-Agent header
when communicating to the Azure Quantum service.
"""
def __init__(
self,
subscription_id: Optional[str] = None,
resource_group: Optional[str] = None,
name: Optional[str] = None,
storage: Optional[str] = None,
resource_id: Optional[str] = None,
location: Optional[str] = None,
credential: Optional[object] = None,
user_agent: Optional[str] = None,
**kwargs: Any,
) -> None:
connection_params = WorkspaceConnectionParams(
location=location,
subscription_id=subscription_id,
resource_group=resource_group,
workspace_name=name,
credential=credential,
resource_id=resource_id,
user_agent=user_agent,
**kwargs
).default_from_env_vars()
logger.info("Using %s environment.", connection_params.environment)
connection_params.assert_complete()
connection_params.on_new_client_request = self._on_new_client_request
self._connection_params = connection_params
self._storage = storage
# Create QuantumClient
self._client = self._create_client()
def _on_new_client_request(self) -> None:
"""
An internal callback method used by the WorkspaceConnectionParams
to ask the Workspace to recreate the underlying Azure SDK REST API client.
This is used when some value (such as the UserAgent) has changed
in the WorkspaceConnectionParams and requires the client to be
recreated.
"""
self._client = self._create_client()
@property
def location(self) -> str:
"""
Returns the Azure location of the Quantum Workspace.
:return: Azure location name.
:rtype: str
"""
return self._connection_params.location
@property
def subscription_id(self) -> str:
"""
Returns the Azure Subscription ID of the Quantum Workspace.
:return: Azure Subscription ID.
:rtype: str
"""
return self._connection_params.subscription_id
@property
def resource_group(self) -> str:
"""
Returns the Azure Resource Group of the Quantum Workspace.
:return: Azure Resource Group name.
:rtype: str
"""
return self._connection_params.resource_group
@property
def name(self) -> str:
"""
Returns the Name of the Quantum Workspace.
:return: Azure Quantum Workspace name.
:rtype: str
"""
return self._connection_params.workspace_name
@property
def credential(self) -> Any:
"""
Returns the Credential used to connect to the Quantum Workspace.
:return: Azure SDK Credential from [Azure.Identity](https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes).
:rtype: typing.Any
"""
return self._connection_params.credential
@property
def storage(self) -> str:
"""
Returns the Azure Storage account name associated with the Quantum Workspace.
:return: Azure Storage account name.
:rtype: str
"""
return self._storage
def _create_client(self) -> QuantumClient:
""""
An internal method to (re)create the underlying Azure SDK REST API client.
:return: Azure SDK REST API client for Azure Quantum.
:rtype: QuantumClient
"""
connection_params = self._connection_params
kwargs = {}
if connection_params.api_version:
kwargs["api_version"] = connection_params.api_version
client = QuantumClient(
credential=connection_params.get_credential_or_default(),
subscription_id=connection_params.subscription_id,
resource_group_name=connection_params.resource_group,
workspace_name=connection_params.workspace_name,
azure_region=connection_params.location,
user_agent=connection_params.get_full_user_agent(),
credential_scopes = [ConnectionConstants.DATA_PLANE_CREDENTIAL_SCOPE],
endpoint=connection_params.quantum_endpoint,
authentication_policy=connection_params.get_auth_policy(),
**kwargs
)
return client
@property
def user_agent(self) -> str:
"""
Returns the Workspace's UserAgent string that is sent to
the service via the UserAgent header.
:return: User Agent string.
:rtype: str
"""
return self._connection_params.get_full_user_agent()
def append_user_agent(self, value: str) -> None:
"""
Append a new value to the Workspace's UserAgent.
The values are appended using a dash.
:param value:
UserAgent value to add, e.g. "azure-quantum-<plugin>"
"""
self._connection_params.append_user_agent(value=value)
@classmethod
def from_connection_string(cls, connection_string: str, **kwargs) -> Workspace:
"""
Creates a new Azure Quantum Workspace client from a connection string.
:param connection_string:
A valid connection string, usually obtained from the
`Quantum Workspace -> Operations -> Access Keys` blade in the Azure Portal.
:return: New Azure Quantum Workspace client.
:rtype: Workspace
"""
connection_params = WorkspaceConnectionParams(connection_string=connection_string)
return cls(
subscription_id=connection_params.subscription_id,
resource_group=connection_params.resource_group,
name=connection_params.workspace_name,
location=connection_params.location,
credential=connection_params.get_credential_or_default(),
**kwargs)
def _get_top_level_items_client(self) -> TopLevelItemsOperations:
"""
Returns the internal Azure SDK REST API client
for the `{workspace}/topLevelItems` API.
:return: REST API client for the `topLevelItems` API.
:rtype: TopLevelItemsOperations
"""
return self._client.top_level_items
def _get_sessions_client(self) -> SessionsOperations:
"""
Returns the internal Azure SDK REST API client
for the `{workspace}/sessions` API.
:return: REST API client for the `sessions` API.
:rtype: SessionsOperations
"""
return self._client.sessions
def _get_jobs_client(self) -> JobsOperations:
"""
Returns the internal Azure SDK REST API client
for the `{workspace}/jobs` API.
:return: REST API client for the `jobs` API.
:rtype: JobsOperations
"""
return self._client.jobs
def _get_workspace_storage_client(self) -> StorageOperations:
"""
Returns the internal Azure SDK REST API client
for the `{workspace}/storage` API.
:return: REST API client for the `storage` API.
:rtype: StorageOperations
"""
return self._client.storage
def _get_quotas_client(self) -> QuotasOperations:
"""
Returns the internal Azure SDK REST API client
for the `{workspace}/quotas` API.
:return: REST API client for the `quotas` API.
:rtype: QuotasOperations
"""
return self._client.quotas
def _get_linked_storage_sas_uri(
self,
container_name: str,
blob_name: Optional[str] = None
) -> str:
"""
Calls the service and returns a container/blob SAS URL
for the Storage associated with the Quantum Workspace.
:param container_name:
The name of the storage container.
:param blob_name:
Optional name of the blob. Defaults to `None`.
:return: Storage Account SAS URL to a container or blob.
:rtype: str
"""
client = self._get_workspace_storage_client()
blob_details = BlobDetails(
container_name=container_name, blob_name=blob_name
)
container_uri = client.sas_uri(blob_details=blob_details)
logger.debug("Container URI from service: %s", container_uri)
return container_uri.sas_uri
def submit_job(self, job: Job) -> Job:
"""
Submits a job to be processed in the Workspace.
:param job:
Job to submit.
:return: Azure Quantum Job that was submitted, with an updated status.
:rtype: Job
"""
client = self._get_jobs_client()
details = client.create(
job.details.id, job.details
)
return Job(self, details)
def cancel_job(self, job: Job) -> Job:
"""
Requests the Workspace to cancel the
execution of a job.
:param job:
Job to cancel.
:return: Azure Quantum Job that was requested to be cancelled, with an updated status.
:rtype: Job
"""
client = self._get_jobs_client()
client.cancel(job.details.id)
details = client.get(job.id)
return Job(self, details)
def get_job(self, job_id: str) -> Job:
"""
Returns the job corresponding to the given id.
:param job_id:
Id of a job to fetch.
:return: Azure Quantum Job.
:rtype: Job
"""
# pylint: disable=import-outside-toplevel
from azure.quantum.target.target_factory import TargetFactory
from azure.quantum.target import Target
client = self._get_jobs_client()
details = client.get(job_id)
target_factory = TargetFactory(base_cls=Target, workspace=self)
# pylint: disable=protected-access
target_cls = target_factory._target_cls(
details.provider_id,
details.target)
job_cls = target_cls._get_job_class()
return job_cls(self, details)
def list_jobs(
self,
name_match: Optional[str] = None,
status: Optional[JobStatus] = None,
created_after: Optional[datetime] = None
) -> List[Job]:
"""
Returns list of jobs that meet optional (limited) filter criteria.
:param name_match:
Optional Regular Expression for job name matching. Defaults to `None`.
:param status:
Optional filter by job status. Defaults to `None`.
:param created_after:
Optional filter by jobs that were created after the given time. Defaults to `None`.
:return: Jobs that matched the search criteria.
:rtype: typing.List[Job]
"""
client = self._get_jobs_client()
jobs = client.list()
result = []
for j in jobs:
deserialized_job = Job(self, j)
if deserialized_job.matches_filter(name_match, status, created_after):
result.append(deserialized_job)
return result
def _get_target_status(
self,
name: Optional[str] = None,
provider_id: Optional[str] = None,
) -> List[Tuple[str, TargetStatus]]:
"""
Returns a list of tuples containing the `Provider ID` and `Target Status`,
with the option of filtering that list by a combination of Provider ID and Target Name.
:param name:
Optional name of the Target to filter for. Defaults to `None`.
:param provider_id:
Optional Provider ID to filter for. Defaults to `None`.
:return: List of tuples containing Provider ID and TargetStatus.
:rtype: typing.List[typing.Tuple[str, TargetStatus]]
"""
return [
(provider.id, target)
for provider in self._client.providers.get_status()
for target in provider.targets
if (provider_id is None or provider.id.lower() == provider_id.lower())
and (name is None or target.id.lower() == name.lower())
]
def get_targets(
self,
name: Optional[str] = None,
provider_id: Optional[str] = None,
) -> Union[Target, Iterable[Target]]:
"""
Returns all available targets for this workspace filtered by Target name and Provider ID.
If the target name is passed, a single `Target` object will be returned.
Otherwise it returns a iterable/list of `Target` objects, optionally filtered by the Provider ID.
:param name:
Optional target name to filter by, defaults to `None`.
:param provider_id:
Optional provider Id to filter by, defaults to `None`.
:return: A single Azure Quantum Target or a iterable/list of Targets.
:rtype: typing.Union[Target, typing.Iterable[Target]]
"""
# pylint: disable=import-outside-toplevel
from azure.quantum.target.target_factory import TargetFactory
from azure.quantum.target import Target
target_factory = TargetFactory(
base_cls=Target,
workspace=self
)
return target_factory.get_targets(
name=name,
provider_id=provider_id
)
def get_quotas(self) -> List[Dict[str, Any]]:
"""
Get a list of quotas for the given workspace.
Each quota is represented as a dictionary, containing the
properties for that quota.
Common Quota properties are:
- "dimension": The dimension that the quota is applied to.
- "scope": The scope that the quota is applied to.
- "provider_id": The provider that the quota is applied to.
- "utilization": The current utilization of the quota.
- "limit": The limit of the quota.
- "period": The period that the quota is applied to.
:return: Workspace quotas.
:rtype: typing.List[typing.Dict[str, typing.Any]
"""
client = self._get_quotas_client()
return [q.as_dict() for q in client.list()]
def list_top_level_items(
self
) -> List[Union[Job, Session]]:
"""
Get a list of top level items for the given workspace,
which can be standalone Jobs (Jobs not associated with a Session)
or Sessions (which can contain Jobs).
:return: List of Workspace top level Jobs or Sessions.
:rtype: typing.List[typing.Union[Job, Session]]
"""
client = self._get_top_level_items_client()
item_details_list = client.list()
result = [WorkspaceItemFactory.__new__(workspace=self, item_details=item_details)
for item_details in item_details_list]
return result
def list_sessions(
self
) -> List[Session]:
"""
Get the list of sessions in the given workspace.
:return: List of Workspace Sessions.
:rtype: typing.List[Session]
"""
client = self._get_sessions_client()
session_details_list = client.list()
result = [Session(workspace=self,details=session_details)
for session_details in session_details_list]
return result
def open_session(
self,
session: Session,
) -> None:
"""
Opens/creates a session in the given workspace.
:param session:
The session to be opened/created.
:return: A new open Azure Quantum Session.
:rtype: Session
"""
client = self._get_sessions_client()
session.details = client.open(
session_id=session.id,
session=session.details)
def close_session(
self,
session: Session
) -> None:
"""
Closes a session in the given workspace if the
session is not in a terminal state.
Otherwise, just refreshes the session details.
:param session:
The session to be closed.
"""
client = self._get_sessions_client()
if not session.is_in_terminal_state():
session.details = client.close(session_id=session.id)
else:
session.details = client.get(session_id=session.id)
if session.target:
if (session.target.latest_session
and session.target.latest_session.id == session.id):
session.target.latest_session.details = session.details
def refresh_session(
self,
session: Session
) -> None:
"""
Updates the session details with the latest information
from the workspace.
:param session:
The session to be refreshed.
"""
session.details = self.get_session(session_id=session.id).details
def get_session(
self,
session_id: str
) -> Session:
"""
Gets a session from the workspace.
:param session_id:
The id of session to be retrieved.
:return: Azure Quantum Session
:rtype: Session
"""
client = self._get_sessions_client()
session_details = client.get(session_id=session_id)
result = Session(workspace=self, details=session_details)
return result
def list_session_jobs(
self,
session_id: str
) -> List[Job]:
"""
Gets all jobs associated with a session.
:param session_id:
The id of session.
:return: List of all jobs associated with a session.
:rtype: typing.List[Job]
"""
client = self._get_sessions_client()
job_details_list = client.jobs_list(session_id=session_id)
result = [Job(workspace=self, job_details=job_details)
for job_details in job_details_list]
return result
def get_container_uri(
self,
job_id: Optional[str] = None,
container_name: Optional[str] = None,
container_name_format: Optional[str] = "job-{job_id}"
) -> str:
"""
Get container URI based on job ID or container name.
Creates a new container if it does not yet exist.
:param job_id:
Job ID, defaults to `None`.
:param container_name:
Container name, defaults to `None`.
:param container_name_format:
Container name format, defaults to "job-{job_id}".
:return: Container URI.
:rtype: str
"""
if container_name is None:
if job_id is not None:
container_name = container_name_format.format(job_id=job_id)
elif job_id is None:
container_name = f"{self.name}-data"
# Create container URI and get container client
if self.storage is None:
# Get linked storage account from the service, create
# a new container if it does not yet exist
container_uri = self._get_linked_storage_sas_uri(
container_name
)
container_client = ContainerClient.from_container_url(
container_uri
)
create_container_using_client(container_client)
else:
# Use the storage acount specified to generate container URI,
# create a new container if it does not yet exist
container_uri = get_container_uri(
self.storage, container_name
)
return container_uri
|
azure-quantum-python/azure-quantum/azure/quantum/workspace.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/azure/quantum/workspace.py",
"repo_id": "azure-quantum-python",
"token_count": 9294
}
| 377 |
##
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
##
from typing import Dict, Any, Union, Optional
from unittest.mock import MagicMock
import pytest
from numpy import pi, mean
from azure.quantum.target import Rigetti
from azure.quantum.target.rigetti import Result, InputParams
from common import QuantumTestBase, DEFAULT_TIMEOUT_SECS
READOUT = "ro"
BELL_STATE_QUIL = f"""
DECLARE {READOUT} BIT[2]
H 0
CNOT 0 1
MEASURE 0 {READOUT}[0]
MEASURE 1 {READOUT}[1]
"""
SYNTAX_ERROR_QUIL = "a\n" + BELL_STATE_QUIL
PARAMETER_NAME = "theta"
PARAMETRIZED_QUIL = f"""
DECLARE {READOUT} BIT[1]
DECLARE {PARAMETER_NAME} REAL[1]
RX({PARAMETER_NAME}) 0
MEASURE 0 {READOUT}[0]
"""
@pytest.mark.rigetti
@pytest.mark.live_test
class TestRigettiTarget(QuantumTestBase):
"""Tests the azure.quantum.target.Rigetti class."""
def _run_job(
self,
quil: str,
input_params: Union[InputParams, Dict[str, Any], None],
shots: int = None,
) -> Optional[Result]:
workspace = self.create_workspace()
target = Rigetti(workspace=workspace)
job = target.submit(
input_data=quil,
name="qdk-python-test",
shots=shots,
input_params=input_params,
)
job.wait_until_completed(timeout_secs=DEFAULT_TIMEOUT_SECS)
job.refresh()
job = workspace.get_job(job.id)
self.assertTrue(job.has_completed())
return Result(job)
def test_job_submit_rigetti_typed_input_params(self) -> None:
num_shots = 5
result = self._run_job(BELL_STATE_QUIL, InputParams(count=num_shots))
self.assertIsNotNone(result)
readout = result[READOUT]
self.assertEqual(len(readout), num_shots)
for shot in readout:
self.assertEqual(len(shot), 2, "Bell state program should only measure 2 qubits")
def test_job_submit_rigetti_typed_input_params_with_shots(self) -> None:
shots = 5
result = self._run_job(BELL_STATE_QUIL, input_params=InputParams(), shots=shots)
self.assertIsNotNone(result)
readout = result[READOUT]
self.assertEqual(len(readout), shots)
for shot in readout:
self.assertEqual(len(shot), 2, "Bell state program should only measure 2 qubits")
def test_job_submit_rigetti_with_conflicting_shots_and_count_from_input_params(self) -> None:
shots = 5
with pytest.warns(
match="Parameter 'shots' conflicts with the 'count' field of the 'input_params' parameter. "
"Please, provide only one option for setting shots. Defaulting to 'shots' parameter."
):
result = self._run_job(
BELL_STATE_QUIL,
input_params={"count": 1},
shots=shots
)
self.assertIsNotNone(result)
readout = result[READOUT]
self.assertEqual(len(readout), shots)
for shot in readout:
self.assertEqual(len(shot), 2, "Bell state program should only measure 2 qubits")
def test_job_submit_rigetti_dict_input_params(self) -> None:
num_shots = 5
result = self._run_job(BELL_STATE_QUIL, {"count": num_shots})
self.assertIsNotNone(result)
readout = result[READOUT]
self.assertEqual(len(readout), num_shots)
for shot in readout:
self.assertEqual(len(shot), 2, "Bell state program should only measure 2 qubits")
def test_job_submit_rigetti_dict_input_params_with_shots(self) -> None:
shots = 5
result = self._run_job(BELL_STATE_QUIL,input_params={}, shots=shots)
self.assertIsNotNone(result)
readout = result[READOUT]
self.assertEqual(len(readout), shots)
for shot in readout:
self.assertEqual(len(shot), 2, "Bell state program should only measure 2 qubits")
def test_job_submit_rigetti_default_input_params(self) -> None:
result = self._run_job(BELL_STATE_QUIL, None)
self.assertIsNotNone(result)
readout = result[READOUT]
self.assertEqual(len(readout), 1)
for shot in readout:
self.assertEqual(len(shot), 2, "Bell state program should only measure 2 qubits")
def test_job_submit_rigetti_with_count(self) -> None:
shots = 100
with pytest.warns(
match="Field 'count' from the 'input_params' parameter is subject to change in future versions. "
"Please, use 'shots' parameter instead."
):
result = self._run_job(BELL_STATE_QUIL, input_params={"count": shots})
self.assertIsNotNone(result)
readout = result[READOUT]
self.assertEqual(len(readout), shots)
def test_quil_syntax_error(self) -> None:
with pytest.raises(RuntimeError) as err:
self._run_job(SYNTAX_ERROR_QUIL, None)
self.assertIn("could not be executed because the operator a is not known", str(
err.value
))
def test_parametrized_quil(self) -> None:
result = self._run_job(
PARAMETRIZED_QUIL,
InputParams(
count=5, substitutions={PARAMETER_NAME: [[0.0], [pi], [2 * pi]]}
),
)
self.assertIsNotNone(result)
readout = result[READOUT]
self.assertEqual(len(readout), 5 * 3)
self.assertEqual(mean(readout[0:5]), 0)
self.assertEqual(mean(readout[5:10]), 1)
self.assertEqual(mean(readout[10:15]), 0)
class FakeJob:
def __init__(self, json: bytes, details=None) -> None:
self.json = json
if details is None:
details = MagicMock()
details.status = "Succeeded"
self.details = details
def download_data(self, _) -> bytes:
return self.json
class TestResult(QuantumTestBase):
def test_integers(self) -> None:
result = Result(FakeJob(b'{"ro": [[0, 0], [1, 1]]}'))
self.assertEqual(result[READOUT], [[0, 0], [1, 1]])
def test_unsuccessful_job(self) -> None:
details = MagicMock()
details.status = "Failed"
details.error_data = "Some error message"
with pytest.raises(RuntimeError) as err:
Result(FakeJob(b'{"ro": [[0, 0], [1, 1]]}', details))
err_string = str(err.value)
self.assertIn(details.status, err_string)
self.assertIn(details.error_data, err_string)
|
azure-quantum-python/azure-quantum/tests/unit/test_rigetti.py/0
|
{
"file_path": "azure-quantum-python/azure-quantum/tests/unit/test_rigetti.py",
"repo_id": "azure-quantum-python",
"token_count": 2911
}
| 378 |
---
page_type: sample
author: msoeken
description: A practical introduction into quantum signal processing (QSP)
ms.author: [email protected]
ms.date: 05/18/2022
languages:
- python
products:
- azure-quantum
---
# A practical introduction into quantum signal processing (QSP)
This is an Azure Quantum sample illustrates how to evaluate polynomials using Qiskit, a single qubit, and quantum signal processing.
This sample is available as part of the Azure Quantum notebook samples gallery in the Azure Portal. For an example of how to run these notebooks in Azure, see [this getting started guide](https://learn.microsoft.com/azure/quantum/get-started-jupyter-notebook).
## Manifest
- [signal-processing.ipynb](https://github.com/microsoft/azure-quantum-python/blob/main/samples/quantum-signal-processing/signal-processing.ipynb): Azure Quantum notebook for quantum signal processing
|
azure-quantum-python/samples/quantum-signal-processing/README.md/0
|
{
"file_path": "azure-quantum-python/samples/quantum-signal-processing/README.md",
"repo_id": "azure-quantum-python",
"token_count": 247
}
| 379 |
#!/bin/bash
# assume working directory to be "visualization/build"
cd ../react-lib
npm install
if [ $? -ne 0 ]; then
echo 'Failed to install: react-lib'
exit 1
else
echo 'Successfully install: react-lib'
fi
npm run lint
npm run sortpackagejson || true
npm run build:prod
if [ $? -ne 0 ]; then
echo 'Failed to build: react-lib'
exit 1
else
echo 'Successfully build: react-lib'
fi
npm link
if [ $? -ne 0 ]; then
echo 'Failed to create link: react-lib'
exit 1
else
echo 'Successfully created link: react-lib'
fi
cd node_modules/react
npm link
if [ $? -ne 0 ]; then
echo 'Failed to create link: node_modules/react'
exit 1
else
echo 'Successfully created link: node_modules/react'
fi
cd ../../../js-lib
npm link react quantum-visualization
if [ $? -ne 0 ]; then
echo 'Failed to link react and quantum-visualization to js-lib.'
exit 1
else
echo 'Successfully linked react and quantum-visualization to js-lib'
fi
npm run sortpackagejson || true
npm run build:prod
if [ $? -ne 0 ]; then
echo 'Failed to build js-lib'
exit 1
else
echo 'Successfully built js-lib'
fi
echo 'Successfully built js-lib and dependencies.'
echo 'js-lib to be published to microsoft-visualization/index.js artifact.'
exit 0
|
azure-quantum-python/visualization/build/build-jslib.sh/0
|
{
"file_path": "azure-quantum-python/visualization/build/build-jslib.sh",
"repo_id": "azure-quantum-python",
"token_count": 429
}
| 380 |
/*------------------------------------
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
All rights reserved.
------------------------------------ */
import React from "react";
import { create } from "react-test-renderer";
import LineChart, { LineChartProps } from "../LineChart";
describe("Line chart tests", () => {
it("Verify Line Chart", () => {
const chartDictionary: { [key: string]: any } = {
numberTFactoryInvocations: "100",
numberTStates: "5",
algorithmRuntime: "10 ms",
tFactoryRuntime: "1 ms",
algorithmRuntimeFormatted: "10 ms",
tFactoryRuntimeFormatted: "1 ms",
chartLength: 800,
};
const lineProps: LineChartProps = {
width: 1000,
height: 1000,
chartData: chartDictionary,
};
const component = create(<LineChart {...lineProps}></LineChart>);
expect(component.toJSON()).toMatchSnapshot("LineChart");
});
});
|
azure-quantum-python/visualization/react-lib/src/components/d3-visualization-components/__tests__/LineChart.test.tsx/0
|
{
"file_path": "azure-quantum-python/visualization/react-lib/src/components/d3-visualization-components/__tests__/LineChart.test.tsx",
"repo_id": "azure-quantum-python",
"token_count": 317
}
| 381 |
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
version: 2
sphinx:
configuration: docs/conf.py
build:
os: "ubuntu-20.04"
tools:
python: "3"
nodejs: "16"
formats: all
python:
install:
- requirements: docs/requirements.txt
- method: pip
path: ./python
|
bistring/.readthedocs.yml/0
|
{
"file_path": "bistring/.readthedocs.yml",
"repo_id": "bistring",
"token_count": 140
}
| 382 |
{
"compilerOptions": {
"target": "es2020",
"module": "esnext",
"moduleResolution": "node",
"esModuleInterop": true,
"removeComments": true,
"declaration": true,
"outDir": "dist",
"declarationDir": ".",
"strict": true,
"sourceMap": true,
"declarationMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"dist"
],
"typedocOptions": {
"excludePrivate": true
}
}
|
bistring/js/tsconfig.json/0
|
{
"file_path": "bistring/js/tsconfig.json",
"repo_id": "bistring",
"token_count": 262
}
| 383 |
[mypy]
mypy_path = ./stubs
disallow_subclassing_any = True
disallow_untyped_calls = True
disallow_untyped_defs = True
disallow_incomplete_defs = True
disallow_untyped_decorators = True
no_implicit_optional = True
warn_no_return = True
warn_return_any = True
warn_unreachable = True
warn_incomplete_stub = True
warn_redundant_casts = True
show_error_context = True
|
bistring/python/mypy.ini/0
|
{
"file_path": "bistring/python/mypy.ini",
"repo_id": "bistring",
"token_count": 134
}
| 384 |
# Instructions for Contributing Code
## Contributing bug fixes and features
The Bot Framework team is currently accepting contributions in the form of bug fixes and new
features. Any submission must have an issue tracking it in the issue tracker that has
been approved by the Bot Framework team. Your pull request should include a link to
the bug that you are fixing. If you've submitted a PR for a bug, please post a
comment in the bug to avoid duplication of effort.
## Legal
If your contribution is more than 15 lines of code, you will need to complete a Contributor
License Agreement (CLA). Briefly, this agreement testifies that you are granting us permission
to use the submitted change according to the terms of the project's license, and that the work
being submitted is under appropriate copyright.
Please submit a Contributor License Agreement (CLA) before submitting a pull request.
You may visit https://cla.azure.com to sign digitally. Alternatively, download the
agreement ([Microsoft Contribution License Agreement.docx](https://www.codeplex.com/Download?ProjectName=typescript&DownloadId=822190) or
[Microsoft Contribution License Agreement.pdf](https://www.codeplex.com/Download?ProjectName=typescript&DownloadId=921298)), sign, scan,
and email it back to <[email protected]>. Be sure to include your github user name along with the agreement. Once we have received the
signed CLA, we'll review the request.
|
botbuilder-python/Contributing.md/0
|
{
"file_path": "botbuilder-python/Contributing.md",
"repo_id": "botbuilder-python",
"token_count": 342
}
| 385 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""
This sample shows how to create a bot that demonstrates the following:
- Use [LUIS](https://www.luis.ai) to implement core AI capabilities.
- Implement a multi-turn conversation using Dialogs.
- Handle user interruptions for such things as `Help` or `Cancel`.
- Prompt for and validate requests for information from the user.
"""
from http import HTTPStatus
from aiohttp import web
from aiohttp.web import Request, Response, json_response
from botbuilder.core import (
ConversationState,
MemoryStorage,
UserState,
)
from botbuilder.core.integration import aiohttp_error_middleware
from botbuilder.integration.aiohttp import ConfigurationBotFrameworkAuthentication
from botbuilder.schema import Activity
from config import DefaultConfig
from dialogs import MainDialog, BookingDialog
from bots import DialogAndWelcomeBot
from adapter_with_error_handler import AdapterWithErrorHandler
from flight_booking_recognizer import FlightBookingRecognizer
CONFIG = DefaultConfig()
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = ConfigurationBotFrameworkAuthentication(CONFIG)
# Create MemoryStorage, UserState and ConversationState
MEMORY = MemoryStorage()
USER_STATE = UserState(MEMORY)
CONVERSATION_STATE = ConversationState(MEMORY)
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE)
# Create dialogs and Bot
RECOGNIZER = FlightBookingRecognizer(CONFIG)
BOOKING_DIALOG = BookingDialog()
DIALOG = MainDialog(RECOGNIZER, BOOKING_DIALOG)
BOT = DialogAndWelcomeBot(CONVERSATION_STATE, USER_STATE, DIALOG)
# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
# Main bot message handler.
if "application/json" in req.headers["Content-Type"]:
body = await req.json()
else:
return Response(status=HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
activity = Activity().deserialize(body)
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
response = await ADAPTER.process_activity(auth_header, activity, BOT.on_turn)
if response:
return json_response(data=response.body, status=response.status)
return Response(status=HTTPStatus.OK)
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
if __name__ == "__main__":
try:
web.run_app(APP, host="localhost", port=CONFIG.PORT)
except Exception as error:
raise error
|
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/app.py/0
|
{
"file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/app.py",
"repo_id": "botbuilder-python",
"token_count": 815
}
| 386 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import sys
import traceback
from datetime import datetime
from http import HTTPStatus
from aiohttp import web
from aiohttp.web import Request, Response, json_response
from botbuilder.core import TurnContext
from botbuilder.core.integration import aiohttp_error_middleware
from botbuilder.integration.aiohttp import CloudAdapter, ConfigurationBotFrameworkAuthentication
from botbuilder.schema import Activity, ActivityTypes
from bot import MyBot
from config import DefaultConfig
CONFIG = DefaultConfig()
# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
ADAPTER = CloudAdapter(ConfigurationBotFrameworkAuthentication(CONFIG))
# Catch-all for errors.
async def on_error(context: TurnContext, error: Exception):
# This check writes out errors to console log .vs. app insights.
# NOTE: In production environment, you should consider logging this to Azure
# application insights.
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
traceback.print_exc()
# Send a message to the user
await context.send_activity("The bot encountered an error or bug.")
await context.send_activity(
"To continue to run this bot, please fix the bot source code."
)
# Send a trace activity if we're talking to the Bot Framework Emulator
if context.activity.channel_id == "emulator":
# Create a trace activity that contains the error object
trace_activity = Activity(
label="TurnError",
name="on_turn_error Trace",
timestamp=datetime.utcnow(),
type=ActivityTypes.trace,
value=f"{error}",
value_type="https://www.botframework.com/schemas/error",
)
# Send a trace activity, which will be displayed in Bot Framework Emulator
await context.send_activity(trace_activity)
ADAPTER.on_turn_error = on_error
# Create the Bot
BOT = MyBot()
# Listen for incoming requests on /api/messages
async def messages(req: Request) -> Response:
# Main bot message handler.
if "application/json" in req.headers["Content-Type"]:
body = await req.json()
else:
return Response(status=HTTPStatus.UNSUPPORTED_MEDIA_TYPE)
activity = Activity().deserialize(body)
auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""
response = await ADAPTER.process_activity(auth_header, activity, BOT.on_turn)
if response:
return json_response(data=response.body, status=response.status)
return Response(status=HTTPStatus.OK)
APP = web.Application(middlewares=[aiohttp_error_middleware])
APP.router.add_post("/api/messages", messages)
if __name__ == "__main__":
try:
web.run_app(APP, host="localhost", port=CONFIG.PORT)
except Exception as error:
raise error
|
botbuilder-python/generators/app/templates/echo/{{cookiecutter.bot_name}}/app.py/0
|
{
"file_path": "botbuilder-python/generators/app/templates/echo/{{cookiecutter.bot_name}}/app.py",
"repo_id": "botbuilder-python",
"token_count": 976
}
| 387 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import hashlib
import hmac
import json
import os
import uuid
import datetime
import time
import aiounittest
import requests
import pytest
SKIP = os.getenv("SlackChannel") == ""
class SlackClient(aiounittest.AsyncTestCase):
@pytest.mark.skipif(not SKIP, reason="Needs the env.SlackChannel to run.")
async def test_send_and_receive_slack_message(self):
# Arrange
echo_guid = str(uuid.uuid4())
# Act
await self._send_message_async(echo_guid)
response = await self._receive_message_async()
# Assert
self.assertEqual(f"Echo: {echo_guid}", response)
async def _receive_message_async(self) -> str:
last_message = ""
i = 0
while "Echo" not in last_message and i < 60:
url = (
f"{self._slack_url_base}/conversations.history?token="
f"{self._slack_bot_token}&channel={self._slack_channel}"
)
response = requests.get(
url,
)
last_message = response.json()["messages"][0]["text"]
time.sleep(1)
i += 1
return last_message
async def _send_message_async(self, echo_guid: str) -> None:
timestamp = str(int(datetime.datetime.utcnow().timestamp()))
message = self._create_message(echo_guid)
hub_signature = self._create_hub_signature(message, timestamp)
headers = {
"X-Slack-Request-Timestamp": timestamp,
"X-Slack-Signature": hub_signature,
"Content-type": "application/json",
}
url = f"https://{self._bot_name}.azurewebsites.net/api/messages"
requests.post(url, headers=headers, data=message)
def _create_message(self, echo_guid: str) -> str:
slack_event = {
"client_msg_id": "client_msg_id",
"type": "message",
"text": echo_guid,
"user": "userId",
"channel": self._slack_channel,
"channel_type": "im",
}
message = {
"token": self._slack_verification_token,
"team_id": "team_id",
"api_app_id": "apiAppId",
"event": slack_event,
"type": "event_callback",
}
return json.dumps(message)
def _create_hub_signature(self, message: str, timestamp: str) -> str:
signature = ["v0", timestamp, message]
base_string = ":".join(signature)
computed_signature = "V0=" + hmac.new(
bytes(self._slack_client_signing_secret, encoding="utf8"),
msg=bytes(base_string, "utf-8"),
digestmod=hashlib.sha256,
).hexdigest().upper().replace("-", "")
return computed_signature
@classmethod
def setUpClass(cls) -> None:
cls._slack_url_base: str = "https://slack.com/api"
cls._slack_channel = os.getenv("SlackChannel")
if not cls._slack_channel:
raise Exception('Environment variable "SlackChannel" not found.')
cls._slack_bot_token = os.getenv("SlackBotToken")
if not cls._slack_bot_token:
raise Exception('Environment variable "SlackBotToken" not found.')
cls._slack_client_signing_secret = os.getenv("SlackClientSigningSecret")
if not cls._slack_client_signing_secret:
raise Exception(
'Environment variable "SlackClientSigningSecret" not found.'
)
cls._slack_verification_token = os.getenv("SlackVerificationToken")
if not cls._slack_verification_token:
raise Exception('Environment variable "SlackVerificationToken" not found.')
cls._bot_name = os.getenv("BotName")
if not cls._bot_name:
raise Exception('Environment variable "BotName" not found.')
|
botbuilder-python/libraries/botbuilder-adapters-slack/tests/test_slack_client.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-adapters-slack/tests/test_slack_client.py",
"repo_id": "botbuilder-python",
"token_count": 1781
}
| 388 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import platform
from collections import OrderedDict
from typing import Dict, List, Union
import azure.cognitiveservices.language.luis.runtime.models as runtime_models
from azure.cognitiveservices.language.luis.runtime.models import (
CompositeEntityModel,
EntityModel,
LuisResult,
)
from msrest import Serializer
from botbuilder.core import IntentScore, RecognizerResult
from .. import __title__, __version__
class LuisUtil:
"""
Utility functions used to extract and transform data from Luis SDK
"""
_metadata_key: str = "$instance"
@staticmethod
def normalized_intent(intent: str) -> str:
return intent.replace(".", "_").replace(" ", "_")
@staticmethod
def get_intents(luis_result: LuisResult) -> Dict[str, IntentScore]:
if luis_result.intents is not None:
return {
LuisUtil.normalized_intent(i.intent): IntentScore(i.score or 0)
for i in luis_result.intents
}
return {
LuisUtil.normalized_intent(
luis_result.top_scoring_intent.intent
): IntentScore(luis_result.top_scoring_intent.score or 0)
}
@staticmethod
def extract_entities_and_metadata(
entities: List[EntityModel],
composite_entities: List[CompositeEntityModel],
verbose: bool,
) -> Dict[str, object]:
entities_and_metadata = {}
if verbose:
entities_and_metadata[LuisUtil._metadata_key] = {}
composite_entity_types = set()
# We start by populating composite entities so that entities covered by them are removed from the entities list
if composite_entities:
composite_entity_types = set(ce.parent_type for ce in composite_entities)
current = entities
for composite_entity in composite_entities:
current = LuisUtil.populate_composite_entity_model(
composite_entity, current, entities_and_metadata, verbose
)
entities = current
for entity in entities:
# we'll address composite entities separately
if entity.type in composite_entity_types:
continue
LuisUtil.add_property(
entities_and_metadata,
LuisUtil.extract_normalized_entity_name(entity),
LuisUtil.extract_entity_value(entity),
)
if verbose:
LuisUtil.add_property(
entities_and_metadata[LuisUtil._metadata_key],
LuisUtil.extract_normalized_entity_name(entity),
LuisUtil.extract_entity_metadata(entity),
)
return entities_and_metadata
@staticmethod
def number(value: object) -> Union[int, float]:
if value is None:
return None
try:
str_value = str(value)
int_value = int(str_value)
return int_value
except ValueError:
float_value = float(str_value)
return float_value
@staticmethod
def extract_entity_value(entity: EntityModel) -> object:
if (
entity.additional_properties is None
or "resolution" not in entity.additional_properties
):
return entity.entity
resolution = entity.additional_properties["resolution"]
if entity.type.startswith("builtin.datetime."):
return resolution
if entity.type.startswith("builtin.datetimeV2."):
if not resolution["values"]:
return resolution
resolution_values = resolution["values"]
val_type = resolution["values"][0]["type"]
timexes = [val["timex"] for val in resolution_values]
distinct_timexes = list(OrderedDict.fromkeys(timexes))
return {"type": val_type, "timex": distinct_timexes}
if entity.type in {"builtin.number", "builtin.ordinal"}:
return LuisUtil.number(resolution["value"])
if entity.type == "builtin.percentage":
svalue = str(resolution["value"])
if svalue.endswith("%"):
svalue = svalue[:-1]
return LuisUtil.number(svalue)
if entity.type in {
"builtin.age",
"builtin.dimension",
"builtin.currency",
"builtin.temperature",
}:
units = resolution["unit"]
val = LuisUtil.number(resolution["value"])
obj = {}
if val is not None:
obj["number"] = val
obj["units"] = units
return obj
value = resolution.get("value")
return value if value is not None else resolution.get("values")
@staticmethod
def extract_entity_metadata(entity: EntityModel) -> Dict:
obj = dict(
startIndex=int(entity.start_index),
endIndex=int(entity.end_index + 1),
text=entity.entity,
type=entity.type,
)
if entity.additional_properties is not None:
if "score" in entity.additional_properties:
obj["score"] = float(entity.additional_properties["score"])
resolution = entity.additional_properties.get("resolution")
if resolution is not None and resolution.get("subtype") is not None:
obj["subtype"] = resolution["subtype"]
return obj
@staticmethod
def extract_normalized_entity_name(entity: EntityModel) -> str:
# Type::Role -> Role
type = entity.type.split(":")[-1]
if type.startswith("builtin.datetimeV2."):
type = "datetime"
if type.startswith("builtin.currency"):
type = "money"
if type.startswith("builtin."):
type = type[8:]
role = (
entity.additional_properties["role"]
if entity.additional_properties is not None
and "role" in entity.additional_properties
else ""
)
if role and not role.isspace():
type = role
return type.replace(".", "_").replace(" ", "_")
@staticmethod
def populate_composite_entity_model(
composite_entity: CompositeEntityModel,
entities: List[EntityModel],
entities_and_metadata: Dict,
verbose: bool,
) -> List[EntityModel]:
children_entities = {}
children_entities_metadata = {}
if verbose:
children_entities[LuisUtil._metadata_key] = {}
# This is now implemented as O(n^2) search and can be reduced to O(2n) using a map as an optimization if n grows
composite_entity_metadata = next(
(
ent
for ent in entities
if ent.type == composite_entity.parent_type
and ent.entity == composite_entity.value
),
None,
)
# This is an error case and should not happen in theory
if composite_entity_metadata is None:
return entities
if verbose:
children_entities_metadata = LuisUtil.extract_entity_metadata(
composite_entity_metadata
)
children_entities[LuisUtil._metadata_key] = {}
covered_set: List[EntityModel] = []
for child in composite_entity.children:
for entity in entities:
# We already covered this entity
if entity in covered_set:
continue
# This entity doesn't belong to this composite entity
if child.type != entity.type or not LuisUtil.composite_contains_entity(
composite_entity_metadata, entity
):
continue
# Add to the set to ensure that we don't consider the same child entity more than once per composite
covered_set.append(entity)
LuisUtil.add_property(
children_entities,
LuisUtil.extract_normalized_entity_name(entity),
LuisUtil.extract_entity_value(entity),
)
if verbose:
LuisUtil.add_property(
children_entities[LuisUtil._metadata_key],
LuisUtil.extract_normalized_entity_name(entity),
LuisUtil.extract_entity_metadata(entity),
)
LuisUtil.add_property(
entities_and_metadata,
LuisUtil.extract_normalized_entity_name(composite_entity_metadata),
children_entities,
)
if verbose:
LuisUtil.add_property(
entities_and_metadata[LuisUtil._metadata_key],
LuisUtil.extract_normalized_entity_name(composite_entity_metadata),
children_entities_metadata,
)
# filter entities that were covered by this composite entity
return [entity for entity in entities if entity not in covered_set]
@staticmethod
def composite_contains_entity(
composite_entity_metadata: EntityModel, entity: EntityModel
) -> bool:
return (
entity.start_index >= composite_entity_metadata.start_index
and entity.end_index <= composite_entity_metadata.end_index
)
@staticmethod
def add_property(obj: Dict[str, object], key: str, value: object) -> None:
# If a property doesn't exist add it to a new array, otherwise append it to the existing array.
if key in obj:
obj[key].append(value)
else:
obj[key] = [value]
@staticmethod
def add_properties(luis: LuisResult, result: RecognizerResult) -> None:
if luis.sentiment_analysis is not None:
result.properties["sentiment"] = {
"label": luis.sentiment_analysis.label,
"score": luis.sentiment_analysis.score,
}
@staticmethod
def get_user_agent():
package_user_agent = f"{__title__}/{__version__}"
uname = platform.uname()
os_version = f"{uname.machine}-{uname.system}-{uname.version}"
py_version = f"Python,Version={platform.python_version()}"
platform_user_agent = f"({os_version}; {py_version})"
user_agent = f"{package_user_agent} {platform_user_agent}"
return user_agent
@staticmethod
def recognizer_result_as_dict(
recognizer_result: RecognizerResult,
) -> Dict[str, object]:
# an internal method that returns a dict for json serialization.
intents: Dict[str, Dict[str, float]] = (
{
name: LuisUtil.intent_score_as_dict(intent_score)
for name, intent_score in recognizer_result.intents.items()
}
if recognizer_result.intents is not None
else None
)
dictionary: Dict[str, object] = {
"text": recognizer_result.text,
"alteredText": recognizer_result.altered_text,
"intents": intents,
"entities": recognizer_result.entities,
}
if recognizer_result.properties is not None:
for key, value in recognizer_result.properties.items():
if key not in dictionary:
if isinstance(value, LuisResult):
dictionary[key] = LuisUtil.luis_result_as_dict(value)
else:
dictionary[key] = value
return dictionary
@staticmethod
def intent_score_as_dict(intent_score: IntentScore) -> Dict[str, float]:
if intent_score is None:
return None
return {"score": intent_score.score}
@staticmethod
def luis_result_as_dict(luis_result: LuisResult) -> Dict[str, object]:
if luis_result is None:
return None
client_models = {
k: v for k, v in runtime_models.__dict__.items() if isinstance(v, type)
}
serializer = Serializer(client_models)
result = serializer.body(luis_result, "LuisResult")
return result
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/luis_util.py",
"repo_id": "botbuilder-python",
"token_count": 5620
}
| 389 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from msrest.serialization import Model
from .query_result import QueryResult
class QueryResults(Model):
"""Contains answers for a user query."""
_attribute_map = {
"answers": {"key": "answers", "type": "[QueryResult]"},
"active_learning_enabled": {"key": "activeLearningEnabled", "type": "bool"},
}
def __init__(
self, answers: List[QueryResult], active_learning_enabled: bool = None, **kwargs
):
"""
Parameters:
-----------
answers: The answers for a user query.
active_learning_enabled: The active learning enable flag.
"""
super().__init__(**kwargs)
self.answers = answers
self.active_learning_enabled = active_learning_enabled
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_results.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/query_results.py",
"repo_id": "botbuilder-python",
"token_count": 313
}
| 390 |
@ECHO OFF
cd C:\Users\v-asho\Desktop\Python\botbuilder-python\libraries\botbuilder-ai
python -m compileall .
IF %ERRORLEVEL% NEQ 0 (
ECHO [Error] build failed!
exit /b %errorlevel%
)
python -O -m compileall .
IF %ERRORLEVEL% NEQ 0 (
ECHO [Error] build failed!
exit /b %errorlevel%
)
pip install .
IF %ERRORLEVEL% NEQ 0 (
ECHO [Error] DIALOGS Install failed!
exit /b %errorlevel%
)
python -m unittest discover ./tests
IF %ERRORLEVEL% NEQ 0 (
ECHO [Error] Test failed!
exit /b %errorlevel%
|
botbuilder-python/libraries/botbuilder-ai/run_test.cmd/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/run_test.cmd",
"repo_id": "botbuilder-python",
"token_count": 198
}
| 391 |
{
"entities": {
"$instance": {
"Address": [
{
"endIndex": 13,
"modelType": "Composite Entity Extractor",
"recognitionSources": [
"model"
],
"score": 0.7160641,
"startIndex": 8,
"text": "35 WA",
"type": "Address"
},
{
"endIndex": 33,
"modelType": "Composite Entity Extractor",
"recognitionSources": [
"externalEntities"
],
"startIndex": 17,
"text": "repent harelquin",
"type": "Address"
}
]
},
"Address": [
{
"$instance": {
"number": [
{
"endIndex": 10,
"modelType": "Prebuilt Entity Extractor",
"recognitionSources": [
"model"
],
"startIndex": 8,
"text": "35",
"type": "builtin.number"
}
],
"State": [
{
"endIndex": 13,
"modelType": "Entity Extractor",
"recognitionSources": [
"model"
],
"score": 0.614376,
"startIndex": 11,
"text": "WA",
"type": "State"
}
]
},
"number": [
35
],
"State": [
"WA"
]
},
{
"number": [
3
],
"State": [
"France"
]
}
]
},
"intents": {
"Cancel": {
"score": 0.00325984019
},
"Delivery": {
"score": 0.482009649
},
"EntityTests": {
"score": 0.00372873852
},
"Greeting": {
"score": 0.00283122621
},
"Help": {
"score": 0.00292110164
},
"None": {
"score": 0.0208108239
},
"Roles": {
"score": 0.069060266
},
"search": {
"score": 0.009682492
},
"SpecifyName": {
"score": 0.00586992875
},
"Travel": {
"score": 0.007831623
},
"Weather_GetForecast": {
"score": 0.009580207
}
},
"sentiment": {
"label": "neutral",
"score": 0.5
},
"text": "deliver 35 WA to repent harelquin",
"v3": {
"options": {
"externalEntities": [
{
"entityLength": 16,
"entityName": "Address",
"resolution": {
"number": [
3
],
"State": [
"France"
]
},
"startIndex": 17
}
],
"includeAllIntents": true,
"includeAPIResults": true,
"includeInstanceData": true,
"log": true,
"preferExternalEntities": true,
"slot": "production"
},
"response": {
"prediction": {
"entities": {
"$instance": {
"Address": [
{
"length": 5,
"modelType": "Composite Entity Extractor",
"modelTypeId": 4,
"recognitionSources": [
"model"
],
"score": 0.7160641,
"startIndex": 8,
"text": "35 WA",
"type": "Address"
},
{
"length": 16,
"modelType": "Composite Entity Extractor",
"modelTypeId": 4,
"recognitionSources": [
"externalEntities"
],
"startIndex": 17,
"text": "repent harelquin",
"type": "Address"
}
]
},
"Address": [
{
"$instance": {
"number": [
{
"length": 2,
"modelType": "Prebuilt Entity Extractor",
"modelTypeId": 2,
"recognitionSources": [
"model"
],
"startIndex": 8,
"text": "35",
"type": "builtin.number"
}
],
"State": [
{
"length": 2,
"modelType": "Entity Extractor",
"modelTypeId": 1,
"recognitionSources": [
"model"
],
"score": 0.614376,
"startIndex": 11,
"text": "WA",
"type": "State"
}
]
},
"number": [
35
],
"State": [
"WA"
]
},
{
"number": [
3
],
"State": [
"France"
]
}
]
},
"intents": {
"Cancel": {
"score": 0.00325984019
},
"Delivery": {
"score": 0.482009649
},
"EntityTests": {
"score": 0.00372873852
},
"Greeting": {
"score": 0.00283122621
},
"Help": {
"score": 0.00292110164
},
"None": {
"score": 0.0208108239
},
"Roles": {
"score": 0.069060266
},
"search": {
"score": 0.009682492
},
"SpecifyName": {
"score": 0.00586992875
},
"Travel": {
"score": 0.007831623
},
"Weather.GetForecast": {
"score": 0.009580207
}
},
"normalizedQuery": "deliver 35 wa to repent harelquin",
"sentiment": {
"label": "neutral",
"score": 0.5
},
"topIntent": "Delivery"
},
"query": "deliver 35 WA to repent harelquin"
}
}
}
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/ExternalEntitiesAndComposite_v3.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/ExternalEntitiesAndComposite_v3.json",
"repo_id": "botbuilder-python",
"token_count": 4412
}
| 392 |
{
"text": "http://foo.com is where you can get a weather forecast for seattle",
"intents": {
"Weather_GetForecast": {
"score": 0.8973387
},
"EntityTests": {
"score": 0.6120084
},
"None": {
"score": 0.038558647
},
"search": {
"score": 0.0183345526
},
"Travel": {
"score": 0.00512401946
},
"Delivery": {
"score": 0.00396467233
},
"SpecifyName": {
"score": 0.00337156886
},
"Help": {
"score": 0.00175959955
},
"Cancel": {
"score": 0.000602799933
},
"Greeting": {
"score": 0.000445256825
}
},
"entities": {
"$instance": {
"Composite2": [
{
"startIndex": 0,
"endIndex": 66,
"text": "http : / / foo . com is where you can get a weather forecast for seattle",
"type": "Composite2",
"score": 0.572650731
}
]
},
"Composite2": [
{
"$instance": {
"Weather_Location": [
{
"startIndex": 59,
"endIndex": 66,
"text": "seattle",
"type": "Weather.Location",
"score": 0.8812625
}
],
"url": [
{
"startIndex": 0,
"endIndex": 14,
"text": "http://foo.com",
"type": "builtin.url"
}
]
},
"Weather_Location": [
"seattle"
],
"url": [
"http://foo.com"
]
}
]
},
"sentiment": {
"label": "neutral",
"score": 0.5
},
"luisResult": {
"query": "http://foo.com is where you can get a weather forecast for seattle",
"topScoringIntent": {
"intent": "Weather.GetForecast",
"score": 0.8973387
},
"intents": [
{
"intent": "Weather.GetForecast",
"score": 0.8973387
},
{
"intent": "EntityTests",
"score": 0.6120084
},
{
"intent": "None",
"score": 0.038558647
},
{
"intent": "search",
"score": 0.0183345526
},
{
"intent": "Travel",
"score": 0.00512401946
},
{
"intent": "Delivery",
"score": 0.00396467233
},
{
"intent": "SpecifyName",
"score": 0.00337156886
},
{
"intent": "Help",
"score": 0.00175959955
},
{
"intent": "Cancel",
"score": 0.000602799933
},
{
"intent": "Greeting",
"score": 0.000445256825
}
],
"entities": [
{
"entity": "seattle",
"type": "Weather.Location",
"startIndex": 59,
"endIndex": 65,
"score": 0.8812625
},
{
"entity": "http : / / foo . com is where you can get a weather forecast for seattle",
"type": "Composite2",
"startIndex": 0,
"endIndex": 65,
"score": 0.572650731
},
{
"entity": "http://foo.com",
"type": "builtin.url",
"startIndex": 0,
"endIndex": 13,
"resolution": {
"value": "http://foo.com"
}
}
],
"compositeEntities": [
{
"parentType": "Composite2",
"value": "http : / / foo . com is where you can get a weather forecast for seattle",
"children": [
{
"type": "Weather.Location",
"value": "seattle"
},
{
"type": "builtin.url",
"value": "http://foo.com"
}
]
}
],
"sentimentAnalysis": {
"label": "neutral",
"score": 0.5
}
}
}
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/Prebuilt.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/Prebuilt.json",
"repo_id": "botbuilder-python",
"token_count": 2101
}
| 393 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Django Application Insights package."""
from . import common
from .bot_telemetry_middleware import BotTelemetryMiddleware
from .logging import LoggingHandler
from .middleware import ApplicationInsightsMiddleware
__all__ = [
"BotTelemetryMiddleware",
"ApplicationInsightsMiddleware",
"LoggingHandler",
"create_client",
]
def create_client():
"""Returns an :class:`applicationinsights.TelemetryClient` instance using the instrumentation key
and other settings found in the current Django project's `settings.py` file."""
return common.create_client()
|
botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/django/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/django/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 188
}
| 394 |
{
"tests/test_cosmos_storage.py": true,
"tests/test_cosmos_storage.py::TestCosmosDbStorage::()::test_cosmos_storage_write_should_overwrite_cached_value_with_valid_newer_e_tag": true,
"tests/test_cosmos_storage.py::TestCosmosDbStorage::()::test_cosmos_storage_write_should_raise_a_key_error_with_older_e_tag": true
}
|
botbuilder-python/libraries/botbuilder-azure/.cache/v/cache/lastfailed/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-azure/.cache/v/cache/lastfailed",
"repo_id": "botbuilder-python",
"token_count": 123
}
| 395 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from botbuilder.schema import InvokeResponse
from . import conversation_reference_extension
from .about import __version__
from .activity_handler import ActivityHandler
from .auto_save_state_middleware import AutoSaveStateMiddleware
from .bot import Bot
from .bot_assert import BotAssert
from .bot_adapter import BotAdapter
from .bot_framework_adapter import BotFrameworkAdapter, BotFrameworkAdapterSettings
from .bot_state import BotState
from .bot_state_set import BotStateSet
from .bot_telemetry_client import BotTelemetryClient, Severity
from .card_factory import CardFactory
from .channel_service_handler import BotActionNotImplementedError, ChannelServiceHandler
from .cloud_adapter_base import CloudAdapterBase
from .cloud_channel_service_handler import CloudChannelServiceHandler
from .component_registration import ComponentRegistration
from .conversation_state import ConversationState
from .oauth.extended_user_token_provider import ExtendedUserTokenProvider
from .oauth.user_token_provider import UserTokenProvider
from .intent_score import IntentScore
from .memory_storage import MemoryStorage
from .memory_transcript_store import MemoryTranscriptStore
from .message_factory import MessageFactory
from .middleware_set import AnonymousReceiveMiddleware, Middleware, MiddlewareSet
from .null_telemetry_client import NullTelemetryClient
from .private_conversation_state import PrivateConversationState
from .queue_storage import QueueStorage
from .recognizer import Recognizer
from .recognizer_result import RecognizerResult, TopIntent
from .show_typing_middleware import ShowTypingMiddleware
from .state_property_accessor import StatePropertyAccessor
from .state_property_info import StatePropertyInfo
from .storage import Storage, StoreItem, calculate_change_hash
from .telemetry_constants import TelemetryConstants
from .telemetry_logger_constants import TelemetryLoggerConstants
from .telemetry_logger_middleware import TelemetryLoggerMiddleware
from .turn_context import TurnContext
from .transcript_logger import TranscriptLogger, TranscriptLoggerMiddleware
from .user_state import UserState
from .register_class_middleware import RegisterClassMiddleware
from .adapter_extensions import AdapterExtensions
__all__ = [
"ActivityHandler",
"AdapterExtensions",
"AnonymousReceiveMiddleware",
"AutoSaveStateMiddleware",
"Bot",
"BotActionNotImplementedError",
"BotAdapter",
"BotAssert",
"BotFrameworkAdapter",
"BotFrameworkAdapterSettings",
"BotState",
"BotStateSet",
"BotTelemetryClient",
"calculate_change_hash",
"CardFactory",
"ChannelServiceHandler",
"CloudAdapterBase",
"CloudChannelServiceHandler",
"ComponentRegistration",
"ConversationState",
"conversation_reference_extension",
"ExtendedUserTokenProvider",
"IntentScore",
"InvokeResponse",
"MemoryStorage",
"MemoryTranscriptStore",
"MessageFactory",
"Middleware",
"MiddlewareSet",
"NullTelemetryClient",
"PrivateConversationState",
"QueueStorage",
"RegisterClassMiddleware",
"Recognizer",
"RecognizerResult",
"Severity",
"ShowTypingMiddleware",
"StatePropertyAccessor",
"StatePropertyInfo",
"Storage",
"StoreItem",
"TelemetryConstants",
"TelemetryLoggerConstants",
"TelemetryLoggerMiddleware",
"TopIntent",
"TranscriptLogger",
"TranscriptLoggerMiddleware",
"TurnContext",
"UserState",
"UserTokenProvider",
"__version__",
]
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 1096
}
| 396 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
from asyncio import sleep
from copy import Error
from http import HTTPStatus
from typing import Awaitable, Callable, List, Union
from uuid import uuid4
from botbuilder.core.invoke_response import InvokeResponse
from botbuilder.schema import (
Activity,
ActivityEventNames,
ActivityTypes,
ConversationAccount,
ConversationReference,
ConversationResourceResponse,
ConversationParameters,
DeliveryModes,
ExpectedReplies,
ResourceResponse,
)
from botframework.connector import Channels, ConnectorClient
from botframework.connector.auth import (
AuthenticationConstants,
BotFrameworkAuthentication,
ClaimsIdentity,
)
from botframework.connector.auth.authenticate_request_result import (
AuthenticateRequestResult,
)
from botframework.connector.auth.connector_factory import ConnectorFactory
from botframework.connector.auth.user_token_client import UserTokenClient
from .bot_adapter import BotAdapter
from .conversation_reference_extension import get_continuation_activity
from .turn_context import TurnContext
class CloudAdapterBase(BotAdapter, ABC):
CONNECTOR_FACTORY_KEY = "ConnectorFactory"
USER_TOKEN_CLIENT_KEY = "UserTokenClient"
def __init__(
self, bot_framework_authentication: BotFrameworkAuthentication
) -> None:
super().__init__()
if not bot_framework_authentication:
raise TypeError("Expected BotFrameworkAuthentication but got None instead")
self.bot_framework_authentication = bot_framework_authentication
async def send_activities(
self, context: TurnContext, activities: List[Activity]
) -> List[ResourceResponse]:
if not context:
raise TypeError("Expected TurnContext but got None instead")
if activities is None:
raise TypeError("Expected Activities list but got None instead")
if len(activities) == 0:
raise TypeError("Expecting one or more activities, but the list was empty.")
responses = []
for activity in activities:
activity.id = None
response = ResourceResponse()
if activity.type == "delay":
delay_time = int((activity.value or 1000) / 1000)
await sleep(delay_time)
elif activity.type == ActivityTypes.invoke_response:
context.turn_state[self._INVOKE_RESPONSE_KEY] = activity
elif (
activity.type == ActivityTypes.trace
and activity.channel_id != Channels.emulator
):
# no-op
pass
else:
connector_client: ConnectorClient = context.turn_state.get(
self.BOT_CONNECTOR_CLIENT_KEY
)
if not connector_client:
raise Error("Unable to extract ConnectorClient from turn context.")
if activity.reply_to_id:
response = await connector_client.conversations.reply_to_activity(
activity.conversation.id, activity.reply_to_id, activity
)
else:
response = (
await connector_client.conversations.send_to_conversation(
activity.conversation.id, activity
)
)
response = response or ResourceResponse(id=activity.id or "")
responses.append(response)
return responses
async def update_activity(self, context: TurnContext, activity: Activity):
if not context:
raise TypeError("Expected TurnContext but got None instead")
if activity is None:
raise TypeError("Expected Activity but got None instead")
connector_client: ConnectorClient = context.turn_state.get(
self.BOT_CONNECTOR_CLIENT_KEY
)
if not connector_client:
raise Error("Unable to extract ConnectorClient from turn context.")
response = await connector_client.conversations.update_activity(
activity.conversation.id, activity.reply_to_id, activity
)
response_id = response.id if response and response.id else None
return ResourceResponse(id=response_id) if response_id else None
async def delete_activity(
self, context: TurnContext, reference: ConversationReference
):
if not context:
raise TypeError("Expected TurnContext but got None instead")
if not reference:
raise TypeError("Expected ConversationReference but got None instead")
connector_client: ConnectorClient = context.turn_state.get(
self.BOT_CONNECTOR_CLIENT_KEY
)
if not connector_client:
raise Error("Unable to extract ConnectorClient from turn context.")
await connector_client.conversations.delete_activity(
reference.conversation.id, reference.activity_id
)
async def continue_conversation( # pylint: disable=arguments-differ
self,
reference: ConversationReference,
callback: Callable,
bot_app_id: str,
):
"""
Sends a proactive message to a conversation.
Call this method to proactively send a message to a conversation.
Most channels require a user to initiate a conversation with a bot before the bot can send activities
to the user.
:param reference: A reference to the conversation to continue.
:type reference: :class:`botbuilder.schema.ConversationReference`
:param callback: The method to call for the resulting bot turn.
:type callback: :class:`typing.Callable`
:param bot_app_id: The application Id of the bot. This is the appId returned by the Azure portal registration,
and is generally found in the `MicrosoftAppId` parameter in `config.py`.
:type bot_app_id: :class:`typing.str`
"""
return await self.process_proactive(
self.create_claims_identity(bot_app_id),
get_continuation_activity(reference),
None,
callback,
)
async def continue_conversation_with_claims(
self,
claims_identity: ClaimsIdentity,
reference: ConversationReference,
audience: str,
logic: Callable[[TurnContext], Awaitable],
):
return await self.process_proactive(
claims_identity, get_continuation_activity(reference), audience, logic
)
async def create_conversation( # pylint: disable=arguments-differ
self,
bot_app_id: str,
callback: Callable[[TurnContext], Awaitable] = None,
conversation_parameters: ConversationParameters = None,
channel_id: str = None,
service_url: str = None,
audience: str = None,
):
if not service_url:
raise TypeError(
"CloudAdapter.create_conversation(): service_url is required."
)
if not conversation_parameters:
raise TypeError(
"CloudAdapter.create_conversation(): conversation_parameters is required."
)
if not callback:
raise TypeError("CloudAdapter.create_conversation(): callback is required.")
# Create a ClaimsIdentity, to create the connector and for adding to the turn context.
claims_identity = self.create_claims_identity(bot_app_id)
claims_identity.claims[AuthenticationConstants.SERVICE_URL_CLAIM] = service_url
# create the connectror factory
connector_factory = self.bot_framework_authentication.create_connector_factory(
claims_identity
)
# Create the connector client to use for outbound requests.
connector_client = await connector_factory.create(service_url, audience)
# Make the actual create conversation call using the connector.
create_conversation_result = (
await connector_client.conversations.create_conversation(
conversation_parameters
)
)
# Create the create activity to communicate the results to the application.
create_activity = self._create_create_activity(
create_conversation_result, channel_id, service_url, conversation_parameters
)
# Create a UserTokenClient instance for the application to use. (For example, in the OAuthPrompt.)
user_token_client = (
await self.bot_framework_authentication.create_user_token_client(
claims_identity
)
)
# Create a turn context and run the pipeline.
context = self._create_turn_context(
create_activity,
claims_identity,
None,
connector_client,
user_token_client,
callback,
connector_factory,
)
# Run the pipeline
await self.run_pipeline(context, callback)
async def process_proactive(
self,
claims_identity: ClaimsIdentity,
continuation_activity: Activity,
audience: str,
logic: Callable[[TurnContext], Awaitable],
):
# Create the connector factory and the inbound request, extracting parameters and then create a
# connector for outbound requests.
connector_factory = self.bot_framework_authentication.create_connector_factory(
claims_identity
)
# Create the connector client to use for outbound requests.
connector_client = await connector_factory.create(
continuation_activity.service_url, audience
)
# Create a UserTokenClient instance for the application to use. (For example, in the OAuthPrompt.)
user_token_client = (
await self.bot_framework_authentication.create_user_token_client(
claims_identity
)
)
# Create a turn context and run the pipeline.
context = self._create_turn_context(
continuation_activity,
claims_identity,
audience,
connector_client,
user_token_client,
logic,
connector_factory,
)
# Run the pipeline
await self.run_pipeline(context, logic)
async def process_activity(
self,
auth_header_or_authenticate_request_result: Union[
str, AuthenticateRequestResult
],
activity: Activity,
logic: Callable[[TurnContext], Awaitable],
):
"""
Creates a turn context and runs the middleware pipeline for an incoming activity.
:param auth_header: The HTTP authentication header of the request
:type auth_header: :class:`typing.Union[typing.str, AuthenticateRequestResult]`
:param activity: The incoming activity
:type activity: :class:`Activity`
:param logic: The logic to execute at the end of the adapter's middleware pipeline.
:type logic: :class:`typing.Callable`
:return: A task that represents the work queued to execute.
.. remarks::
This class 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.
Call this method to reactively send a message to a conversation.
If the task completes successfully, then an :class:`InvokeResponse` is returned;
otherwise. `null` is returned.
"""
# Authenticate the inbound request, extracting parameters and create a ConnectorFactory for creating a
# Connector for outbound requests.
authenticate_request_result = (
await self.bot_framework_authentication.authenticate_request(
activity, auth_header_or_authenticate_request_result
)
if isinstance(auth_header_or_authenticate_request_result, str)
else auth_header_or_authenticate_request_result
)
# Set the caller_id on the activity
activity.caller_id = authenticate_request_result.caller_id
# Create the connector client to use for outbound requests.
connector_client = (
await authenticate_request_result.connector_factory.create(
activity.service_url, authenticate_request_result.audience
)
if authenticate_request_result.connector_factory
else None
)
if not connector_client:
raise Error("Unable to extract ConnectorClient from turn context.")
# Create a UserTokenClient instance for the application to use.
# (For example, it would be used in a sign-in prompt.)
user_token_client = (
await self.bot_framework_authentication.create_user_token_client(
authenticate_request_result.claims_identity
)
)
# Create a turn context and run the pipeline.
context = self._create_turn_context(
activity,
authenticate_request_result.claims_identity,
authenticate_request_result.audience,
connector_client,
user_token_client,
logic,
authenticate_request_result.connector_factory,
)
# Run the pipeline
await self.run_pipeline(context, logic)
# If there are any results they will have been left on the TurnContext.
return self._process_turn_results(context)
def create_claims_identity(self, bot_app_id: str = "") -> ClaimsIdentity:
return ClaimsIdentity(
{
AuthenticationConstants.AUDIENCE_CLAIM: bot_app_id,
AuthenticationConstants.APP_ID_CLAIM: bot_app_id,
},
True,
)
def _create_create_activity(
self,
create_conversation_result: ConversationResourceResponse,
channel_id: str,
service_url: str,
conversation_parameters: ConversationParameters,
) -> Activity:
# Create a conversation update activity to represent the result.
activity = Activity.create_event_activity()
activity.name = ActivityEventNames.create_conversation
activity.channel_id = channel_id
activity.service_url = service_url
activity.id = create_conversation_result.activity_id or str(uuid4())
activity.conversation = ConversationAccount(
id=create_conversation_result.id,
tenant_id=conversation_parameters.tenant_id,
)
activity.channel_data = conversation_parameters.channel_data
activity.recipient = conversation_parameters.bot
return activity
def _create_turn_context(
self,
activity: Activity,
claims_identity: ClaimsIdentity,
oauth_scope: str,
connector_client: ConnectorClient,
user_token_client: UserTokenClient,
logic: Callable[[TurnContext], Awaitable],
connector_factory: ConnectorFactory,
) -> TurnContext:
context = TurnContext(self, activity)
context.turn_state[self.BOT_IDENTITY_KEY] = claims_identity
context.turn_state[self.BOT_CONNECTOR_CLIENT_KEY] = connector_client
context.turn_state[self.USER_TOKEN_CLIENT_KEY] = user_token_client
context.turn_state[self.BOT_CALLBACK_HANDLER_KEY] = logic
context.turn_state[self.CONNECTOR_FACTORY_KEY] = connector_factory
context.turn_state[self.BOT_OAUTH_SCOPE_KEY] = oauth_scope
return context
def _process_turn_results(self, context: TurnContext) -> InvokeResponse:
# Handle ExpectedReplies scenarios where all activities have been
# buffered and sent back at once in an invoke response.
if context.activity.delivery_mode == DeliveryModes.expect_replies:
return InvokeResponse(
status=HTTPStatus.OK,
body=ExpectedReplies(activities=context.buffered_reply_activities),
)
# Handle Invoke scenarios where the bot will return a specific body and return code.
if context.activity.type == ActivityTypes.invoke:
activity_invoke_response: Activity = context.turn_state.get(
self._INVOKE_RESPONSE_KEY
)
if not activity_invoke_response:
return InvokeResponse(status=HTTPStatus.NOT_IMPLEMENTED)
return activity_invoke_response.value
# No body to return
return None
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/cloud_adapter_base.py",
"repo_id": "botbuilder-python",
"token_count": 6782
}
| 397 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class InvokeResponse:
"""
Tuple class containing an HTTP Status Code and a JSON serializable
object. The HTTP Status code is, in the invoke activity scenario, what will
be set in the resulting POST. The Body of the resulting POST will be
JSON serialized content.
The body content is defined by the producer. The caller must know what
the content is and deserialize as needed.
"""
def __init__(self, status: int = None, body: object = None):
"""
Gets or sets the HTTP status and/or body code for the response
:param status: The HTTP status code.
:param body: The JSON serializable body content for the response. This object
must be serializable by the core Python json routines. The caller is responsible
for serializing more complex/nested objects into native classes (lists and
dictionaries of strings are acceptable).
"""
self.status = status
self.body = body
def is_successful_status_code(self) -> bool:
"""
Gets a value indicating whether the invoke response was successful.
:return: A value that indicates if the HTTP response was successful. true if status is in
the Successful range (200-299); otherwise false.
"""
return 200 <= self.status <= 299
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/invoke_response.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/invoke_response.py",
"repo_id": "botbuilder-python",
"token_count": 447
}
| 398 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Callable, Awaitable
from botbuilder.core import Middleware, TurnContext
class RegisterClassMiddleware(Middleware):
"""
Middleware for adding an object to or registering a service with the current turn context.
"""
def __init__(self, service, key: str = None):
self.service = service
self._key = key
async def on_turn(
self, context: TurnContext, logic: Callable[[TurnContext], Awaitable]
):
# C# has TurnStateCollection with has overrides for adding items
# to TurnState. Python does not. In C#'s case, there is an 'Add'
# to handle adding object, and that uses the fully qualified class name.
key = self._key or self.fullname(self.service)
context.turn_state[key] = self.service
await logic()
@staticmethod
def fullname(obj):
module = obj.__class__.__module__
if module is None or module == str.__class__.__module__:
return obj.__class__.__name__ # Avoid reporting __builtin__
return module + "." + obj.__class__.__name__
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/register_class_middleware.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/register_class_middleware.py",
"repo_id": "botbuilder-python",
"token_count": 418
}
| 399 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .bot_framework_http_adapter_base import BotFrameworkHttpAdapterBase
from .streaming_activity_processor import StreamingActivityProcessor
from .streaming_http_client import StreamingHttpDriver
from .streaming_request_handler import StreamingRequestHandler
from .version_info import VersionInfo
__all__ = [
"BotFrameworkHttpAdapterBase",
"StreamingActivityProcessor",
"StreamingHttpDriver",
"StreamingRequestHandler",
"VersionInfo",
]
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/streaming/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/streaming/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 151
}
| 400 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import re
from copy import copy, deepcopy
from datetime import datetime
from typing import List, Callable, Union, Dict
from botbuilder.schema import (
Activity,
ActivityTypes,
ConversationReference,
InputHints,
Mention,
ResourceResponse,
DeliveryModes,
)
from .re_escape import escape
class TurnContext:
# Same constant as in the BF Adapter, duplicating here to avoid circular dependency
_INVOKE_RESPONSE_KEY = "BotFrameworkAdapter.InvokeResponse"
def __init__(self, adapter_or_context, request: Activity = None):
"""
Creates a new TurnContext instance.
:param adapter_or_context:
:param request:
"""
if isinstance(adapter_or_context, TurnContext):
adapter_or_context.copy_to(self)
else:
self.adapter = adapter_or_context
self._activity = request
self.responses: List[Activity] = []
self._services: dict = {}
self._on_send_activities: Callable[
["TurnContext", List[Activity], Callable], List[ResourceResponse]
] = []
self._on_update_activity: Callable[
["TurnContext", Activity, Callable], ResourceResponse
] = []
self._on_delete_activity: Callable[
["TurnContext", ConversationReference, Callable], None
] = []
self._responded: bool = False
if self.adapter is None:
raise TypeError("TurnContext must be instantiated with an adapter.")
if self.activity is None:
raise TypeError(
"TurnContext must be instantiated with a request parameter of type Activity."
)
self._turn_state = {}
# A list of activities to send when `context.Activity.DeliveryMode == 'expectReplies'`
self.buffered_reply_activities = []
@property
def turn_state(self) -> Dict[str, object]:
return self._turn_state
def copy_to(self, context: "TurnContext") -> None:
"""
Called when this TurnContext instance is passed into the constructor of a new TurnContext
instance. Can be overridden in derived classes.
:param context:
:return:
"""
for attribute in [
"adapter",
"activity",
"_responded",
"_services",
"_on_send_activities",
"_on_update_activity",
"_on_delete_activity",
]:
setattr(context, attribute, getattr(self, attribute))
@property
def activity(self):
"""
The received activity.
:return:
"""
return self._activity
@activity.setter
def activity(self, value):
"""
Used to set TurnContext._activity when a context object is created. Only takes instances of Activities.
:param value:
:return:
"""
if not isinstance(value, Activity):
raise TypeError(
"TurnContext: cannot set `activity` to a type other than Activity."
)
self._activity = value
@property
def responded(self) -> bool:
"""
If `true` at least one response has been sent for the current turn of conversation.
:return:
"""
return self._responded
@responded.setter
def responded(self, value: bool):
if not value:
raise ValueError("TurnContext: cannot set TurnContext.responded to False.")
self._responded = True
@property
def services(self):
"""
Map of services and other values cached for the lifetime of the turn.
:return:
"""
return self._services
def get(self, key: str) -> object:
if not key or not isinstance(key, str):
raise TypeError('"key" must be a valid string.')
try:
return self._services[key]
except KeyError:
raise KeyError("%s not found in TurnContext._services." % key)
def has(self, key: str) -> bool:
"""
Returns True is set() has been called for a key. The cached value may be of type 'None'.
:param key:
:return:
"""
if key in self._services:
return True
return False
def set(self, key: str, value: object) -> None:
"""
Caches a value for the lifetime of the current turn.
:param key:
:param value:
:return:
"""
if not key or not isinstance(key, str):
raise KeyError('"key" must be a valid string.')
self._services[key] = value
async def send_activity(
self,
activity_or_text: Union[Activity, str],
speak: str = None,
input_hint: str = None,
) -> ResourceResponse:
"""
Sends a single activity or message to the user.
:param activity_or_text:
:return:
"""
if isinstance(activity_or_text, str):
activity_or_text = Activity(
text=activity_or_text,
input_hint=input_hint or InputHints.accepting_input,
speak=speak,
)
result = await self.send_activities([activity_or_text])
return result[0] if result else None
async def send_activities(
self, activities: List[Activity]
) -> List[ResourceResponse]:
sent_non_trace_activity = False
ref = TurnContext.get_conversation_reference(self.activity)
def activity_validator(activity: Activity) -> Activity:
if not getattr(activity, "type", None):
activity.type = ActivityTypes.message
if activity.type != ActivityTypes.trace:
nonlocal sent_non_trace_activity
sent_non_trace_activity = True
if not activity.input_hint:
activity.input_hint = "acceptingInput"
activity.id = None
return activity
output = [
activity_validator(
TurnContext.apply_conversation_reference(deepcopy(act), ref)
)
for act in activities
]
# send activities through adapter
async def logic():
nonlocal sent_non_trace_activity
if self.activity.delivery_mode == DeliveryModes.expect_replies:
responses = []
for activity in output:
self.buffered_reply_activities.append(activity)
# Ensure the TurnState has the InvokeResponseKey, since this activity
# is not being sent through the adapter, where it would be added to TurnState.
if activity.type == ActivityTypes.invoke_response:
self.turn_state[TurnContext._INVOKE_RESPONSE_KEY] = activity
responses.append(ResourceResponse())
if sent_non_trace_activity:
self.responded = True
return responses
responses = await self.adapter.send_activities(self, output)
if sent_non_trace_activity:
self.responded = True
return responses
return await self._emit(self._on_send_activities, output, logic())
async def update_activity(self, activity: Activity):
"""
Replaces an existing activity.
:param activity:
:return:
"""
reference = TurnContext.get_conversation_reference(self.activity)
return await self._emit(
self._on_update_activity,
TurnContext.apply_conversation_reference(activity, reference),
self.adapter.update_activity(self, activity),
)
async def delete_activity(self, id_or_reference: Union[str, ConversationReference]):
"""
Deletes an existing activity.
:param id_or_reference:
:return:
"""
if isinstance(id_or_reference, str):
reference = TurnContext.get_conversation_reference(self.activity)
reference.activity_id = id_or_reference
else:
reference = id_or_reference
return await self._emit(
self._on_delete_activity,
reference,
self.adapter.delete_activity(self, reference),
)
def on_send_activities(self, handler) -> "TurnContext":
"""
Registers a handler to be notified of and potentially intercept the sending of activities.
:param handler:
:return:
"""
self._on_send_activities.append(handler)
return self
def on_update_activity(self, handler) -> "TurnContext":
"""
Registers a handler to be notified of and potentially intercept an activity being updated.
:param handler:
:return:
"""
self._on_update_activity.append(handler)
return self
def on_delete_activity(self, handler) -> "TurnContext":
"""
Registers a handler to be notified of and potentially intercept an activity being deleted.
:param handler:
:return:
"""
self._on_delete_activity.append(handler)
return self
async def _emit(self, plugins, arg, logic):
handlers = copy(plugins)
async def emit_next(i: int):
context = self
try:
if i < len(handlers):
async def next_handler():
await emit_next(i + 1)
await handlers[i](context, arg, next_handler)
except Exception as error:
raise error
await emit_next(0)
# logic does not use parentheses because it's a coroutine
return await logic
async def send_trace_activity(
self, name: str, value: object = None, value_type: str = None, label: str = None
) -> ResourceResponse:
trace_activity = Activity(
type=ActivityTypes.trace,
timestamp=datetime.utcnow(),
name=name,
value=value,
value_type=value_type,
label=label,
)
return await self.send_activity(trace_activity)
@staticmethod
def get_conversation_reference(activity: Activity) -> ConversationReference:
"""
Returns the conversation reference for an activity. This can be saved as a plain old JSON
object and then later used to message the user proactively.
Usage Example:
reference = TurnContext.get_conversation_reference(context.request)
:param activity:
:return:
"""
return ConversationReference(
activity_id=activity.id,
user=copy(activity.from_property),
bot=copy(activity.recipient),
conversation=copy(activity.conversation),
channel_id=activity.channel_id,
locale=activity.locale,
service_url=activity.service_url,
)
@staticmethod
def apply_conversation_reference(
activity: Activity, reference: ConversationReference, is_incoming: bool = False
) -> Activity:
"""
Updates an activity with the delivery information from a conversation reference. Calling
this after get_conversation_reference on an incoming activity
will properly address the reply to a received activity.
:param activity:
:param reference:
:param is_incoming:
:return:
"""
activity.channel_id = reference.channel_id
activity.locale = reference.locale
activity.service_url = reference.service_url
activity.conversation = reference.conversation
if is_incoming:
activity.from_property = reference.user
activity.recipient = reference.bot
if reference.activity_id:
activity.id = reference.activity_id
else:
activity.from_property = reference.bot
activity.recipient = reference.user
if reference.activity_id:
activity.reply_to_id = reference.activity_id
return activity
@staticmethod
def get_reply_conversation_reference(
activity: Activity, reply: ResourceResponse
) -> ConversationReference:
reference: ConversationReference = TurnContext.get_conversation_reference(
activity
)
# Update the reference with the new outgoing Activity's id.
reference.activity_id = reply.id
return reference
@staticmethod
def remove_recipient_mention(activity: Activity) -> str:
return TurnContext.remove_mention_text(activity, activity.recipient.id)
@staticmethod
def remove_mention_text(activity: Activity, identifier: str) -> str:
mentions = TurnContext.get_mentions(activity)
for mention in mentions:
if mention.additional_properties["mentioned"]["id"] == identifier:
mention_name_match = re.match(
r"<at(.*)>(.*?)<\/at>",
escape(mention.additional_properties["text"]),
re.IGNORECASE,
)
if mention_name_match:
activity.text = re.sub(
mention_name_match.groups()[1], "", activity.text
)
activity.text = re.sub(r"<at><\/at>", "", activity.text)
return activity.text
@staticmethod
def get_mentions(activity: Activity) -> List[Mention]:
result: List[Mention] = []
if activity.entities is not None:
for entity in activity.entities:
if entity.type.lower() == "mention":
result.append(entity)
return result
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/turn_context.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/turn_context.py",
"repo_id": "botbuilder-python",
"token_count": 6051
}
| 401 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import aiounittest
from botframework.connector import Channels
from botbuilder.core import TurnContext, MessageFactory
from botbuilder.core.teams import TeamsInfo, TeamsActivityHandler
from botbuilder.schema import (
Activity,
ChannelAccount,
ConversationAccount,
)
from simple_adapter_with_create_conversation import SimpleAdapterWithCreateConversation
ACTIVITY = Activity(
id="1234",
type="message",
text="test",
from_property=ChannelAccount(id="user", name="User Name"),
recipient=ChannelAccount(id="bot", name="Bot Name"),
conversation=ConversationAccount(id="convo", name="Convo Name"),
channel_data={"channelData": {}},
channel_id="UnitTest",
locale="en-us",
service_url="https://example.org",
)
class TestTeamsInfo(aiounittest.AsyncTestCase):
async def test_send_message_to_teams_channels_without_activity(self):
def create_conversation():
pass
adapter = SimpleAdapterWithCreateConversation(
call_create_conversation=create_conversation
)
activity = Activity()
turn_context = TurnContext(adapter, activity)
try:
await TeamsInfo.send_message_to_teams_channel(
turn_context, None, "channelId123"
)
except ValueError:
pass
else:
assert False, "should have raise ValueError"
async def test_send_message_to_teams(self):
def create_conversation():
pass
adapter = SimpleAdapterWithCreateConversation(
call_create_conversation=create_conversation
)
turn_context = TurnContext(adapter, ACTIVITY)
handler = TestTeamsActivityHandler()
await handler.on_turn(turn_context)
async def test_send_message_to_teams_channels_without_turn_context(self):
try:
await TeamsInfo.send_message_to_teams_channel(
None, ACTIVITY, "channelId123"
)
except ValueError:
pass
else:
assert False, "should have raise ValueError"
async def test_send_message_to_teams_channels_without_teams_channel_id(self):
def create_conversation():
pass
adapter = SimpleAdapterWithCreateConversation(
call_create_conversation=create_conversation
)
turn_context = TurnContext(adapter, ACTIVITY)
try:
await TeamsInfo.send_message_to_teams_channel(turn_context, ACTIVITY, "")
except ValueError:
pass
else:
assert False, "should have raise ValueError"
async def test_send_message_to_teams_channel_works(self):
adapter = SimpleAdapterWithCreateConversation()
turn_context = TurnContext(adapter, ACTIVITY)
result = await TeamsInfo.send_message_to_teams_channel(
turn_context, ACTIVITY, "teamId123"
)
assert result[0].activity_id == "new_conversation_id"
assert result[1] == "reference123"
async def test_get_team_details_works_without_team_id(self):
adapter = SimpleAdapterWithCreateConversation()
ACTIVITY.channel_data = {}
turn_context = TurnContext(adapter, ACTIVITY)
result = TeamsInfo.get_team_id(turn_context)
assert result == ""
async def test_get_team_details_works_with_team_id(self):
adapter = SimpleAdapterWithCreateConversation()
team_id = "teamId123"
ACTIVITY.channel_data = {"team": {"id": team_id}}
turn_context = TurnContext(adapter, ACTIVITY)
result = TeamsInfo.get_team_id(turn_context)
assert result == team_id
async def test_get_team_details_without_team_id(self):
def create_conversation():
pass
adapter = SimpleAdapterWithCreateConversation(
call_create_conversation=create_conversation
)
turn_context = TurnContext(adapter, ACTIVITY)
try:
await TeamsInfo.get_team_details(turn_context)
except TypeError:
pass
else:
assert False, "should have raise TypeError"
async def test_get_team_channels_without_team_id(self):
def create_conversation():
pass
adapter = SimpleAdapterWithCreateConversation(
call_create_conversation=create_conversation
)
turn_context = TurnContext(adapter, ACTIVITY)
try:
await TeamsInfo.get_team_channels(turn_context)
except TypeError:
pass
else:
assert False, "should have raise TypeError"
async def test_get_paged_team_members_without_team_id(self):
def create_conversation():
pass
adapter = SimpleAdapterWithCreateConversation(
call_create_conversation=create_conversation
)
turn_context = TurnContext(adapter, ACTIVITY)
try:
await TeamsInfo.get_paged_team_members(turn_context)
except TypeError:
pass
else:
assert False, "should have raise TypeError"
async def test_get_team_members_without_team_id(self):
def create_conversation():
pass
adapter = SimpleAdapterWithCreateConversation(
call_create_conversation=create_conversation
)
turn_context = TurnContext(adapter, ACTIVITY)
try:
await TeamsInfo.get_team_member(turn_context)
except TypeError:
pass
else:
assert False, "should have raise TypeError"
async def test_get_team_members_without_member_id(self):
def create_conversation():
pass
adapter = SimpleAdapterWithCreateConversation(
call_create_conversation=create_conversation
)
turn_context = TurnContext(adapter, ACTIVITY)
try:
await TeamsInfo.get_team_member(turn_context, "teamId123")
except TypeError:
pass
else:
assert False, "should have raise TypeError"
async def test_get_participant(self):
adapter = SimpleAdapterWithCreateConversation()
activity = Activity(
type="message",
text="Test-get_participant",
channel_id=Channels.ms_teams,
from_property=ChannelAccount(aad_object_id="participantId-1"),
channel_data={
"meeting": {"id": "meetingId-1"},
"tenant": {"id": "tenantId-1"},
},
service_url="https://test.coffee",
)
turn_context = TurnContext(adapter, activity)
handler = TeamsActivityHandler()
await handler.on_turn(turn_context)
async def test_get_meeting_info(self):
adapter = SimpleAdapterWithCreateConversation()
activity = Activity(
type="message",
text="Test-get_meeting_info",
channel_id=Channels.ms_teams,
from_property=ChannelAccount(aad_object_id="participantId-1"),
channel_data={"meeting": {"id": "meetingId-1"}},
service_url="https://test.coffee",
)
turn_context = TurnContext(adapter, activity)
handler = TeamsActivityHandler()
await handler.on_turn(turn_context)
class TestTeamsActivityHandler(TeamsActivityHandler):
async def on_turn(self, turn_context: TurnContext):
await super().on_turn(turn_context)
if turn_context.activity.text == "test_send_message_to_teams_channel":
await self.call_send_message_to_teams(turn_context)
async def call_send_message_to_teams(self, turn_context: TurnContext):
msg = MessageFactory.text("call_send_message_to_teams")
channel_id = "teams_channel_123"
reference = await TeamsInfo.send_message_to_teams_channel(
turn_context, msg, channel_id
)
assert reference[0].activity_id == "new_conversation_id"
assert reference[1] == "reference123"
|
botbuilder-python/libraries/botbuilder-core/tests/teams/test_teams_info.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/teams/test_teams_info.py",
"repo_id": "botbuilder-python",
"token_count": 3487
}
| 402 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import asyncio
from uuid import uuid4
import aiounittest
from botbuilder.core import ShowTypingMiddleware, TurnContext
from botbuilder.core.adapters import TestAdapter
from botbuilder.schema import Activity, ActivityTypes
from botframework.connector.auth import AuthenticationConstants, ClaimsIdentity
class SkillTestAdapter(TestAdapter):
def create_turn_context(self, activity: Activity) -> TurnContext:
turn_context = super().create_turn_context(activity)
claims_identity = ClaimsIdentity(
claims={
AuthenticationConstants.VERSION_CLAIM: "2.0",
AuthenticationConstants.AUDIENCE_CLAIM: str(uuid4()),
AuthenticationConstants.AUTHORIZED_PARTY: str(uuid4()),
},
is_authenticated=True,
)
turn_context.turn_state[self.BOT_IDENTITY_KEY] = claims_identity
return turn_context
class TestShowTypingMiddleware(aiounittest.AsyncTestCase):
async def test_should_automatically_send_a_typing_indicator(self):
async def aux(context):
await asyncio.sleep(0.600)
await context.send_activity(f"echo:{context.activity.text}")
def assert_is_typing(activity, description): # pylint: disable=unused-argument
assert activity.type == ActivityTypes.typing
adapter = TestAdapter(aux)
adapter.use(ShowTypingMiddleware())
step1 = await adapter.send("foo")
step2 = await step1.assert_reply(assert_is_typing)
step3 = await step2.assert_reply("echo:foo")
step4 = await step3.send("bar")
step5 = await step4.assert_reply(assert_is_typing)
await step5.assert_reply("echo:bar")
async def test_should_not_automatically_send_a_typing_indicator_if_no_middleware(
self,
):
async def aux(context):
await context.send_activity(f"echo:{context.activity.text}")
adapter = TestAdapter(aux)
step1 = await adapter.send("foo")
await step1.assert_reply("echo:foo")
async def test_should_not_immediately_respond_with_message(self):
async def aux(context):
await asyncio.sleep(0.600)
await context.send_activity(f"echo:{context.activity.text}")
def assert_is_not_message(
activity, description
): # pylint: disable=unused-argument
assert activity.type != ActivityTypes.message
adapter = TestAdapter(aux)
adapter.use(ShowTypingMiddleware())
step1 = await adapter.send("foo")
await step1.assert_reply(assert_is_not_message)
async def test_should_immediately_respond_with_message_if_no_middleware(self):
async def aux(context):
await context.send_activity(f"echo:{context.activity.text}")
def assert_is_message(activity, description): # pylint: disable=unused-argument
assert activity.type == ActivityTypes.message
adapter = TestAdapter(aux)
step1 = await adapter.send("foo")
await step1.assert_reply(assert_is_message)
async def test_not_send_not_send_typing_indicator_when_bot_running_as_skill(self):
async def aux(context):
await asyncio.sleep(1)
await context.send_activity(f"echo:{context.activity.text}")
skill_adapter = SkillTestAdapter(aux)
skill_adapter.use(ShowTypingMiddleware(0.001, 1))
step1 = await skill_adapter.send("foo")
await step1.assert_reply("echo:foo")
|
botbuilder-python/libraries/botbuilder-core/tests/test_show_typing_middleware.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/test_show_typing_middleware.py",
"repo_id": "botbuilder-python",
"token_count": 1439
}
| 403 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List, Union
from recognizers_number import NumberModel, NumberRecognizer, OrdinalModel
from recognizers_text import Culture
from .choice import Choice
from .find import Find
from .find_choices_options import FindChoicesOptions
from .found_choice import FoundChoice
from .model_result import ModelResult
class ChoiceRecognizers:
"""Contains methods for matching user input against a list of choices."""
@staticmethod
def recognize_choices(
utterance: str,
choices: List[Union[str, Choice]],
options: FindChoicesOptions = None,
) -> List[ModelResult]:
"""
Matches user input against a list of choices.
This is layered above the `Find.find_choices()` function, and adds logic to let the user specify
their choice by index (they can say "one" to pick `choice[0]`) or ordinal position
(they can say "the second one" to pick `choice[1]`.)
The user's utterance is recognized in the following order:
- By name using `find_choices()`
- By 1's based ordinal position.
- By 1's based index position.
Parameters:
-----------
utterance: The input.
choices: The list of choices.
options: (Optional) Options to control the recognition strategy.
Returns:
--------
A list of found choices, sorted by most relevant first.
"""
if utterance is None:
utterance = ""
# Normalize list of choices
choices_list = [
Choice(value=choice) if isinstance(choice, str) else choice
for choice in choices
]
# Try finding choices by text search first
# - We only want to use a single strategy for returning results to avoid issues where utterances
# like the "the third one" or "the red one" or "the first division book" would miss-recognize as
# a numerical index or ordinal as well.
locale = options.locale if (options and options.locale) else Culture.English
matched = Find.find_choices(utterance, choices_list, options)
if not matched:
matches = []
if not options or options.recognize_ordinals:
# Next try finding by ordinal
matches = ChoiceRecognizers._recognize_ordinal(utterance, locale)
for match in matches:
ChoiceRecognizers._match_choice_by_index(
choices_list, matched, match
)
if not matches and (not options or options.recognize_numbers):
# Then try by numerical index
matches = ChoiceRecognizers._recognize_number(utterance, locale)
for match in matches:
ChoiceRecognizers._match_choice_by_index(
choices_list, matched, match
)
# Sort any found matches by their position within the utterance.
# - The results from find_choices() are already properly sorted so we just need this
# for ordinal & numerical lookups.
matched = sorted(matched, key=lambda model_result: model_result.start)
return matched
@staticmethod
def _recognize_ordinal(utterance: str, culture: str) -> List[ModelResult]:
model: OrdinalModel = NumberRecognizer(culture).get_ordinal_model(culture)
return list(
map(ChoiceRecognizers._found_choice_constructor, model.parse(utterance))
)
@staticmethod
def _match_choice_by_index(
choices: List[Choice], matched: List[ModelResult], match: ModelResult
):
try:
index: int = int(match.resolution.value) - 1
if 0 <= index < len(choices):
choice = choices[index]
matched.append(
ModelResult(
start=match.start,
end=match.end,
type_name="choice",
text=match.text,
resolution=FoundChoice(
value=choice.value, index=index, score=1.0
),
)
)
except:
# noop here, as in dotnet/node repos
pass
@staticmethod
def _recognize_number(utterance: str, culture: str) -> List[ModelResult]:
model: NumberModel = NumberRecognizer(culture).get_number_model(culture)
return list(
map(ChoiceRecognizers._found_choice_constructor, model.parse(utterance))
)
@staticmethod
def _found_choice_constructor(value_model: ModelResult) -> ModelResult:
return ModelResult(
start=value_model.start,
end=value_model.end,
type_name="choice",
text=value_model.text,
resolution=FoundChoice(
value=value_model.resolution["value"], index=0, score=1.0
),
)
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/choice_recognizers.py",
"repo_id": "botbuilder-python",
"token_count": 2200
}
| 404 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from enum import Enum
class DialogEvents(str, Enum):
begin_dialog = "beginDialog"
reprompt_dialog = "repromptDialog"
cancel_dialog = "cancelDialog"
activity_received = "activityReceived"
version_changed = "versionChanged"
error = "error"
custom = "custom"
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_events.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_events.py",
"repo_id": "botbuilder-python",
"token_count": 125
}
| 405 |
from typing import List
from botbuilder.dialogs.memory.scopes import MemoryScope
from .path_resolver_base import PathResolverBase
class DialogStateManagerConfiguration:
def __init__(self):
self.path_resolvers: List[PathResolverBase] = list()
self.memory_scopes: List[MemoryScope] = list()
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/dialog_state_manager_configuration.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/dialog_state_manager_configuration.py",
"repo_id": "botbuilder-python",
"token_count": 104
}
| 406 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.dialogs.memory import scope_path
from .memory_scope import MemoryScope
class DialogMemoryScope(MemoryScope):
def __init__(self):
# pylint: disable=import-outside-toplevel
super().__init__(scope_path.DIALOG)
# This import is to avoid circular dependency issues
from botbuilder.dialogs import DialogContainer
self._dialog_container_cls = DialogContainer
def get_memory(self, dialog_context: "DialogContext") -> object:
if not dialog_context:
raise TypeError(f"Expecting: DialogContext, but received None")
# if active dialog is a container dialog then "dialog" binds to it.
if dialog_context.active_dialog:
dialog = dialog_context.find_dialog_sync(dialog_context.active_dialog.id)
if isinstance(dialog, self._dialog_container_cls):
return dialog_context.active_dialog.state
# Otherwise we always bind to parent, or if there is no parent the active dialog
parent_state = (
dialog_context.parent.active_dialog.state
if dialog_context.parent and dialog_context.parent.active_dialog
else None
)
dc_state = (
dialog_context.active_dialog.state if dialog_context.active_dialog else None
)
return parent_state or dc_state
def set_memory(self, dialog_context: "DialogContext", memory: object):
if not dialog_context:
raise TypeError(f"Expecting: DialogContext, but received None")
if not memory:
raise TypeError(f"Expecting: memory object, but received None")
# If active dialog is a container dialog then "dialog" binds to it.
# Otherwise the "dialog" will bind to the dialogs parent assuming it
# is a container.
parent = dialog_context
if not self.is_container(parent) and self.is_container(parent.parent):
parent = parent.parent
# If there's no active dialog then throw an error.
if not parent.active_dialog:
raise Exception(
"Cannot set DialogMemoryScope. There is no active dialog dialog or parent dialog in the context"
)
parent.active_dialog.state = memory
def is_container(self, dialog_context: "DialogContext"):
if dialog_context and dialog_context.active_dialog:
dialog = dialog_context.find_dialog_sync(dialog_context.active_dialog.id)
if isinstance(dialog, self._dialog_container_cls):
return True
return False
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/dialog_memory_scope.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/scopes/dialog_memory_scope.py",
"repo_id": "botbuilder-python",
"token_count": 1037
}
| 407 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Callable, Dict
from recognizers_number import recognize_number
from recognizers_text import Culture, ModelResult
from babel.numbers import parse_decimal
from botbuilder.core.turn_context import TurnContext
from botbuilder.schema import ActivityTypes
from .prompt import Prompt, PromptValidatorContext
from .prompt_options import PromptOptions
from .prompt_recognizer_result import PromptRecognizerResult
class NumberPrompt(Prompt):
# TODO: PromptValidator needs to be fixed
# Does not accept answer as intended (times out)
def __init__(
self,
dialog_id: str,
validator: Callable[[PromptValidatorContext], bool] = None,
default_locale: str = None,
):
super(NumberPrompt, self).__init__(dialog_id, validator)
self.default_locale = default_locale
async def on_prompt(
self,
turn_context: TurnContext,
state: Dict[str, object],
options: PromptOptions,
is_retry: bool,
):
if not turn_context:
raise TypeError("NumberPrompt.on_prompt(): turn_context cannot be None.")
if not options:
raise TypeError("NumberPrompt.on_prompt(): options cannot be None.")
if is_retry and options.retry_prompt is not None:
await turn_context.send_activity(options.retry_prompt)
elif options.prompt is not None:
await turn_context.send_activity(options.prompt)
async def on_recognize(
self,
turn_context: TurnContext,
state: Dict[str, object],
options: PromptOptions,
) -> PromptRecognizerResult:
if not turn_context:
raise TypeError("NumberPrompt.on_recognize(): turn_context cannot be None.")
result = PromptRecognizerResult()
if turn_context.activity.type == ActivityTypes.message:
utterance = turn_context.activity.text
if not utterance:
return result
culture = self._get_culture(turn_context)
results: [ModelResult] = recognize_number(utterance, culture)
if results:
result.succeeded = True
result.value = parse_decimal(
results[0].resolution["value"], locale=culture.replace("-", "_")
)
return result
def _get_culture(self, turn_context: TurnContext):
culture = (
turn_context.activity.locale
if turn_context.activity.locale
else self.default_locale
)
if not culture:
culture = Culture.English
return culture
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/number_prompt.py",
"repo_id": "botbuilder-python",
"token_count": 1105
}
| 408 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Dict
from .dialog_context import DialogContext
from .dialog_reason import DialogReason
from .dialog_turn_result import DialogTurnResult
from .dialog_state import DialogState
class WaterfallStepContext(DialogContext):
def __init__(
self,
parent,
dc: DialogContext,
options: object,
values: Dict[str, object],
index: int,
reason: DialogReason,
result: object = None,
):
super(WaterfallStepContext, self).__init__(
dc.dialogs, dc.context, DialogState(dc.stack)
)
self._wf_parent = parent
self._next_called = False
self._index = index
self._options = options
self._reason = reason
self._result = result
self._values = values
self.parent = dc.parent
@property
def index(self) -> int:
return self._index
@property
def options(self) -> object:
return self._options
@property
def reason(self) -> DialogReason:
return self._reason
@property
def result(self) -> object:
return self._result
@property
def values(self) -> Dict[str, object]:
return self._values
async def next(self, result: object) -> DialogTurnResult:
if self._next_called is True:
raise Exception(
"WaterfallStepContext.next(): method already called for dialog and step '%s'[%s]."
% (self._wf_parent.id, self._index)
)
# Trigger next step
self._next_called = True
return await self._wf_parent.resume_dialog(
self, DialogReason.NextCalled, result
)
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_step_context.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/waterfall_step_context.py",
"repo_id": "botbuilder-python",
"token_count": 748
}
| 409 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import aiounittest
from botbuilder.dialogs.prompts import DateTimePrompt, PromptOptions
from botbuilder.core import MessageFactory
from botbuilder.core import ConversationState, MemoryStorage, TurnContext
from botbuilder.dialogs import DialogSet, DialogTurnStatus
from botbuilder.core.adapters import TestAdapter, TestFlow
class DatetimePromptTests(aiounittest.AsyncTestCase):
async def test_date_time_prompt(self):
# Create new ConversationState with MemoryStorage and register the state as middleware.
conver_state = ConversationState(MemoryStorage())
# Create a DialogState property
dialog_state = conver_state.create_property("dialogState")
# Create new DialogSet.
dialogs = DialogSet(dialog_state)
# Create and add DateTime prompt to DialogSet.
date_time_prompt = DateTimePrompt("DateTimePrompt")
dialogs.add(date_time_prompt)
# Initialize TestAdapter
async def exec_test(turn_context: TurnContext) -> None:
prompt_msg = "What date would you like?"
dialog_context = await dialogs.create_context(turn_context)
results = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
options = PromptOptions(prompt=MessageFactory.text(prompt_msg))
await dialog_context.begin_dialog("DateTimePrompt", options)
else:
if results.status == DialogTurnStatus.Complete:
resolution = results.result[0]
reply = MessageFactory.text(
f"Timex: '{resolution.timex}' Value: '{resolution.value}'"
)
await turn_context.send_activity(reply)
await conver_state.save_changes(turn_context)
adapt = TestAdapter(exec_test)
test_flow = TestFlow(None, adapt)
tf2 = await test_flow.send("hello")
tf3 = await tf2.assert_reply("What date would you like?")
tf4 = await tf3.send("5th December 2018 at 9am")
await tf4.assert_reply("Timex: '2018-12-05T09' Value: '2018-12-05 09:00:00'")
|
botbuilder-python/libraries/botbuilder-dialogs/tests/test_date_time_prompt.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/tests/test_date_time_prompt.py",
"repo_id": "botbuilder-python",
"token_count": 893
}
| 410 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC, abstractmethod
from typing import Optional
from aiohttp.web import (
Request,
Response,
WebSocketResponse,
)
from botbuilder.core import Bot
class BotFrameworkHttpAdapterIntegrationBase(ABC):
@abstractmethod
async def process(
self, request: Request, bot: Bot, ws_response: WebSocketResponse = None
) -> Optional[Response]:
raise NotImplementedError()
|
botbuilder-python/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_adapter_integration_base.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/bot_framework_http_adapter_integration_base.py",
"repo_id": "botbuilder-python",
"token_count": 160
}
| 411 |
from .aiohttp_telemetry_middleware import bot_telemetry_middleware
from .aiohttp_telemetry_processor import AiohttpTelemetryProcessor
__all__ = [
"bot_telemetry_middleware",
"AiohttpTelemetryProcessor",
]
|
botbuilder-python/libraries/botbuilder-integration-applicationinsights-aiohttp/botbuilder/integration/applicationinsights/aiohttp/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-integration-applicationinsights-aiohttp/botbuilder/integration/applicationinsights/aiohttp/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 74
}
| 412 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from msrest.serialization import Model
from botbuilder.schema import (
Attachment,
ChannelAccount,
PagedMembersResult,
ConversationAccount,
)
class TabEntityContext(Model):
"""
Current TabRequest entity context, or 'tabEntityId'.
:param tab_entity_id: Gets or sets the entity id of the tab.
:type tab_entity_id: str
"""
_attribute_map = {
"tab_entity_id": {"key": "tabEntityId", "type": "str"},
}
def __init__(self, *, tab_entity_id=None, **kwargs) -> None:
super(TabEntityContext, self).__init__(**kwargs)
self.tab_entity_id = tab_entity_id
self._custom_init()
def _custom_init(self):
return
class TaskModuleRequest(Model):
"""Task module invoke request value payload.
:param data: User input data. Free payload with key-value pairs.
:type data: object
:param context: Current user context, i.e., the current theme
:type context:
~botframework.connector.teams.models.TaskModuleRequestContext
:param tab_entity_context: Gets or sets current tab request context.
:type tab_entity_context:
~botframework.connector.teams.models.TabEntityContext
"""
_attribute_map = {
"data": {"key": "data", "type": "object"},
"context": {"key": "context", "type": "TaskModuleRequestContext"},
"tab_entity_context": {"key": "tabContext", "type": "TabEntityContext"},
}
def __init__(
self, *, data=None, context=None, tab_entity_context=None, **kwargs
) -> None:
super(TaskModuleRequest, self).__init__(**kwargs)
self.data = data
self.context = context
self.tab_entity_context = tab_entity_context
class AppBasedLinkQuery(Model):
"""Invoke request body type for app-based link query.
:param url: Url queried by user
:type url: str
:param state: The magic code for OAuth Flow
:type state: str
"""
_attribute_map = {
"url": {"key": "url", "type": "str"},
"state": {"key": "state", "type": "str"},
}
def __init__(self, *, url: str = None, state: str = None, **kwargs) -> None:
super(AppBasedLinkQuery, self).__init__(**kwargs)
self.url = url
self.state = state
class ChannelInfo(Model):
"""A channel info object which describes the channel.
:param id: Unique identifier representing a channel
:type id: str
:param name: Name of the channel
:type name: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
}
def __init__(self, *, id: str = None, name: str = None, **kwargs) -> None:
super(ChannelInfo, self).__init__(**kwargs)
self.id = id
self.name = name
class CacheInfo(Model):
"""A cache info object which notifies Teams how long an object should be cached for.
:param cache_type: Type of Cache Info
:type cache_type: str
:param cache_duration: Duration of the Cached Info.
:type cache_duration: int
"""
_attribute_map = {
"cache_type": {"key": "cacheType", "type": "str"},
"cache_duration": {"key": "cacheDuration", "type": "int"},
}
def __init__(
self, *, cache_type: str = None, cache_duration: int = None, **kwargs
) -> None:
super(CacheInfo, self).__init__(**kwargs)
self.cache_type = cache_type
self.cache_duration = cache_duration
class ConversationList(Model):
"""List of channels under a team.
:param conversations:
:type conversations:
list[~botframework.connector.teams.models.ChannelInfo]
"""
_attribute_map = {
"conversations": {"key": "conversations", "type": "[ChannelInfo]"},
}
def __init__(self, *, conversations=None, **kwargs) -> None:
super(ConversationList, self).__init__(**kwargs)
self.conversations = conversations
class FileConsentCard(Model):
"""File consent card attachment.
:param description: File description.
:type description: str
:param size_in_bytes: Size of the file to be uploaded in Bytes.
:type size_in_bytes: long
:param accept_context: Context sent back to the Bot if user consented to
upload. This is free flow schema and is sent back in Value field of
Activity.
:type accept_context: object
:param decline_context: Context sent back to the Bot if user declined.
This is free flow schema and is sent back in Value field of Activity.
:type decline_context: object
"""
_attribute_map = {
"description": {"key": "description", "type": "str"},
"size_in_bytes": {"key": "sizeInBytes", "type": "long"},
"accept_context": {"key": "acceptContext", "type": "object"},
"decline_context": {"key": "declineContext", "type": "object"},
}
def __init__(
self,
*,
description: str = None,
size_in_bytes: int = None,
accept_context=None,
decline_context=None,
**kwargs
) -> None:
super(FileConsentCard, self).__init__(**kwargs)
self.description = description
self.size_in_bytes = size_in_bytes
self.accept_context = accept_context
self.decline_context = decline_context
class FileConsentCardResponse(Model):
"""Represents the value of the invoke activity sent when the user acts on a
file consent card.
:param action: The action the user took. Possible values include:
'accept', 'decline'
:type action: str
:param context: The context associated with the action.
:type context: object
:param upload_info: If the user accepted the file, contains information
about the file to be uploaded.
:type upload_info: ~botframework.connector.teams.models.FileUploadInfo
"""
_attribute_map = {
"action": {"key": "action", "type": "str"},
"context": {"key": "context", "type": "object"},
"upload_info": {"key": "uploadInfo", "type": "FileUploadInfo"},
}
def __init__(
self, *, action=None, context=None, upload_info=None, **kwargs
) -> None:
super(FileConsentCardResponse, self).__init__(**kwargs)
self.action = action
self.context = context
self.upload_info = upload_info
class FileDownloadInfo(Model):
"""File download info attachment.
:param download_url: File download url.
:type download_url: str
:param unique_id: Unique Id for the file.
:type unique_id: str
:param file_type: Type of file.
:type file_type: str
:param etag: ETag for the file.
:type etag: object
"""
_attribute_map = {
"download_url": {"key": "downloadUrl", "type": "str"},
"unique_id": {"key": "uniqueId", "type": "str"},
"file_type": {"key": "fileType", "type": "str"},
"etag": {"key": "etag", "type": "object"},
}
def __init__(
self,
*,
download_url: str = None,
unique_id: str = None,
file_type: str = None,
etag=None,
**kwargs
) -> None:
super(FileDownloadInfo, self).__init__(**kwargs)
self.download_url = download_url
self.unique_id = unique_id
self.file_type = file_type
self.etag = etag
class FileInfoCard(Model):
"""File info card.
:param unique_id: Unique Id for the file.
:type unique_id: str
:param file_type: Type of file.
:type file_type: str
:param etag: ETag for the file.
:type etag: object
"""
_attribute_map = {
"unique_id": {"key": "uniqueId", "type": "str"},
"file_type": {"key": "fileType", "type": "str"},
"etag": {"key": "etag", "type": "object"},
}
def __init__(
self, *, unique_id: str = None, file_type: str = None, etag=None, **kwargs
) -> None:
super(FileInfoCard, self).__init__(**kwargs)
self.unique_id = unique_id
self.file_type = file_type
self.etag = etag
class FileUploadInfo(Model):
"""Information about the file to be uploaded.
:param name: Name of the file.
:type name: str
:param upload_url: URL to an upload session that the bot can use to set
the file contents.
:type upload_url: str
:param content_url: URL to file.
:type content_url: str
:param unique_id: ID that uniquely identifies the file.
:type unique_id: str
:param file_type: Type of the file.
:type file_type: str
"""
_attribute_map = {
"name": {"key": "name", "type": "str"},
"upload_url": {"key": "uploadUrl", "type": "str"},
"content_url": {"key": "contentUrl", "type": "str"},
"unique_id": {"key": "uniqueId", "type": "str"},
"file_type": {"key": "fileType", "type": "str"},
}
def __init__(
self,
*,
name: str = None,
upload_url: str = None,
content_url: str = None,
unique_id: str = None,
file_type: str = None,
**kwargs
) -> None:
super(FileUploadInfo, self).__init__(**kwargs)
self.name = name
self.upload_url = upload_url
self.content_url = content_url
self.unique_id = unique_id
self.file_type = file_type
class MessageActionsPayloadApp(Model):
"""Represents an application entity.
:param application_identity_type: The type of application. Possible values
include: 'aadApplication', 'bot', 'tenantBot', 'office365Connector',
'webhook'
:type application_identity_type: str or
~botframework.connector.teams.models.enum
:param id: The id of the application.
:type id: str
:param display_name: The plaintext display name of the application.
:type display_name: str
"""
_attribute_map = {
"application_identity_type": {"key": "applicationIdentityType", "type": "str"},
"id": {"key": "id", "type": "str"},
"display_name": {"key": "displayName", "type": "str"},
}
def __init__(
self,
*,
application_identity_type=None,
id: str = None,
display_name: str = None,
**kwargs
) -> None:
super(MessageActionsPayloadApp, self).__init__(**kwargs)
self.application_identity_type = application_identity_type
self.id = id
self.display_name = display_name
class MessageActionsPayloadAttachment(Model):
"""Represents the attachment in a message.
:param id: The id of the attachment.
:type id: str
:param content_type: The type of the attachment.
:type content_type: str
:param content_url: The url of the attachment, in case of a external link.
:type content_url: str
:param content: The content of the attachment, in case of a code snippet,
email, or file.
:type content: object
:param name: The plaintext display name of the attachment.
:type name: str
:param thumbnail_url: The url of a thumbnail image that might be embedded
in the attachment, in case of a card.
:type thumbnail_url: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"content_type": {"key": "contentType", "type": "str"},
"content_url": {"key": "contentUrl", "type": "str"},
"content": {"key": "content", "type": "object"},
"name": {"key": "name", "type": "str"},
"thumbnail_url": {"key": "thumbnailUrl", "type": "str"},
}
def __init__(
self,
*,
id: str = None,
content_type: str = None,
content_url: str = None,
content=None,
name: str = None,
thumbnail_url: str = None,
**kwargs
) -> None:
super(MessageActionsPayloadAttachment, self).__init__(**kwargs)
self.id = id
self.content_type = content_type
self.content_url = content_url
self.content = content
self.name = name
self.thumbnail_url = thumbnail_url
class MessageActionsPayloadBody(Model):
"""Plaintext/HTML representation of the content of the message.
:param content_type: Type of the content. Possible values include: 'html',
'text'
:type content_type: str
:param content: The content of the body.
:type content: str
"""
_attribute_map = {
"content_type": {"key": "contentType", "type": "str"},
"content": {"key": "content", "type": "str"},
}
def __init__(self, *, content_type=None, content: str = None, **kwargs) -> None:
super(MessageActionsPayloadBody, self).__init__(**kwargs)
self.content_type = content_type
self.content = content
class MessageActionsPayloadConversation(Model):
"""Represents a team or channel entity.
:param conversation_identity_type: The type of conversation, whether a
team or channel. Possible values include: 'team', 'channel'
:type conversation_identity_type: str or
~botframework.connector.teams.models.enum
:param id: The id of the team or channel.
:type id: str
:param display_name: The plaintext display name of the team or channel
entity.
:type display_name: str
"""
_attribute_map = {
"conversation_identity_type": {
"key": "conversationIdentityType",
"type": "str",
},
"id": {"key": "id", "type": "str"},
"display_name": {"key": "displayName", "type": "str"},
}
def __init__(
self,
*,
conversation_identity_type=None,
id: str = None,
display_name: str = None,
**kwargs
) -> None:
super(MessageActionsPayloadConversation, self).__init__(**kwargs)
self.conversation_identity_type = conversation_identity_type
self.id = id
self.display_name = display_name
class MessageActionsPayloadFrom(Model):
"""Represents a user, application, or conversation type that either sent or
was referenced in a message.
:param user: Represents details of the user.
:type user: ~botframework.connector.teams.models.MessageActionsPayloadUser
:param application: Represents details of the app.
:type application:
~botframework.connector.teams.models.MessageActionsPayloadApp
:param conversation: Represents details of the converesation.
:type conversation:
~botframework.connector.teams.models.MessageActionsPayloadConversation
"""
_attribute_map = {
"user": {"key": "user", "type": "MessageActionsPayloadUser"},
"application": {"key": "application", "type": "MessageActionsPayloadApp"},
"conversation": {
"key": "conversation",
"type": "MessageActionsPayloadConversation",
},
}
def __init__(
self, *, user=None, application=None, conversation=None, **kwargs
) -> None:
super(MessageActionsPayloadFrom, self).__init__(**kwargs)
self.user = user
self.application = application
self.conversation = conversation
class MessageActionsPayloadMention(Model):
"""Represents the entity that was mentioned in the message.
:param id: The id of the mentioned entity.
:type id: int
:param mention_text: The plaintext display name of the mentioned entity.
:type mention_text: str
:param mentioned: Provides more details on the mentioned entity.
:type mentioned:
~botframework.connector.teams.models.MessageActionsPayloadFrom
"""
_attribute_map = {
"id": {"key": "id", "type": "int"},
"mention_text": {"key": "mentionText", "type": "str"},
"mentioned": {"key": "mentioned", "type": "MessageActionsPayloadFrom"},
}
def __init__(
self, *, id: int = None, mention_text: str = None, mentioned=None, **kwargs
) -> None:
super(MessageActionsPayloadMention, self).__init__(**kwargs)
self.id = id
self.mention_text = mention_text
self.mentioned = mentioned
class MessageActionsPayloadReaction(Model):
"""Represents the reaction of a user to a message.
:param reaction_type: The type of reaction given to the message. Possible
values include: 'like', 'heart', 'laugh', 'surprised', 'sad', 'angry'
:type reaction_type: str
:param created_date_time: Timestamp of when the user reacted to the
message.
:type created_date_time: str
:param user: The user with which the reaction is associated.
:type user: ~botframework.connector.teams.models.MessageActionsPayloadFrom
"""
_attribute_map = {
"reaction_type": {"key": "reactionType", "type": "str"},
"created_date_time": {"key": "createdDateTime", "type": "str"},
"user": {"key": "user", "type": "MessageActionsPayloadFrom"},
}
def __init__(
self, *, reaction_type=None, created_date_time: str = None, user=None, **kwargs
) -> None:
super(MessageActionsPayloadReaction, self).__init__(**kwargs)
self.reaction_type = reaction_type
self.created_date_time = created_date_time
self.user = user
class MessageActionsPayloadUser(Model):
"""Represents a user entity.
:param user_identity_type: The identity type of the user. Possible values
include: 'aadUser', 'onPremiseAadUser', 'anonymousGuest', 'federatedUser'
:type user_identity_type: str
:param id: The id of the user.
:type id: str
:param display_name: The plaintext display name of the user.
:type display_name: str
"""
_attribute_map = {
"user_identity_type": {"key": "userIdentityType", "type": "str"},
"id": {"key": "id", "type": "str"},
"display_name": {"key": "displayName", "type": "str"},
}
def __init__(
self,
*,
user_identity_type=None,
id: str = None,
display_name: str = None,
**kwargs
) -> None:
super(MessageActionsPayloadUser, self).__init__(**kwargs)
self.user_identity_type = user_identity_type
self.id = id
self.display_name = display_name
class MessageActionsPayload(Model):
"""Represents the individual message within a chat or channel where a message
actions is taken.
:param id: Unique id of the message.
:type id: str
:param reply_to_id: Id of the parent/root message of the thread.
:type reply_to_id: str
:param message_type: Type of message - automatically set to message.
Possible values include: 'message'
:type message_type: str
:param created_date_time: Timestamp of when the message was created.
:type created_date_time: str
:param last_modified_date_time: Timestamp of when the message was edited
or updated.
:type last_modified_date_time: str
:param deleted: Indicates whether a message has been soft deleted.
:type deleted: bool
:param subject: Subject line of the message.
:type subject: str
:param summary: Summary text of the message that could be used for
notifications.
:type summary: str
:param importance: The importance of the message. Possible values include:
'normal', 'high', 'urgent'
:type importance: str
:param locale: Locale of the message set by the client.
:type locale: str
:param link_to_message: Link back to the message.
:type link_to_message: str
:param from_property: Sender of the message.
:type from_property:
~botframework.connector.teams.models.MessageActionsPayloadFrom
:param body: Plaintext/HTML representation of the content of the message.
:type body: ~botframework.connector.teams.models.MessageActionsPayloadBody
:param attachment_layout: How the attachment(s) are displayed in the
message.
:type attachment_layout: str
:param attachments: Attachments in the message - card, image, file, etc.
:type attachments:
list[~botframework.connector.teams.models.MessageActionsPayloadAttachment]
:param mentions: List of entities mentioned in the message.
:type mentions:
list[~botframework.connector.teams.models.MessageActionsPayloadMention]
:param reactions: Reactions for the message.
:type reactions:
list[~botframework.connector.teams.models.MessageActionsPayloadReaction]
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"reply_to_id": {"key": "replyToId", "type": "str"},
"message_type": {"key": "messageType", "type": "str"},
"created_date_time": {"key": "createdDateTime", "type": "str"},
"last_modified_date_time": {"key": "lastModifiedDateTime", "type": "str"},
"deleted": {"key": "deleted", "type": "bool"},
"subject": {"key": "subject", "type": "str"},
"summary": {"key": "summary", "type": "str"},
"importance": {"key": "importance", "type": "str"},
"locale": {"key": "locale", "type": "str"},
"link_to_message": {"key": "linkToMessage", "type": "str"},
"from_property": {"key": "from", "type": "MessageActionsPayloadFrom"},
"body": {"key": "body", "type": "MessageActionsPayloadBody"},
"attachment_layout": {"key": "attachmentLayout", "type": "str"},
"attachments": {
"key": "attachments",
"type": "[MessageActionsPayloadAttachment]",
},
"mentions": {"key": "mentions", "type": "[MessageActionsPayloadMention]"},
"reactions": {"key": "reactions", "type": "[MessageActionsPayloadReaction]"},
}
def __init__(
self,
*,
id: str = None,
reply_to_id: str = None,
message_type=None,
created_date_time: str = None,
last_modified_date_time: str = None,
deleted: bool = None,
subject: str = None,
summary: str = None,
importance=None,
locale: str = None,
link_to_message: str = None,
from_property=None,
body=None,
attachment_layout: str = None,
attachments=None,
mentions=None,
reactions=None,
**kwargs
) -> None:
super(MessageActionsPayload, self).__init__(**kwargs)
self.id = id
self.reply_to_id = reply_to_id
self.message_type = message_type
self.created_date_time = created_date_time
self.last_modified_date_time = last_modified_date_time
self.deleted = deleted
self.subject = subject
self.summary = summary
self.importance = importance
self.locale = locale
self.link_to_message = link_to_message
self.from_property = from_property
self.body = body
self.attachment_layout = attachment_layout
self.attachments = attachments
self.mentions = mentions
self.reactions = reactions
class MessagingExtensionAction(TaskModuleRequest):
"""Messaging extension action.
:param data: User input data. Free payload with key-value pairs.
:type data: object
:param context: Current user context, i.e., the current theme
:type context:
~botframework.connector.teams.models.TaskModuleRequestContext
:param command_id: Id of the command assigned by Bot
:type command_id: str
:param command_context: The context from which the command originates.
Possible values include: 'message', 'compose', 'commandbox'
:type command_context: str
:param bot_message_preview_action: Bot message preview action taken by
user. Possible values include: 'edit', 'send'
:type bot_message_preview_action: str or
~botframework.connector.teams.models.enum
:param bot_activity_preview:
:type bot_activity_preview:
list[~botframework.schema.models.Activity]
:param message_payload: Message content sent as part of the command
request.
:type message_payload:
~botframework.connector.teams.models.MessageActionsPayload
"""
_attribute_map = {
"data": {"key": "data", "type": "object"},
"context": {"key": "context", "type": "TaskModuleRequestContext"},
"command_id": {"key": "commandId", "type": "str"},
"command_context": {"key": "commandContext", "type": "str"},
"bot_message_preview_action": {"key": "botMessagePreviewAction", "type": "str"},
"bot_activity_preview": {"key": "botActivityPreview", "type": "[Activity]"},
"message_payload": {"key": "messagePayload", "type": "MessageActionsPayload"},
}
def __init__(
self,
*,
data=None,
context=None,
command_id: str = None,
command_context=None,
bot_message_preview_action=None,
bot_activity_preview=None,
message_payload=None,
**kwargs
) -> None:
super(MessagingExtensionAction, self).__init__(
data=data, context=context, **kwargs
)
self.command_id = command_id
self.command_context = command_context
self.bot_message_preview_action = bot_message_preview_action
self.bot_activity_preview = bot_activity_preview
self.message_payload = message_payload
class MessagingExtensionActionResponse(Model):
"""Response of messaging extension action.
:param task: The JSON for the Adaptive card to appear in the task module.
:type task: ~botframework.connector.teams.models.TaskModuleResponseBase
:param compose_extension:
:type compose_extension:
~botframework.connector.teams.models.MessagingExtensionResult
:param cache_info: CacheInfo for this MessagingExtensionActionResponse.
:type cache_info: ~botframework.connector.teams.models.CacheInfo
"""
_attribute_map = {
"task": {"key": "task", "type": "TaskModuleResponseBase"},
"compose_extension": {
"key": "composeExtension",
"type": "MessagingExtensionResult",
},
"cache_info": {"key": "cacheInfo", "type": "CacheInfo"},
}
def __init__(
self,
*,
task=None,
compose_extension=None,
cache_info: CacheInfo = None,
**kwargs
) -> None:
super(MessagingExtensionActionResponse, self).__init__(**kwargs)
self.task = task
self.compose_extension = compose_extension
self.cache_info = cache_info
class MessagingExtensionAttachment(Attachment):
"""Messaging extension attachment.
:param content_type: mimetype/Contenttype for the file
:type content_type: str
:param content_url: Content Url
:type content_url: str
:param content: Embedded content
:type content: object
:param name: (OPTIONAL) The name of the attachment
:type name: str
:param thumbnail_url: (OPTIONAL) Thumbnail associated with attachment
:type thumbnail_url: str
:param preview:
:type preview: ~botframework.connector.teams.models.Attachment
"""
_attribute_map = {
"content_type": {"key": "contentType", "type": "str"},
"content_url": {"key": "contentUrl", "type": "str"},
"content": {"key": "content", "type": "object"},
"name": {"key": "name", "type": "str"},
"thumbnail_url": {"key": "thumbnailUrl", "type": "str"},
"preview": {"key": "preview", "type": "Attachment"},
}
def __init__(
self,
*,
content_type: str = None,
content_url: str = None,
content=None,
name: str = None,
thumbnail_url: str = None,
preview=None,
**kwargs
) -> None:
super(MessagingExtensionAttachment, self).__init__(
content_type=content_type,
content_url=content_url,
content=content,
name=name,
thumbnail_url=thumbnail_url,
**kwargs
)
self.preview = preview
class MessagingExtensionParameter(Model):
"""Messaging extension query parameters.
:param name: Name of the parameter
:type name: str
:param value: Value of the parameter
:type value: object
"""
_attribute_map = {
"name": {"key": "name", "type": "str"},
"value": {"key": "value", "type": "object"},
}
def __init__(self, *, name: str = None, value=None, **kwargs) -> None:
super(MessagingExtensionParameter, self).__init__(**kwargs)
self.name = name
self.value = value
class MessagingExtensionQuery(Model):
"""Messaging extension query.
:param command_id: Id of the command assigned by Bot
:type command_id: str
:param parameters: Parameters for the query
:type parameters:
list[~botframework.connector.teams.models.MessagingExtensionParameter]
:param query_options:
:type query_options:
~botframework.connector.teams.models.MessagingExtensionQueryOptions
:param state: State parameter passed back to the bot after
authentication/configuration flow
:type state: str
"""
_attribute_map = {
"command_id": {"key": "commandId", "type": "str"},
"parameters": {"key": "parameters", "type": "[MessagingExtensionParameter]"},
"query_options": {
"key": "queryOptions",
"type": "MessagingExtensionQueryOptions",
},
"state": {"key": "state", "type": "str"},
}
def __init__(
self,
*,
command_id: str = None,
parameters=None,
query_options=None,
state: str = None,
**kwargs
) -> None:
super(MessagingExtensionQuery, self).__init__(**kwargs)
self.command_id = command_id
self.parameters = parameters
self.query_options = query_options
self.state = state
class MessagingExtensionQueryOptions(Model):
"""Messaging extension query options.
:param skip: Number of entities to skip
:type skip: int
:param count: Number of entities to fetch
:type count: int
"""
_attribute_map = {
"skip": {"key": "skip", "type": "int"},
"count": {"key": "count", "type": "int"},
}
def __init__(self, *, skip: int = None, count: int = None, **kwargs) -> None:
super(MessagingExtensionQueryOptions, self).__init__(**kwargs)
self.skip = skip
self.count = count
class MessagingExtensionResponse(Model):
"""Messaging extension response.
:param compose_extension:
:type compose_extension: ~botframework.connector.teams.models.MessagingExtensionResult
:param cache_info: CacheInfo for this MessagingExtensionResponse.
:type cache_info: ~botframework.connector.teams.models.CacheInfo
"""
_attribute_map = {
"compose_extension": {
"key": "composeExtension",
"type": "MessagingExtensionResult",
},
"cache_info": {"key": "cacheInfo", "type": CacheInfo},
}
def __init__(self, *, compose_extension=None, cache_info=None, **kwargs) -> None:
super(MessagingExtensionResponse, self).__init__(**kwargs)
self.compose_extension = compose_extension
self.cache_info = cache_info
class MessagingExtensionResult(Model):
"""Messaging extension result.
:param attachment_layout: Hint for how to deal with multiple attachments.
Possible values include: 'list', 'grid'
:type attachment_layout: str
:param type: The type of the result. Possible values include: 'result',
'auth', 'config', 'message', 'botMessagePreview'
:type type: str
:param attachments: (Only when type is result) Attachments
:type attachments:
list[~botframework.connector.teams.models.MessagingExtensionAttachment]
:param suggested_actions:
:type suggested_actions:
~botframework.connector.teams.models.MessagingExtensionSuggestedAction
:param text: (Only when type is message) Text
:type text: str
:param activity_preview: (Only when type is botMessagePreview) Message
activity to preview
:type activity_preview: ~botframework.connector.teams.models.Activity
"""
_attribute_map = {
"attachment_layout": {"key": "attachmentLayout", "type": "str"},
"type": {"key": "type", "type": "str"},
"attachments": {"key": "attachments", "type": "[MessagingExtensionAttachment]"},
"suggested_actions": {
"key": "suggestedActions",
"type": "MessagingExtensionSuggestedAction",
},
"text": {"key": "text", "type": "str"},
"activity_preview": {"key": "activityPreview", "type": "Activity"},
}
def __init__(
self,
*,
attachment_layout=None,
type=None,
attachments=None,
suggested_actions=None,
text: str = None,
activity_preview=None,
**kwargs
) -> None:
super(MessagingExtensionResult, self).__init__(**kwargs)
self.attachment_layout = attachment_layout
self.type = type
self.attachments = attachments
self.suggested_actions = suggested_actions
self.text = text
self.activity_preview = activity_preview
class MessagingExtensionSuggestedAction(Model):
"""Messaging extension Actions (Only when type is auth or config).
:param actions: Actions
:type actions: list[~botframework.connector.teams.models.CardAction]
"""
_attribute_map = {
"actions": {"key": "actions", "type": "[CardAction]"},
}
def __init__(self, *, actions=None, **kwargs) -> None:
super(MessagingExtensionSuggestedAction, self).__init__(**kwargs)
self.actions = actions
class NotificationInfo(Model):
"""Specifies if a notification is to be sent for the mentions.
:param alert: true if notification is to be sent to the user, false
otherwise.
:type alert: bool
"""
_attribute_map = {
"alert": {"key": "alert", "type": "bool"},
"alert_in_meeting": {"key": "alertInMeeting", "type": "bool"},
"external_resource_url": {"key": "externalResourceUrl", "type": "str"},
}
def __init__(
self,
*,
alert: bool = None,
alert_in_meeting: bool = None,
external_resource_url: str = None,
**kwargs
) -> None:
super(NotificationInfo, self).__init__(**kwargs)
self.alert = alert
self.alert_in_meeting = alert_in_meeting
self.external_resource_url = external_resource_url
class O365ConnectorCard(Model):
"""O365 connector card.
:param title: Title of the item
:type title: str
:param text: Text for the card
:type text: str
:param summary: Summary for the card
:type summary: str
:param theme_color: Theme color for the card
:type theme_color: str
:param sections: Set of sections for the current card
:type sections:
list[~botframework.connector.teams.models.O365ConnectorCardSection]
:param potential_action: Set of actions for the current card
:type potential_action:
list[~botframework.connector.teams.models.O365ConnectorCardActionBase]
"""
_attribute_map = {
"title": {"key": "title", "type": "str"},
"text": {"key": "text", "type": "str"},
"summary": {"key": "summary", "type": "str"},
"theme_color": {"key": "themeColor", "type": "str"},
"sections": {"key": "sections", "type": "[O365ConnectorCardSection]"},
"potential_action": {
"key": "potentialAction",
"type": "[O365ConnectorCardActionBase]",
},
}
def __init__(
self,
*,
title: str = None,
text: str = None,
summary: str = None,
theme_color: str = None,
sections=None,
potential_action=None,
**kwargs
) -> None:
super(O365ConnectorCard, self).__init__(**kwargs)
self.title = title
self.text = text
self.summary = summary
self.theme_color = theme_color
self.sections = sections
self.potential_action = potential_action
class O365ConnectorCardInputBase(Model):
"""O365 connector card input for ActionCard action.
:param type: Input type name. Possible values include: 'textInput',
'dateInput', 'multichoiceInput'
:type type: str
:param id: Input Id. It must be unique per entire O365 connector card.
:type id: str
:param is_required: Define if this input is a required field. Default
value is false.
:type is_required: bool
:param title: Input title that will be shown as the placeholder
:type title: str
:param value: Default value for this input field
:type value: str
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"id": {"key": "id", "type": "str"},
"is_required": {"key": "isRequired", "type": "bool"},
"title": {"key": "title", "type": "str"},
"value": {"key": "value", "type": "str"},
}
def __init__(
self,
*,
type=None,
id: str = None,
is_required: bool = None,
title: str = None,
value: str = None,
**kwargs
) -> None:
super(O365ConnectorCardInputBase, self).__init__(**kwargs)
self.type = type
self.id = id
self.is_required = is_required
self.title = title
self.value = value
class O365ConnectorCardActionBase(Model):
"""O365 connector card action base.
:param type: Type of the action. Possible values include: 'ViewAction',
'OpenUri', 'HttpPOST', 'ActionCard'
:type type: str
:param name: Name of the action that will be used as button title
:type name: str
:param id: Action Id
:type id: str
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"name": {"key": "name", "type": "str"},
"id": {"key": "@id", "type": "str"},
}
def __init__(
self, *, type=None, name: str = None, id: str = None, **kwargs
) -> None:
super(O365ConnectorCardActionBase, self).__init__(**kwargs)
self.type = type
self.name = name
self.id = id
class O365ConnectorCardActionCard(O365ConnectorCardActionBase):
"""O365 connector card ActionCard action.
:param type: Type of the action. Possible values include: 'ViewAction',
'OpenUri', 'HttpPOST', 'ActionCard'
:type type: str
:param name: Name of the action that will be used as button title
:type name: str
:param id: Action Id
:type id: str
:param inputs: Set of inputs contained in this ActionCard whose each item
can be in any subtype of O365ConnectorCardInputBase
:type inputs:
list[~botframework.connector.teams.models.O365ConnectorCardInputBase]
:param actions: Set of actions contained in this ActionCard whose each
item can be in any subtype of O365ConnectorCardActionBase except
O365ConnectorCardActionCard, as nested ActionCard is forbidden.
:type actions:
list[~botframework.connector.teams.models.O365ConnectorCardActionBase]
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"name": {"key": "name", "type": "str"},
"id": {"key": "@id", "type": "str"},
"inputs": {"key": "inputs", "type": "[O365ConnectorCardInputBase]"},
"actions": {"key": "actions", "type": "[O365ConnectorCardActionBase]"},
}
def __init__(
self,
*,
type=None,
name: str = None,
id: str = None,
inputs=None,
actions=None,
**kwargs
) -> None:
super(O365ConnectorCardActionCard, self).__init__(
type=type, name=name, id=id, **kwargs
)
self.inputs = inputs
self.actions = actions
class O365ConnectorCardActionQuery(Model):
"""O365 connector card HttpPOST invoke query.
:param body: The results of body string defined in
IO365ConnectorCardHttpPOST with substituted input values
:type body: str
:param action_id: Action Id associated with the HttpPOST action button
triggered, defined in O365ConnectorCardActionBase.
:type action_id: str
"""
_attribute_map = {
"body": {"key": "body", "type": "str"},
"action_id": {"key": "actionId", "type": "str"},
}
def __init__(self, *, body: str = None, actionId: str = None, **kwargs) -> None:
super(O365ConnectorCardActionQuery, self).__init__(**kwargs)
self.body = body
# This is how it comes in from Teams
self.action_id = actionId
class O365ConnectorCardDateInput(O365ConnectorCardInputBase):
"""O365 connector card date input.
:param type: Input type name. Possible values include: 'textInput',
'dateInput', 'multichoiceInput'
:type type: str
:param id: Input Id. It must be unique per entire O365 connector card.
:type id: str
:param is_required: Define if this input is a required field. Default
value is false.
:type is_required: bool
:param title: Input title that will be shown as the placeholder
:type title: str
:param value: Default value for this input field
:type value: str
:param include_time: Include time input field. Default value is false
(date only).
:type include_time: bool
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"id": {"key": "id", "type": "str"},
"is_required": {"key": "isRequired", "type": "bool"},
"title": {"key": "title", "type": "str"},
"value": {"key": "value", "type": "str"},
"include_time": {"key": "includeTime", "type": "bool"},
}
def __init__(
self,
*,
type=None,
id: str = None,
is_required: bool = None,
title: str = None,
value: str = None,
include_time: bool = None,
**kwargs
) -> None:
super(O365ConnectorCardDateInput, self).__init__(
type=type,
id=id,
is_required=is_required,
title=title,
value=value,
**kwargs
)
self.include_time = include_time
class O365ConnectorCardFact(Model):
"""O365 connector card fact.
:param name: Display name of the fact
:type name: str
:param value: Display value for the fact
:type value: str
"""
_attribute_map = {
"name": {"key": "name", "type": "str"},
"value": {"key": "value", "type": "str"},
}
def __init__(self, *, name: str = None, value: str = None, **kwargs) -> None:
super(O365ConnectorCardFact, self).__init__(**kwargs)
self.name = name
self.value = value
class O365ConnectorCardHttpPOST(O365ConnectorCardActionBase):
"""O365 connector card HttpPOST action.
:param type: Type of the action. Possible values include: 'ViewAction',
'OpenUri', 'HttpPOST', 'ActionCard'
:type type: str
:param name: Name of the action that will be used as button title
:type name: str
:param id: Action Id
:type id: str
:param body: Content to be posted back to bots via invoke
:type body: str
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"name": {"key": "name", "type": "str"},
"id": {"key": "@id", "type": "str"},
"body": {"key": "body", "type": "str"},
}
def __init__(
self, *, type=None, name: str = None, id: str = None, body: str = None, **kwargs
) -> None:
super(O365ConnectorCardHttpPOST, self).__init__(
type=type, name=name, id=id, **kwargs
)
self.body = body
class O365ConnectorCardImage(Model):
"""O365 connector card image.
:param image: URL for the image
:type image: str
:param title: Alternative text for the image
:type title: str
"""
_attribute_map = {
"image": {"key": "image", "type": "str"},
"title": {"key": "title", "type": "str"},
}
def __init__(self, *, image: str = None, title: str = None, **kwargs) -> None:
super(O365ConnectorCardImage, self).__init__(**kwargs)
self.image = image
self.title = title
class O365ConnectorCardMultichoiceInput(O365ConnectorCardInputBase):
"""O365 connector card multiple choice input.
:param type: Input type name. Possible values include: 'textInput',
'dateInput', 'multichoiceInput'
:type type: str
:param id: Input Id. It must be unique per entire O365 connector card.
:type id: str
:param is_required: Define if this input is a required field. Default
value is false.
:type is_required: bool
:param title: Input title that will be shown as the placeholder
:type title: str
:param value: Default value for this input field
:type value: str
:param choices: Set of choices whose each item can be in any subtype of
O365ConnectorCardMultichoiceInputChoice.
:type choices:
list[~botframework.connector.teams.models.O365ConnectorCardMultichoiceInputChoice]
:param style: Choice item rendering style. Default value is 'compact'.
Possible values include: 'compact', 'expanded'
:type style: str
:param is_multi_select: Define if this input field allows multiple
selections. Default value is false.
:type is_multi_select: bool
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"id": {"key": "id", "type": "str"},
"is_required": {"key": "isRequired", "type": "bool"},
"title": {"key": "title", "type": "str"},
"value": {"key": "value", "type": "str"},
"choices": {
"key": "choices",
"type": "[O365ConnectorCardMultichoiceInputChoice]",
},
"style": {"key": "style", "type": "str"},
"is_multi_select": {"key": "isMultiSelect", "type": "bool"},
}
def __init__(
self,
*,
type=None,
id: str = None,
is_required: bool = None,
title: str = None,
value: str = None,
choices=None,
style=None,
is_multi_select: bool = None,
**kwargs
) -> None:
super(O365ConnectorCardMultichoiceInput, self).__init__(
type=type,
id=id,
is_required=is_required,
title=title,
value=value,
**kwargs
)
self.choices = choices
self.style = style
self.is_multi_select = is_multi_select
class O365ConnectorCardMultichoiceInputChoice(Model):
"""O365O365 connector card multiple choice input item.
:param display: The text rendered on ActionCard.
:type display: str
:param value: The value received as results.
:type value: str
"""
_attribute_map = {
"display": {"key": "display", "type": "str"},
"value": {"key": "value", "type": "str"},
}
def __init__(self, *, display: str = None, value: str = None, **kwargs) -> None:
super(O365ConnectorCardMultichoiceInputChoice, self).__init__(**kwargs)
self.display = display
self.value = value
class O365ConnectorCardOpenUri(O365ConnectorCardActionBase):
"""O365 connector card OpenUri action.
:param type: Type of the action. Possible values include: 'ViewAction',
'OpenUri', 'HttpPOST', 'ActionCard'
:type type: str
:param name: Name of the action that will be used as button title
:type name: str
:param id: Action Id
:type id: str
:param targets: Target os / urls
:type targets:
list[~botframework.connector.teams.models.O365ConnectorCardOpenUriTarget]
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"name": {"key": "name", "type": "str"},
"id": {"key": "@id", "type": "str"},
"targets": {"key": "targets", "type": "[O365ConnectorCardOpenUriTarget]"},
}
def __init__(
self, *, type=None, name: str = None, id: str = None, targets=None, **kwargs
) -> None:
super(O365ConnectorCardOpenUri, self).__init__(
type=type, name=name, id=id, **kwargs
)
self.targets = targets
class O365ConnectorCardOpenUriTarget(Model):
"""O365 connector card OpenUri target.
:param os: Target operating system. Possible values include: 'default',
'iOS', 'android', 'windows'
:type os: str
:param uri: Target url
:type uri: str
"""
_attribute_map = {
"os": {"key": "os", "type": "str"},
"uri": {"key": "uri", "type": "str"},
}
def __init__(self, *, os=None, uri: str = None, **kwargs) -> None:
super(O365ConnectorCardOpenUriTarget, self).__init__(**kwargs)
self.os = os
self.uri = uri
class O365ConnectorCardSection(Model):
"""O365 connector card section.
:param title: Title of the section
:type title: str
:param text: Text for the section
:type text: str
:param activity_title: Activity title
:type activity_title: str
:param activity_subtitle: Activity subtitle
:type activity_subtitle: str
:param activity_text: Activity text
:type activity_text: str
:param activity_image: Activity image
:type activity_image: str
:param activity_image_type: Describes how Activity image is rendered.
Possible values include: 'avatar', 'article'
:type activity_image_type: str or
~botframework.connector.teams.models.enum
:param markdown: Use markdown for all text contents. Default value is
true.
:type markdown: bool
:param facts: Set of facts for the current section
:type facts:
list[~botframework.connector.teams.models.O365ConnectorCardFact]
:param images: Set of images for the current section
:type images:
list[~botframework.connector.teams.models.O365ConnectorCardImage]
:param potential_action: Set of actions for the current section
:type potential_action:
list[~botframework.connector.teams.models.O365ConnectorCardActionBase]
"""
_attribute_map = {
"title": {"key": "title", "type": "str"},
"text": {"key": "text", "type": "str"},
"activity_title": {"key": "activityTitle", "type": "str"},
"activity_subtitle": {"key": "activitySubtitle", "type": "str"},
"activity_text": {"key": "activityText", "type": "str"},
"activity_image": {"key": "activityImage", "type": "str"},
"activity_image_type": {"key": "activityImageType", "type": "str"},
"markdown": {"key": "markdown", "type": "bool"},
"facts": {"key": "facts", "type": "[O365ConnectorCardFact]"},
"images": {"key": "images", "type": "[O365ConnectorCardImage]"},
"potential_action": {
"key": "potentialAction",
"type": "[O365ConnectorCardActionBase]",
},
}
def __init__(
self,
*,
title: str = None,
text: str = None,
activity_title: str = None,
activity_subtitle: str = None,
activity_text: str = None,
activity_image: str = None,
activity_image_type=None,
markdown: bool = None,
facts=None,
images=None,
potential_action=None,
**kwargs
) -> None:
super(O365ConnectorCardSection, self).__init__(**kwargs)
self.title = title
self.text = text
self.activity_title = activity_title
self.activity_subtitle = activity_subtitle
self.activity_text = activity_text
self.activity_image = activity_image
self.activity_image_type = activity_image_type
self.markdown = markdown
self.facts = facts
self.images = images
self.potential_action = potential_action
class O365ConnectorCardTextInput(O365ConnectorCardInputBase):
"""O365 connector card text input.
:param type: Input type name. Possible values include: 'textInput',
'dateInput', 'multichoiceInput'
:type type: str
:param id: Input Id. It must be unique per entire O365 connector card.
:type id: str
:param is_required: Define if this input is a required field. Default
value is false.
:type is_required: bool
:param title: Input title that will be shown as the placeholder
:type title: str
:param value: Default value for this input field
:type value: str
:param is_multiline: Define if text input is allowed for multiple lines.
Default value is false.
:type is_multiline: bool
:param max_length: Maximum length of text input. Default value is
unlimited.
:type max_length: float
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"id": {"key": "id", "type": "str"},
"is_required": {"key": "isRequired", "type": "bool"},
"title": {"key": "title", "type": "str"},
"value": {"key": "value", "type": "str"},
"is_multiline": {"key": "isMultiline", "type": "bool"},
"max_length": {"key": "maxLength", "type": "float"},
}
def __init__(
self,
*,
type=None,
id: str = None,
is_required: bool = None,
title: str = None,
value: str = None,
is_multiline: bool = None,
max_length: float = None,
**kwargs
) -> None:
super(O365ConnectorCardTextInput, self).__init__(
type=type,
id=id,
is_required=is_required,
title=title,
value=value,
**kwargs
)
self.is_multiline = is_multiline
self.max_length = max_length
class O365ConnectorCardViewAction(O365ConnectorCardActionBase):
"""O365 connector card ViewAction action.
:param type: Type of the action. Possible values include: 'ViewAction',
'OpenUri', 'HttpPOST', 'ActionCard'
:type type: str
:param name: Name of the action that will be used as button title
:type name: str
:param id: Action Id
:type id: str
:param target: Target urls, only the first url effective for card button
:type target: list[str]
"""
_attribute_map = {
"type": {"key": "@type", "type": "str"},
"name": {"key": "name", "type": "str"},
"id": {"key": "@id", "type": "str"},
"target": {"key": "target", "type": "[str]"},
}
def __init__(
self, *, type=None, name: str = None, id: str = None, target=None, **kwargs
) -> None:
super(O365ConnectorCardViewAction, self).__init__(
type=type, name=name, id=id, **kwargs
)
self.target = target
class SigninStateVerificationQuery(Model):
"""Signin state (part of signin action auth flow) verification invoke query.
:param state: The state string originally received when the signin web
flow is finished with a state posted back to client via tab SDK
microsoftTeams.authentication.notifySuccess(state)
:type state: str
"""
_attribute_map = {
"state": {"key": "state", "type": "str"},
}
def __init__(self, *, state: str = None, **kwargs) -> None:
super(SigninStateVerificationQuery, self).__init__(**kwargs)
self.state = state
class TaskModuleResponseBase(Model):
"""Base class for Task Module responses.
:param type: Choice of action options when responding to the task/submit
message. Possible values include: 'message', 'continue'
:type type: str
"""
_attribute_map = {
"type": {"key": "type", "type": "str"},
}
def __init__(self, *, type=None, **kwargs) -> None:
super(TaskModuleResponseBase, self).__init__(**kwargs)
self.type = type
class TaskModuleContinueResponse(TaskModuleResponseBase):
"""Task Module Response with continue action.
:param value: The JSON for the Adaptive card to appear in the task module.
:type value: ~botframework.connector.teams.models.TaskModuleTaskInfo
"""
_attribute_map = {
"type": {"key": "type", "type": "str"},
"value": {"key": "value", "type": "TaskModuleTaskInfo"},
}
def __init__(self, *, value=None, **kwargs) -> None:
super(TaskModuleContinueResponse, self).__init__(type="continue", **kwargs)
self.value = value
class TaskModuleMessageResponse(TaskModuleResponseBase):
"""Task Module response with message action.
:param value: Teams will display the value of value in a popup message
box.
:type value: str
"""
_attribute_map = {
"type": {"key": "type", "type": "str"},
"value": {"key": "value", "type": "str"},
}
def __init__(self, *, value: str = None, **kwargs) -> None:
super(TaskModuleMessageResponse, self).__init__(type="message", **kwargs)
self.value = value
class TaskModuleRequestContext(Model):
"""Current user context, i.e., the current theme.
:param theme:
:type theme: str
"""
_attribute_map = {
"theme": {"key": "theme", "type": "str"},
}
def __init__(self, *, theme: str = None, **kwargs) -> None:
super(TaskModuleRequestContext, self).__init__(**kwargs)
self.theme = theme
class TaskModuleResponse(Model):
"""Envelope for Task Module Response.
:param task: The JSON for the Adaptive card to appear in the task module.
:type task: ~botframework.connector.teams.models.TaskModuleResponseBase
:param cache_info: CacheInfo for this TaskModuleResponse.
:type cache_info: ~botframework.connector.teams.models.CacheInfo
"""
_attribute_map = {
"task": {"key": "task", "type": "TaskModuleResponseBase"},
"cache_info": {"key": "cacheInfo", "type": "CacheInfo"},
}
def __init__(self, *, task=None, cache_info=None, **kwargs) -> None:
super(TaskModuleResponse, self).__init__(**kwargs)
self.task = task
self.cache_info = cache_info
class TaskModuleTaskInfo(Model):
"""Metadata for a Task Module.
:param title: Appears below the app name and to the right of the app icon.
:type title: str
:param height: This can be a number, representing the task module's height
in pixels, or a string, one of: small, medium, large.
:type height: object
:param width: This can be a number, representing the task module's width
in pixels, or a string, one of: small, medium, large.
:type width: object
:param url: The URL of what is loaded as an iframe inside the task module.
One of url or card is required.
:type url: str
:param card: The JSON for the Adaptive card to appear in the task module.
:type card: ~botframework.connector.teams.models.Attachment
:param fallback_url: If a client does not support the task module feature,
this URL is opened in a browser tab.
:type fallback_url: str
:param completion_bot_id: If a client does not support the task module
feature, this URL is opened in a browser tab.
:type completion_bot_id: str
"""
_attribute_map = {
"title": {"key": "title", "type": "str"},
"height": {"key": "height", "type": "object"},
"width": {"key": "width", "type": "object"},
"url": {"key": "url", "type": "str"},
"card": {"key": "card", "type": "Attachment"},
"fallback_url": {"key": "fallbackUrl", "type": "str"},
"completion_bot_id": {"key": "completionBotId", "type": "str"},
}
def __init__(
self,
*,
title: str = None,
height=None,
width=None,
url: str = None,
card=None,
fallback_url: str = None,
completion_bot_id: str = None,
**kwargs
) -> None:
super(TaskModuleTaskInfo, self).__init__(**kwargs)
self.title = title
self.height = height
self.width = width
self.url = url
self.card = card
self.fallback_url = fallback_url
self.completion_bot_id = completion_bot_id
class TeamDetails(Model):
"""Details related to a team.
:param id: Unique identifier representing a team
:type id: str
:param name: Name of team.
:type name: str
:param aad_group_id: Azure Active Directory (AAD) Group Id for the team.
:type aad_group_id: str
:param channel_count: The count of channels in the team.
:type channel_count: int
:param member_count: The count of members in the team.
:type member_count: int
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"aad_group_id": {"key": "aadGroupId", "type": "str"},
"channel_count": {"key": "channelCount", "type": "int"},
"member_count": {"key": "memberCount", "type": "int"},
}
def __init__(
self,
*,
id: str = None,
name: str = None,
aad_group_id: str = None,
member_count: int = None,
channel_count: int = None,
**kwargs
) -> None:
super(TeamDetails, self).__init__(**kwargs)
self.id = id
self.name = name
self.aad_group_id = aad_group_id
self.channel_count = channel_count
self.member_count = member_count
class TeamInfo(Model):
"""Describes a team.
:param id: Unique identifier representing a team
:type id: str
:param name: Name of team.
:type name: str
:param name: Azure AD Teams group ID.
:type name: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"aad_group_id": {"key": "aadGroupId", "type": "str"},
}
def __init__(
self, *, id: str = None, name: str = None, aad_group_id: str = None, **kwargs
) -> None:
super(TeamInfo, self).__init__(**kwargs)
self.id = id
self.name = name
self.aad_group_id = aad_group_id
class TeamsChannelAccount(ChannelAccount):
"""Teams channel account detailing user Azure Active Directory details.
:param id: Channel id for the user or bot on this channel (Example:
[email protected], or @joesmith or 123456)
:type id: str
:param name: Display friendly name
:type name: str
:param given_name: Given name part of the user name.
:type given_name: str
:param surname: Surname part of the user name.
:type surname: str
:param email: Email Id of the user.
:type email: str
:param user_principal_name: Unique user principal name.
:type user_principal_name: str
:param tenant_id: Tenant Id of the user.
:type tenant_id: str
:param user_role: User Role of the user.
:type user_role: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
"name": {"key": "name", "type": "str"},
"given_name": {"key": "givenName", "type": "str"},
"surname": {"key": "surname", "type": "str"},
"email": {"key": "email", "type": "str"},
"user_principal_name": {"key": "userPrincipalName", "type": "str"},
"aad_object_id": {"key": "aadObjectId", "type": "str"},
"tenant_id": {"key": "tenantId", "type": "str"},
"user_role": {"key": "userRole", "type": "str"},
}
def __init__(
self,
*,
id: str = None,
name: str = None,
given_name: str = None,
surname: str = None,
email: str = None,
user_principal_name: str = None,
tenant_id: str = None,
user_role: str = None,
**kwargs
) -> None:
super(TeamsChannelAccount, self).__init__(id=id, name=name, **kwargs)
self.given_name = given_name
self.surname = surname
self.email = email
self.user_principal_name = user_principal_name
self.tenant_id = tenant_id
self.user_role = user_role
class TeamsPagedMembersResult(PagedMembersResult):
"""Page of members for Teams.
:param continuation_token: Paging token
:type continuation_token: str
:param members: The Teams Channel Accounts.
:type members: list[~botframework.connector.models.TeamsChannelAccount]
"""
_attribute_map = {
"continuation_token": {"key": "continuationToken", "type": "str"},
"members": {"key": "members", "type": "[TeamsChannelAccount]"},
}
def __init__(
self,
*,
continuation_token: str = None,
members: List[TeamsChannelAccount] = None,
**kwargs
) -> None:
super(TeamsPagedMembersResult, self).__init__(
continuation_token=continuation_token, members=members, **kwargs
)
self.continuation_token = continuation_token
self.members = members
class TeamsChannelData(Model):
"""Channel data specific to messages received in Microsoft Teams.
:param channel: Information about the channel in which the message was
sent
:type channel: ~botframework.connector.teams.models.ChannelInfo
:param event_type: Type of event.
:type event_type: str
:param team: Information about the team in which the message was sent
:type team: ~botframework.connector.teams.models.TeamInfo
:param notification: Notification settings for the message
:type notification: ~botframework.connector.teams.models.NotificationInfo
:param tenant: Information about the tenant in which the message was sent
:type tenant: ~botframework.connector.teams.models.TenantInfo
:param meeting: Information about the meeting in which the message was sent
:type meeting: ~botframework.connector.teams.models.TeamsMeetingInfo
"""
_attribute_map = {
"channel": {"key": "channel", "type": "ChannelInfo"},
"event_type": {"key": "eventType", "type": "str"},
"team": {"key": "team", "type": "TeamInfo"},
"notification": {"key": "notification", "type": "NotificationInfo"},
"tenant": {"key": "tenant", "type": "TenantInfo"},
"meeting": {"key": "meeting", "type": "TeamsMeetingInfo"},
}
def __init__(
self,
*,
channel=None,
event_type: str = None,
team=None,
notification=None,
tenant=None,
meeting=None,
**kwargs
) -> None:
super(TeamsChannelData, self).__init__(**kwargs)
self.channel = channel
# doing camel case here since that's how the data comes in
self.event_type = event_type
self.team = team
self.notification = notification
self.tenant = tenant
self.meeting = meeting
class TenantInfo(Model):
"""Describes a tenant.
:param id: Unique identifier representing a tenant
:type id: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
}
def __init__(self, *, id: str = None, **kwargs) -> None:
super(TenantInfo, self).__init__(**kwargs)
self.id = id
class TeamsMeetingInfo(Model):
"""Describes a Teams Meeting.
:param id: Unique identifier representing a meeting
:type id: str
"""
_attribute_map = {
"id": {"key": "id", "type": "str"},
}
def __init__(self, *, id: str = None, **kwargs) -> None:
super(TeamsMeetingInfo, self).__init__(**kwargs)
self.id = id
class MeetingParticipantInfo(Model):
"""Teams meeting participant details.
:param role: Role of the participant in the current meeting.
:type role: str
:param in_meeting: True, if the participant is in the meeting.
:type in_meeting: bool
"""
_attribute_map = {
"role": {"key": "role", "type": "str"},
"in_meeting": {"key": "inMeeting", "type": "bool"},
}
def __init__(self, *, role: str = None, in_meeting: bool = None, **kwargs) -> None:
super(MeetingParticipantInfo, self).__init__(**kwargs)
self.role = role
self.in_meeting = in_meeting
class TeamsMeetingParticipant(Model):
"""Teams participant channel account detailing user Azure Active Directory and meeting participant details.
:param user: Teams Channel Account information for this meeting participant
:type user: TeamsChannelAccount
:param meeting: >Information specific to this participant in the specific meeting.
:type meeting: MeetingParticipantInfo
:param conversation: Conversation Account for the meeting.
:type conversation: ConversationAccount
"""
_attribute_map = {
"user": {"key": "user", "type": "TeamsChannelAccount"},
"meeting": {"key": "meeting", "type": "MeetingParticipantInfo"},
"conversation": {"key": "conversation", "type": "ConversationAccount"},
}
def __init__(
self,
*,
user: TeamsChannelAccount = None,
meeting: MeetingParticipantInfo = None,
conversation: ConversationAccount = None,
**kwargs
) -> None:
super(TeamsMeetingParticipant, self).__init__(**kwargs)
self.user = user
self.meeting = meeting
self.conversation = conversation
class TabContext(Model):
"""
Current tab request context, i.e., the current theme.
:param theme: Gets or sets the current user's theme.
:type theme: str
"""
_attribute_map = {
"theme": {"key": "theme", "type": "str"},
}
def __init__(self, *, theme=None, **kwargs) -> None:
super(TabContext, self).__init__(**kwargs)
self.theme = theme
self._custom_init()
def _custom_init(self):
return
class TabRequest(Model):
"""
Invoke ('tab/fetch') request value payload.
:param tab_entity_context: Gets or sets current tab entity request context.
:type tab_entity_context:
~botframework.connector.teams.models.TabEntityContext
:param context: Gets or sets current tab entity request context.
:type context:
~botframework.connector.teams.models.TabContext
:param state: Gets or sets state, which is the magic code for OAuth Flow.
:type state: str
"""
_attribute_map = {
"tab_entity_context": {"key": "tabContext", "type": "TabEntityContext"},
"context": {"key": "context", "type": "TabContext"},
"state": {"key": "state", "type": "str"},
}
def __init__(
self, *, tab_entity_context=None, context=None, state=None, **kwargs
) -> None:
super(TabRequest, self).__init__(**kwargs)
self.tab_entity_context = tab_entity_context
self.context = context
self.state = state
self._custom_init()
def _custom_init(self):
return
class TabResponseCard(Model):
"""
Envelope for cards for a Tab request.
:param card: Gets or sets adaptive card for this card tab response.
:type card: object
"""
_attribute_map = {
"card": {"key": "card", "type": "object"},
}
def __init__(self, *, card=None, **kwargs) -> None:
super(TabResponseCard, self).__init__(**kwargs)
self.card = card
self._custom_init()
def _custom_init(self):
return
class TabResponseCards(Model):
"""
Envelope for cards for a TabResponse.
:param cards: Gets or sets adaptive card for this card tab response.
:type cards:
list[ ~botframework.connector.teams.models.TabResponseCard]
"""
_attribute_map = {
"cards": {"key": "cards", "type": "[TabResponseCard]"},
}
def __init__(self, *, cards=None, **kwargs) -> None:
super(TabResponseCards, self).__init__(**kwargs)
self.cards = cards
self._custom_init()
def _custom_init(self):
return
class TabResponsePayload(Model):
"""
Initializes a new instance of the TabResponsePayload class.
:param type: Gets or sets choice of action options when responding to the
tab/fetch message. Possible values include: 'continue', 'auth' or 'silentAuth'
:type type: str
:param value: Gets or sets the TabResponseCards when responding to
tab/fetch activity with type of 'continue'.
:type value: TabResponseCards
:param suggested_actions: Gets or sets the Suggested Actions for this card tab.
:type suggested_actions: TabSuggestedActions
"""
_attribute_map = {
"type": {"key": "type", "type": "str"},
"value": {"key": "value", "type": "TabResponseCards"},
"suggested_actions": {"key": "suggestedActions", "type": "TabSuggestedActions"},
}
def __init__(
self, *, type=None, value=None, suggested_actions=None, **kwargs
) -> None:
super(TabResponsePayload, self).__init__(**kwargs)
self.type = type
self.value = value
self.suggested_actions = suggested_actions
self._custom_init()
def _custom_init(self):
return
class TabResponse(Model):
"""
Envelope for Card Tab Response Payload.
:param tab: Possible values include: 'continue', 'auth' or 'silentAuth'
:type type: ~botframework.connector.teams.models.TabResponsePayload
"""
_attribute_map = {
"tab": {"key": "tab", "type": "TabResponsePayload"},
}
def __init__(self, *, tab=None, **kwargs) -> None:
super(TabResponse, self).__init__(**kwargs)
self.tab = tab
self._custom_init()
def _custom_init(self):
return
class TabSumit(Model):
"""
Invoke ('tab/submit') request value payload.
:param tab_entity_context: Gets or sets current tab entity request context.
:type tab_entity_context:
~botframework.connector.teams.models.TabEntityContext
:param context: Gets or sets current tab entity request context.
:type context:
~botframework.connector.teams.models.TabContext
:param data: User input data. Free payload containing properties of key-value pairs.
:type data:
~botframework.connector.teams.models.TabSubmitData
"""
_attribute_map = {
"tab_entity_context": {"key": "tabContext", "type": "TabEntityContext"},
"context": {"key": "context", "type": "TabContext"},
"data": {"key": "data", "type": "TabSubmitData"},
}
def __init__(
self, *, tab_entity_context=None, context=None, data=None, **kwargs
) -> None:
super(TabSumit, self).__init__(**kwargs)
self.tab_entity_context = tab_entity_context
self.context = context
self.data = data
self._custom_init()
def _custom_init(self):
return
class TabSubmitData(Model):
"""
Invoke ('tab/submit') request value payload data.
:param type: Currently, 'tab/submit'.
:type type: str
:param properties: Gets or sets properties that are not otherwise defined by the TabSubmit
type but that might appear in the serialized REST JSON object.
:type properties: object
"""
_attribute_map = {
"type": {"key": "type", "type": "str"},
"properties": {"key": "properties", "type": "{object}"},
}
def __init__(self, *, type=None, properties=None, **kwargs) -> None:
super(TabSubmitData, self).__init__(**kwargs)
self.type = type
self.properties = properties
self._custom_init()
def _custom_init(self):
return
class TabSubmit(Model):
"""
Initializes a new instance of the TabSubmit class.
:param tab_entity_context: Gets or sets current tab entity request context.
:type tab_entity_context: ~botframework.connector.teams.models.TabEntityContext
:param context: Gets or sets current user context, i.e., the current theme.
:type context: ~botframework.connector.teams.models.TabContext
:param data: User input data. Free payload containing properties of key-value pairs.
:type data: ~botframework.connector.teams.models.TabSubmitData
"""
_attribute_map = {
"tab_entity_context": {"key": "tabContext", "type": "TabEntityContext"},
"context": {"key": "context", "type": "TabContext"},
"data": {"key": "data", "type": "TabSubmitData"},
}
def __init__(
self, *, tab_entity_context=None, context=None, data=None, **kwargs
) -> None:
super(TabSubmit, self).__init__(**kwargs)
self.tab_entity_context = tab_entity_context
self.context = context
self.data = data
self._custom_init()
def _custom_init(self):
return
class TabSuggestedActions(Model):
"""
Tab SuggestedActions (Only when type is 'auth' or 'silentAuth').
:param actions: Gets or sets adaptive card for this card tab response.
:type actions: list[~botframework.connector.models.CardAction]
"""
_attribute_map = {
"actions": {"key": "actions", "type": "[CardAction]"},
}
def __init__(self, *, actions=None, **kwargs) -> None:
super(TabSuggestedActions, self).__init__(**kwargs)
self.actions = actions
self._custom_init()
def _custom_init(self):
return
class TaskModuleCardResponse(TaskModuleResponseBase):
"""
Tab Response to 'task/submit' from a tab.
:param value: The JSON for the Adaptive cards to appear in the tab.
:type value: ~botframework.connector.teams.models.TabResponse
"""
_attribute_map = {
"value": {"key": "value", "type": "TabResponse"},
}
def __init__(self, *, value=None, **kwargs) -> None:
super(TaskModuleCardResponse, self).__init__("continue", **kwargs)
self.value = value
self._custom_init()
def _custom_init(self):
return
class MeetingDetailsBase(Model):
"""Specific details of a Teams meeting.
:param id: The meeting's Id, encoded as a BASE64 string.
:type id: str
:param join_url: The URL used to join the meeting.
:type join_url: str
:param title: The title of the meeting.
:type title: str
"""
_attribute_map = {
"id": {"key": "uniqueId", "type": "str"},
"join_url": {"key": "joinUrl", "type": "str"},
"title": {"key": "title", "type": "str"},
}
def __init__(
self, *, id: str = None, join_url: str = None, title: str = None, **kwargs
) -> None:
super(MeetingDetailsBase, self).__init__(**kwargs)
self.id = id
self.join_url = join_url
self.title = title
class MeetingDetails(MeetingDetailsBase):
"""Specific details of a Teams meeting.
:param ms_graph_resource_id: The MsGraphResourceId, used specifically for MS Graph API calls.
:type ms_graph_resource_id: str
:param scheduled_start_time: The meeting's scheduled start time, in UTC.
:type scheduled_start_time: str
:param scheduled_end_time: The meeting's scheduled end time, in UTC.
:type scheduled_end_time: str
:param type: The meeting's type.
:type type: str
"""
_attribute_map = {
"ms_graph_resource_id": {"key": "msGraphResourceId", "type": "str"},
"scheduled_start_time": {"key": "scheduledStartTime", "type": "str"},
"scheduled_end_time": {"key": "scheduledEndTime", "type": "str"},
"type": {"key": "type", "type": "str"},
}
def __init__(
self,
*,
ms_graph_resource_id: str = None,
scheduled_start_time: str = None,
scheduled_end_time: str = None,
type: str = None,
**kwargs
) -> None:
super(MeetingDetails, self).__init__(**kwargs)
self.ms_graph_resource_id = ms_graph_resource_id
self.scheduled_start_time = scheduled_start_time
self.scheduled_end_time = scheduled_end_time
self.type = type
class MeetingInfo(Model):
"""General information about a Teams meeting.
:param details: The specific details of a Teams meeting.
:type details: ~botframework.connector.teams.models.MeetingDetails
:param conversation: The Conversation Account for the meeting.
:type conversation: ~botbuilder.schema.models.ConversationAccount
:param organizer: The meeting's scheduled start time, in UTC.
:type organizer: ~botbuilder.schema.models.TeamsChannelAccount
"""
_attribute_map = {
"details": {"key": "details", "type": "object"},
"conversation": {"key": "conversation", "type": "object"},
"organizer": {"key": "organizer", "type": "object"},
}
def __init__(
self,
*,
details: MeetingDetails = None,
conversation: ConversationAccount = None,
organizer: TeamsChannelAccount = None,
**kwargs
) -> None:
super(MeetingInfo, self).__init__(**kwargs)
self.details = details
self.conversation = conversation
self.organizer = organizer
class MeetingEventDetails(MeetingDetailsBase):
"""Base class for Teams meting start and end events.
:param meeting_type: The meeting's type.
:type meeting_type: str
"""
_attribute_map = {"meeting_type": {"key": "MeetingType", "type": "str"}}
def __init__(self, *, meeting_type: str = None, **kwargs):
super(MeetingEventDetails, self).__init__(**kwargs)
self.meeting_type = meeting_type
class MeetingStartEventDetails(MeetingDetailsBase):
"""Specific details of a Teams meeting start event.
:param start_time: Timestamp for meeting start, in UTC.
:type start_time: str
"""
_attribute_map = {"start_time": {"key": "StartTime", "type": "str"}}
def __init__(self, *, start_time: str = None, **kwargs):
super(MeetingStartEventDetails, self).__init__(**kwargs)
self.start_time = start_time
class MeetingEndEventDetails(MeetingDetailsBase):
"""Specific details of a Teams meeting end event.
:param end_time: Timestamp for meeting end, in UTC.
:type end_time: str
"""
_attribute_map = {"end_time": {"key": "EndTime", "type": "str"}}
def __init__(self, *, end_time: str = None, **kwargs):
super(MeetingEndEventDetails, self).__init__(**kwargs)
self.end_time = end_time
|
botbuilder-python/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-schema/botbuilder/schema/teams/_models_py3.py",
"repo_id": "botbuilder-python",
"token_count": 32258
}
| 413 |
include *.rst
include azure_bdist_wheel.py
|
botbuilder-python/libraries/botframework-connector/MANIFEST.in/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/MANIFEST.in",
"repo_id": "botbuilder-python",
"token_count": 15
}
| 414 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from copy import deepcopy
from json import dumps, loads
from logging import Logger
from botbuilder.schema import (
Activity,
ConversationReference,
ConversationAccount,
ChannelAccount,
InvokeResponse,
RoleTypes,
)
from ..http_client_factory import HttpClientFactory
from ..http_request import HttpRequest
from .._not_implemented_http_client import _NotImplementedHttpClient
from ..skills.bot_framework_client import BotFrameworkClient
from .service_client_credentials_factory import ServiceClientCredentialsFactory
class _BotFrameworkClientImpl(BotFrameworkClient):
def __init__(
self,
credentials_factory: ServiceClientCredentialsFactory,
http_client_factory: HttpClientFactory,
login_endpoint: str,
logger: Logger = None,
):
self._credentials_factory = credentials_factory
self._http_client = (
http_client_factory.create_client()
if http_client_factory
else _NotImplementedHttpClient()
)
self._login_endpoint = login_endpoint
self._logger = logger
async def post_activity(
self,
from_bot_id: str,
to_bot_id: str,
to_url: str,
service_url: str,
conversation_id: str,
activity: Activity,
) -> InvokeResponse:
if not to_url:
raise TypeError("to_url")
if not service_url:
raise TypeError("service_url")
if not conversation_id:
raise TypeError("conversation_id")
if not activity:
raise TypeError("activity")
if self._logger:
self._logger.log(20, f"post to skill '{to_bot_id}' at '{to_url}'")
credentials = await self._credentials_factory.create_credentials(
from_bot_id, to_bot_id, self._login_endpoint, True
)
# Get token for the skill call
token = credentials.get_access_token() if credentials.microsoft_app_id else None
# Clone the activity so we can modify it before sending without impacting the original object.
activity_copy = deepcopy(activity)
# Apply the appropriate addressing to the newly created Activity.
activity_copy.relates_to = ConversationReference(
service_url=activity_copy.service_url,
activity_id=activity_copy.id,
channel_id=activity_copy.channel_id,
conversation=ConversationAccount(
id=activity_copy.conversation.id,
name=activity_copy.conversation.name,
conversation_type=activity_copy.conversation.conversation_type,
aad_object_id=activity_copy.conversation.aad_object_id,
is_group=activity_copy.conversation.is_group,
role=activity_copy.conversation.role,
tenant_id=activity_copy.conversation.tenant_id,
properties=activity_copy.conversation.properties,
),
bot=None,
)
activity_copy.conversation.id = conversation_id
activity_copy.service_url = service_url
if not activity_copy.recipient:
activity_copy.recipient = ChannelAccount(role=RoleTypes.skill)
else:
activity_copy.recipient.role = RoleTypes.skill
headers_dict = {
"Content-type": "application/json; charset=utf-8",
"x-ms-conversation-id": conversation_id,
}
if token:
headers_dict.update(
{
"Authorization": f"Bearer {token}",
}
)
json_content = dumps(activity_copy.serialize()).encode("utf-8")
request = HttpRequest(
request_uri=to_url, content=json_content, headers=headers_dict
)
response = await self._http_client.post(request=request)
data = await response.read_content_str()
if not await response.is_succesful() and self._logger:
# Otherwise we can assume we don't have to deserialize - so just log the content so it's not lost.
self._logger.log(
40,
f"Bot Framework call failed to '{to_url}' returning '{int(response.status_code)}' and '{data}'",
)
return InvokeResponse(
status=response.status_code, body=loads(data) if data else None
)
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/_bot_framework_client_impl.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/_bot_framework_client_impl.py",
"repo_id": "botbuilder-python",
"token_count": 1949
}
| 415 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class Claim:
def __init__(self, claim_type: str, value):
self.type = claim_type
self.value = value
class ClaimsIdentity:
def __init__(
self, claims: dict, is_authenticated: bool, authentication_type: str = None
):
self.claims = claims
self.is_authenticated = is_authenticated
self.authentication_type = authentication_type
def get_claim_value(self, claim_type: str):
return self.claims.get(claim_type)
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/claims_identity.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/claims_identity.py",
"repo_id": "botbuilder-python",
"token_count": 212
}
| 416 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC, abstractmethod
from base64 import b64encode
from json import dumps
from typing import Dict, List
from botbuilder.schema import Activity, TokenResponse, TokenExchangeState
from botframework.connector.token_api.models import (
SignInUrlResponse,
TokenExchangeRequest,
TokenStatus,
)
class UserTokenClient(ABC):
@abstractmethod
async def get_user_token(
self, user_id: str, connection_name: str, channel_id: str, magic_code: str
) -> TokenResponse:
"""
Attempts to retrieve the token for a user that's in a login flow.
:param user_id: The user id that will be associated with the token.
:param connection_name: Name of the auth connection to use.
:param channel_id: The channel Id that will be associated with the token.
:param magic_code: (Optional) Optional user entered code to validate.
:return: A TokenResponse object.
"""
raise NotImplementedError()
@abstractmethod
async def get_sign_in_resource(
self, connection_name: str, activity: Activity, final_redirect: str
) -> SignInUrlResponse:
"""
Get the raw signin link to be sent to the user for signin for a connection name.
:param connection_name: Name of the auth connection to use.
:param activity: The Activity from which to derive the token exchange state.
:param final_redirect: The final URL that the OAuth flow will redirect to.
:return: A SignInUrlResponse.
"""
raise NotImplementedError()
@abstractmethod
async def sign_out_user(self, user_id: str, connection_name: str, channel_id: str):
"""
Signs the user out with the token server.
:param user_id: The user id that will be associated with the token.
:param connection_name: Name of the auth connection to use.
:param channel_id: The channel Id that will be associated with the token.
"""
raise NotImplementedError()
@abstractmethod
async def get_token_status(
self, user_id: str, channel_id: str, include_filter: str
) -> List[TokenStatus]:
"""
Retrieves the token status for each configured connection for the given user.
:param user_id: The user id that will be associated with the token.
:param channel_id: The channel Id that will be associated with the token.
:param include_filter: The include filter.
:return: A list of TokenStatus objects.
"""
raise NotImplementedError()
@abstractmethod
async def get_aad_tokens(
self,
user_id: str,
connection_name: str,
resource_urls: List[str],
channel_id: str,
) -> Dict[str, TokenResponse]:
"""
Retrieves Azure Active Directory tokens for particular resources on a configured connection.
:param user_id: The user id that will be associated with the token.
:param connection_name: Name of the auth connection to use.
:param resource_urls: The list of resource URLs to retrieve tokens for.
:param channel_id: The channel Id that will be associated with the token.
:return: A Dictionary of resource_urls to the corresponding TokenResponse.
"""
raise NotImplementedError()
@abstractmethod
async def exchange_token(
self,
user_id: str,
connection_name: str,
channel_id: str,
exchange_request: TokenExchangeRequest,
) -> TokenResponse:
"""
Performs a token exchange operation such as for single sign-on.
:param user_id The user id that will be associated with the token.
:param connection_name Name of the auth connection to use.
:param channel_id The channel Id that will be associated with the token.
:param exchange_request The exchange request details, either a token to exchange or a uri to exchange.
:return: A TokenResponse object.
"""
raise NotImplementedError()
@staticmethod
def create_token_exchange_state(
app_id: str, connection_name: str, activity: Activity
) -> str:
"""
Helper function to create the Base64 encoded token exchange state used in getSignInResource calls.
:param app_id The app_id to include in the token exchange state.
:param connection_name The connection_name to include in the token exchange state.
:param activity The [Activity](xref:botframework-schema.Activity) from which to derive the token exchange state.
:return: Base64 encoded token exchange state.
"""
if app_id is None or not isinstance(app_id, str):
raise TypeError("app_id")
if connection_name is None or not isinstance(connection_name, str):
raise TypeError("connection_name")
if activity is None or not isinstance(activity, Activity):
raise TypeError("activity")
token_exchange_state = TokenExchangeState(
connection_name=connection_name,
conversation=Activity.get_conversation_reference(activity),
relates_to=activity.relates_to,
ms_app_id=app_id,
)
tes_string = b64encode(
dumps(token_exchange_state.serialize()).encode(
encoding="UTF-8", errors="strict"
)
).decode()
return tes_string
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/user_token_client.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/user_token_client.py",
"repo_id": "botbuilder-python",
"token_count": 2035
}
| 417 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .teams_connector_client import TeamsConnectorClient
from .version import VERSION
__all__ = ["TeamsConnectorClient"]
__version__ = VERSION
|
botbuilder-python/libraries/botframework-connector/botframework/connector/teams/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/teams/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 92
}
| 418 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from ._bot_sign_in_operations import BotSignInOperations
from ._user_token_operations import UserTokenOperations
__all__ = ["BotSignInOperations", "UserTokenOperations"]
|
botbuilder-python/libraries/botframework-connector/botframework/connector/token_api/operations/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/token_api/operations/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 101
}
| 419 |
interactions:
- request:
body: '{"recipient": {"id": "U19KH8EHJ:T03CWQ0QB"}, "channelId": "slack", "text":
"Error!", "from": {"id": "B21UTEF8S:T03CWQ0QB"}, "type": "message"}'
headers:
Accept: [application/json]
Accept-Encoding: ['gzip, deflate']
Connection: [keep-alive]
Content-Length: ['142']
Content-Type: [application/json; charset=utf-8]
User-Agent: [python/3.5.3 (Linux-4.11.0-041100-generic-x86_64-with-Ubuntu-17.04-zesty)
requests/2.18.1 msrest/0.4.23 azure-botframework-connector/v3.0]
method: POST
uri: https://slack.botframework.com/v3/conversations/123/activities
response:
body: {string: "{\r\n \"error\": {\r\n \"code\": \"ServiceError\",\r\n \
\ \"message\": \"Invalid ConversationId: 123\"\r\n }\r\n}"}
headers:
cache-control: [no-cache]
content-length: ['98']
content-type: [application/json; charset=utf-8]
date: ['Tue, 26 Dec 2017 13:51:33 GMT']
expires: ['-1']
pragma: [no-cache]
request-context: ['appId=cid-v1:6814484e-c0d5-40ea-9dba-74ff29ca4f62']
server: [Microsoft-IIS/10.0]
strict-transport-security: [max-age=31536000]
x-powered-by: [ASP.NET]
status: {code: 400, message: Bad Request}
version: 1
|
botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_send_to_conversation_with_invalid_conversation_id_fails.yaml/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_send_to_conversation_with_invalid_conversation_id_fails.yaml",
"repo_id": "botbuilder-python",
"token_count": 595
}
| 420 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .about import __version__, __title__
from .receive_request import ReceiveRequest
from .payload_stream import PayloadStream
from .protocol_adapter import ProtocolAdapter
from .receive_response import ReceiveResponse
from .request_handler import RequestHandler
from .streaming_request import StreamingRequest
from .streaming_response import StreamingResponse
__all__ = [
"ReceiveRequest",
"ProtocolAdapter",
"ReceiveResponse",
"PayloadStream",
"RequestHandler",
"StreamingRequest",
"StreamingResponse",
"__title__",
"__version__",
]
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 225
}
| 421 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from uuid import UUID
from botframework.streaming.payload_transport import PayloadSender
from botframework.streaming.payloads.models import Header
class CancelDisassembler:
def __init__(self, *, sender: PayloadSender, identifier: UUID, type: str):
self._sender = sender
self._identifier = identifier
self._type = type
async def disassemble(self):
header = Header(type=self._type, id=self._identifier, end=True)
header.payload_length = 0
self._sender.send_payload(header, None, True, None)
return
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/disassemblers/cancel_disassembler.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/disassemblers/cancel_disassembler.py",
"repo_id": "botbuilder-python",
"token_count": 232
}
| 422 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import asyncio
from uuid import UUID
from botframework.streaming.payload_transport import PayloadSender
from botframework.streaming.payloads.disassemblers import (
CancelDisassembler,
RequestDisassembler,
ResponseDisassembler,
ResponseMessageStreamDisassembler,
)
from botframework.streaming.payloads.models import PayloadTypes
class SendOperations:
def __init__(self, payload_sender: PayloadSender):
self._payload_sender = payload_sender
async def send_request(
self, identifier: UUID, request: "streaming.StreamingRequest"
):
disassembler = RequestDisassembler(self._payload_sender, identifier, request)
await disassembler.disassemble()
if request.streams:
tasks = [
ResponseMessageStreamDisassembler(
self._payload_sender, content_stream
).disassemble()
for content_stream in request.streams
]
await asyncio.gather(*tasks)
async def send_response(
self, identifier: UUID, response: "streaming.StreamingResponse"
):
disassembler = ResponseDisassembler(self._payload_sender, identifier, response)
await disassembler.disassemble()
if response.streams:
tasks = [
ResponseMessageStreamDisassembler(
self._payload_sender, content_stream
).disassemble()
for content_stream in response.streams
]
await asyncio.gather(*tasks)
async def send_cancel_all(self, identifier: UUID):
disassembler = CancelDisassembler(
sender=self._payload_sender,
identifier=identifier,
type=PayloadTypes.CANCEL_ALL,
)
await disassembler.disassemble()
async def send_cancel_stream(self, identifier: UUID):
disassembler = CancelDisassembler(
sender=self._payload_sender,
identifier=identifier,
type=PayloadTypes.CANCEL_STREAM,
)
await disassembler.disassemble()
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/send_operations.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/send_operations.py",
"repo_id": "botbuilder-python",
"token_count": 925
}
| 423 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
from typing import List, Any
from .web_socket_close_status import WebSocketCloseStatus
from .web_socket_state import WebSocketState
from .web_socket_message_type import WebSocketMessageType
class WebSocketMessage:
def __init__(self, *, message_type: WebSocketMessageType, data: List[int]):
self.message_type = message_type
self.data = data
class WebSocket(ABC):
def dispose(self):
raise NotImplementedError()
async def close(self, close_status: WebSocketCloseStatus, status_description: str):
raise NotImplementedError()
async def receive(self) -> WebSocketMessage:
raise NotImplementedError()
async def send(
self, buffer: Any, message_type: WebSocketMessageType, end_of_message: bool
):
raise NotImplementedError()
@property
def status(self) -> WebSocketState:
raise NotImplementedError()
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/web_socket/web_socket.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/web_socket/web_socket.py",
"repo_id": "botbuilder-python",
"token_count": 339
}
| 424 |
import json
from http import HTTPStatus
import aiounittest
from botbuilder.schema import Activity
from botframework.streaming import ReceiveResponse, StreamingResponse
from botframework.streaming.payloads import ResponseMessageStream
class TestResponses(aiounittest.AsyncTestCase):
async def test_receive_response_empty_streams(self):
sut = ReceiveResponse()
self.assertIsNotNone(sut.streams)
self.assertEqual(0, len(sut.streams))
async def test_receive_response_none_properties(self):
sut = ReceiveResponse()
self.assertEqual(0, sut.status_code)
async def test_streaming_response_null_properties(self):
sut = StreamingResponse()
self.assertEqual(0, sut.status_code)
self.assertIsNone(sut.streams)
async def test_streaming_response_add_stream_none_throws(self):
sut = StreamingResponse()
with self.assertRaises(TypeError):
sut.add_stream(None)
async def test_streaming_response_add_stream_success(self):
sut = StreamingResponse()
content = "hi"
sut.add_stream(content)
self.assertIsNotNone(sut.streams)
self.assertEqual(1, len(sut.streams))
self.assertEqual(content, sut.streams[0].content)
async def test_streaming_response_add_stream_existing_list_success(self):
sut = StreamingResponse()
content = "hi"
content_2 = "hello"
sut.streams = [ResponseMessageStream(content=content_2)]
sut.add_stream(content)
self.assertIsNotNone(sut.streams)
self.assertEqual(2, len(sut.streams))
self.assertEqual(content_2, sut.streams[0].content)
self.assertEqual(content, sut.streams[1].content)
async def test_streaming_response_not_found_success(self):
sut = StreamingResponse.not_found()
self.assertEqual(HTTPStatus.NOT_FOUND, sut.status_code)
self.assertIsNone(sut.streams)
async def test_streaming_response_forbidden_success(self):
sut = StreamingResponse.forbidden()
self.assertEqual(HTTPStatus.FORBIDDEN, sut.status_code)
self.assertIsNone(sut.streams)
async def test_streaming_response_ok_success(self):
sut = StreamingResponse.ok()
self.assertEqual(HTTPStatus.OK, sut.status_code)
self.assertIsNone(sut.streams)
async def test_streaming_response_internal_server_error_success(self):
sut = StreamingResponse.internal_server_error()
self.assertEqual(HTTPStatus.INTERNAL_SERVER_ERROR, sut.status_code)
self.assertIsNone(sut.streams)
async def test_streaming_response_create_with_body_success(self):
content = "hi"
sut = StreamingResponse.create_response(HTTPStatus.OK, content)
self.assertEqual(HTTPStatus.OK, sut.status_code)
self.assertIsNotNone(sut.streams)
self.assertEqual(1, len(sut.streams))
self.assertEqual(content, sut.streams[0].content)
async def test_streaming_response_set_body_string_success(self):
sut = StreamingResponse()
sut.set_body("123")
self.assertIsNotNone(sut.streams)
self.assertEqual(1, len(sut.streams))
self.assertIsInstance(sut.streams[0].content, list)
self.assertIsInstance(sut.streams[0].content[0], int)
self.assertEqual("123", bytes(sut.streams[0].content).decode("utf-8-sig"))
async def test_streaming_response_set_body_none_does_not_throw(self):
sut = StreamingResponse()
sut.set_body(None)
async def test_streaming_response_set_body_success(self):
sut = StreamingResponse()
activity = Activity(text="hi", type="message")
sut.set_body(activity)
self.assertIsNotNone(sut.streams)
self.assertEqual(1, len(sut.streams))
self.assertIsInstance(sut.streams[0].content, list)
self.assertIsInstance(sut.streams[0].content[0], int)
assert_activity = Activity.deserialize(
json.loads(bytes(sut.streams[0].content).decode("utf-8-sig"))
)
self.assertEqual(activity.text, assert_activity.text)
self.assertEqual(activity.type, assert_activity.type)
async def test_receive_base_read_body_as_string_no_content_empty_string(self):
sut = ReceiveResponse()
sut.streams = []
result = sut.read_body_as_str()
self.assertEqual("", result)
|
botbuilder-python/libraries/botframework-streaming/tests/test_responses.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/tests/test_responses.py",
"repo_id": "botbuilder-python",
"token_count": 1847
}
| 425 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from . import dialog_helper
__all__ = ["dialog_helper"]
|
botbuilder-python/tests/experimental/sso/parent/helpers/__init__.py/0
|
{
"file_path": "botbuilder-python/tests/experimental/sso/parent/helpers/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 43
}
| 426 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .child_bot import ChildBot
__all__ = ["ChildBot"]
|
botbuilder-python/tests/skills/skills-buffered/child/bots/__init__.py/0
|
{
"file_path": "botbuilder-python/tests/skills/skills-buffered/child/bots/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 41
}
| 427 |
from .logout_dialog import LogoutDialog
from .main_dialog import MainDialog
__all__ = [
"LogoutDialog",
"MainDialog"
]
|
botbuilder-python/tests/skills/skills-prototypes/dialog-to-dialog/authentication-bot/dialogs/__init__.py/0
|
{
"file_path": "botbuilder-python/tests/skills/skills-prototypes/dialog-to-dialog/authentication-bot/dialogs/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 48
}
| 428 |
from .dummy_middleware import DummyMiddleware
__all__ = ["DummyMiddleware"]
|
botbuilder-python/tests/skills/skills-prototypes/simple-bot-to-bot/simple-root-bot/middleware/__init__.py/0
|
{
"file_path": "botbuilder-python/tests/skills/skills-prototypes/simple-bot-to-bot/simple-root-bot/middleware/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 25
}
| 429 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Abrevehookabove" format="2">
<advance width="1200"/>
<unicode hex="1EB2"/>
<outline>
<component base="A"/>
<component base="brevecomb.case"/>
<component base="hookabovecomb.case" yOffset="400"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_brevehookabove.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_brevehookabove.glif",
"repo_id": "cascadia-code",
"token_count": 112
}
| 430 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Amacron" format="2">
<advance width="1200"/>
<unicode hex="0100"/>
<outline>
<component base="A"/>
<component base="macroncomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_macron.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_macron.glif",
"repo_id": "cascadia-code",
"token_count": 89
}
| 431 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Uhornacute" format="2">
<advance width="1200"/>
<unicode hex="1EE8"/>
<outline>
<component base="Uhorn"/>
<component base="acutecomb.case" xOffset="79"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/U_hornacute.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/U_hornacute.glif",
"repo_id": "cascadia-code",
"token_count": 99
}
| 432 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="_bar" format="2">
<advance width="1200"/>
<anchor x="596" y="318" name="_center"/>
<outline>
<contour>
<point x="254" y="219" type="line"/>
<point x="925" y="219" type="line"/>
<point x="925" y="397" type="line"/>
<point x="254" y="397" type="line"/>
</contour>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_bar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_bar.glif",
"repo_id": "cascadia-code",
"token_count": 234
}
| 433 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ainTwodotshorizontalabove-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="ain-ar.medi"/>
<component base="twodotshorizontalabove-ar" xOffset="10" yOffset="283"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_wodotshorizontalabove-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_wodotshorizontalabove-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 172
}
| 434 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefFathatan-ar" format="2">
<advance width="1200"/>
<unicode hex="FD3D"/>
<outline>
<component base="alef-ar"/>
<component base="fathatan-ar" xOffset="489" yOffset="-252"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>fathatan-ar</string>
</dict>
</array>
<key>com.schriftgestaltung.Glyphs.glyph.leftMetricsKey</key>
<string>alef-ar</string>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefF_athatan-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefF_athatan-ar.glif",
"repo_id": "cascadia-code",
"token_count": 397
}
| 435 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefMaksura-ar.init.alt" format="2">
<advance width="1200"/>
<anchor x="0" y="0" name="overlap"/>
<outline>
<component base="behDotless-ar.init.alt"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.67,0.95,0.38,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefM_aksura-ar.init.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefM_aksura-ar.init.alt.glif",
"repo_id": "cascadia-code",
"token_count": 166
}
| 436 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="bar_bar_greater.liga" format="2">
<advance width="1200"/>
<outline>
<contour>
<point x="1551" y="-10" type="line"/>
<point x="3055" y="575" type="line"/>
<point x="3055" y="843" type="line"/>
<point x="1551" y="1430" type="line"/>
</contour>
<contour>
<point x="1818" y="303" type="line"/>
<point x="1818" y="1116" type="line"/>
<point x="1737" y="1059" type="line"/>
<point x="2705" y="726" type="line"/>
<point x="2705" y="692" type="line"/>
<point x="1737" y="360" type="line"/>
</contour>
<component base="bar" xScale="-1" xOffset="1460"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>bar</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bar_bar_greater.liga.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bar_bar_greater.liga.glif",
"repo_id": "cascadia-code",
"token_count": 526
}
| 437 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behThreedotshorizontalbelow-ar.init.alt" format="2">
<advance width="1200"/>
<anchor x="908" y="-414" name="bottom"/>
<anchor x="0" y="0" name="overlap"/>
<outline>
<component base="behDotless-ar.init.alt"/>
<component base="_dots.horz.below" xOffset="302" yOffset="-18"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>_dots.horz.below</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotshorizontalbelow-ar.init.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotshorizontalbelow-ar.init.alt.glif",
"repo_id": "cascadia-code",
"token_count": 431
}
| 438 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behThreedotsupbelow-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.medi"/>
<component base="threedotsupbelow-ar" xOffset="-10" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotsupbelow-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behT_hreedotsupbelow-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 173
}
| 439 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behVbelow-ar.fina.alt" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.fina.alt"/>
<component base="_vbelow-ar" xOffset="-710" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>_vbelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_below-ar.fina.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_below-ar.fina.alt.glif",
"repo_id": "cascadia-code",
"token_count": 350
}
| 440 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="beheh-ar" format="2">
<advance width="1200"/>
<unicode hex="0680"/>
<outline>
<component base="behDotless-ar"/>
<component base="fourdotsbelow-ar" xOffset="-20" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>fourdotsbelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/beheh-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/beheh-ar.glif",
"repo_id": "cascadia-code",
"token_count": 352
}
| 441 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="checkerBoardFillInverse.stypo" format="2">
<advance width="1200"/>
<outline>
<contour>
<point x="300" y="1900" type="line"/>
<point x="600" y="1900" type="line"/>
<point x="600" y="1305" type="line"/>
<point x="300" y="1305" type="line"/>
</contour>
<contour>
<point x="900" y="1900" type="line"/>
<point x="1200" y="1900" type="line"/>
<point x="1200" y="1305" type="line"/>
<point x="900" y="1305" type="line"/>
</contour>
<contour>
<point x="0" y="1305" type="line"/>
<point x="300" y="1305" type="line"/>
<point x="300" y="710" type="line"/>
<point x="0" y="710" type="line"/>
</contour>
<contour>
<point x="600" y="1305" type="line"/>
<point x="900" y="1305" type="line"/>
<point x="900" y="710" type="line"/>
<point x="600" y="710" type="line"/>
</contour>
<contour>
<point x="300" y="710" type="line"/>
<point x="600" y="710" type="line"/>
<point x="600" y="115" type="line"/>
<point x="300" y="115" type="line"/>
</contour>
<contour>
<point x="900" y="710" type="line"/>
<point x="1200" y="710" type="line"/>
<point x="1200" y="115" type="line"/>
<point x="900" y="115" type="line"/>
</contour>
<contour>
<point x="0" y="115" type="line"/>
<point x="300" y="115" type="line"/>
<point x="300" y="-480" type="line"/>
<point x="0" y="-480" type="line"/>
</contour>
<contour>
<point x="600" y="115" type="line"/>
<point x="900" y="115" type="line"/>
<point x="900" y="-480" type="line"/>
<point x="600" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/checkerB_oardF_illI_nverse.stypo.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/checkerB_oardF_illI_nverse.stypo.glif",
"repo_id": "cascadia-code",
"token_count": 843
}
| 442 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="colonsign" format="2">
<advance width="1200"/>
<unicode hex="20A1"/>
<outline>
<contour>
<point x="740" y="-330" type="line"/>
<point x="1096" y="1692" type="line"/>
<point x="893" y="1716" type="line"/>
<point x="537" y="-306" type="line"/>
</contour>
<contour>
<point x="443" y="-330" type="line"/>
<point x="799" y="1692" type="line"/>
<point x="596" y="1716" type="line"/>
<point x="240" y="-306" type="line"/>
</contour>
<component base="C"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>C</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/colonsign.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/colonsign.glif",
"repo_id": "cascadia-code",
"token_count": 473
}
| 443 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dalVinvertedabove-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="dal-ar.fina"/>
<component base="vinvertedabove-ar" xOffset="36" yOffset="492"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalV_invertedabove-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dalV_invertedabove-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 167
}
| 444 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ddahal-ar" format="2">
<advance width="1200"/>
<unicode hex="068D"/>
<outline>
<component base="dal-ar"/>
<component base="twodotshorizontalbelow-ar" xOffset="-30" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ddahal-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ddahal-ar.glif",
"repo_id": "cascadia-code",
"token_count": 176
}
| 445 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dieresis" format="2">
<advance width="1200"/>
<unicode hex="00A8"/>
<outline>
<component base="dieresiscomb"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>dieresiscomb</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dieresis.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dieresis.glif",
"repo_id": "cascadia-code",
"token_count": 278
}
| 446 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="dotbelow-ar" format="2">
<advance width="1200"/>
<anchor x="602" y="-117" name="_bottom"/>
<anchor x="602" y="-2" name="_bottom.dot"/>
<anchor x="599" y="-414" name="bottom"/>
<outline>
<component base="_dot-ar" yOffset="-782"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>_dot-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dotbelow-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/dotbelow-ar.glif",
"repo_id": "cascadia-code",
"token_count": 373
}
| 447 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ecircumflex" format="2">
<advance width="1200"/>
<unicode hex="00EA"/>
<outline>
<component base="e"/>
<component base="circumflexcomb"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ecircumflex.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ecircumflex.glif",
"repo_id": "cascadia-code",
"token_count": 90
}
| 448 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="eight-persian" format="2">
<advance width="1200"/>
<unicode hex="06F8"/>
<outline>
<component base="eight-ar"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.glyph.leftMetricsKey</key>
<string>eight-ar</string>
<key>com.schriftgestaltung.Glyphs.glyph.rightMetricsKey</key>
<string>eight-ar</string>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/eight-persian.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/eight-persian.glif",
"repo_id": "cascadia-code",
"token_count": 239
}
| 449 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="exclamdouble" format="2">
<advance width="1200"/>
<unicode hex="203C"/>
<outline>
<component base="exclam" xOffset="-270"/>
<component base="exclam" xOffset="270"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>exclam</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>exclam</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/exclamdouble.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/exclamdouble.glif",
"repo_id": "cascadia-code",
"token_count": 427
}
| 450 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="fehDotMovedbelow-ar" format="2">
<advance width="1200"/>
<unicode hex="06A2"/>
<outline>
<component base="fehDotless-ar"/>
<component base="dotbelow-ar" xOffset="290" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>dotbelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fehD_otM_ovedbelow-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fehD_otM_ovedbelow-ar.glif",
"repo_id": "cascadia-code",
"token_count": 353
}
| 451 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="fehThreedotsupbelow-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="fehDotless-ar.init"/>
<component base="threedotsupbelow-ar" xOffset="115" yOffset="-18"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>threedotsupbelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fehT_hreedotsupbelow-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fehT_hreedotsupbelow-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 352
}
| 452 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="finalpedagesh-hb" format="2">
<advance width="1200"/>
<unicode hex="FB43"/>
<outline>
<component base="finalpe-hb"/>
<component base="dagesh-hb" xOffset="-52" yOffset="241"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.97,1,0,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/finalpedagesh-hb.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/finalpedagesh-hb.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 453 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="fullstop-ar" format="2">
<advance width="1200"/>
<unicode hex="06D4"/>
<outline>
<contour>
<point x="352" y="0" type="line"/>
<point x="830" y="0" type="line"/>
<point x="848" y="225" type="line"/>
<point x="371" y="225" type="line"/>
</contour>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fullstop-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/fullstop-ar.glif",
"repo_id": "cascadia-code",
"token_count": 230
}
| 454 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="gafThreedots-ar.init" format="2">
<advance width="1200"/>
<anchor x="422" y="1850" name="top"/>
<outline>
<component base="gaf-ar.init"/>
<component base="threedotsupabove-ar.v2" xScale="0.7" yScale="0.7" xOffset="39" yOffset="998"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/gafT_hreedots-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/gafT_hreedots-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 203
}
| 455 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="geresh-hb" format="2">
<advance width="1200"/>
<unicode hex="05F3"/>
<outline>
<contour>
<point x="365" y="730" type="line"/>
<point x="567" y="730" type="line"/>
<point x="919" y="1420" type="line"/>
<point x="534" y="1420" type="line"/>
</contour>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.97,1,0,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/geresh-hb.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/geresh-hb.glif",
"repo_id": "cascadia-code",
"token_count": 231
}
| 456 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="gueh-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="gaf-ar.init"/>
<component base="twodotsverticalbelow-ar" xOffset="-33" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/gueh-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/gueh-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 168
}
| 457 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="hahFourbelow-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="hah-ar.medi"/>
<component base="four-persianbelow-ar" xOffset="80" yOffset="76"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>four-persianbelow-ar</string>
</dict>
</array>
<key>com.schriftgestaltung.Glyphs.glyph.rightMetricsKey</key>
<string>_part.instroke</string>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahF_ourbelow-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahF_ourbelow-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 395
}
| 458 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="hahTahbelow-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="hah-ar.medi"/>
<component base="tahbelow-ar" xOffset="80" yOffset="76"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>tahbelow-ar</string>
</dict>
</array>
<key>com.schriftgestaltung.Glyphs.glyph.rightMetricsKey</key>
<string>_part.instroke</string>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahT_ahbelow-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahT_ahbelow-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 392
}
| 459 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="hahTwodotsverticalabove-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="hah-ar.medi"/>
<component base="twodotsverticalabove-ar" xOffset="-34" yOffset="352"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahT_wodotsverticalabove-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/hahT_wodotsverticalabove-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 173
}
| 460 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.