text:
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast

from msrest import Serializer

from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.polling.base_polling import LROBasePolling
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict

from .. import models as _models
from .._vendor import MixinABC, _convert_request, _format_url_section
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]

_SERIALIZER = Serializer()
_SERIALIZER.client_side_validation = False

def build_train_custom_model_async_request(
    *,
    json: Optional[_models.TrainRequest] = None,
    content: Any = None,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None))  # type: Optional[str]
    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models")

    # Construct headers
    if content_type is not None:
        _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=_url,
        headers=_headers,
        json=json,
        content=content,
        **kwargs
    )

def build_get_custom_model_request(
    model_id: str,
    *,
    include_keys: Optional[bool] = False,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models/{modelId}")
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    if include_keys is not None:
        _params['includeKeys'] = _SERIALIZER.query("include_keys", include_keys, 'bool')

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=_url,
        params=_params,
        headers=_headers,
        **kwargs
    )

def build_delete_custom_model_request(
    model_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models/{modelId}")
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="DELETE",
        url=_url,
        headers=_headers,
        **kwargs
    )

def build_analyze_with_custom_model_request_initial(
    model_id: str,
    *,
    json: Optional[_models.SourcePath] = None,
    content: Any = None,
    include_text_details: Optional[bool] = False,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None))  # type: Optional[Union[str, "_models.ContentType"]]
    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models/{modelId}/analyze")
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    if include_text_details is not None:
        _params['includeTextDetails'] = _SERIALIZER.query("include_text_details", include_text_details, 'bool')

    # Construct headers
    if content_type is not None:
        _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=_url,
        params=_params,
        headers=_headers,
        json=json,
        content=content,
        **kwargs
    )

def build_get_analyze_form_result_request(
    model_id: str,
    result_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models/{modelId}/analyzeResults/{resultId}")
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
        "resultId": _SERIALIZER.url("result_id", result_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=_url,
        headers=_headers,
        **kwargs
    )

def build_copy_custom_model_request_initial(
    model_id: str,
    *,
    json: Optional[_models.CopyRequest] = None,
    content: Any = None,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None))  # type: Optional[str]
    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models/{modelId}/copy")
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct headers
    if content_type is not None:
        _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=_url,
        headers=_headers,
        json=json,
        content=content,
        **kwargs
    )

def build_get_custom_model_copy_result_request(
    model_id: str,
    result_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models/{modelId}/copyResults/{resultId}")
    path_format_arguments = {
        "modelId": _SERIALIZER.url("model_id", model_id, 'str'),
        "resultId": _SERIALIZER.url("result_id", result_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=_url,
        headers=_headers,
        **kwargs
    )

def build_generate_model_copy_authorization_request(
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models/copyAuthorization")

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=_url,
        headers=_headers,
        **kwargs
    )

def build_analyze_receipt_async_request_initial(
    *,
    json: Optional[_models.SourcePath] = None,
    content: Any = None,
    include_text_details: Optional[bool] = False,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None))  # type: Optional[Union[str, "_models.ContentType"]]
    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/prebuilt/receipt/analyze")

    # Construct parameters
    if include_text_details is not None:
        _params['includeTextDetails'] = _SERIALIZER.query("include_text_details", include_text_details, 'bool')

    # Construct headers
    if content_type is not None:
        _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=_url,
        params=_params,
        headers=_headers,
        json=json,
        content=content,
        **kwargs
    )

