text:
from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload
import urllib.parse

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError,
    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.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.arm_polling import ARMPolling

from .. import models as _models
from .._serialization import Serializer
from .._vendor import _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_list_request(
    resource_group_name: str,
    azure_dev_ops_connector_name: str,
    azure_dev_ops_org_name: str,
    subscription_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "azureDevOpsConnectorName": _SERIALIZER.url(
            "azure_dev_ops_connector_name", azure_dev_ops_connector_name, "str"
        ),
        "azureDevOpsOrgName": _SERIALIZER.url("azure_dev_ops_org_name", azure_dev_ops_org_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

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

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

def build_get_request(
    resource_group_name: str,
    azure_dev_ops_connector_name: str,
    azure_dev_ops_org_name: str,
    azure_dev_ops_project_name: str,
    subscription_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01-preview"))  # type: str
    accept = _headers.pop("Accept", "application/json")

    # Construct URL
    _url = kwargs.pop(
        "template_url",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects/{azureDevOpsProjectName}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "azureDevOpsConnectorName": _SERIALIZER.url(
            "azure_dev_ops_connector_name", azure_dev_ops_connector_name, "str"
        ),
        "azureDevOpsOrgName": _SERIALIZER.url("azure_dev_ops_org_name", azure_dev_ops_org_name, "str"),
        "azureDevOpsProjectName": _SERIALIZER.url("azure_dev_ops_project_name", azure_dev_ops_project_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

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

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

def build_create_or_update_request(
    resource_group_name: str,
    azure_dev_ops_connector_name: str,
    azure_dev_ops_org_name: str,
    azure_dev_ops_project_name: str,
    subscription_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01-preview"))  # type: str
    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",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects/{azureDevOpsProjectName}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "azureDevOpsConnectorName": _SERIALIZER.url(
            "azure_dev_ops_connector_name", azure_dev_ops_connector_name, "str"
        ),
        "azureDevOpsOrgName": _SERIALIZER.url("azure_dev_ops_org_name", azure_dev_ops_org_name, "str"),
        "azureDevOpsProjectName": _SERIALIZER.url("azure_dev_ops_project_name", azure_dev_ops_project_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # 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="PUT", url=_url, params=_params, headers=_headers, **kwargs)

def build_update_request(
    resource_group_name: str,
    azure_dev_ops_connector_name: str,
    azure_dev_ops_org_name: str,
    azure_dev_ops_project_name: str,
    subscription_id: str,
    **kwargs: Any
) -> HttpRequest:
    _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
    _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

    api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-09-01-preview"))  # type: str
    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",
        "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects/{azureDevOpsProjectName}",
    )  # pylint: disable=line-too-long
    path_format_arguments = {
        "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str", min_length=1),
        "resourceGroupName": _SERIALIZER.url(
            "resource_group_name", resource_group_name, "str", max_length=90, min_length=1
        ),
        "azureDevOpsConnectorName": _SERIALIZER.url(
            "azure_dev_ops_connector_name", azure_dev_ops_connector_name, "str"
        ),
        "azureDevOpsOrgName": _SERIALIZER.url("azure_dev_ops_org_name", azure_dev_ops_org_name, "str"),
        "azureDevOpsProjectName": _SERIALIZER.url("azure_dev_ops_project_name", azure_dev_ops_project_name, "str"),
    }

    _url = _format_url_section(_url, **path_format_arguments)

    # Construct parameters
    _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str")

    # 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="PATCH", url=_url, params=_params, headers=_headers, **kwargs)

class AzureDevOpsProjectOperations:
    """
    .. warning::
        **DO NOT** instantiate this class directly.

        Instead, you should access the following operations through
        :class:`~azure.mgmt.securitydevops.MicrosoftSecurityDevOps`'s
        :attr:`azure_dev_ops_project` attribute.
    """

    models = _models

    def __init__(self, *args, **kwargs):
        input_args = list(args)
        self._client = input_args.pop(0) if input_args else kwargs.pop("client")
        self._config = input_args.pop(0) if input_args else kwargs.pop("config")
        self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
        self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")

    @distributed_trace
    def list(
        self, resource_group_name: str, azure_dev_ops_connector_name: str, azure_dev_ops_org_name: str, **kwargs: Any
    ) -> Iterable["_models.AzureDevOpsProject"]:
        """list.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param azure_dev_ops_connector_name: Name of the AzureDevOps Connector. Required.
        :type azure_dev_ops_connector_name: str
        :param azure_dev_ops_org_name: Name of the AzureDevOps Org. Required.
        :type azure_dev_ops_org_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: An iterator like instance of either AzureDevOpsProject or the result of cls(response)
        :rtype: ~azure.core.paging.ItemPaged[~azure.mgmt.securitydevops.models.AzureDevOpsProject]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = kwargs.pop("headers", {}) or {}
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.AzureDevOpsProjectListResponse]

        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

        def prepare_request(next_link=None):
            if not next_link:

                request = build_list_request(
                    resource_group_name=resource_group_name,
                    azure_dev_ops_connector_name=azure_dev_ops_connector_name,
                    azure_dev_ops_org_name=azure_dev_ops_org_name,
                    subscription_id=self._config.subscription_id,
                    api_version=api_version,
                    template_url=self.list.metadata["url"],
                    headers=_headers,
                    params=_params,
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore

            else:
                # make call to next link with the client's api-version
                _parsed_next_link = urllib.parse.urlparse(next_link)
                _next_request_params = case_insensitive_dict(
                    {
                        key: [urllib.parse.quote(v) for v in value]
                        for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items()
                    }
                )
                _next_request_params["api-version"] = self._config.api_version
                request = HttpRequest(
                    "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params
                )
                request = _convert_request(request)
                request.url = self._client.format_url(request.url)  # type: ignore
                request.method = "GET"
            return request

        def extract_data(pipeline_response):
            deserialized = self._deserialize("AzureDevOpsProjectListResponse", pipeline_response)
            list_of_elem = deserialized.value
            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(  # 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, error_format=ARMErrorFormat)

            return pipeline_response

        return ItemPaged(get_next, extract_data)

    list.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects"}  # type: ignore

    @distributed_trace
    def get(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        **kwargs: Any
    ) -> _models.AzureDevOpsProject:
        """Returns a monitored AzureDevOps Project resource for a given ID.

        Returns a monitored AzureDevOps Project resource for a given ID.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param azure_dev_ops_connector_name: Name of the AzureDevOps Connector. Required.
        :type azure_dev_ops_connector_name: str
        :param azure_dev_ops_org_name: Name of the AzureDevOps Org. Required.
        :type azure_dev_ops_org_name: str
        :param azure_dev_ops_project_name: Name of the AzureDevOps Project. Required.
        :type azure_dev_ops_project_name: str
        :keyword callable cls: A custom type or function that will be passed the direct response
        :return: AzureDevOpsProject or the result of cls(response)
        :rtype: ~azure.mgmt.securitydevops.models.AzureDevOpsProject
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.AzureDevOpsProject]

        request = build_get_request(
            resource_group_name=resource_group_name,
            azure_dev_ops_connector_name=azure_dev_ops_connector_name,
            azure_dev_ops_org_name=azure_dev_ops_org_name,
            azure_dev_ops_project_name=azure_dev_ops_project_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            template_url=self.get.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # 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, error_format=ARMErrorFormat)

        deserialized = self._deserialize("AzureDevOpsProject", pipeline_response)

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

        return deserialized

    get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects/{azureDevOpsProjectName}"}  # type: ignore

    def _create_or_update_initial(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        azure_dev_ops_project: Union[_models.AzureDevOpsProject, IO],
        **kwargs: Any
    ) -> _models.AzureDevOpsProject:
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.AzureDevOpsProject]

        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(azure_dev_ops_project, (IO, bytes)):
            _content = azure_dev_ops_project
        else:
            _json = self._serialize.body(azure_dev_ops_project, "AzureDevOpsProject")

        request = build_create_or_update_request(
            resource_group_name=resource_group_name,
            azure_dev_ops_connector_name=azure_dev_ops_connector_name,
            azure_dev_ops_org_name=azure_dev_ops_org_name,
            azure_dev_ops_project_name=azure_dev_ops_project_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            template_url=self._create_or_update_initial.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # 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, 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, error_format=ARMErrorFormat)

        if response.status_code == 200:
            deserialized = self._deserialize("AzureDevOpsProject", pipeline_response)

        if response.status_code == 201:
            deserialized = self._deserialize("AzureDevOpsProject", pipeline_response)

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

        return deserialized

    _create_or_update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects/{azureDevOpsProjectName}"}  # type: ignore

    @overload
    def begin_create_or_update(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        azure_dev_ops_project: _models.AzureDevOpsProject,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> LROPoller[_models.AzureDevOpsProject]:
        """Creates or updates an Azure DevOps Project.

        Creates or updates an Azure DevOps Project.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param azure_dev_ops_connector_name: Name of the AzureDevOps Connector. Required.
        :type azure_dev_ops_connector_name: str
        :param azure_dev_ops_org_name: Name of the AzureDevOps Org. Required.
        :type azure_dev_ops_org_name: str
        :param azure_dev_ops_project_name: Name of the AzureDevOps Project. Required.
        :type azure_dev_ops_project_name: str
        :param azure_dev_ops_project: Azure DevOps Org resource payload. Required.
        :type azure_dev_ops_project: ~azure.mgmt.securitydevops.models.AzureDevOpsProject
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :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 ARMPolling. 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 AzureDevOpsProject or the result of
         cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.securitydevops.models.AzureDevOpsProject]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def begin_create_or_update(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        azure_dev_ops_project: IO,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> LROPoller[_models.AzureDevOpsProject]:
        """Creates or updates an Azure DevOps Project.

        Creates or updates an Azure DevOps Project.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param azure_dev_ops_connector_name: Name of the AzureDevOps Connector. Required.
        :type azure_dev_ops_connector_name: str
        :param azure_dev_ops_org_name: Name of the AzureDevOps Org. Required.
        :type azure_dev_ops_org_name: str
        :param azure_dev_ops_project_name: Name of the AzureDevOps Project. Required.
        :type azure_dev_ops_project_name: str
        :param azure_dev_ops_project: Azure DevOps Org resource payload. Required.
        :type azure_dev_ops_project: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :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 ARMPolling. 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 AzureDevOpsProject or the result of
         cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.securitydevops.models.AzureDevOpsProject]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def begin_create_or_update(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        azure_dev_ops_project: Union[_models.AzureDevOpsProject, IO],
        **kwargs: Any
    ) -> LROPoller[_models.AzureDevOpsProject]:
        """Creates or updates an Azure DevOps Project.

        Creates or updates an Azure DevOps Project.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param azure_dev_ops_connector_name: Name of the AzureDevOps Connector. Required.
        :type azure_dev_ops_connector_name: str
        :param azure_dev_ops_org_name: Name of the AzureDevOps Org. Required.
        :type azure_dev_ops_org_name: str
        :param azure_dev_ops_project_name: Name of the AzureDevOps Project. Required.
        :type azure_dev_ops_project_name: str
        :param azure_dev_ops_project: Azure DevOps Org resource payload. Is either a model type or a IO
         type. Required.
        :type azure_dev_ops_project: ~azure.mgmt.securitydevops.models.AzureDevOpsProject or IO
        :keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
         Default value is None.
        :paramtype content_type: str
        :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 ARMPolling. 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 AzureDevOpsProject or the result of
         cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.securitydevops.models.AzureDevOpsProject]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.AzureDevOpsProject]
        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._create_or_update_initial(  # type: ignore
                resource_group_name=resource_group_name,
                azure_dev_ops_connector_name=azure_dev_ops_connector_name,
                azure_dev_ops_org_name=azure_dev_ops_org_name,
                azure_dev_ops_project_name=azure_dev_ops_project_name,
                azure_dev_ops_project=azure_dev_ops_project,
                api_version=api_version,
                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):
            deserialized = self._deserialize("AzureDevOpsProject", pipeline_response)
            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized

        if polling is True:
            polling_method = cast(
                PollingMethod, ARMPolling(lro_delay, lro_options={"final-state-via": "azure-async-operation"}, **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_create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects/{azureDevOpsProjectName}"}  # type: ignore

    def _update_initial(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        azure_dev_ops_project: Optional[Union[_models.AzureDevOpsProject, IO]] = None,
        **kwargs: Any
    ) -> _models.AzureDevOpsProject:
        error_map = {
            401: ClientAuthenticationError,
            404: ResourceNotFoundError,
            409: ResourceExistsError,
            304: ResourceNotModifiedError,
        }
        error_map.update(kwargs.pop("error_map", {}) or {})

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

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.AzureDevOpsProject]

        content_type = content_type or "application/json"
        _json = None
        _content = None
        if isinstance(azure_dev_ops_project, (IO, bytes)):
            _content = azure_dev_ops_project
        else:
            if azure_dev_ops_project is not None:
                _json = self._serialize.body(azure_dev_ops_project, "AzureDevOpsProject")
            else:
                _json = None

        request = build_update_request(
            resource_group_name=resource_group_name,
            azure_dev_ops_connector_name=azure_dev_ops_connector_name,
            azure_dev_ops_org_name=azure_dev_ops_org_name,
            azure_dev_ops_project_name=azure_dev_ops_project_name,
            subscription_id=self._config.subscription_id,
            api_version=api_version,
            content_type=content_type,
            json=_json,
            content=_content,
            template_url=self._update_initial.metadata["url"],
            headers=_headers,
            params=_params,
        )
        request = _convert_request(request)
        request.url = self._client.format_url(request.url)  # 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)
            error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, pipeline_response)
            raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)

        deserialized = self._deserialize("AzureDevOpsProject", pipeline_response)

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

        return deserialized

    _update_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects/{azureDevOpsProjectName}"}  # type: ignore

    @overload
    def begin_update(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        azure_dev_ops_project: Optional[_models.AzureDevOpsProject] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> LROPoller[_models.AzureDevOpsProject]:
        """Update monitored AzureDevOps Project details.

        Update monitored AzureDevOps Project details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param azure_dev_ops_connector_name: Name of the AzureDevOps Connector. Required.
        :type azure_dev_ops_connector_name: str
        :param azure_dev_ops_org_name: Name of the AzureDevOps Org. Required.
        :type azure_dev_ops_org_name: str
        :param azure_dev_ops_project_name: Name of the AzureDevOps Project. Required.
        :type azure_dev_ops_project_name: str
        :param azure_dev_ops_project: Azure DevOps Org resource payload. Default value is None.
        :type azure_dev_ops_project: ~azure.mgmt.securitydevops.models.AzureDevOpsProject
        :keyword content_type: Body Parameter content-type. Content type parameter for JSON body.
         Default value is "application/json".
        :paramtype content_type: str
        :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 ARMPolling. 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 AzureDevOpsProject or the result of
         cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.securitydevops.models.AzureDevOpsProject]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @overload
    def begin_update(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        azure_dev_ops_project: Optional[IO] = None,
        *,
        content_type: str = "application/json",
        **kwargs: Any
    ) -> LROPoller[_models.AzureDevOpsProject]:
        """Update monitored AzureDevOps Project details.

        Update monitored AzureDevOps Project details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param azure_dev_ops_connector_name: Name of the AzureDevOps Connector. Required.
        :type azure_dev_ops_connector_name: str
        :param azure_dev_ops_org_name: Name of the AzureDevOps Org. Required.
        :type azure_dev_ops_org_name: str
        :param azure_dev_ops_project_name: Name of the AzureDevOps Project. Required.
        :type azure_dev_ops_project_name: str
        :param azure_dev_ops_project: Azure DevOps Org resource payload. Default value is None.
        :type azure_dev_ops_project: IO
        :keyword content_type: Body Parameter content-type. Content type parameter for binary body.
         Default value is "application/json".
        :paramtype content_type: str
        :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 ARMPolling. 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 AzureDevOpsProject or the result of
         cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.securitydevops.models.AzureDevOpsProject]
        :raises ~azure.core.exceptions.HttpResponseError:
        """

    @distributed_trace
    def begin_update(
        self,
        resource_group_name: str,
        azure_dev_ops_connector_name: str,
        azure_dev_ops_org_name: str,
        azure_dev_ops_project_name: str,
        azure_dev_ops_project: Optional[Union[_models.AzureDevOpsProject, IO]] = None,
        **kwargs: Any
    ) -> LROPoller[_models.AzureDevOpsProject]:
        """Update monitored AzureDevOps Project details.

        Update monitored AzureDevOps Project details.

        :param resource_group_name: The name of the resource group. The name is case insensitive.
         Required.
        :type resource_group_name: str
        :param azure_dev_ops_connector_name: Name of the AzureDevOps Connector. Required.
        :type azure_dev_ops_connector_name: str
        :param azure_dev_ops_org_name: Name of the AzureDevOps Org. Required.
        :type azure_dev_ops_org_name: str
        :param azure_dev_ops_project_name: Name of the AzureDevOps Project. Required.
        :type azure_dev_ops_project_name: str
        :param azure_dev_ops_project: Azure DevOps Org resource payload. Is either a model type or a IO
         type. Default value is None.
        :type azure_dev_ops_project: ~azure.mgmt.securitydevops.models.AzureDevOpsProject or IO
        :keyword content_type: Body Parameter content-type. Known values are: 'application/json'.
         Default value is None.
        :paramtype content_type: str
        :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 ARMPolling. 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 AzureDevOpsProject or the result of
         cls(response)
        :rtype: ~azure.core.polling.LROPoller[~azure.mgmt.securitydevops.models.AzureDevOpsProject]
        :raises ~azure.core.exceptions.HttpResponseError:
        """
        _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {})
        _params = case_insensitive_dict(kwargs.pop("params", {}) or {})

        api_version = kwargs.pop("api_version", _params.pop("api-version", self._config.api_version))  # type: str
        content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None))  # type: Optional[str]
        cls = kwargs.pop("cls", None)  # type: ClsType[_models.AzureDevOpsProject]
        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._update_initial(  # type: ignore
                resource_group_name=resource_group_name,
                azure_dev_ops_connector_name=azure_dev_ops_connector_name,
                azure_dev_ops_org_name=azure_dev_ops_org_name,
                azure_dev_ops_project_name=azure_dev_ops_project_name,
                azure_dev_ops_project=azure_dev_ops_project,
                api_version=api_version,
                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):
            deserialized = self._deserialize("AzureDevOpsProject", pipeline_response)
            if cls:
                return cls(pipeline_response, deserialized, {})
            return deserialized

        if polling is True:
            polling_method = cast(PollingMethod, ARMPolling(lro_delay, **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_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.SecurityDevOps/azureDevOpsConnectors/{azureDevOpsConnectorName}/orgs/{azureDevOpsOrgName}/projects/{azureDevOpsProjectName}"}  # type: ignore


text:
export * from './Tw2Curve';
export * from './Tw2ColorCurve';
export * from './Tw2ColorCurve2';
export * from './Tw2EventCurve';
export * from './Tw2PerlinCurve';
export * from './Tw2QuaternionCurve';
export * from './Tw2RandomConstantCurve';
export * from './Tw2RigidOrientation';
export * from './Tw2RotationCurve';
export * from './Tw2ScalarCurve';
export * from './Tw2ScalarCurve2';
export * from './Tw2SineCurve';
export * from './Tw2Vector2Curve';
export * from './Tw2Vector3Curve';
export * from './Tw2VectorCurve';

redpajama_set_name: RedPajamaGithub


text:
use learning::error::{Error, ErrorKind};
use linalg::{Matrix, Vector, Axes};
use super::Transformer;

use rulinalg::utils;

use libnum::{Float, FromPrimitive};

/// The Standardizer
///
/// The Standardizer provides an implementation of `Transformer`
/// which allows us to transform the input data to have a new mean
/// and standard deviation.
///
/// See the module description for more information.
#[derive(Debug)]
pub struct Standardizer<T: Float> {
    /// Means per column of input data
    means: Option<Vector<T>>,
    /// Variances per column of input data
    variances: Option<Vector<T>>,
    /// The mean of the new data (default 0)
    scaled_mean: T,
    /// The standard deviation of the new data (default 1)
    scaled_stdev: T,
}

/// Create a `Standardizer` with mean `0` and standard
/// deviation `1`.
impl<T: Float> Default for Standardizer<T> {
    fn default() -> Standardizer<T> {
        Standardizer {
            means: None,
            variances: None,
            scaled_mean: T::zero(),
            scaled_stdev: T::one(),
        }
    }
}

impl<T: Float> Standardizer<T> {
    /// Constructs a new `Standardizer` with the given mean and variance
    ///
    /// # Examples
    ///
    /// ```
    /// use rusty_machine::data::transforms::Standardizer;
    ///
    /// // Constructs a new `Standardizer` which will give the data
    /// // mean `0` and standard deviation `2`.
    /// let transformer = Standardizer::new(0.0, 2.0);
    /// ```
    pub fn new(mean: T, stdev: T) -> Standardizer<T> {
        Standardizer {
            means: None,
            variances: None,
            scaled_mean: mean,
            scaled_stdev: stdev,
        }
    }
}

impl<T: Float + FromPrimitive> Transformer<Matrix<T>> for Standardizer<T> {
    fn transform(&mut self, mut inputs: Matrix<T>) -> Result<Matrix<T>, Error> {
        if inputs.rows() <= 1 {
            Err(Error::new(ErrorKind::InvalidData,
                           "Cannot standardize data with only one row."))
        } else {
            let mean = inputs.mean(Axes::Row);
            let variance = inputs.variance(Axes::Row);

            if mean.data().iter().any(|x| !x.is_finite()) {
                return Err(Error::new(ErrorKind::InvalidData, "Some data point is non-finite."));
            }

            for row in inputs.iter_rows_mut() {
                // Subtract the mean
                utils::in_place_vec_bin_op(row, &mean.data(), |x, &y| *x = *x - y);
                utils::in_place_vec_bin_op(row, &variance.data(), |x, &y| {
                    *x = (*x * self.scaled_stdev / y.sqrt()) + self.scaled_mean
                });
            }

            self.means = Some(mean);
            self.variances = Some(variance);
            Ok(inputs)
        }
    }

    fn inv_transform(&self, mut inputs: Matrix<T>) -> Result<Matrix<T>, Error> {
        if let (&Some(ref means), &Some(ref variances)) = (&self.means, &self.variances) {

            let features = means.size();
            if inputs.cols() != features {
                return Err(Error::new(ErrorKind::InvalidData,
                                      "Inputs have different feature count than transformer."));
            }

            for row in inputs.iter_rows_mut() {
                utils::in_place_vec_bin_op(row, &variances.data(), |x, &y| {
                    *x = (*x - self.scaled_mean) * y.sqrt() / self.scaled_stdev
                });

                // Add the mean
                utils::in_place_vec_bin_op(row, &means.data(), |x, &y| *x = *x + y);
            }

            Ok(inputs)
        } else {
            Err(Error::new(ErrorKind::InvalidState, "Transformer has not been fitted."))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::Transformer;
    use linalg::{Axes, Matrix};

    use std::f64;

    #[test]
    fn single_row_test() {
        let inputs = Matrix::new(1, 2, vec![1.0, 2.0]);

        let mut standardizer = Standardizer::default();

        let res = standardizer.transform(inputs);
        assert!(res.is_err());
    }

    #[test]
    fn nan_data_test() {
        let inputs = Matrix::new(2, 2, vec![f64::NAN; 4]);

        let mut standardizer = Standardizer::default();

        let res = standardizer.transform(inputs);
        assert!(res.is_err());
    }

    #[test]
    fn inf_data_test() {
        let inputs = Matrix::new(2, 2, vec![f64::INFINITY; 4]);

        let mut standardizer = Standardizer::default();

        let res = standardizer.transform(inputs);
        assert!(res.is_err());
    }

    #[test]
    fn basic_standardize_test() {
        let inputs = Matrix::new(2, 2, vec![-1.0f32, 2.0, 0.0, 3.0]);

        let mut standardizer = Standardizer::default();
        let transformed = standardizer.transform(inputs).unwrap();

        let new_mean = transformed.mean(Axes::Row);
        let new_var = transformed.variance(Axes::Row);

        assert!(new_mean.data().iter().all(|x| x.abs() < 1e-5));
        assert!(new_var.data().iter().all(|x| (x.abs() - 1.0) < 1e-5));
    }

    #[test]
    fn custom_standardize_test() {
        let inputs = Matrix::new(2, 2, vec![-1.0f32, 2.0, 0.0, 3.0]);

        let mut standardizer = Standardizer::new(1.0, 2.0);
        let transformed = standardizer.transform(inputs).unwrap();

        let new_mean = transformed.mean(Axes::Row);
        let new_var = transformed.variance(Axes::Row);

        assert!(new_mean.data().iter().all(|x| (x.abs() - 1.0) < 1e-5));
        assert!(new_var.data().iter().all(|x| (x.abs() - 4.0) < 1e-5));
    }

    #[test]
    fn inv_transform_identity_test() {
        let inputs = Matrix::new(2, 2, vec![-1.0f32, 2.0, 0.0, 3.0]);

        let mut standardizer = Standardizer::new(1.0, 3.0);
        let transformed = standardizer.transform(inputs.clone()).unwrap();

        let original = standardizer.inv_transform(transformed).unwrap();

        assert!((inputs - original).data().iter().all(|x| x.abs() < 1e-5));
    }
}


text:
#pragma once
#include <aws/inspector2/Inspector2_EXPORTS.h>
#include <aws/inspector2/Inspector2Request.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Inspector2
{
namespace Model
{

  /**
   */
  class AWS_INSPECTOR2_API BatchGetFreeTrialInfoRequest : public Inspector2Request
  {
  public:
    BatchGetFreeTrialInfoRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "BatchGetFreeTrialInfo"; }

    Aws::String SerializePayload() const override;

    /**
     *
The account IDs to get free trial status for.

     */
    inline const Aws::Vector<Aws::String>& GetAccountIds() const{ return m_accountIds; }

    /**
     *
The account IDs to get free trial status for.

     */
    inline bool AccountIdsHasBeenSet() const { return m_accountIdsHasBeenSet; }

    /**
     *
The account IDs to get free trial status for.

     */
    inline void SetAccountIds(const Aws::Vector<Aws::String>& value) { m_accountIdsHasBeenSet = true; m_accountIds = value; }

    /**
     *
The account IDs to get free trial status for.

     */
    inline void SetAccountIds(Aws::Vector<Aws::String>&& value) { m_accountIdsHasBeenSet = true; m_accountIds = std::move(value); }

    /**
     *
The account IDs to get free trial status for.

     */
    inline BatchGetFreeTrialInfoRequest& WithAccountIds(const Aws::Vector<Aws::String>& value) { SetAccountIds(value); return *this;}

    /**
     *
The account IDs to get free trial status for.

     */
    inline BatchGetFreeTrialInfoRequest& WithAccountIds(Aws::Vector<Aws::String>&& value) { SetAccountIds(std::move(value)); return *this;}

    /**
     *
The account IDs to get free trial status for.

     */
    inline BatchGetFreeTrialInfoRequest& AddAccountIds(const Aws::String& value) { m_accountIdsHasBeenSet = true; m_accountIds.push_back(value); return *this; }

    /**
     *
The account IDs to get free trial status for.

     */
    inline BatchGetFreeTrialInfoRequest& AddAccountIds(Aws::String&& value) { m_accountIdsHasBeenSet = true; m_accountIds.push_back(std::move(value)); return *this; }

    /**
     *
The account IDs to get free trial status for.

     */
    inline BatchGetFreeTrialInfoRequest& AddAccountIds(const char* value) { m_accountIdsHasBeenSet = true; m_accountIds.push_back(value); return *this; }

  private:

    Aws::Vector<Aws::String> m_accountIds;
    bool m_accountIdsHasBeenSet = false;
  };

} // namespace Model
} // namespace Inspector2
} // namespace Aws


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Timers;
using VidyoIntegration.TraceLib;
using Nancy;
using Nancy.ModelBinding;
using Nancy.Routing;
using VidyoIntegration.CommonLib.CicTypes;
using VidyoIntegration.CommonLib.CicTypes.RequestClasses;
using VidyoIntegration.CommonLib.CicTypes.TransportClasses;
using VidyoIntegration.CommonLib.CommonTypes;
using VidyoIntegration.CommonLib.VidyoTypes;
using VidyoIntegration.CommonLib.VidyoTypes.RequestClasses;
using VidyoIntegration.ConversationManagerLib;
using Timer = System.Timers.Timer;
using Trace = VidyoIntegration.CommonLib.Trace;

namespace VidyoIntegration.CoreServiceLib
{
    public class CoreRequestRouter : NancyModule
    {
        private const string UriPrefix = "/ininvid/v1";
        private static DateTime _initializedDateTime = DateTime.Now;
        private static Dictionary<string, int> _requestCounter = new Dictionary<string, int>();

        public CoreRequestRouter(IRouteCacheProvider routeCacheProvider)
        {
            // Section: /conversations
            #region POST /conversations
            Post[UriPrefix + "/conversations"] = _p =>
            {
                using (Trace.Cic.scope("POST /conversations"))
                {
                    try
                    {
                        UpdateCount("post /conversations");

                        var request = this.Bind<CreateConversationRequest>();

                        #region Validation

                        // Check Queue
                        if (string.IsNullOrEmpty(request.QueueName))
                            return new Response
                            {
                                StatusCode = HttpStatusCode.BadRequest,
                                ReasonPhrase = "Value cannot be empty: queueName"
                            };
                        if (request.QueueType == CicQueueType.None)
                            return new Response
                            {
                                StatusCode = HttpStatusCode.BadRequest,
                                ReasonPhrase = "Value cannot be empty: queueType"
                            };

                        // Check media type parameters
                        if (request.MediaTypeParameters == null)
                            return new Response
                            {
                                StatusCode = HttpStatusCode.BadRequest,
                                ReasonPhrase = "Value cannot be empty: mediaTypeParameters"
                            };

                        // Check type to block requests for new chat (unable to support at this time due to icelib constraints)
                        if (request.MediaTypeParameters is ChatInteractionMediaTypeParameters)
                            return new Response
                            {
                                StatusCode = HttpStatusCode.BadRequest,
                                ReasonPhrase = "MediaType of Chat is not supported for new conversation requests"
                            };

                        // Prevent null collections
                        if (request.MediaTypeParameters.AdditionalAttributes == null)
                            request.MediaTypeParameters.AdditionalAttributes = new List<KeyValuePair<string, string>>();

                        #endregion

                        // Create conversation
                        var conversation = CoreService.Instance.CreateConversation(request);
                        return conversation ?? (dynamic)new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Failed to create conversation"
                        };
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in POST /conversations: " + ex.Message, EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion
            #region POST /conversations/attach
            Post[UriPrefix + "/conversations/attach"] = _p =>
            {
                using (Trace.Cic.scope("POST /conversations/attach"))
                {
                    try
                    {
                        UpdateCount("post /conversations/attach");

                        var request = this.Bind<AttachConversationRequest>();

                        #region Validation

                        // Check interaction ID
                        if (request.InteractionId <= 0)
                            return new Response
                            {
                                StatusCode = HttpStatusCode.BadRequest,
                                ReasonPhrase = "Value cannot be empty: interactionId"
                            };

                        // Prevent null collections
                        if (request.AdditionalAttributes == null)
                            request.AdditionalAttributes = new List<KeyValuePair<string, string>>();

                        #endregion

                        // Create conversation
                        var conversation = CoreService.Instance.AttachConversation(request);
                        return conversation ?? (dynamic)new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Failed to create conversation"
                        };
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in POST /conversations: " + ex.Message, EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion
            #region GET /conversations
            Get[UriPrefix + "/conversations"] = _p =>
            {
                using (Trace.Cic.scope("GET /conversations"))
                {
                    try
                    {
                        UpdateCount("get /conversations");

                        return ConversationManager.ConversationList;
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in GET /conversations: " + ex.Message, EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion

            #region GET /conversations/{conversationId}
            Get[UriPrefix + "/conversations/{conversationId}"] = _p =>
            {
                using (Trace.Cic.scope("GET /conversations/{conversationId}"))
                {
                    try
                    {
                        UpdateCount("get /conversations/{conversationId}");

                        // Validate input
                        if (((Guid)_p.conversationId) == Guid.Empty)
                            return new Response
                            {
                                StatusCode = HttpStatusCode.BadRequest,
                                ReasonPhrase = "Value cannot be empty: conversationId"
                            };

                        // Return room
                        var conversation = ConversationManager.GetConversation((Guid)_p.conversationId);
                        return conversation ??
                               (dynamic)new Response
                               {
                                   StatusCode = HttpStatusCode.Gone,
                                   ReasonPhrase = "Conversation not found"
                               };
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /conversations/{conversationId}: " + ex.Message,
                               EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        };
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in GET /conversations/{conversationId}: " + ex.Message, EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion
            #region DELETE /conversations/{conversationId}
            Delete[UriPrefix + "/conversations/{conversationId}"] = _p =>
            {
                using (Trace.Cic.scope("DELETE /conversations/{conversationId}"))
                {
                    try
                    {
                        UpdateCount("delete /conversations/{conversationId}");

                        // Validate input
                        if (((Guid)_p.conversationId) == Guid.Empty)
                            return new Response
                            {
                                StatusCode = HttpStatusCode.BadRequest,
                                ReasonPhrase = "Value cannot be empty: conversationId"
                            };

                        // Cleanup
                        return CoreService.Instance.CleanupConversation((Guid) _p.conversationId)
                            ? new Response
                            {
                                StatusCode = HttpStatusCode.NoContent,
                                ReasonPhrase = "Conversation deleted"
                            }
                            : new Response
                            {
                                StatusCode = HttpStatusCode.Gone,
                                ReasonPhrase = "Unable to delete conversation"
                            };
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in DELETE /conversations/{conversationId}: " + ex.Message,
                               EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        };
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in DELETE /conversations/{conversationId}: " + ex.Message, EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion

            // Section: /coreservice
            #region POST /coreservice/initialize
            Post[UriPrefix + "/coreservice/initialize"] = _p =>
            {
                using (Trace.Cic.scope("POST /coreservice/initialize"))
                {
                    try
                    {
                        UpdateCount("post /coreservice/initialize");

                        var x = CoreService.Instance;

                        return new Response
                        {
                            StatusCode = HttpStatusCode.NoContent,
                            ReasonPhrase = "Initialized"
                        };
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in POST /coreservice/initialize: " + ex.Message, EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion
            #region GET /coreservice/info
            Get[UriPrefix + "/coreservice/info"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /coreservice/info"))
                {
                    try
                    {
                        UpdateCount("get /coreservice/info");

                        var info = new CicInfo
                        {
                            ConversationCount = ConversationManager.ConversationList.Count,
                            IsConnectedToCic = CoreService.Instance.IsConnected,
                            CicServer = CoreService.Instance.CicServer,
                            CicUser = CoreService.Instance.CicUser,
                            Uptime = DateTime.Now.Subtract(_initializedDateTime),
                            SessionManager = CoreService.Instance.SessionManager,
                            ConnectionMessage = CoreService.Instance.ConnectionMessage,
                            RequestCounts = _requestCounter
                        };

                        return info;
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /coreservice/info: " + ex.Message,
                            EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion
            #region GET /coreservice/info/routes
            Get[UriPrefix + "/coreservice/info/routes"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /coreservice/info/routes"))
                {
                    try
                    {
                        UpdateCount("get /coreservice/info/routes");

                        // Get cache of defined routes
                        var routes = routeCacheProvider.GetCache();
                        var serviceInfoList = new List<ServiceInfo>();

                        // Process routes
                        foreach (var route in routes)
                        {
                            // We only want info for this service
                            if (!(route.Key == GetType())) continue;

                            // Create ServiceInfo for the service
                            var serviceInfo = new ServiceInfo
                            {
                                ServiceName = route.Key.FullName,
                                Routes = new List<RouteInfo>()
                            };

                            // Add the collection of routes
                            serviceInfo.Routes.AddRange(route.Value.Select(mapping => new RouteInfo
                            {
                                Method = mapping.Item2.Method,
                                Path = mapping.Item2.Path
                            }));

                            // Add the ServiceInfo item to the list
                            serviceInfoList.Add(serviceInfo);
                        }
                        return serviceInfoList;
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /coreservice/info/routes: " + ex.Message,
                            EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion

            // Section: /queues
            #region GET /queues/stats?queues[]={queue}
            Get[UriPrefix + "/queues/stats"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /queues/stats?queues[]={queue}"))
                {
                    try
                    {
                        UpdateCount("get /queues/stats?queues[]={queue}");

                        var request = this.Bind<GetQueueInfoRequest>();

                        var result = CoreService.Instance.GetQueueInfo(request);
                        return result ??
                               (dynamic) new Response
                               {
                                   StatusCode = HttpStatusCode.InternalServerError,
                                   ReasonPhrase = "Failed to get queue info"
                               };
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /queues/stats?queues[]={queue}: " + ex.Message,
                            EventId.GenericError);
                        return new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        };
                    }
                }
            };
            #endregion
        }

        private static void UpdateCount(string key)
        {
            if (!_requestCounter.ContainsKey(key))
                _requestCounter[key] = 0;
            _requestCounter[key]++;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DisqusN.Resources.Threads
{
    public static class ThreadRequests
    {
        public static ThreadListPostsRequest ListPosts(ThreadListPostsParameters parameters)
        {
            return new ThreadListPostsRequest();
        }
    }

    public abstract class ThreadRequest
    {

    }

    public class ThreadListPostsRequest : ThreadRequest
    {

    }

    public abstract class ThreadParameters
    {
        public int ThreadId { get; set; }
    }

    public class ThreadListPostsParameters : ThreadParameters
    {

    }
}


text:
import pytest

import numpy as np
import pybinding as pb
from pybinding.repository import graphene, examples

@pytest.fixture
def ring_model():
    def ring(inner_radius, outer_radius):
        def contains(x, y, _):
            r = np.sqrt(x**2 + y**2)
            return np.logical_and(inner_radius < r, r < outer_radius)
        return pb.FreeformShape(contains, width=[2 * outer_radius, 2 * outer_radius])

    return pb.Model(graphene.monolayer(), ring(3, 5))

@pytest.fixture
def square_model(width=2, height=3):
    def square_lattice(d=1, t=1):
        lat = pb.Lattice(a1=[d, 0], a2=[0, d])
        lat.add_sublattices(('A', [0, 0]))
        lat.add_hoppings(
            ([0, 1], 'A', 'A', -t),
            ([1, 0], 'A', 'A', -t),
        )
        return lat
    return pb.Model(square_lattice(), pb.rectangle(width, height))

def linear_onsite(k=1):
    @pb.onsite_energy_modifier
    def onsite(x):
        return k * x
    return onsite

def linear_hopping(k=1):
    @pb.hopping_energy_modifier
    def hopping(x1, x2):
        return 0.5 * k * (x1 + x2)
    return hopping

def test_api(ring_model):
    with pytest.raises(RuntimeError) as excinfo:
        ring_model.attach_lead(0, pb.line(0, 0))
    assert "Lead direction must be one of" in str(excinfo.value)

    for direction in [3, -3]:
        with pytest.raises(RuntimeError) as excinfo:
            ring_model.attach_lead(direction, pb.line(0, 0))
        assert "not valid for a 2D lattice" in str(excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        pb.Model(examples.chain_lattice()).attach_lead(2, pb.line(0, 0))
    assert "Attaching leads to 1D lattices is not supported" in str(excinfo.value)

def test_partial_miss(ring_model):
    with pytest.raises(RuntimeError) as excinfo:
        ring_model.attach_lead(2, pb.line([0, -5], [5, -5]))
        assert ring_model.system
    assert "partially misses main structure" in str(excinfo.value)

def test_complete_miss(ring_model):
    with pytest.raises(RuntimeError) as excinfo:
        ring_model.attach_lead(2, pb.line([4, -5], [5, -5]))
        assert ring_model.system
    assert "completely misses main structure" in str(excinfo.value)

def test_empty(ring_model):
    with pytest.raises(RuntimeError) as excinfo:
        ring_model.attach_lead(2, pb.line(0, 0))
        assert ring_model.system
    assert "no sites in lead junction" in str(excinfo.value)

def test_attach():
    """Attach 2 leads to a square lattice system"""
    w, h = 2, 3
    model = square_model(w, h)
    model.attach_lead(-1, pb.line([0, -h/2], [0, h/2]))
    model.attach_lead(+1, pb.line([0, -h/2], [0, h/2]))
    assert len(model.leads) == 2
    assert np.all(model.leads[0].indices == [0, 2, 4])
    assert np.all(model.leads[1].indices == [1, 3, 5])

    # Linear hopping grows from lead 0 to system to lead 1
    model.add(linear_hopping())
    assert model.leads[0].h1.data.max() < model.hamiltonian.data.min()
    assert model.hamiltonian.data.max() < model.leads[1].h1.data.min()

    # With the linear hopping modifier, the h1 hoppings should be equal to the
    # x position between the lead and main system
    x_mid_0 = (model.system.x.min() + model.leads[0].system.x.max()) / 2
    assert np.allclose(model.leads[0].h1.data, x_mid_0)
    x_mid_1 = (model.system.x.max() + model.leads[1].system.x.min()) / 2
    assert np.allclose(model.leads[1].h1.data, x_mid_1)

    # Linear onsite potential grows from lead 0 to system to lead 1
    model.add(linear_onsite())
    assert model.leads[0].h0.diagonal().max() < model.hamiltonian.diagonal().min()
    assert model.hamiltonian.diagonal().max() < model.leads[1].h0.diagonal().min()


text:
package reuse.jmx.numbers.operator;

public class Subtract extends AbstractBinaryOperator {
	private static final long serialVersionUID = 1L;

	public Subtract(Number left, Number right) {
		super(left, right);
	}

	@Override
	public double doubleValue() {
		return left.doubleValue() - right.doubleValue();
	}
}


text:
package org.jetbrains.idea.devkit.inspections.quickfix;

import com.google.common.collect.ImmutableMap;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.roots.ui.configuration.ModulesAlphaComparator;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListSeparator;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.util.Consumer;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.DomService;
import com.intellij.xml.util.IncludedXmlTag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.idea.devkit.dom.Extensions;
import org.jetbrains.idea.devkit.dom.IdeaPlugin;

import javax.swing.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class PluginDescriptorChooser {

  private static final ImmutableMap<String, String> INTELLIJ_MODULES = ImmutableMap.<String, String>builder()
    .put("platform-api", "PlatformExtensions.xml")
    .put("platform-impl", "PlatformExtensions.xml")
    .put("lang-api", "LangExtensions.xml")
    .put("lang-impl", "LangExtensions.xml")
    .put("vcs-api", "VcsExtensions.xml")
    .put("vcs-impl", "VcsExtensions.xml")
    .put("openapi", "IdeaPlugin.xml")
    .put("java-impl", "IdeaPlugin.xml")
    .build();

  public static void show(final Project project,
                          final Editor editor,
                          final PsiFile file,
                          final Consumer<DomFileElement<IdeaPlugin>> consumer) {
    final Module module = ModuleUtilCore.findModuleForPsiElement(file);
    assert module != null;
    List<DomFileElement<IdeaPlugin>> elements =
      DomService.getInstance().getFileElements(IdeaPlugin.class,
                                               project,
                                               module.getModuleWithDependenciesScope());

    elements = ContainerUtil.filter(elements, new Condition<DomFileElement<IdeaPlugin>>() {
      @Override
      public boolean value(DomFileElement<IdeaPlugin> element) {
        VirtualFile virtualFile = element.getFile().getVirtualFile();
        return virtualFile != null && ProjectRootManager.getInstance(project).getFileIndex().isInContent(virtualFile);
      }
    });

    elements = findAppropriateIntelliJModule(module.getName(), elements);

    if (elements.isEmpty()) {
      HintManager.getInstance().showErrorHint(editor, "Cannot find plugin descriptor");
      return;
    }

    if (elements.size() == 1) {
      consumer.consume(elements.get(0));
      return;
    }

    final BaseListPopupStep<PluginDescriptorCandidate> popupStep =
      new BaseListPopupStep<PluginDescriptorCandidate>("Choose Plugin Descriptor",
                                                       createCandidates(module, elements)) {

        @Override
        public boolean isSpeedSearchEnabled() {
          return true;
        }

        @Override
        public Icon getIconFor(PluginDescriptorCandidate candidate) {
          return candidate.getIcon();
        }

        @NotNull
        @Override
        public String getTextFor(PluginDescriptorCandidate candidate) {
          return candidate.getText();
        }

        @Nullable
        @Override
        public ListSeparator getSeparatorAbove(PluginDescriptorCandidate candidate) {
          final String separatorText = candidate.getSeparatorText();
          if (separatorText != null) {
            return new ListSeparator(separatorText);
          }
          return null;
        }

        @Override
        public PopupStep onChosen(PluginDescriptorCandidate selectedValue, boolean finalChoice) {
          consumer.consume(selectedValue.myDomFileElement);
          return FINAL_CHOICE;
        }
      };
    JBPopupFactory.getInstance().createListPopup(popupStep).showInBestPositionFor(editor);
  }

  @NotNull
  public static Extensions findOrCreateExtensionsForEP(DomFileElement<IdeaPlugin> domFileElement, String epName) {
    final IdeaPlugin ideaPlugin = domFileElement.getRootElement();
    final List<Extensions> extensionsList = ideaPlugin.getExtensions();
    for (Extensions extensions : extensionsList) {
      if (extensions.getXmlTag() instanceof IncludedXmlTag) {
        continue;
      }
      String s = extensions.getDefaultExtensionNs().getStringValue();
      if (s != null && epName.startsWith(s)) {
        return extensions;
      }
    }

    Extensions extensions = ideaPlugin.addExtensions();
    final String epPrefix = StringUtil.getPackageName(epName);
    extensions.getDefaultExtensionNs().setStringValue(epPrefix);
    return extensions;
  }

  private static List<PluginDescriptorCandidate> createCandidates(final Module currentModule,
                                                                  List<DomFileElement<IdeaPlugin>> elements) {
    Collections.sort(elements, new Comparator<DomFileElement<IdeaPlugin>>() {
      @Override
      public int compare(DomFileElement<IdeaPlugin> o1, DomFileElement<IdeaPlugin> o2) {
        // current module = first group
        final Module module1 = o1.getModule();
        final Module module2 = o2.getModule();
        final int byAlpha = ModulesAlphaComparator.INSTANCE.compare(module1, module2);
        if (byAlpha == 0) return 0;

        if (currentModule.equals(module1)) return -1;
        if (currentModule.equals(module2)) return 1;

        return byAlpha;
      }
    });
    Collections.sort(elements, new Comparator<DomFileElement<IdeaPlugin>>() {
      @Override
      public int compare(DomFileElement<IdeaPlugin> o1, DomFileElement<IdeaPlugin> o2) {
        if (!Comparing.equal(o1.getModule(), o2.getModule())) return 0;
        return o1.getFile().getName().compareTo(o2.getFile().getName());
      }
    });

    return ContainerUtil.map(elements, new Function<DomFileElement<IdeaPlugin>, PluginDescriptorCandidate>() {

      private Module myLastModule = currentModule;

      @Override
      public PluginDescriptorCandidate fun(DomFileElement<IdeaPlugin> element) {
        final Module module = element.getModule();
        boolean startsNewGroup = !myLastModule.equals(module);
        myLastModule = module;
        return new PluginDescriptorCandidate(element, startsNewGroup);
      }
    });
  }

  private static List<DomFileElement<IdeaPlugin>> findAppropriateIntelliJModule(String moduleName,
                                                                                List<DomFileElement<IdeaPlugin>> elements) {
    String extensionsFile = INTELLIJ_MODULES.get(moduleName);
    if (extensionsFile != null) {
      for (DomFileElement<IdeaPlugin> element : elements) {
        if (element.getFile().getName().equals(extensionsFile)) {
          return Collections.singletonList(element);
        }
      }
    }
    return elements;
  }

  private static class PluginDescriptorCandidate {
    private final DomFileElement<IdeaPlugin> myDomFileElement;
    private final boolean myStartsNewGroup;

    private PluginDescriptorCandidate(DomFileElement<IdeaPlugin> domFileElement,
                                      boolean startsNewGroup) {
      myDomFileElement = domFileElement;
      myStartsNewGroup = startsNewGroup;
    }

    public String getText() {
      final String name = myDomFileElement.getFile().getName();
      final String pluginId = getPluginId();
      return pluginId != null ? name + " [" + pluginId + "]" : name;
    }

    public Icon getIcon() {
      return getPluginId() != null ? AllIcons.Nodes.Plugin : EmptyIcon.create(AllIcons.Nodes.Plugin);
    }

    public String getSeparatorText() {
      if (!myStartsNewGroup) return null;

      final Module module = myDomFileElement.getModule();
      return module == null ? null : module.getName();
    }

    private String getPluginId() {
      return myDomFileElement.getRootElement().getPluginId();
    }
  }
}


text:
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="elemT033.xsd">
	<test xsi:type="base-A">1</test>
</root>


text:
/*************************************************************************************************

*Filename: reverserFunc.c
*Authors: Andrew Lamb
*Last Modified: 24/12/2012
*Description:	Program that reverses the order of the letters in words, function reverses characters for the individual words

*************************************************************************************************/

#include <stdio.h>
//#include <stdlib.h> //include if Malloc is wanted
#include <string.h> //include if str functions are needed

const int SENTENCE_LENGTH = 10000; //define constant variable of 10000 characters
void swap_characters_in_word (char *words, int start_of_word);	//declare function to reverse characters in words

int main(void)
{
	char words[SENTENCE_LENGTH]; //set word array
	int start_of_word = 0;

	printf("Please enter a sentence:\n"); //Ask for input
	fgets(words, SENTENCE_LENGTH, stdin); //Get sentence from user - NB fgets output ends with '\n' '\0'
	printf("You entered: %s\n", words); //(Check that program has stored user input)

	swap_characters_in_word(words, start_of_word);

	printf ("You Entered: %s\n", words); //print reversed words

	return 0; //All OK
}	//END Main

/********** FUNCTION TO REVERSE CHARACTERS IN WORDS **************/
void swap_characters_in_word (char *words, int start_of_word)
{
	int counterPos = 0;
	int counterNeg = 0;
	int get_length;
	int end_of_word;
	char temporary;

	get_length = strlen(words); //Gets length of sentence
	words[get_length -1] = ' '; //replace '\n' with ' ' could alternatively loop through sentence until '\n' found and then replace it

	//Loop through sentence:
	for (counterPos = 0; words[counterPos] != '\0'; counterPos++) //run counter until '\0' reached in sentence
	{
		//Get End and start of words entered
		if ((words[counterPos] == ' ') && (words[counterPos -1] != ' ')) //if positive counter reaches a space character in sentence:
		{
			end_of_word = counterPos - 1;
			for (counterNeg = (counterPos - 1); words[counterNeg] != '\0' && words[counterNeg] != ' '; counterNeg--) //subtracts one from counterPos so that it's not a ' ', runs negative counter backwards until  it reaches '\0' or another ' ' character
			{
				start_of_word = counterNeg;
			}

			//change order of characters in word using the "temporary" char variable and another loop
			for (end_of_word = counterPos - 1; end_of_word >= start_of_word; end_of_word--)
			{
				temporary = words[end_of_word];
				words[end_of_word] = words[start_of_word];
				words[start_of_word] = temporary;
				start_of_word++;
			}
		}
	}
}


text:
package com.consol.citrus.websocket.endpoint;

import com.consol.citrus.exceptions.ActionTimeoutException;
import com.consol.citrus.message.DefaultMessage;
import com.consol.citrus.message.Message;
import com.consol.citrus.testng.AbstractTestNGUnitTest;
import com.consol.citrus.websocket.handler.CitrusWebSocketHandler;
import com.consol.citrus.websocket.message.WebSocketMessage;
import com.consol.citrus.websocket.server.WebSocketServerEndpointConfiguration;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.web.socket.*;
import org.testng.Assert;
import org.testng.annotations.Test;

import static org.mockito.Mockito.*;

public class WebSocketEndpointTest extends AbstractTestNGUnitTest {

    private WebSocketSession session = Mockito.mock(WebSocketSession.class);
    private WebSocketSession session2 = Mockito.mock(WebSocketSession.class);
    private WebSocketSession session3 = Mockito.mock(WebSocketSession.class);

    @Test
    public void testWebSocketEndpoint() throws Exception {
        WebSocketServerEndpointConfiguration endpointConfiguration = new WebSocketServerEndpointConfiguration();
        WebSocketEndpoint webSocketEndpoint = new WebSocketEndpoint(endpointConfiguration);
        String endpointUri = "/test";

        CitrusWebSocketHandler handler = new CitrusWebSocketHandler();
        endpointConfiguration.setHandler(handler);

        final String requestBody = "<TestRequest><Message>Hello World!</Message></TestRequest>";

        final Message responseMessage = new DefaultMessage("<TestResponse><Message>Hello World!</Message></TestResponse>");

        endpointConfiguration.setEndpointUri(endpointUri);

        reset(session);

        when(session.getId()).thenReturn("test-socket-1");
        when(session.isOpen()).thenReturn(true);

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                org.springframework.web.socket.WebSocketMessage request = (org.springframework.web.socket.WebSocketMessage) invocation.getArguments()[0];

                Assert.assertTrue(TextMessage.class.isInstance(request));
                Assert.assertEquals(((TextMessage)request).getPayload(), responseMessage.getPayload(String.class));
                Assert.assertTrue(request.isLast());
                return null;
            }
        }).when(session).sendMessage(any(org.springframework.web.socket.WebSocketMessage.class));

        handler.afterConnectionEstablished(session);
        handler.handleMessage(session, new TextMessage(requestBody));

        WebSocketMessage requestMessage = (WebSocketMessage) webSocketEndpoint.createConsumer().receive(context);
        Assert.assertEquals(requestMessage.getPayload(), requestBody);
        Assert.assertTrue(requestMessage.isLast());

        webSocketEndpoint.createProducer().send(responseMessage, context);

    }

    @Test
    public void testWebSocketEndpointMultipleSessions() throws Exception {
        WebSocketServerEndpointConfiguration endpointConfiguration = new WebSocketServerEndpointConfiguration();
        WebSocketEndpoint webSocketEndpoint = new WebSocketEndpoint(endpointConfiguration);
        String endpointUri = "/test";

        CitrusWebSocketHandler handler = new CitrusWebSocketHandler();
        endpointConfiguration.setHandler(handler);

        final String requestBody = "<TestRequest><Message>Hello World!</Message></TestRequest>";

        final Message responseMessage = new DefaultMessage("<TestResponse><Message>Hello World!</Message></TestResponse>");

        endpointConfiguration.setEndpointUri(endpointUri);

        reset(session, session2, session3);

        when(session.getId()).thenReturn("test-socket-1");
        when(session2.getId()).thenReturn("test-socket-2");
        when(session3.getId()).thenReturn("test-socket-3");
        when(session.isOpen()).thenReturn(true);
        when(session2.isOpen()).thenReturn(true);

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                org.springframework.web.socket.WebSocketMessage request = (org.springframework.web.socket.WebSocketMessage) invocation.getArguments()[0];

                Assert.assertTrue(TextMessage.class.isInstance(request));
                Assert.assertEquals(((TextMessage)request).getPayload(), responseMessage.getPayload(String.class));
                Assert.assertTrue(request.isLast());
                return null;
            }
        }).when(session).sendMessage(any(org.springframework.web.socket.WebSocketMessage.class));

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                org.springframework.web.socket.WebSocketMessage request = (org.springframework.web.socket.WebSocketMessage) invocation.getArguments()[0];

                Assert.assertTrue(TextMessage.class.isInstance(request));
                Assert.assertEquals(((TextMessage)request).getPayload(), responseMessage.getPayload(String.class));
                Assert.assertTrue(request.isLast());
                return null;
            }
        }).when(session2).sendMessage(any(org.springframework.web.socket.WebSocketMessage.class));

        handler.afterConnectionEstablished(session);
        handler.afterConnectionEstablished(session2);
        handler.afterConnectionEstablished(session3);
        handler.afterConnectionClosed(session3, CloseStatus.NORMAL);

        handler.handleMessage(session, new TextMessage(requestBody));

        WebSocketMessage requestMessage = (WebSocketMessage) webSocketEndpoint.createConsumer().receive(context);
        Assert.assertEquals(requestMessage.getPayload(), requestBody);
        Assert.assertTrue(requestMessage.isLast());

        webSocketEndpoint.createProducer().send(responseMessage, context);

    }

    @Test
    public void testWebSocketEndpointTimeout() throws Exception {
        WebSocketServerEndpointConfiguration endpointConfiguration = new WebSocketServerEndpointConfiguration();
        WebSocketEndpoint webSocketEndpoint = new WebSocketEndpoint(endpointConfiguration);
        String endpointUri = "/test";

        CitrusWebSocketHandler handler = new CitrusWebSocketHandler();
        endpointConfiguration.setHandler(handler);
        endpointConfiguration.setEndpointUri(endpointUri);
        endpointConfiguration.setTimeout(1000L);

        reset(session);
        when(session.getId()).thenReturn("test-socket-1");
        handler.afterConnectionEstablished(session);

        try {
            webSocketEndpoint.createConsumer().receive(context, endpointConfiguration.getTimeout());
            Assert.fail("Missing timeout exception on web socket endpoint");
        } catch (ActionTimeoutException e) {
            Assert.assertTrue(e.getMessage().contains(endpointUri));
        }

    }
}


text:
use_inline_resources
#require 'mysql2'

def whyrun_supported?
  true
end

def conn
  @conn ||= begin
  Chef::Log.debug("Establishing connection to DB :default_file => #{@new_resource.defaults_file} :username => #{@new_resource.username} ")
  c = Mysql2::Client.new(
    :default_file => @new_resource.defaults_file ,
    :username => @new_resource.username,
    :password => @new_resource.password
  )
  end
end

action :create do
  @new_resource.networks.each do | source_addr |
    @new_resource.tables.each do | table |
      sql =  "GRANT #{@new_resource.grant} ON #{@new_resource.database}.#{table} TO "
      sql += "'#{@new_resource.user}'@'#{source_addr}'"
      secure_sql = sql
      if @new_resource.user_password
        secure_sql += "  IDENTIFIED BY 'XXXXXXXXX'"
        sql += " IDENTIFIED BY '#{@new_resource.user_password}'"
      end
      if @new_resource.with_grant
        secure_sql += " WITH GRANT OPTION"
        sql += " WITH GRANT OPTION"
      end
      converge_by(secure_sql) do
        Chef::Log.debug("Running #{secure_sql}")
          results = conn.query(sql)
        new_resource.updated_by_last_action(true)
      end
    end
  end
end
action :revoke do
  @new_resource.networks.each do | source_addr |
    @new_resource.tables.each do | table |
      sql =  "REVOKE #{@new_resource.grant} ON #{@new_resource.database}.#{table} FROM "
      sql += "'#{@new_resource.user}'@'#{source_addr}'"
      secure_sql = sql
      converge_by(secure_sql) do
        Chef::Log.debug("Running #{secure_sql}")
        begin
          results = conn.query(sql)
        rescue Mysql2::Error =>  err
          Chef::Log.debug( "Mysql REVOKE action error #{err.message}")
        end
        new_resource.updated_by_last_action(true)
      end
    end
  end
end

action :remove do
  @new_resource.networks.each do | source_addr |
    sql =  "DROP user '#{@new_resource.user}'@'#{source_addr}'"
    secure_sql = sql
    converge_by(secure_sql) do
      Chef::Log.debug("Running #{secure_sql}")
      begin
        results = conn.query(sql)
      rescue Mysql2::Error =>  err
        Chef::Log.debug( "Mysql REMOVE action error #{err.message}")
      end
      new_resource.updated_by_last_action(true)
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/objects/office-supplies/staple-removers" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/office-supplies/staple-removers</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Staple Removers</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/office-supplies/staple-removers</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/objects/office-supplies/staple-removers</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
/* -*- c-basic-offset: 4 -*- */
#ifndef PROCLIKEFS_H
#define PROCLIKEFS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <linux/fs.h>
#include <linux/list.h>
#include <linux/version.h>

struct proclikefs_file_system;

#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 0, 0)
typedef struct dentry *(*proclikefs_mountfunc)(struct file_system_type *, int, const char *, void *);
#elif LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 19)
typedef int (*proclikefs_mountfunc)(struct file_system_type *, int, const char *, void *, struct vfsmount *);
#else
typedef struct super_block *(*proclikefs_mountfunc)(struct file_system_type *, int, const char *, void *);
#endif

struct proclikefs_file_system *proclikefs_register_filesystem
		(const char *name, int fs_flags,
		 proclikefs_mountfunc mountfunc);
void proclikefs_reinitialize_supers(struct proclikefs_file_system *,
		 void (*reread_super) (struct super_block *));
void proclikefs_unregister_filesystem(struct proclikefs_file_system *);

void proclikefs_read_super(struct super_block *);
void proclikefs_put_super(struct super_block *);

struct file_operations *proclikefs_new_file_operations(struct proclikefs_file_system *pfs, const char *name);
struct inode_operations *proclikefs_new_inode_operations(struct proclikefs_file_system *pfs, const char *name);

#ifdef __cplusplus
}
#endif
#endif