def build_get_analyze_receipt_result_request(
    result_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/prebuilt/receipt/analyzeResults/{resultId}")
    path_format_arguments = {
        "resultId": _SERIALIZER.url("result_id", result_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=_url,
        headers=_headers,
        **kwargs
    )

def build_analyze_layout_async_request_initial(
    *,
    json: Optional[_models.SourcePath] = None,
    content: Any = None,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    content_type = kwargs.pop('content_type', _headers.pop('Content-Type', None))  # type: Optional[Union[str, "_models.ContentType"]]
    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/layout/analyze")

    # Construct headers
    if content_type is not None:
        _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str')
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="POST",
        url=_url,
        headers=_headers,
        json=json,
        content=content,
        **kwargs
    )

def build_get_analyze_layout_result_request(
    result_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})

    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/layout/analyzeResults/{resultId}")
    path_format_arguments = {
        "resultId": _SERIALIZER.url("result_id", result_id, 'str'),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=_url,
        headers=_headers,
        **kwargs
    )

def build_list_custom_models_request(
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    op = kwargs.pop('op', _params.pop('op', "full"))  # type: str
    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models")

    # Construct parameters
    _params['op'] = _SERIALIZER.query("op", op, 'str')

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=_url,
        params=_params,
        headers=_headers,
        **kwargs
    )

def build_get_custom_models_request(
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    op = kwargs.pop('op', _params.pop('op', "summary"))  # type: str
    accept = _headers.pop('Accept', "application/json")

    # Construct URL
    _url = kwargs.pop("template_url", "/custom/models")

    # Construct parameters
    _params['op'] = _SERIALIZER.query("op", op, 'str')

    # Construct headers
    _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str')

    return HttpRequest(
        method="GET",
        url=_url,
        params=_params,
        headers=_headers,
        **kwargs
    )

class FormRecognizerClientOperationsMixin(MixinABC):

    @distributed_trace
    def train_custom_model_async(  # pylint: disable=inconsistent-return-statements
        self,
        train_request: _models.TrainRequest,
        **kwargs: Any
    ) -> None:
        """Train Custom Model.

        Create and train a custom model. The request must include a source parameter that is either an
        externally accessible Azure storage blob container Uri (preferably a Shared Access Signature
        Uri) or valid path to a data folder in a locally mounted drive. When local paths are specified,
        they must follow the Linux/Unix path format and be an absolute path rooted to the input mount
        configuration setting value e.g., if '{Mounts:Input}' configuration setting value is '/input'
        then a valid source path would be '/input/contosodataset'. All data to be trained is expected
        to be under the source folder or sub folders under it. Models are trained using documents that
        are of the following content type - 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff'.
        Other type of content is ignored.

        :param train_request: Training request parameters.
        :type train_request: ~azure.ai.formrecognizer.v2_0.models.TrainRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = self._serialize.body(train_request, 'TrainRequest')

        request = build_train_custom_model_async_request(
            content_type=content_type,
            json=_json,
            template_url=self.train_custom_model_async.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        response_headers = {}
        response_headers['Location']=self._deserialize('str', response.headers.get('Location'))

        if cls:
            return cls(pipeline_response, None, response_headers)

    train_custom_model_async.metadata = {'url': "/custom/models"}  # type: ignore

    @distributed_trace
    def get_custom_model(
        self,
        model_id: str,
        include_keys: Optional[bool] = False,
        **kwargs: Any
    ) -> _models.Model:
        """Get Custom Model.

        Get detailed information about a custom model.

        :param model_id: Model identifier.
        :type model_id: str
        :param include_keys: Include list of extracted keys in model information. Default value is
         False.
        :type include_keys: bool
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: Model, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.Model
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.Model]

        request = build_get_custom_model_request(
            model_id=model_id,
            include_keys=include_keys,
            template_url=self.get_custom_model.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('Model', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get_custom_model.metadata = {'url': "/custom/models/{modelId}"}  # type: ignore

    @distributed_trace
    def delete_custom_model(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        **kwargs: Any
    ) -> None:
        """Delete Custom Model.

        Mark model for deletion. Model artifacts will be permanently removed within a predetermined
        period.

        :param model_id: Model identifier.
        :type model_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: None, or the result of cls(response)
        :rtype: None
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        request = build_delete_custom_model_request(
            model_id=model_id,
            template_url=self.delete_custom_model.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [204]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        if cls:
            return cls(pipeline_response, None, {})

    delete_custom_model.metadata = {'url': "/custom/models/{modelId}"}  # type: ignore

    def _analyze_with_custom_model_initial(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        include_text_details: Optional[bool] = False,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = None
        _content = None
        content_type = content_type or ""
        if content_type.split(";")[0] in ['application/json']:
            if file_stream is not None:
                _json = self._serialize.body(file_stream, 'SourcePath')
        elif content_type.split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            _content = file_stream
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(content_type)
            )

        request = build_analyze_with_custom_model_request_initial(
            model_id=model_id,
            content_type=content_type,
            json=_json,
            content=_content,
            include_text_details=include_text_details,
            template_url=self._analyze_with_custom_model_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))

        if cls:
            return cls(pipeline_response, None, response_headers)

    _analyze_with_custom_model_initial.metadata = {'url': "/custom/models/{modelId}/analyze"}  # type: ignore

    @distributed_trace
    def begin_analyze_with_custom_model(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        include_text_details: Optional[bool] = False,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> LROPoller[None]:
        """Analyze Form.

        Extract key-value pairs, tables, and semantic values from a given document. The input document
        must be of one of the supported content types - 'application/pdf', 'image/jpeg', 'image/png' or
        'image/tiff'. Alternatively, use 'application/json' type to specify the location (Uri or local
        path) of the document to be analyzed.

        :param model_id: Model identifier.
        :type model_id: str
        :param include_text_details: Include text lines and element references in the result. Default
         value is False.
        :type include_text_details: bool
        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream. Default value is None.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword content_type: Media type of the body sent to the API. Known values are:
         "application/pdf", "image/jpeg", "image/png", "image/tiff", and "application/json". Default
         value is "application/json".
        :paramtype content_type: str or ~azure.ai.formrecognizer.v2_0.models.ContentType
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._analyze_with_custom_model_initial(  # type: ignore
                model_id=model_id,
                include_text_details=include_text_details,
                file_stream=file_stream,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            if cls:
                return cls(pipeline_response, None, {})

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True:
            polling_method = cast(PollingMethod, LROBasePolling(
                lro_delay,

                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: PollingMethod
        elif polling is False: polling_method = cast(PollingMethod, NoPolling())
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        return LROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_analyze_with_custom_model.metadata = {'url': "/custom/models/{modelId}/analyze"}  # type: ignore

    @distributed_trace
    def get_analyze_form_result(
        self,
        model_id: str,
        result_id: str,
        **kwargs: Any
    ) -> _models.AnalyzeOperationResult:
        """Get Analyze Form Result.

        Obtain current status and the result of the analyze form operation.

        :param model_id: Model identifier.
        :type model_id: str
        :param result_id: Analyze operation result identifier.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AnalyzeOperationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.AnalyzeOperationResult]

        request = build_get_analyze_form_result_request(
            model_id=model_id,
            result_id=result_id,
            template_url=self.get_analyze_form_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('AnalyzeOperationResult', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get_analyze_form_result.metadata = {'url': "/custom/models/{modelId}/analyzeResults/{resultId}"}  # type: ignore

    def _copy_custom_model_initial(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        copy_request: _models.CopyRequest,
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = self._serialize.body(copy_request, 'CopyRequest')

        request = build_copy_custom_model_request_initial(
            model_id=model_id,
            content_type=content_type,
            json=_json,
            template_url=self._copy_custom_model_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))

        if cls:
            return cls(pipeline_response, None, response_headers)

    _copy_custom_model_initial.metadata = {'url': "/custom/models/{modelId}/copy"}  # type: ignore

    @distributed_trace
    def begin_copy_custom_model(  # pylint: disable=inconsistent-return-statements
        self,
        model_id: str,
        copy_request: _models.CopyRequest,
        **kwargs: Any
    ) -> LROPoller[None]:
        """Copy Custom Model.

        Copy custom model stored in this resource (the source) to user specified target Form Recognizer
        resource.

        :param model_id: Model identifier.
        :type model_id: str
        :param copy_request: Copy request parameters.
        :type copy_request: ~azure.ai.formrecognizer.v2_0.models.CopyRequest
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = kwargs.pop("params", {}) or {}

        content_type = kwargs.pop('content_type', _headers.pop('Content-Type', "application/json"))  # type: Optional[str]
        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._copy_custom_model_initial(  # type: ignore
                model_id=model_id,
                copy_request=copy_request,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            if cls:
                return cls(pipeline_response, None, {})

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True:
            polling_method = cast(PollingMethod, LROBasePolling(
                lro_delay,

                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: PollingMethod
        elif polling is False: polling_method = cast(PollingMethod, NoPolling())
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        return LROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_copy_custom_model.metadata = {'url': "/custom/models/{modelId}/copy"}  # type: ignore

    @distributed_trace
    def get_custom_model_copy_result(
        self,
        model_id: str,
        result_id: str,
        **kwargs: Any
    ) -> _models.CopyOperationResult:
        """Get Custom Model Copy Result.

        Obtain current status and the result of a custom model copy operation.

        :param model_id: Model identifier.
        :type model_id: str
        :param result_id: Copy operation result identifier.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: CopyOperationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.CopyOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.CopyOperationResult]

        request = build_get_custom_model_copy_result_request(
            model_id=model_id,
            result_id=result_id,
            template_url=self.get_custom_model_copy_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('CopyOperationResult', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get_custom_model_copy_result.metadata = {'url': "/custom/models/{modelId}/copyResults/{resultId}"}  # type: ignore

    @distributed_trace
    def generate_model_copy_authorization(
        self,
        **kwargs: Any
    ) -> _models.CopyAuthorizationResult:
        """Generate Copy Authorization.

        Generate authorization to copy a model into the target Form Recognizer resource.

        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: CopyAuthorizationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.CopyAuthorizationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.CopyAuthorizationResult]

        request = build_generate_model_copy_authorization_request(
            template_url=self.generate_model_copy_authorization.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [201]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        response_headers = {}
        response_headers['Location']=self._deserialize('str', response.headers.get('Location'))

        deserialized = self._deserialize('CopyAuthorizationResult', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, response_headers)

        return deserialized

    generate_model_copy_authorization.metadata = {'url': "/custom/models/copyAuthorization"}  # type: ignore

    def _analyze_receipt_async_initial(  # pylint: disable=inconsistent-return-statements
        self,
        include_text_details: Optional[bool] = False,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = None
        _content = None
        content_type = content_type or ""
        if content_type.split(";")[0] in ['application/json']:
            if file_stream is not None:
                _json = self._serialize.body(file_stream, 'SourcePath')
        elif content_type.split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            _content = file_stream
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(content_type)
            )

        request = build_analyze_receipt_async_request_initial(
            content_type=content_type,
            json=_json,
            content=_content,
            include_text_details=include_text_details,
            template_url=self._analyze_receipt_async_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))

        if cls:
            return cls(pipeline_response, None, response_headers)

    _analyze_receipt_async_initial.metadata = {'url': "/prebuilt/receipt/analyze"}  # type: ignore

    @distributed_trace
    def begin_analyze_receipt_async(  # pylint: disable=inconsistent-return-statements
        self,
        include_text_details: Optional[bool] = False,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> LROPoller[None]:
        """Analyze Receipt.

        Extract field text and semantic values from a given receipt document. The input document must
        be of one of the supported content types - 'application/pdf', 'image/jpeg', 'image/png' or
        'image/tiff'. Alternatively, use 'application/json' type to specify the location (Uri or local
        path) of the document to be analyzed.

        :param include_text_details: Include text lines and element references in the result. Default
         value is False.
        :type include_text_details: bool
        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream. Default value is None.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword content_type: Media type of the body sent to the API. Known values are:
         "application/pdf", "image/jpeg", "image/png", "image/tiff", and "application/json". Default
         value is "application/json".
        :paramtype content_type: str or ~azure.ai.formrecognizer.v2_0.models.ContentType
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._analyze_receipt_async_initial(  # type: ignore
                include_text_details=include_text_details,
                file_stream=file_stream,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            if cls:
                return cls(pipeline_response, None, {})

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True:
            polling_method = cast(PollingMethod, LROBasePolling(
                lro_delay,

                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: PollingMethod
        elif polling is False: polling_method = cast(PollingMethod, NoPolling())
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        return LROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_analyze_receipt_async.metadata = {'url': "/prebuilt/receipt/analyze"}  # type: ignore

    @distributed_trace
    def get_analyze_receipt_result(
        self,
        result_id: str,
        **kwargs: Any
    ) -> _models.AnalyzeOperationResult:
        """Get Analyze Receipt Result.

        Track the progress and obtain the result of the analyze receipt operation.

        :param result_id: Analyze operation result identifier.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AnalyzeOperationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.AnalyzeOperationResult]

        request = build_get_analyze_receipt_result_request(
            result_id=result_id,
            template_url=self.get_analyze_receipt_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('AnalyzeOperationResult', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get_analyze_receipt_result.metadata = {'url': "/prebuilt/receipt/analyzeResults/{resultId}"}  # type: ignore

    def _analyze_layout_async_initial(  # pylint: disable=inconsistent-return-statements
        self,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> None:
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]

        _json = None
        _content = None
        content_type = content_type or ""
        if content_type.split(";")[0] in ['application/json']:
            if file_stream is not None:
                _json = self._serialize.body(file_stream, 'SourcePath')
        elif content_type.split(";")[0] in ['application/pdf', 'image/jpeg', 'image/png', 'image/tiff']:
            _content = file_stream
        else:
            raise ValueError(
                "The content_type '{}' is not one of the allowed values: "
                "['application/pdf', 'image/jpeg', 'image/png', 'image/tiff', 'application/json']".format(content_type)
            )

        request = build_analyze_layout_async_request_initial(
            content_type=content_type,
            json=_json,
            content=_content,
            template_url=self._analyze_layout_async_initial.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [202]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            raise HttpResponseError(response=response)

        response_headers = {}
        response_headers['Operation-Location']=self._deserialize('str', response.headers.get('Operation-Location'))

        if cls:
            return cls(pipeline_response, None, response_headers)

    _analyze_layout_async_initial.metadata = {'url': "/layout/analyze"}  # type: ignore

    @distributed_trace
    def begin_analyze_layout_async(  # pylint: disable=inconsistent-return-statements
        self,
        file_stream: Optional[Union[IO, _models.SourcePath]] = None,
        *,
        content_type: Optional[Union[str, "_models.ContentType"]] = "application/json",
        **kwargs: Any
    ) -> LROPoller[None]:
        """Analyze Layout.

        Extract text and layout information from a given document. The input document must be of one of
        the supported content types - 'application/pdf', 'image/jpeg', 'image/png' or 'image/tiff'.
        Alternatively, use 'application/json' type to specify the location (Uri or local path) of the
        document to be analyzed.

        :param file_stream: .json, .pdf, .jpg, .png or .tiff type file stream. Default value is None.
        :type file_stream: IO or ~azure.ai.formrecognizer.v2_0.models.SourcePath
        :keyword content_type: Media type of the body sent to the API. Known values are:
         "application/pdf", "image/jpeg", "image/png", "image/tiff", and "application/json". Default
         value is "application/json".
        :paramtype content_type: str or ~azure.ai.formrecognizer.v2_0.models.ContentType
        :keyword callable cls: A custom type or function that will be passed the direct response
        :keyword str continuation_token: A continuation token to restart a poller from a saved state.
        :keyword polling: By default, your polling method will be LROBasePolling. Pass in False for
         this operation to not poll, or pass in your own initialized polling object for a personal
         polling strategy.
        :paramtype polling: bool or ~azure.core.polling.PollingMethod
        :keyword int polling_interval: Default waiting time between two polls for LRO operations if no
         Retry-After header is present.
        :return: An instance of LROPoller that returns either None or the result of cls(response)
        :rtype: ~azure.core.polling.LROPoller[None]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[None]
        polling = kwargs.pop('polling', True)  # type: Union[bool, PollingMethod]
        lro_delay = kwargs.pop(
            'polling_interval',
            self._config.polling_interval
        )
        cont_token = kwargs.pop('continuation_token', None)  # type: Optional[str]
        if cont_token is None:
            raw_result = self._analyze_layout_async_initial(  # type: ignore
                file_stream=file_stream,
                content_type=content_type,
                cls=lambda x,y,z: x,
                headers=_headers,
                params=_params,
                **kwargs
            )
        kwargs.pop('error_map', None)

        def get_long_running_output(pipeline_response):
            if cls:
                return cls(pipeline_response, None, {})

        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }

        if polling is True:
            polling_method = cast(PollingMethod, LROBasePolling(
                lro_delay,

                path_format_arguments=path_format_arguments,
                **kwargs
        ))  # type: PollingMethod
        elif polling is False: polling_method = cast(PollingMethod, NoPolling())
        else: polling_method = polling
        if cont_token:
            return LROPoller.from_continuation_token(
                polling_method=polling_method,
                continuation_token=cont_token,
                client=self._client,
                deserialization_callback=get_long_running_output
            )
        return LROPoller(self._client, raw_result, get_long_running_output, polling_method)

    begin_analyze_layout_async.metadata = {'url': "/layout/analyze"}  # type: ignore

    @distributed_trace
    def get_analyze_layout_result(
        self,
        result_id: str,
        **kwargs: Any
    ) -> _models.AnalyzeOperationResult:
        """Get Analyze Layout Result.

        Track the progress and obtain the result of the analyze layout operation.

        :param result_id: Analyze operation result identifier.
        :type result_id: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AnalyzeOperationResult, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.AnalyzeOperationResult
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = kwargs.pop("params", {}) or {}

        cls = kwargs.pop('cls', None)  # type: ClsType[_models.AnalyzeOperationResult]

        request = build_get_analyze_layout_result_request(
            result_id=result_id,
            template_url=self.get_analyze_layout_result.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('AnalyzeOperationResult', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get_analyze_layout_result.metadata = {'url': "/layout/analyzeResults/{resultId}"}  # type: ignore

    @distributed_trace
    def list_custom_models(
        self,
        **kwargs: Any
    ) -> Iterable[_models.Models]:
        """List Custom Models.

        Get information about all custom models.

        :keyword op: Specify whether to return summary or full list of models. Default value is "full".
         Note that overriding this default value may result in unsupported behavior.
        :paramtype op: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either Models or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.ai.formrecognizer.v2_0.models.Models]
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        op = kwargs.pop('op', _params.pop('op', "full"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.Models]

        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})
        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_custom_models_request(
                    op=op,
                    template_url=self.list_custom_models.metadata['url'],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                path_format_arguments = {
                    "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

            else:

                request = build_list_custom_models_request(
                    op=op,
                    template_url=next_link,
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                path_format_arguments = {
                    "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

                path_format_arguments = {
                    "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
                }
                request.method = "GET"
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize("Models", pipeline_response)
            list_of_elem = deserialized.model_list
            if cls:
                list_of_elem = cls(list_of_elem)
            return deserialized.next_link or None, iter(list_of_elem)

        def get_next(next_link=None):
            request = prepare_request(next_link)

            pipeline_response = self._client._pipeline.run(  # pylint: disable=protected-access
                request,
                stream=False,
                **kwargs
            )
            response = pipeline_response.http_response

            if response.status_code not in [200]:
                map_error(status_code=response.status_code, response=response, error_map=error_map)
                error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
                raise HttpResponseError(response=response, model=error)

            return pipeline_response

        return ItemPaged(
            get_next, extract_data
        )
    list_custom_models.metadata = {'url': "/custom/models"}  # type: ignore

    @distributed_trace
    def get_custom_models(
        self,
        **kwargs: Any
    ) -> _models.Models:
        """Get Custom Models.

        Get information about all custom models.

        :keyword op: Specify whether to return summary or full list of models. Default value is
         "summary". Note that overriding this default value may result in unsupported behavior.
        :paramtype op: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: Models, or the result of cls(response)
        :rtype: ~azure.ai.formrecognizer.v2_0.models.Models
        :raises: ~azure.core.exceptions.HttpResponseError
        """
        error_map = {
            401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
        }
        error_map.update(kwargs.pop('error_map', {}) or {})

        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        op = kwargs.pop('op', _params.pop('op', "summary"))  # type: str
        cls = kwargs.pop('cls', None)  # type: ClsType[_models.Models]

        request = build_get_custom_models_request(
            op=op,
            template_url=self.get_custom_models.metadata['url'],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        path_format_arguments = {
            "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
        }
        request.url = self._client.format_url(request.url, **path_format_arguments)  # type: ignore

        pipeline_response = self._client._pipeline.run(  # type: ignore # pylint: disable=protected-access
            request,
            stream=False,
            **kwargs
        )
        response = pipeline_response.http_response

        if response.status_code not in [200]:
            map_error(status_code=response.status_code, response=response, error_map=error_map)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error)

        deserialized = self._deserialize('Models', pipeline_response)

        if cls:
            return cls(pipeline_response, deserialized, {})

        return deserialized

    get_custom_models.metadata = {'url': "/custom/models"}  # type: ignore


text:
title: Errors
id: eff214d5-cd61-4318-b351-14f765bbe4fc
overview: >
  When a form submission encounters a validation error, this Tag allows
  you to show your user where everything went south.
description: Display form errors.
parameters:
  -
    name: formset|in
    type: string
    description: >
      The name of the formset this tag should be targeting. This is only required if you do _not_ use the `form:set` tag, or
      if you don't have a `formset` defined in the current context.
variables:
  -
    name: value
    type: string
    description: >
      The output of the errors tag is a primitive array. That means in each iteration the `{{ value }}` will output
      a different error message. See the example below.
---
## Example {#example}

This tag can be used both as a conditional and as the data itself.

```
{{ form:set is="contact" }}
    {{ if {form:errors} }}
        <p>Oops, here's what went wrong:</p>
        <ul>
            {{ form:errors }}
                <li>{{ value }}</li>
            {{ /form:errors }}
        </ul>
    {{ /if }}

    {{ form:create }}
        ...
    {{ /form:create }}
{{ /form:set }}
```

Note that since `form:errors` is a Tag rather than a variable, it should be wrapped with single braces when
inside the conditional.

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Text;
using Jasily.DependencyInjection.MemberInjection.Internal;
using JetBrains.Annotations;
using Microsoft.Extensions.DependencyInjection;

namespace Jasily.DependencyInjection.MemberInjection
{
    /// <summary>
    /// extension method for <see cref="IServiceCollection"/>.
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// add <see cref="IMemberInjectorFactory{T}"/> services to <paramref name="serviceCollection"/>.
        /// </summary>
        /// <param name="serviceCollection"></param>
        /// <exception cref="ArgumentNullException">throw if <paramref name="serviceCollection"/> is null.</exception>
        public static void AddMemberInjection([NotNull] this IServiceCollection serviceCollection)
        {
            if (serviceCollection == null) throw new ArgumentNullException(nameof(serviceCollection));

            serviceCollection.AddSingleton(typeof(IMemberInjectorFactory<>), typeof(MemberInjectorFactory<>));
            serviceCollection.AddSingleton(typeof(IInstanceInjector<>), typeof(InstanceInjector<>));
            serviceCollection.AddSingleton(typeof(IInjectFieldsSelector<>), typeof(DefaultInjectFieldsSelector<>));
            serviceCollection.AddSingleton(typeof(IInjectPropertiesSelector<>), typeof(DefaultInjectPropertiesSelector<>));
        }
    }
}


text:
//
//  UIView+HYExtension.h
//  趣味信息分享
//
//  Created by Huanying on 16/4/19.
//  Copyright © 2016年 huanying. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIView (HYExtension)
@property(nonatomic,assign)CGFloat width;
@property(nonatomic,assign)CGFloat height;
@property(nonatomic,assign)CGFloat x;
@property(nonatomic,assign)CGFloat y;
@property(nonatomic,assign)CGSize size;
@property(nonatomic,assign) CGFloat centerX;
@property(nonatomic,assign) CGFloat centerY;
/**
 *  判断一个控件是否真正显示在主窗口上(用户能看见 )
 */
-(BOOL)isShowingOnKeyWindow;

/**在分类中声明@property,只会生成方法的声明,不会生成方法的实现和带有_下划线的成员变量*/
@end


text:
<?php

/**
 * This is the index-action
 *
 * @author Dave Lens <dave.lens@netlash.com>
 */
class FrontendMailmotorIndex extends FrontendBaseBlock
{
	const MAILINGS_PAGING_LIMIT = 10;

	/**
	 * The datagrid object
	 *
	 * @var	SpoonDataGrid
	 */
	private $datagrid;

	/**
	 * Execute the extra
	 */
	public function execute()
	{
		parent::execute();
		$this->tpl->assign('hideContentTitle', true);
		$this->loadTemplate();
		$this->loadDataGrid();
		$this->parseDataGrid();

	}

	/**
	 * Load the datagrid
	 */
	private function loadDataGrid()
	{
		// create a new source-object
		$source = new SpoonDataGridSourceDB(FrontendModel::getContainer()->get('database'), array(FrontendMailmotorModel::QRY_DATAGRID_BROWSE_SENT, array('sent', FRONTEND_LANGUAGE)));

		// create datagrid
		$this->dataGrid = new SpoonDataGrid($source);
		$this->dataGrid->setCompileDirectory(FRONTEND_CACHE_PATH . '/compiled_templates');

		// set hidden columns
		$this->dataGrid->setColumnsHidden(array('id', 'status'));

		// set headers values
		$headers['name'] = SpoonFilter::ucfirst(FL::lbl('Name'));
		$headers['send_on'] = SpoonFilter::ucfirst(FL::lbl('Sent'));

		// set headers
		$this->dataGrid->setHeaderLabels($headers);

		// sorting columns
		$this->dataGrid->setSortingColumns(array('name', 'send_on'), 'name');
		$this->dataGrid->setSortParameter('desc');

		// set colum URLs
		$this->dataGrid->setColumnURL('name', FrontendNavigation::getURLForBlock('mailmotor', 'detail') . '/[id]');

		// set column functions
		$this->dataGrid->setColumnFunction(array('SpoonDate', 'getTimeAgo'), array('[send_on]'), 'send_on', true);

		// add styles
		$this->dataGrid->setColumnAttributes('name', array('class' => 'title'));

		// set paging limit
		$this->dataGrid->setPagingLimit(self::MAILINGS_PAGING_LIMIT);
	}

	/**
	 * parse the datagrid
	 */
	private function parseDataGrid()
	{
		// parse the datagrid in the template
		$this->tpl->assign('dataGrid', ($this->dataGrid->getNumResults() != 0) ? $this->dataGrid->getContent() : false);
	}
}


text:
<?xml version="1.0" ?><section version="5.0" xml:id="nova_manage_images" xml:lang="zh" xmlns="http://docbook.org/ns/docbook" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xlink="http://www.w3.org/1999/xlink">
    <title>Manage images with the nova client</title>
    <para>You can use the nova client to list images, set and delete
        image metadata, delete images, and take a snapshot of a
        running instance to create an image.</para>
    <para>The safest approach is to shut down the instance before you
        take a snapshot.</para>
    <para>You cannot create a snapshot from an instance that has an
        attached volume. Detach the volume, create the image, and
        re-mount the volume.</para>
    <procedure>
        <title>To create an image</title>
        <step>
            <para>Write any buffered data to disk.</para>
            <para>For more information, see the <link xlink:href="http://docs.openstack.org/openstack-ops/content/snapshots.html">Taking Snapshots</link> in the
                    <citetitle>OpenStack Operations Guide</citetitle>.
           </para>
        </step>
        <step>
            <para>To create the image, list instances to get the
                server ID:</para>
            <screen><prompt>$</prompt> <userinput>nova list</userinput></screen>
            <screen><computeroutput>+--------------------------------------+----------------------+--------+------------+-------------+------------------+
| ID                                   | Name                 | Status | Task State | Power State | Networks         |
+--------------------------------------+----------------------+--------+------------+-------------+------------------+
| 84c6e57d-a6b1-44b6-81eb-fcb36afd31b5 | myCirrosServer       | ACTIVE | None       | Running     | private=10.0.0.3 |
+--------------------------------------+----------------------+--------+------------+-------------+------------------+</computeroutput></screen>
            <para>In this example, the server is named
                    <literal>myCirrosServer</literal>. Use this server
                to create a snapshot, as follows:
                <screen><prompt>$</prompt> <userinput>nova image-create myCirrosServer myCirrosImage</userinput></screen>The
                command creates a qemu snapshot and automatically
                uploads the image to your repository. Only the tenant
                that creates the image has access to it.</para>
        </step>
        <step>
            <para>Get details for your image to check its
                status:</para>
            <screen><prompt>$</prompt> <userinput>nova image-show <replaceable>IMAGE</replaceable></userinput></screen>
            <screen><computeroutput>+-------------------------------------+--------------------------------------+
| Property                            | Value                                |
+-------------------------------------+--------------------------------------+
| metadata owner_id                   | 66265572db174a7aa66eba661f58eb9e     |
| minDisk                             | 0                                    |
| metadata instance_type_name         | m1.small                             |
| metadata instance_type_id           | 5                                    |
| metadata instance_type_memory_mb    | 2048                                 |
| id                                  | 7e5142af-1253-4634-bcc6-89482c5f2e8a |
| metadata instance_type_root_gb      | 20                                   |
| metadata instance_type_rxtx_factor  | 1                                    |
| metadata ramdisk_id                 | 3cf852bd-2332-48f4-9ae4-7d926d50945e |
| metadata image_state                | available                            |
| metadata image_location             | snapshot                             |
| minRam                              | 0                                    |
| metadata instance_type_vcpus        | 1                                    |
| status                              | ACTIVE                               |
| updated                             | 2013-07-22T19:46:42Z                 |
| metadata instance_type_swap         | 0                                    |
| metadata instance_type_vcpu_weight  | None                                 |
| metadata base_image_ref             | 397e713c-b95b-4186-ad46-6126863ea0a9 |
| progress                            | 100                                  |
| metadata instance_type_flavorid     | 2                                    |
| OS-EXT-IMG-SIZE:size                | 14221312                             |
| metadata image_type                 | snapshot                             |
| metadata user_id                    | 376744b5910b4b4da7d8e6cb483b06a8     |
| name                                | myCirrosImage                        |
| created                             | 2013-07-22T19:45:58Z                 |
| metadata instance_uuid              | 84c6e57d-a6b1-44b6-81eb-fcb36afd31b5 |
| server                              | 84c6e57d-a6b1-44b6-81eb-fcb36afd31b5 |
| metadata kernel_id                  | df430cc2-3406-4061-b635-a51c16e488ac |
| metadata instance_type_ephemeral_gb | 0                                    |
+-------------------------------------+--------------------------------------+</computeroutput></screen>
            <para>The image status changes from
                    <literal>SAVING</literal> to
                    <literal>ACTIVE</literal>. Only the tenant who
                creates the image has access to it.</para>
        </step>
    </procedure>
    <procedure>
        <title>To launch an instance from your image</title>
        <step>

            <para>To launch an instance from your image, include the
                image ID and flavor ID, as follows:</para>
            <screen><prompt>$</prompt> <userinput>nova boot newServer --image 7e5142af-1253-4634-bcc6-89482c5f2e8a --flavor 3</userinput></screen>
            <screen><computeroutput>+-------------------------------------+--------------------------------------+
| Property                            | Value                                |
+-------------------------------------+--------------------------------------+
| OS-EXT-STS:task_state               | scheduling                           |
| image                               | myCirrosImage                        |
| OS-EXT-STS:vm_state                 | building                             |
| OS-EXT-SRV-ATTR:instance_name       | instance-00000007                    |
| flavor                              | m1.medium                            |
| id                                  | d7efd3e4-d375-46d1-9d57-372b6e4bdb7f |
| security_groups                     | [{u'name': u'default'}]              |
| user_id                             | 376744b5910b4b4da7d8e6cb483b06a8     |
| OS-DCF:diskConfig                   | MANUAL                               |
| accessIPv4                          |                                      |
| accessIPv6                          |                                      |
| progress                            | 0                                    |
| OS-EXT-STS:power_state              | 0                                    |
| OS-EXT-AZ:availability_zone         | nova                                 |
| config_drive                        |                                      |
| status                              | BUILD                                |
| updated                             | 2013-07-22T19:58:33Z                 |
| hostId                              |                                      |
| OS-EXT-SRV-ATTR:host                | None                                 |
| key_name                            | None                                 |
| OS-EXT-SRV-ATTR:hypervisor_hostname | None                                 |
| name                                | newServer                            |
| adminPass                           | jis88nN46RGP                         |
| tenant_id                           | 66265572db174a7aa66eba661f58eb9e     |
| created                             | 2013-07-22T19:58:33Z                 |
| metadata                            | {}                                   |
+-------------------------------------+--------------------------------------+</computeroutput></screen>
        </step>
    </procedure>
    <simplesect xml:id="troubleshoot">
        <title>Troubleshoot image creation</title>
        <itemizedlist>
            <listitem>
                <para>You cannot create a snapshot from an instance
                    that has an attached volume. Detach the volume,
                    create the image, and re-mount the volume.</para>
            </listitem>
            <listitem>
                <para>Make sure the version of qemu you are using is
                    version 0.14 or greater. Older versions of qemu
                    result in an "<literal>unknown option
                    -s</literal>" error message in the
                        <filename>nova-compute.log</filename>.</para>
            </listitem>
            <listitem>
                <para>Examine the
                        <filename>/var/log/nova-api.log</filename> and
                        <filename>/var/log/nova-compute.log</filename>
                    log files for error messages.</para>
            </listitem>
        </itemizedlist>
    </simplesect>
</section>


text:
var _Contact;
const title = "Neem contact op";
function action() {
  return _action.apply(this, arguments);
}
function _action() {
  _action = babelHelpers.asyncToGenerator(function* () {
    return _Contact || (_Contact = /*#__PURE__*/React.createElement(Contact, {
      title: title
    }));
  });
  return _action.apply(this, arguments);
}


text:
package com.yazilimokulu.mvc.services;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yazilimokulu.mvc.daos.LikeNotificationRepository;
import com.yazilimokulu.mvc.daos.PostRepository;
import com.yazilimokulu.mvc.entities.LikeNotification;
import com.yazilimokulu.mvc.entities.Post;
import com.yazilimokulu.mvc.entities.User;

@Service
public class LikeNotificationServiceImpl implements LikeNotificationService {

	@Autowired
	LikeNotificationRepository likeNotificationRepository;

	@Autowired
	PostRepository postRepository;

	@Autowired
	UserService userService;

	@Override
	public void save(Post post) {
		LikeNotification likeNotification;
		List<User> creatorList;
		if(likeNotificationRepository.findByPostId(post.getId()) !=null){
			likeNotification=likeNotificationRepository.findByPostId(post.getId());
			creatorList=likeNotification.getCreatorUsers();
		}else{
			likeNotification = new LikeNotification();
			creatorList = new ArrayList<>();
		}
		User currentUser=userService.currentUser();
		creatorList.add(currentUser);
		currentUser.getCreatedNotificaitons().add(likeNotification);
		likeNotification.setCreatorUsers(creatorList);
		likeNotification.setPost(post);
		likeNotification.setUser(post.getUser());
		likeNotification.setChecked(false);
		post.getUser().getNotifications().add(likeNotification);
		post.setLikeNotification(likeNotification);
		likeNotificationRepository.save(likeNotification);

	}

	@Override
	public List<LikeNotification> getAllUnCheckedNotifiacitons() {
		return likeNotificationRepository.findByChecked(false);
	}

}


text:
[TOC]

Skim the bug to understand where the last sheriff left things and where you should pick up.

Generally, there are two reasons you might see an alert that a previous sheriff already addressed:

1. The sheriff attempted to fix the alert, but the fix was unsuccessful.

2. The sheriff was unable to fix the alert, but wanted a future sheriff to follow up with it.

Several common scenarios for each, along with suggested responses, are listed below.

## Playbook for common scenarios

### Infra Labs took some action to fix a problem (e.g. restarting the device), but it didn't work.

* Ping the bug and let them know that the device is still having issues. Usually, Infra>Labs knows the obvious next step. For example, if the previous solution was to restart the device, the next step may be to replace the device.

* If neither you nor Infra > Labs knows what to do, escalate the issue [on chat](https://hangouts.google.com/group/gbJlAqcAxqfbHbXH3).

### A previous sheriff identified that a problem was due to an infrastructure outage (e.g. the perf dashboard API is temporarily down) and expected the outage to be over by the time that the snooze expired, but it wasn't.

* Escalate the issue to the team by adding the Speed > Benchmarking component and asking about the issue [on chat]((https://hangouts.google.com/group/gbJlAqcAxqfbHbXH3). Get an estimate of when the issue will be fixed and snooze the alert for that amount of time.

### The bot health sheriff was waiting for a response or action from someone, but it never came.

Escalate by (in increasing order of seriousness):

* Disabling the failing benchmark or story if possible (i.e. it's a non-infra failure)

* Pinging the tracking bug again.

* Pinging the person offline.

* Escalate by asking [on chat](https://hangouts.google.com/group/gbJlAqcAxqfbHbXH3) for help (likely from a Speed Ops manager).

### Other

Escalate by asking [on chat](https://hangouts.google.com/group/gbJlAqcAxqfbHbXH3) for help.


text:
/* -*-Java-*-
 ******************************************************************************
 *
 * File:         LmCharsetCoder.java
 * Description:  Wrapper class for Java CharsetDecoder, CharsetEncoder
 *               classes
 *
 * Created:      10/17/2003
 * Language:     Java
 *
 *
 ******************************************************************************
 */
package org.trafodion.sql.udr;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.*;
import java.util.HashMap;

/**
 *  Java class to Character encoding and decoding between different
 *  character sets and Unicode
 *
 **/
public class LmCharsetCoder
{
   static CharsetDecoder iso88591Decoder_;
   static CharsetEncoder iso88591Encoder_;
   static CharsetDecoder ucs2Decoder_;
   static CharsetEncoder ucs2Encoder_;
   static boolean        reset_;
   static CharsetDecoder sjisDecoder_;
   static CharsetEncoder sjisEncoder_;
   static CharsetDecoder utf8Decoder_;
   static CharsetEncoder utf8Encoder_;

   static HashMap<String, Integer> charsetHashMap_;

   static
   {
      // LOAD ISO88591 character set
      Charset iso88591Charset = Charset.forName("ISO-8859-1");

      iso88591Decoder_ = iso88591Charset.newDecoder();
      iso88591Decoder_.onMalformedInput(CodingErrorAction.REPORT);
      iso88591Decoder_.onUnmappableCharacter(CodingErrorAction.REPORT);

      iso88591Encoder_ = iso88591Charset.newEncoder();
      iso88591Encoder_.onMalformedInput(CodingErrorAction.REPORT);
      iso88591Encoder_.onUnmappableCharacter(CodingErrorAction.REPORT);

      // LOAD UCS2 character set
      Charset ucs2Charset;
      if (System.getProperty("os.name").compareTo("NONSTOP_KERNEL") == 0)
      {
         ucs2Charset = Charset.forName("UTF-16BE");
      }
      else
      {
         ucs2Charset = Charset.forName("UTF-16LE");
      }

      ucs2Decoder_ = ucs2Charset.newDecoder();
      ucs2Decoder_.onMalformedInput(CodingErrorAction.REPORT);
      ucs2Decoder_.onUnmappableCharacter(CodingErrorAction.REPORT);

      ucs2Encoder_ = ucs2Charset.newEncoder();
      ucs2Encoder_.onMalformedInput(CodingErrorAction.REPORT);
      ucs2Encoder_.onUnmappableCharacter(CodingErrorAction.REPORT);

      // LOAD SJIS character set. MS932 is used for SJIS
      // instead of SJIS or Shift_JIS.
      Charset sjisCharset = Charset.forName("MS932");

      sjisDecoder_ = sjisCharset.newDecoder();
      sjisDecoder_.onMalformedInput(CodingErrorAction.REPORT);
      sjisDecoder_.onUnmappableCharacter(CodingErrorAction.REPORT);

      sjisEncoder_ = sjisCharset.newEncoder();
      sjisEncoder_.onMalformedInput(CodingErrorAction.REPORT);
      sjisEncoder_.onUnmappableCharacter(CodingErrorAction.REPORT);

      // LOAD UTF-8 character set
      Charset utf8Charset = Charset.forName("UTF-8");

      utf8Decoder_ = utf8Charset.newDecoder();
      utf8Decoder_.onMalformedInput(CodingErrorAction.REPORT);
      utf8Decoder_.onUnmappableCharacter(CodingErrorAction.REPORT);

      utf8Encoder_ = utf8Charset.newEncoder();
      utf8Encoder_.onMalformedInput(CodingErrorAction.REPORT);
      utf8Encoder_.onUnmappableCharacter(CodingErrorAction.REPORT);

      // A map for charset name to an integer
      charsetHashMap_ = new HashMap<String, Integer>(4);
      charsetHashMap_.put("ISO88591", 1);
      charsetHashMap_.put("UCS2", 2);
      charsetHashMap_.put("SJIS", 3);
      charsetHashMap_.put("UTF8", 4);

      reset_ = System.getProperty("os.name").equals("Linux");
   }

  /**
   * Converts given character set bytes to Unicode String.
   *
   * @param bytes   Array of input character bytes
   * @param fromCharset input character set
   * @param offset  offset into the array
   * @param length  length of the array
   *
   **/
  public static String getUnicodeStringFromBytes(byte[] inputBytes,
                                                 String fromCharset,
                                                 int offset,
                                                 int length)
  throws java.nio.charset.CharacterCodingException
  {
    ByteBuffer bBuffer = ByteBuffer.allocate(length);
    bBuffer.put(inputBytes, 0, length);
    bBuffer.flip();

    CharBuffer cBuffer = null;

    // call proper decoder to decode the bytes
    switch (charsetHashMap_.get(fromCharset))
    {
      case 1:
        cBuffer = iso88591Decoder_.decode(bBuffer);
        break;

      case 2:
        cBuffer = ucs2Decoder_.decode(bBuffer);
        break;

      case 3:
        cBuffer = sjisDecoder_.decode(bBuffer);
        break;

      case 4:
        cBuffer = utf8Decoder_.decode(bBuffer);
        break;
    }

    return cBuffer.toString();
  }

  /**
   * Converts Unicode String to bytes of a given character set.
   *
   * @param inputString   Unicode String
   * @param toCharset     Charset to convert unicode string to
   *
   **/
  public static byte[] getBytesFromUnicodeString(String inputString,
                                                 String toCharset)
  throws java.nio.charset.CharacterCodingException
  {
    ByteBuffer bBuffer = null;

    // call proper encoder to convert the string to bytes
    switch (((Integer)charsetHashMap_.get(toCharset)).intValue())
    {
      case 1:
        bBuffer = iso88591Encoder_.encode(CharBuffer.wrap(inputString));
        break;

      case 2:
        bBuffer = ucs2Encoder_.encode(CharBuffer.wrap(inputString));
        break;

      case 3:
        bBuffer = sjisEncoder_.encode(CharBuffer.wrap(inputString));
        break;

      case 4:
        bBuffer = utf8Encoder_.encode(CharBuffer.wrap(inputString));
        break;
    }

    byte[] outputBytes = bBuffer.array();

// If we don't reset on Linux, Linux throws IllegalStateException
      if (reset_)
        iso88591Decoder_.reset();
    return outputBytes;
  }
}


text:
using FluentNHibernate.Mapping;
using LNF.Impl.Repository.Data;

namespace LNF.Impl.Mappings.Data
{
    internal class ActiveLogMap : ClassMap<ActiveLog>
    {
        internal ActiveLogMap()
        {
            Schema("sselData.dbo");
            Id(x => x.LogID);
            Map(x => x.TableName);
            Map(x => x.Record);
            Map(x => x.EnableDate);
            Map(x => x.DisableDate);
        }
    }
}


text:
<readable><title>3329858093_0ec73f2190</title><content>
A mother is holding her child on a train .
A person holding a baby points out the window at the camera .
A woman and baby are sitting in the window seat of a bus .
a woman holding a young baby inside the window of a train
Young family eating a snack , shown through a window .
</content></readable>


text:
BOT_NAME = 'spojCrawler'

SPIDER_MODULES = ['crawler.spiders']
NEWSPIDER_MODULE = 'crawler.spiders'

ITEM_PIPELINES = {
    'crawler.pipelines.UserscrawlerPipeline': 300,
}

LOG_LEVEL = 'INFO'

DEFAULT_REQUEST_HEADERS = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'pt',
}

DEPTH_PRIORITY = 1
SCHEDULER_DISK_QUEUE = 'scrapy.squeue.PickleFifoDiskQueue'
SCHEDULER_MEMORY_QUEUE = 'scrapy.squeue.FifoMemoryQueue'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'recBot (+http://index-spojrec.rhcloud.com/)'


text:
let {Transform, pipeline: _pipeline} =  require('stream');
const util = require('util');
const pipeline = util.promisify(_pipeline);

// 转换流的参数和可写流一样
let tranform1 = Transform({
    transform(chunk,encoding,callback){
        this.push(chunk.toString().toUpperCase());
        callback();
    }
});
let tranform2 = Transform({
    transform(chunk,encoding,callback){
        console.log(chunk.toString());
        callback();
    }
});
pipeline(
  process.stdin,
  tranform1,
  tranform2
)

setTimeout(()=> {
  process.stdin.write('fdasfdsafdasEOFef\n')
  process.stdin.write(null);
}, 1000);

setTimeout(()=> {
  process.stdin.write('fdasfdsafdasEOFef\n')
  // process.stdin.write(null);
}, 2000);

// process.stdin.pipe(tranform1).pipe(tranform2);


text:
namespace Jint.Parser.Ast
{
    public class WithStatement : Statement
    {
        public Expression Object;
        public Statement Body;
    }
}


text:
package progressutil

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"strings"
	"testing"
)

func TestNoBarsAdded(t *testing.T) {
	pbp := &ProgressBarPrinter{}
	allDone, err := pbp.Print(ioutil.Discard)
	if allDone {
		t.Errorf("shouldn't have gotten all done when no bars have been added")
	}
	if err != ErrorNoBarsAdded {
		t.Errorf("was expecting ErrorNoBarsAdded, got this instead: %v", err)
	}
}

func TestProgressOutOfBounds(t *testing.T) {
	pbp := &ProgressBarPrinter{}
	pb := pbp.AddProgressBar()

	for _, testcase := range []struct {
		progress    float64
		expectedErr error
	}{
		{-0.1, ErrorProgressOutOfBounds},
		{0, nil},
		{0.5, nil},
		{1, nil},
		{1.1, ErrorProgressOutOfBounds},
	} {
		err := pb.SetCurrentProgress(testcase.progress)
		if err != testcase.expectedErr {
			t.Errorf("got unexpected error. expected=%v actual=%v", testcase.expectedErr, err)
		}
		if err == nil {
			currProgress := pb.GetCurrentProgress()
			if currProgress != testcase.progress {
				t.Errorf("no error was returned, but the progress wasn't updated. should be: %d, actual: %d", testcase.progress, currProgress)
			}
		}
	}
}

func TestDrawOne(t *testing.T) {
	pbp := ProgressBarPrinter{}
	pbp.printToTTYAlways = true
	pb := pbp.AddProgressBar()

	pbp.Print(ioutil.Discard)

	for _, testcase := range []struct {
		beforeText   string
		progress     float64
		afterText    string
		shouldBeDone bool
	}{
		{"before", 0, "after", false},
		{"before2", 0.1, "after2", false},
		{"before3", 0.5, "after3", false},
		{"before4", 1, "after4", true},
	} {
		buf := &bytes.Buffer{}
		pb.SetPrintBefore(testcase.beforeText)
		pb.SetPrintAfter(testcase.afterText)
		err := pb.SetCurrentProgress(testcase.progress)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		done, err := pbp.Print(buf)
		if err != nil {
			t.Fatalf("unexpected error: %v", err)
		}
		if done != testcase.shouldBeDone {
			t.Errorf("unexpected done, expected=%b actual=%b", testcase.shouldBeDone, done)
		}

		output := buf.String()

		progressBarSize := 80 - len(fmt.Sprintf("%s [] %s", testcase.beforeText, testcase.afterText))
		currentProgress := int(testcase.progress * float64(progressBarSize))

		bar := fmt.Sprintf("[%s%s]",
			strings.Repeat("=", currentProgress),
			strings.Repeat(" ", progressBarSize-currentProgress))

		expectedOutput := fmt.Sprintf("\033[1A%s %s %s\n", testcase.beforeText, bar, testcase.afterText)

		if output != expectedOutput {
			t.Errorf("unexpected output:\nexpected:\n\n%sactual:\n\n%s", expectedOutput, output)
		}
	}
}


text:
namespace Microsoft.Azure.Management.DataBox.Models
{
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// Request body to get the configuration for the region.
    /// </summary>
    public partial class RegionConfigurationRequest
    {
        /// <summary>
        /// Initializes a new instance of the RegionConfigurationRequest class.
        /// </summary>
        public RegionConfigurationRequest()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the RegionConfigurationRequest class.
        /// </summary>
        /// <param name="scheduleAvailabilityRequest">Request body to get the
        /// availability for scheduling orders.</param>
        /// <param name="transportAvailabilityRequest">Request body to get the
        /// transport availability for given sku.</param>
        public RegionConfigurationRequest(ScheduleAvailabilityRequest scheduleAvailabilityRequest = default(ScheduleAvailabilityRequest), TransportAvailabilityRequest transportAvailabilityRequest = default(TransportAvailabilityRequest))
        {
            ScheduleAvailabilityRequest = scheduleAvailabilityRequest;
            TransportAvailabilityRequest = transportAvailabilityRequest;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets or sets request body to get the availability for scheduling
        /// orders.
        /// </summary>
        [JsonProperty(PropertyName = "scheduleAvailabilityRequest")]
        public ScheduleAvailabilityRequest ScheduleAvailabilityRequest { get; set; }

        /// <summary>
        /// Gets or sets request body to get the transport availability for
        /// given sku.
        /// </summary>
        [JsonProperty(PropertyName = "transportAvailabilityRequest")]
        public TransportAvailabilityRequest TransportAvailabilityRequest { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="Rest.ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (ScheduleAvailabilityRequest != null)
            {
                ScheduleAvailabilityRequest.Validate();
            }
        }
    }
}


text:
;(function($) {
    $.timeout = function(delay) {
        var args = Array.prototype.slice.call(arguments, 1);

        var deferred = $.Deferred(function(deferred) {
            deferred.timeoutID = window.setTimeout(function() {
                deferred.resolveWith(deferred, args);
            }, delay);

            deferred.fail(function() {
                window.clearTimeout(deferred.timeoutID);
            });
        });

        return $.extend(deferred.promise(), {
            clear: function() {
                deferred.rejectWith(deferred, arguments);
            }
        });
    };
})(jQuery);