text:
import dataclasses
import json  # type: ignore
import re
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union
import warnings

from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming
from google.api_core import exceptions as core_exceptions
from google.api_core import retry as retries
from google.auth import credentials as ga_credentials  # type: ignore
from google.auth.transport.grpc import SslCredentials  # type: ignore
from google.auth.transport.requests import AuthorizedSession  # type: ignore
from google.protobuf import json_format
import grpc  # type: ignore
from requests import __version__ as requests_version

try:
    OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
except AttributeError:  # pragma: NO COVER
    OptionalRetry = Union[retries.Retry, object]  # type: ignore

from google.cloud.compute_v1.types import compute

from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
from .base import TargetGrpcProxiesTransport

DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
    gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version,
    grpc_version=None,
    rest_version=requests_version,
)

class TargetGrpcProxiesRestInterceptor:
    """Interceptor for TargetGrpcProxies.

    Interceptors are used to manipulate requests, request metadata, and responses
    in arbitrary ways.
    Example use cases include:
    * Logging
    * Verifying requests according to service or custom semantics
    * Stripping extraneous information from responses

    These use cases and more can be enabled by injecting an
    instance of a custom subclass when constructing the TargetGrpcProxiesRestTransport.

    .. code-block:: python
        class MyCustomTargetGrpcProxiesInterceptor(TargetGrpcProxiesRestInterceptor):
            def pre_delete(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_delete(response):
                logging.log(f"Received response: {response}")

            def pre_get(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_get(response):
                logging.log(f"Received response: {response}")

            def pre_insert(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_insert(response):
                logging.log(f"Received response: {response}")

            def pre_list(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_list(response):
                logging.log(f"Received response: {response}")

            def pre_patch(request, metadata):
                logging.log(f"Received request: {request}")
                return request, metadata

            def post_patch(response):
                logging.log(f"Received response: {response}")

        transport = TargetGrpcProxiesRestTransport(interceptor=MyCustomTargetGrpcProxiesInterceptor())
        client = TargetGrpcProxiesClient(transport=transport)

    """

    def pre_delete(
        self,
        request: compute.DeleteTargetGrpcProxyRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.DeleteTargetGrpcProxyRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for delete

        Override in a subclass to manipulate the request or metadata
        before they are sent to the TargetGrpcProxies server.
        """
        return request, metadata

    def post_delete(self, response: compute.Operation) -> compute.Operation:
        """Post-rpc interceptor for delete

        Override in a subclass to manipulate the response
        after it is returned by the TargetGrpcProxies server but before
        it is returned to user code.
        """
        return response

    def pre_get(
        self,
        request: compute.GetTargetGrpcProxyRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.GetTargetGrpcProxyRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for get

        Override in a subclass to manipulate the request or metadata
        before they are sent to the TargetGrpcProxies server.
        """
        return request, metadata

    def post_get(self, response: compute.TargetGrpcProxy) -> compute.TargetGrpcProxy:
        """Post-rpc interceptor for get

        Override in a subclass to manipulate the response
        after it is returned by the TargetGrpcProxies server but before
        it is returned to user code.
        """
        return response

    def pre_insert(
        self,
        request: compute.InsertTargetGrpcProxyRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.InsertTargetGrpcProxyRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for insert

        Override in a subclass to manipulate the request or metadata
        before they are sent to the TargetGrpcProxies server.
        """
        return request, metadata

    def post_insert(self, response: compute.Operation) -> compute.Operation:
        """Post-rpc interceptor for insert

        Override in a subclass to manipulate the response
        after it is returned by the TargetGrpcProxies server but before
        it is returned to user code.
        """
        return response

    def pre_list(
        self,
        request: compute.ListTargetGrpcProxiesRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.ListTargetGrpcProxiesRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for list

        Override in a subclass to manipulate the request or metadata
        before they are sent to the TargetGrpcProxies server.
        """
        return request, metadata

    def post_list(
        self, response: compute.TargetGrpcProxyList
    ) -> compute.TargetGrpcProxyList:
        """Post-rpc interceptor for list

        Override in a subclass to manipulate the response
        after it is returned by the TargetGrpcProxies server but before
        it is returned to user code.
        """
        return response

    def pre_patch(
        self,
        request: compute.PatchTargetGrpcProxyRequest,
        metadata: Sequence[Tuple[str, str]],
    ) -> Tuple[compute.PatchTargetGrpcProxyRequest, Sequence[Tuple[str, str]]]:
        """Pre-rpc interceptor for patch

        Override in a subclass to manipulate the request or metadata
        before they are sent to the TargetGrpcProxies server.
        """
        return request, metadata

    def post_patch(self, response: compute.Operation) -> compute.Operation:
        """Post-rpc interceptor for patch

        Override in a subclass to manipulate the response
        after it is returned by the TargetGrpcProxies server but before
        it is returned to user code.
        """
        return response

@dataclasses.dataclass
class TargetGrpcProxiesRestStub:
    _session: AuthorizedSession
    _host: str
    _interceptor: TargetGrpcProxiesRestInterceptor

class TargetGrpcProxiesRestTransport(TargetGrpcProxiesTransport):
    """REST backend transport for TargetGrpcProxies.

    The TargetGrpcProxies API.

    This class defines the same methods as the primary client, so the
    primary client can load the underlying transport implementation
    and call it.

    It sends JSON representations of protocol buffers over HTTP/1.1

    NOTE: This REST transport functionality is currently in a beta
    state (preview). We welcome your feedback via an issue in this
    library's source repository. Thank you!
    """

    def __init__(
        self,
        *,
        host: str = "compute.googleapis.com",
        credentials: Optional[ga_credentials.Credentials] = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        url_scheme: str = "https",
        interceptor: Optional[TargetGrpcProxiesRestInterceptor] = None,
        api_audience: Optional[str] = None,
    ) -> None:
        """Instantiate the transport.

        NOTE: This REST transport functionality is currently in a beta
        state (preview). We welcome your feedback via a GitHub issue in
        this library's repository. Thank you!

         Args:
             host (Optional[str]):
                  The hostname to connect to.
             credentials (Optional[google.auth.credentials.Credentials]): The
                 authorization credentials to attach to requests. These
                 credentials identify the application to the service; if none
                 are specified, the client will attempt to ascertain the
                 credentials from the environment.

             credentials_file (Optional[str]): A file with credentials that can
                 be loaded with :func:`google.auth.load_credentials_from_file`.
                 This argument is ignored if ``channel`` is provided.
             scopes (Optional(Sequence[str])): A list of scopes. This argument is
                 ignored if ``channel`` is provided.
             client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client
                 certificate to configure mutual TLS HTTP channel. It is ignored
                 if ``channel`` is provided.
             quota_project_id (Optional[str]): An optional project to use for billing
                 and quota.
             client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                 The client info used to send a user-agent string along with
                 API requests. If ``None``, then default info will be used.
                 Generally, you only need to set this if you are developing
                 your own client library.
             always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                 be used for service account credentials.
             url_scheme: the protocol scheme for the API endpoint.  Normally
                 "https", but for testing or local servers,
                 "http" can be specified.
        """
        # Run the base constructor
        # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc.
        # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the
        # credentials object
        maybe_url_match = re.match("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", host)
        if maybe_url_match is None:
            raise ValueError(
                f"Unexpected hostname structure: {host}"
            )  # pragma: NO COVER

        url_match_items = maybe_url_match.groupdict()

        host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host

        super().__init__(
            host=host,
            credentials=credentials,
            client_info=client_info,
            always_use_jwt_access=always_use_jwt_access,
            api_audience=api_audience,
        )
        self._session = AuthorizedSession(
            self._credentials, default_host=self.DEFAULT_HOST
        )
        if client_cert_source_for_mtls:
            self._session.configure_mtls_channel(client_cert_source_for_mtls)
        self._interceptor = interceptor or TargetGrpcProxiesRestInterceptor()
        self._prep_wrapped_messages(client_info)

    class _Delete(TargetGrpcProxiesRestStub):
        def __hash__(self):
            return hash("Delete")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.DeleteTargetGrpcProxyRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the delete method over HTTP.

            Args:
                request (~.compute.DeleteTargetGrpcProxyRequest):
                    The request object. A request message for
                TargetGrpcProxies.Delete. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "delete",
                    "uri": "/compute/v1/projects/{project}/global/targetGrpcProxies/{target_grpc_proxy}",
                },
            ]
            request, metadata = self._interceptor.pre_delete(request, metadata)
            pb_request = compute.DeleteTargetGrpcProxyRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.Operation()
            pb_resp = compute.Operation.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_delete(resp)
            return resp

    class _Get(TargetGrpcProxiesRestStub):
        def __hash__(self):
            return hash("Get")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.GetTargetGrpcProxyRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.TargetGrpcProxy:
            r"""Call the get method over HTTP.

            Args:
                request (~.compute.GetTargetGrpcProxyRequest):
                    The request object. A request message for
                TargetGrpcProxies.Get. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.TargetGrpcProxy:
                    Represents a Target gRPC Proxy resource. A target gRPC
                proxy is a component of load balancers intended for load
                balancing gRPC traffic. Only global forwarding rules
                with load balancing scheme INTERNAL_SELF_MANAGED can
                reference a target gRPC proxy. The target gRPC Proxy
                references a URL map that specifies how traffic is
                routed to gRPC backend services.

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/global/targetGrpcProxies/{target_grpc_proxy}",
                },
            ]
            request, metadata = self._interceptor.pre_get(request, metadata)
            pb_request = compute.GetTargetGrpcProxyRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.TargetGrpcProxy()
            pb_resp = compute.TargetGrpcProxy.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_get(resp)
            return resp

    class _Insert(TargetGrpcProxiesRestStub):
        def __hash__(self):
            return hash("Insert")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.InsertTargetGrpcProxyRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the insert method over HTTP.

            Args:
                request (~.compute.InsertTargetGrpcProxyRequest):
                    The request object. A request message for
                TargetGrpcProxies.Insert. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "post",
                    "uri": "/compute/v1/projects/{project}/global/targetGrpcProxies",
                    "body": "target_grpc_proxy_resource",
                },
            ]
            request, metadata = self._interceptor.pre_insert(request, metadata)
            pb_request = compute.InsertTargetGrpcProxyRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            # Jsonify the request body

            body = json_format.MessageToJson(
                transcoded_request["body"],
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.Operation()
            pb_resp = compute.Operation.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_insert(resp)
            return resp

    class _List(TargetGrpcProxiesRestStub):
        def __hash__(self):
            return hash("List")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.ListTargetGrpcProxiesRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.TargetGrpcProxyList:
            r"""Call the list method over HTTP.

            Args:
                request (~.compute.ListTargetGrpcProxiesRequest):
                    The request object. A request message for
                TargetGrpcProxies.List. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.TargetGrpcProxyList:

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "get",
                    "uri": "/compute/v1/projects/{project}/global/targetGrpcProxies",
                },
            ]
            request, metadata = self._interceptor.pre_list(request, metadata)
            pb_request = compute.ListTargetGrpcProxiesRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.TargetGrpcProxyList()
            pb_resp = compute.TargetGrpcProxyList.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_list(resp)
            return resp

    class _Patch(TargetGrpcProxiesRestStub):
        def __hash__(self):
            return hash("Patch")

        __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {}

        @classmethod
        def _get_unset_required_fields(cls, message_dict):
            return {
                k: v
                for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items()
                if k not in message_dict
            }

        def __call__(
            self,
            request: compute.PatchTargetGrpcProxyRequest,
            *,
            retry: OptionalRetry = gapic_v1.method.DEFAULT,
            timeout: Optional[float] = None,
            metadata: Sequence[Tuple[str, str]] = (),
        ) -> compute.Operation:
            r"""Call the patch method over HTTP.

            Args:
                request (~.compute.PatchTargetGrpcProxyRequest):
                    The request object. A request message for
                TargetGrpcProxies.Patch. See the method
                description for details.

                retry (google.api_core.retry.Retry): Designation of what errors, if any,
                    should be retried.
                timeout (float): The timeout for this request.
                metadata (Sequence[Tuple[str, str]]): Strings which should be
                    sent along with the request as metadata.

            Returns:
                ~.compute.Operation:
                    Represents an Operation resource. Google Compute Engine
                has three Operation resources: \*
                `Global </compute/docs/reference/rest/v1/globalOperations>`__
                \*
                `Regional </compute/docs/reference/rest/v1/regionOperations>`__
                \*
                `Zonal </compute/docs/reference/rest/v1/zoneOperations>`__
                You can use an operation resource to manage asynchronous
                API requests. For more information, read Handling API
                responses. Operations can be global, regional or zonal.
                - For global operations, use the ``globalOperations``
                resource. - For regional operations, use the
                ``regionOperations`` resource. - For zonal operations,
                use the ``zonalOperations`` resource. For more
                information, read Global, Regional, and Zonal Resources.

            """

            http_options: List[Dict[str, str]] = [
                {
                    "method": "patch",
                    "uri": "/compute/v1/projects/{project}/global/targetGrpcProxies/{target_grpc_proxy}",
                    "body": "target_grpc_proxy_resource",
                },
            ]
            request, metadata = self._interceptor.pre_patch(request, metadata)
            pb_request = compute.PatchTargetGrpcProxyRequest.pb(request)
            transcoded_request = path_template.transcode(http_options, pb_request)

            # Jsonify the request body

            body = json_format.MessageToJson(
                transcoded_request["body"],
                including_default_value_fields=False,
                use_integers_for_enums=False,
            )
            uri = transcoded_request["uri"]
            method = transcoded_request["method"]

            # Jsonify the query params
            query_params = json.loads(
                json_format.MessageToJson(
                    transcoded_request["query_params"],
                    including_default_value_fields=False,
                    use_integers_for_enums=False,
                )
            )
            query_params.update(self._get_unset_required_fields(query_params))

            # Send the request
            headers = dict(metadata)
            headers["Content-Type"] = "application/json"
            response = getattr(self._session, method)(
                "{host}{uri}".format(host=self._host, uri=uri),
                timeout=timeout,
                headers=headers,
                params=rest_helpers.flatten_query_params(query_params, strict=True),
                data=body,
            )

            # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception
            # subclass.
            if response.status_code >= 400:
                raise core_exceptions.from_http_response(response)

            # Return the response
            resp = compute.Operation()
            pb_resp = compute.Operation.pb(resp)

            json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
            resp = self._interceptor.post_patch(resp)
            return resp

    @property
    def delete(
        self,
    ) -> Callable[[compute.DeleteTargetGrpcProxyRequest], compute.Operation]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._Delete(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def get(
        self,
    ) -> Callable[[compute.GetTargetGrpcProxyRequest], compute.TargetGrpcProxy]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._Get(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def insert(
        self,
    ) -> Callable[[compute.InsertTargetGrpcProxyRequest], compute.Operation]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._Insert(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def list(
        self,
    ) -> Callable[[compute.ListTargetGrpcProxiesRequest], compute.TargetGrpcProxyList]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._List(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def patch(
        self,
    ) -> Callable[[compute.PatchTargetGrpcProxyRequest], compute.Operation]:
        # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here.
        # In C++ this would require a dynamic_cast
        return self._Patch(self._session, self._host, self._interceptor)  # type: ignore

    @property
    def kind(self) -> str:
        return "rest"

    def close(self):
        self._session.close()

__all__ = ("TargetGrpcProxiesRestTransport",)


text:
<?php

class Google_Service_Vision_GoogleCloudVisionV1p4beta1Celebrity extends Google_Model
{
  public $description;
  public $displayName;
  public $name;

  public function setDescription($description)
  {
    $this->description = $description;
  }
  public function getDescription()
  {
    return $this->description;
  }
  public function setDisplayName($displayName)
  {
    $this->displayName = $displayName;
  }
  public function getDisplayName()
  {
    return $this->displayName;
  }
  public function setName($name)
  {
    $this->name = $name;
  }
  public function getName()
  {
    return $this->name;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
//use app\assets\AppAsset;
use util\MenuMaker;

?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">

    <meta charset="<?= Yii::$app->charset ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/reset.css" rel="stylesheet" />
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>

    <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/bootstrap.min.css" rel="stylesheet" />

    <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/animate.min.css" rel="stylesheet"/>

    <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/paper-dashboard.css" rel="stylesheet"/>

    <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/demo.css" rel="stylesheet" />

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/latest/css/font-awesome.min.css" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Muli:400,300' rel='stylesheet' type='text/css'>
    <link href="<?php echo Yii::$app->request->baseUrl; ?>/css/themify-icons.css" rel="stylesheet">

    <?php $this->head() ?>

<?php $this->beginBody() ?>

    <?= $content ?>

    <?php
//AppAsset::register($this);
  //  $this->registerLinkTag(['rel' => 'icon', 'type' => 'image/png', 'href' => '/img/favicon.png']);
   // $this->registerJsFile(Yii::$app->request->baseUrl.'/js/Chart.min.js',['depends' => [\yii\web\JqueryAsset::className()],'position'=>\yii\web\View::POS_END]);
    //$this->registerJsFile(Yii::$app->request->baseUrl.'/js/index.js',['depends' => [\yii\web\JqueryAsset::className()],'position'=>\yii\web\View::POS_END]);

    ?>

<?php $this->endBody() ?>

<?php $this->endPage() ?>


text:
/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.47
 * Generated at: 2017-10-24 06:51:51 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp.WEB_002dINF.views.modules.sys;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class tagTreeselect_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

private static org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_0;
private static org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_1;

static {
  _jspx_fnmap_0= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getAdminPath", com.thinkgem.jeesite.common.config.Global.class, "getAdminPath", new Class[] {});
  _jspx_fnmap_1= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fn:indexOf", org.apache.taglibs.standard.functions.Functions.class, "indexOf", new Class[] {java.lang.String.class, java.lang.String.class});
}

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  static {
    _jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>(5);
    _jspx_dependants.put("/WEB-INF/views/include/taglib.jsp", Long.valueOf(1483186160000L));
    _jspx_dependants.put("/WEB-INF/tlds/fns.tld", Long.valueOf(1483186160000L));
    _jspx_dependants.put("/WEB-INF/tlds/shiros.tld", Long.valueOf(1483186160000L));
    _jspx_dependants.put("/WEB-INF/tlds/fnc.tld", Long.valueOf(1483186160000L));
    _jspx_dependants.put("/WEB-INF/views/include/treeview.jsp", Long.valueOf(1483186160000L));
  }

  private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody;
  private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fif_0026_005ftest;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
    _005fjspx_005ftagPool_005fc_005fif_0026_005ftest = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
    _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.release();
    _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.release();
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write('\n');
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      if (_jspx_meth_c_005fset_005f0(_jspx_page_context))
        return;
      out.write('\n');
      if (_jspx_meth_c_005fset_005f1(_jspx_page_context))
        return;
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\t<title>数据选择</title>\n");
      out.write("\t<meta name=\"decorator\" content=\"blank\"/>\n");
      out.write("\t");
      out.write("<link href=\"");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctxStatic}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
      out.write("/jquery-ztree/3.5.12/css/zTreeStyle/zTreeStyle.min.css\" rel=\"stylesheet\" type=\"text/css\"/>\n");
      out.write("");
      out.write("\n");
      out.write("\t\n");
      out.write("\n");
      out.write("\n");
      out.write("\t
\n");
      out.write("\t\t搜索\n");
      out.write("\t
\n");
      out.write("\t
\n");
      out.write("\t\t关键字:\n");
      out.write("\t\t<input type=\"text\" class=\"empty\" id=\"key\" name=\"key\" maxlength=\"50\" style=\"width:110px;\">\n");
      out.write("\t\t<button class=\"btn\" id=\"btn\" onclick=\"searchNode()\">搜索</button>\n");
      out.write("\t
\n");
      out.write("\t

\n");
      out.write("");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }

  private boolean _jspx_meth_c_005fset_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
          throws java.lang.Throwable {
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
    //  c:set
    org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
    _jspx_th_c_005fset_005f0.setPageContext(_jspx_page_context);
    _jspx_th_c_005fset_005f0.setParent(null);
    // /WEB-INF/views/include/taglib.jsp(11,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fset_005f0.setVar("ctx");
    // /WEB-INF/views/include/taglib.jsp(11,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fset_005f0.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}${fns:getAdminPath()}", java.lang.Object.class, (javax.servlet.jsp.PageContext)_jspx_page_context, _jspx_fnmap_0, false));
    int _jspx_eval_c_005fset_005f0 = _jspx_th_c_005fset_005f0.doStartTag();
    if (_jspx_th_c_005fset_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0);
      return true;
    }
    _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0);
    return false;
  }

  private boolean _jspx_meth_c_005fset_005f1(javax.servlet.jsp.PageContext _jspx_page_context)
          throws java.lang.Throwable {
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
    //  c:set
    org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class);
    _jspx_th_c_005fset_005f1.setPageContext(_jspx_page_context);
    _jspx_th_c_005fset_005f1.setParent(null);
    // /WEB-INF/views/include/taglib.jsp(12,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fset_005f1.setVar("ctxStatic");
    // /WEB-INF/views/include/taglib.jsp(12,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fset_005f1.setValue((java.lang.Object) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}/static", java.lang.Object.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false));
    int _jspx_eval_c_005fset_005f1 = _jspx_th_c_005fset_005f1.doStartTag();
    if (_jspx_th_c_005fset_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1);
      return true;
    }
    _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1);
    return false;
  }

  private boolean _jspx_meth_c_005fif_005f0(javax.servlet.jsp.PageContext _jspx_page_context)
          throws java.lang.Throwable {
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context;
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();
    //  c:if
    org.apache.taglibs.standard.tag.rt.core.IfTag _jspx_th_c_005fif_005f0 = (org.apache.taglibs.standard.tag.rt.core.IfTag) _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.get(org.apache.taglibs.standard.tag.rt.core.IfTag.class);
    _jspx_th_c_005fif_005f0.setPageContext(_jspx_page_context);
    _jspx_th_c_005fif_005f0.setParent(null);
    // /WEB-INF/views/modules/sys/tagTreeselect.jsp(34,32) name = test type = boolean reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
    _jspx_th_c_005fif_005f0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${!checked}", java.lang.Boolean.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)).booleanValue());
    int _jspx_eval_c_005fif_005f0 = _jspx_th_c_005fif_005f0.doStartTag();
    if (_jspx_eval_c_005fif_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
      do {
        out.write("\n");
        out.write("\t\t\t\t\t\ttop.$.jBox.getBox().find(\"button[value='ok']\").trigger(\"click\");\n");
        out.write("\t\t\t\t\t\t//$(\"input[type='text']\", top.mainFrame.document).focus();//");
        int evalDoAfterBody = _jspx_th_c_005fif_005f0.doAfterBody();
        if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
          break;
      } while (true);
    }
    if (_jspx_th_c_005fif_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
      _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0);
      return true;
    }
    _005fjspx_005ftagPool_005fc_005fif_0026_005ftest.reuse(_jspx_th_c_005fif_005f0);
    return false;
  }
}


text:
'''
Created by auto_sdk on 2015.04.21
'''
from aliyun.api.base import RestApi
class Ecs20140526ResetDiskRequest(RestApi):
	def __init__(self,domain='ecs.aliyuncs.com',port=80):
		RestApi.__init__(self,domain, port)
		self.DiskId = None
		self.SnapshotId = None

	def getapiname(self):
		return 'ecs.aliyuncs.com.ResetDisk.2014-05-26'


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:cloud="http://www.springframework.org/schema/cloud"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/cloud http://www.springframework.org/schema/cloud/spring-cloud.xsd">

	<cloud:mongo-db-factory id="service-connectionPerHost50-maxWait200-WriteConcernNone" service-name="my-service" write-concern="NONE">
	    <cloud:mongo-options max-wait-time="200" connections-per-host="50"/>
	</cloud:mongo-db-factory>

	<cloud:mongo-db-factory id="service-maxWait200-connectionPerHost50-WriteConcernSafe" service-name="my-service" write-concern="SAFE">
	    <cloud:mongo-options max-wait-time="200" connections-per-host="50"/>
	</cloud:mongo-db-factory>

	<cloud:mongo-db-factory id="service-maxWait200-connectionPerHost50-WriteConcernUnspecified" service-name="my-service">
	    <cloud:mongo-options max-wait-time="200" connections-per-host="50"/>
	</cloud:mongo-db-factory>

	<cloud:mongo-db-factory id="service-maxWaitUnspecified-connectionPerHost50-WriteConcernUnspecified" service-name="my-service">
	    <cloud:mongo-options connections-per-host="50"/>
	</cloud:mongo-db-factory>

	<cloud:mongo-db-factory id="service-maxWait200-connectionPerHostUnspecified-WriteConcernUnspecified" service-name="my-service">
	    <cloud:mongo-options max-wait-time="200"/>
	</cloud:mongo-db-factory>

</beans>


text:
public class SWIGTYPE_p_p_unsigned_long {
  private global::System.Runtime.InteropServices.HandleRef swigCPtr;

  internal SWIGTYPE_p_p_unsigned_long(global::System.IntPtr cPtr, bool futureUse) {
    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
  }

  protected SWIGTYPE_p_p_unsigned_long() {
    swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
  }

  internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SWIGTYPE_p_p_unsigned_long obj) {
    return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
  }
}


text:
title: Custom
page_title: RadSpreadsheet Custom Validation
description: Check our Web Forms article about Custom ContextMenu.
slug: spreadsheet/functionality/validation/custom
tags: custom
published: True
position: 1
---

#  Custom Validation

The **RadSpreadsheet** control allows you to create your own custom **Validation** Dialog, where you can define the criteria and behavior for invalid data that suits best your scenario. You can achieve this, using the **ValidationTemplate** tag of the **RadSpreadsheet** control. The following steps will guide you trough the custom Data Validation dialog implementation:

1. Create a WebUserControl, which will contain the layot and behavior of the custom Validation dialog. In the WebUserControl you can define preferable **Criteria** for data types and implement any further configuration for those types. Also, you can configure the behavior for handling the invalid data and Hint Message.

2. Create JavaScript file that will be the actual connection to the Spreadsheet.ValidationView. In this javascript file, you will need to create the interface for the **ValidationView** object of the **RadSpreadsheet** and the markup of the newly created custom dialog. Manipulating the prototypes of the **ValidationView** you will have a full access and ability to implement or modify the behavior of the default controls in the view and apply your custom one.

3. Create the **RadSpreadsheet** on your page, referencing the custom WebUserControl that contains the new Validation view (dialog) in the **ValidationTemplate** tag and provide a reference to the javascript file that serve as interface for **ValidationView** object of the **RadSpreadsheet** and the custom Validation dialog. At the end, the layout of the aspx page where the **RadSpreadsheet** is defined should look as simple as the below implementation:

````ASP.NET

<%@ Register Src="~/SpreadsheetValidation.ascx" TagPrefix="uc1" TagName="SpreadsheetValidation" %>
....
....
<form id="form1" runat="server">
	<telerik:RadScriptManager runat="server" />

	<script src="Scripts/ValidationView.js"></script>

	<telerik:RadSpreadsheet runat="server" ID="RadSpreadsheet1">
		<ValidationTemplate>
			<uc1:SpreadsheetValidation runat="server" ID="SpreadsheetValidation" />
		</ValidationTemplate>
	</telerik:RadSpreadsheet>

</form>

````

>note You can investigate the entire setup and test the behavior of the **RadSpreadsheet** with Custom **Validation** dialog in this Code Library: [Validation Template for RadSpreadsheet Code Library](https://www.telerik.com/support/code-library/validation-template).


text:
<?php

class Google_Service_YouTube_ChannelSnippet extends Google_Model
{
  public $country;
  public $customUrl;
  public $defaultLanguage;
  public $description;
  protected $localizedType = 'Google_Service_YouTube_ChannelLocalization';
  protected $localizedDataType = '';
  public $publishedAt;
  protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
  protected $thumbnailsDataType = '';
  public $title;

  public function setCountry($country)
  {
    $this->country = $country;
  }
  public function getCountry()
  {
    return $this->country;
  }
  public function setCustomUrl($customUrl)
  {
    $this->customUrl = $customUrl;
  }
  public function getCustomUrl()
  {
    return $this->customUrl;
  }
  public function setDefaultLanguage($defaultLanguage)
  {
    $this->defaultLanguage = $defaultLanguage;
  }
  public function getDefaultLanguage()
  {
    return $this->defaultLanguage;
  }
  public function setDescription($description)
  {
    $this->description = $description;
  }
  public function getDescription()
  {
    return $this->description;
  }
  public function setLocalized(Google_Service_YouTube_ChannelLocalization $localized)
  {
    $this->localized = $localized;
  }
  public function getLocalized()
  {
    return $this->localized;
  }
  public function setPublishedAt($publishedAt)
  {
    $this->publishedAt = $publishedAt;
  }
  public function getPublishedAt()
  {
    return $this->publishedAt;
  }
  public function setThumbnails(Google_Service_YouTube_ThumbnailDetails $thumbnails)
  {
    $this->thumbnails = $thumbnails;
  }
  public function getThumbnails()
  {
    return $this->thumbnails;
  }
  public function setTitle($title)
  {
    $this->title = $title;
  }
  public function getTitle()
  {
    return $this->title;
  }
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:orderInCategory="100"
          android:showAsAction="never"/>
</menu>
<!-- From: file:/Users/BSid/Team16Project/TextbookTrader/app/src/main/res/menu/global.xml -->


text:
using UnityEngine;
using System.Collections;

namespace spawn
{
    /// <summary>
    /// Spawn a new spaceship
    /// </summary>
    public class SpaceshipSpawner : Spawner
    {
        /// <summary>
        /// When the players score hits a multiple of this, spawn a new spaceship
        /// </summary>
        [SerializeField]
        private int m_SpawnWhenScoreIsMultipleOf = 10000;

        /// <summary>
        /// The number of times we have spawned a spaceship
        /// </summary>
        private int m_SpawnCount = 0;

        /// <summary>
        /// Check to see if we are ready to spawn a new spaceship
        /// </summary>
        /// <returns>Ready to spawn?</returns>
        protected override bool CanSpawn()
        {
            int spawnModulus = game.Score.Instance.CurrentScore / m_SpawnWhenScoreIsMultipleOf;

            if (spawnModulus > m_SpawnCount)
            {
                ++m_SpawnCount;
                return true;
            }

            return false;
        }
    }
}


text:
require File.dirname(__FILE__) + '/tag_helper'

module ActionView
  module Helpers
    # Provides functionality for working with JavaScript in your views.
    #
    # == Ajax, controls and visual effects
    #
    # * For information on using Ajax, see
    #   ActionView::Helpers::PrototypeHelper.
    # * For information on using controls and visual effects, see
    #   ActionView::Helpers::ScriptaculousHelper.
    #
    # == Including the JavaScript libraries into your pages
    #
    # Rails includes the Prototype JavaScript framework and the Scriptaculous
    # JavaScript controls and visual effects library.  If you wish to use
    # these libraries and their helpers (ActionView::Helpers::PrototypeHelper
    # and ActionView::Helpers::ScriptaculousHelper), you must do one of the
    # following:
    #
    # * Use <tt><%= javascript_include_tag :defaults %></tt> in the HEAD
    #   section of your page (recommended): This function will return
    #   references to the JavaScript files created by the +rails+ command in
    #   your <tt>public/javascripts</tt> directory. Using it is recommended as
    #   the browser can then cache the libraries instead of fetching all the
    #   functions anew on every request.
    # * Use <tt><%= javascript_include_tag 'prototype' %></tt>: As above, but
    #   will only include the Prototype core library, which means you are able
    #   to use all basic AJAX functionality. For the Scriptaculous-based
    #   JavaScript helpers, like visual effects, autocompletion, drag and drop
    #   and so on, you should use the method described above.
    # * Use <tt><%= define_javascript_functions %></tt>: this will copy all the
    #   JavaScript support functions within a single script block. Not
    #   recommended.
    #
    # For documentation on +javascript_include_tag+ see
    # ActionView::Helpers::AssetTagHelper.
    module JavaScriptHelper
      unless const_defined? :JAVASCRIPT_PATH
        JAVASCRIPT_PATH = File.join(File.dirname(__FILE__), 'javascripts')
      end

      # Returns a link that'll trigger a JavaScript +function+ using the
      # onclick handler and return false after the fact.
      #
      # Examples:
      #   link_to_function "Greeting", "alert('Hello world!')"
      #   link_to_function(image_tag("delete"), "if confirm('Really?'){ do_delete(); }")
      def link_to_function(name, function, html_options = {})
        html_options.symbolize_keys!
        content_tag(
          "a", name,
          html_options.merge({
            :href => html_options[:href] || "#",
            :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function}; return false;"
          })
        )
      end

      # Returns a link that'll trigger a JavaScript +function+ using the
      # onclick handler.
      #
      # Examples:
      #   button_to_function "Greeting", "alert('Hello world!')"
      #   button_to_function "Delete", "if confirm('Really?'){ do_delete(); }")
      def button_to_function(name, function, html_options = {})
        html_options.symbolize_keys!
        tag(:input, html_options.merge({
          :type => "button", :value => name,
          :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};"
        }))
      end

      # Includes the Action Pack JavaScript libraries inside a single <script>
      # tag. The function first includes prototype.js and then its core extensions,
      # (determined by filenames starting with "prototype").
      # Afterwards, any additional scripts will be included in undefined order.
      #
      # Note: The recommended approach is to copy the contents of
      # lib/action_view/helpers/javascripts/ into your application's
      # public/javascripts/ directory, and use +javascript_include_tag+ to
      # create remote <script> links.
      def define_javascript_functions
        javascript = '<script type="text/javascript">'

        # load prototype.js and its extensions first
        prototype_libs = Dir.glob(File.join(JAVASCRIPT_PATH, 'prototype*')).sort.reverse
        prototype_libs.each do |filename|
          javascript << "\n" << IO.read(filename)
        end

        # load other librairies
        (Dir.glob(File.join(JAVASCRIPT_PATH, '*')) - prototype_libs).each do |filename|
          javascript << "\n" << IO.read(filename)
        end
        javascript << '</script>'
      end

      # Escape carrier returns and single and double quotes for JavaScript segments.
      def escape_javascript(javascript)
        (javascript || '').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }
      end

      # Returns a JavaScript tag with the +content+ inside. Example:
      #   javascript_tag "alert('All is good')" # => <script type="text/javascript">alert('All is good')</script>
      def javascript_tag(content)
        content_tag("script", javascript_cdata_section(content), :type => "text/javascript")
      end

      def javascript_cdata_section(content) #:nodoc:
        "\n//#{cdata_section("\n#{content}\n//")}\n"
      end

    protected
      def options_for_javascript(options)
        '{' + options.map {|k, v| "#{k}:#{v}"}.sort.join(', ') + '}'
      end

      def array_or_string_for_javascript(option)
        js_option = if option.kind_of?(Array)
          "['#{option.join('\',\'')}']"
        elsif !option.nil?
          "'#{option}'"
        end
        js_option
      end
    end

    JavascriptHelper = JavaScriptHelper unless const_defined? :JavascriptHelper
  end
end


text:
class CreateVotes < ActiveRecord::Migration
  def change
    create_table :votes do |t|
      t.integer :story_id

      t.timestamps
    end
  end
end


text:
from PyObjCTools.TestSupport import *
import objc
import os

from AppKit import *

try:
    unicode
except NameError:
    unicode = str

class TestNSWorkspace(TestCase):
    def testInfoForFile(self):
        ws = NSWorkspace.sharedWorkspace()

        # A method with 2 output parameters, this means the result
        # is a tuple with 3 elements (return value, param1, param2)
        res = ws.getInfoForFile_application_type_(b'/'.decode('ascii'), None, None)
        self.assert_(isinstance(res, tuple))
        self.assert_(len(res) == 3)
        self.assert_(res[0] == 1)
        self.assert_(res[1] == b'/System/Library/CoreServices/Finder.app'.decode('ascii'))
        self.assert_(res[2] == b''.decode('ascii'))

    def testConstants(self):
        self.assertEqual(NSWorkspaceLaunchAndPrint, 2)
        self.assertEqual(NSWorkspaceLaunchInhibitingBackgroundOnly, 0x00000080)
        self.assertEqual(NSWorkspaceLaunchWithoutAddingToRecents, 0x00000100)
        self.assertEqual(NSWorkspaceLaunchWithoutActivation, 0x00000200)
        self.assertEqual(NSWorkspaceLaunchAsync, 0x00010000)
        self.assertEqual(NSWorkspaceLaunchAllowingClassicStartup, 0x00020000)
        self.assertEqual(NSWorkspaceLaunchPreferringClassic, 0x00040000)
        self.assertEqual(NSWorkspaceLaunchNewInstance, 0x00080000)
        self.assertEqual(NSWorkspaceLaunchAndHide, 0x00100000)
        self.assertEqual(NSWorkspaceLaunchAndHideOthers, 0x00200000)
        self.assertEqual(NSWorkspaceLaunchDefault, (
                NSWorkspaceLaunchAsync | NSWorkspaceLaunchAllowingClassicStartup))

        self.assertEqual(NSExcludeQuickDrawElementsIconCreationOption, 1 << 1)
        self.assertEqual(NSExclude10_4ElementsIconCreationOption, 1 << 2)

        self.assertIsInstance(NSWorkspaceDidLaunchApplicationNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidMountNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidPerformFileOperationNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidTerminateApplicationNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidUnmountNotification, unicode)
        self.assertIsInstance(NSWorkspaceWillLaunchApplicationNotification, unicode)
        self.assertIsInstance(NSWorkspaceWillPowerOffNotification, unicode)
        self.assertIsInstance(NSWorkspaceWillUnmountNotification, unicode)
        self.assertIsInstance(NSWorkspaceWillSleepNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidWakeNotification, unicode)
        self.assertIsInstance(NSWorkspaceSessionDidBecomeActiveNotification, unicode)
        self.assertIsInstance(NSWorkspaceSessionDidResignActiveNotification, unicode)
        self.assertIsInstance(NSPlainFileType, unicode)
        self.assertIsInstance(NSDirectoryFileType, unicode)
        self.assertIsInstance(NSApplicationFileType, unicode)
        self.assertIsInstance(NSFilesystemFileType, unicode)
        self.assertIsInstance(NSShellCommandFileType, unicode)
        self.assertIsInstance(NSWorkspaceMoveOperation, unicode)
        self.assertIsInstance(NSWorkspaceCopyOperation, unicode)
        self.assertIsInstance(NSWorkspaceLinkOperation, unicode)
        self.assertIsInstance(NSWorkspaceCompressOperation, unicode)
        self.assertIsInstance(NSWorkspaceDecompressOperation, unicode)
        self.assertIsInstance(NSWorkspaceEncryptOperation, unicode)
        self.assertIsInstance(NSWorkspaceDecryptOperation, unicode)
        self.assertIsInstance(NSWorkspaceDestroyOperation, unicode)
        self.assertIsInstance(NSWorkspaceRecycleOperation, unicode)
        self.assertIsInstance(NSWorkspaceDuplicateOperation, unicode)
    @min_os_level('10.6')
    def testConstants10_6(self):
        self.assertIsInstance(NSWorkspaceDesktopImageScalingKey, unicode)
        self.assertIsInstance(NSWorkspaceDesktopImageAllowClippingKey, unicode)
        self.assertIsInstance(NSWorkspaceDesktopImageFillColorKey, unicode)
        self.assertIsInstance(NSWorkspaceApplicationKey, unicode)
        self.assertIsInstance(NSWorkspaceDidHideApplicationNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidUnhideApplicationNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidActivateApplicationNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidDeactivateApplicationNotification, unicode)
        self.assertIsInstance(NSWorkspaceVolumeLocalizedNameKey, unicode)
        self.assertIsInstance(NSWorkspaceVolumeURLKey, unicode)
        self.assertIsInstance(NSWorkspaceVolumeOldLocalizedNameKey, unicode)
        self.assertIsInstance(NSWorkspaceVolumeOldURLKey, unicode)
        self.assertIsInstance(NSWorkspaceDidRenameVolumeNotification, unicode)
        self.assertIsInstance(NSWorkspaceScreensDidSleepNotification, unicode)
        self.assertIsInstance(NSWorkspaceScreensDidWakeNotification, unicode)
        self.assertIsInstance(NSWorkspaceDidChangeFileLabelsNotification, unicode)
        self.assertIsInstance(NSWorkspaceActiveSpaceDidChangeNotification, unicode)
        self.assertIsInstance(NSWorkspaceLaunchConfigurationAppleEvent, unicode)
        self.assertIsInstance(NSWorkspaceLaunchConfigurationArguments, unicode)
        self.assertIsInstance(NSWorkspaceLaunchConfigurationEnvironment, unicode)
        self.assertIsInstance(NSWorkspaceLaunchConfigurationArchitecture, unicode)

    def testMethods(self):
        self.assertResultIsBOOL(NSWorkspace.openFile_)
        self.assertResultIsBOOL(NSWorkspace.openFile_withApplication_)
        self.assertResultIsBOOL(NSWorkspace.openFile_withApplication_andDeactivate_)
        self.assertArgIsBOOL(NSWorkspace.openFile_withApplication_andDeactivate_, 2)
        self.assertResultIsBOOL(NSWorkspace.openTempFile_)
        self.assertResultIsBOOL(NSWorkspace.openFile_fromImage_at_inView_)
        self.assertResultIsBOOL(NSWorkspace.openURL_)
        self.assertResultIsBOOL(NSWorkspace.launchApplication_)
        self.assertResultIsBOOL(NSWorkspace.launchApplication_showIcon_autolaunch_)
        self.assertArgIsBOOL(NSWorkspace.launchApplication_showIcon_autolaunch_, 1)
        self.assertArgIsBOOL(NSWorkspace.launchApplication_showIcon_autolaunch_, 2)
        self.assertResultIsBOOL(NSWorkspace.selectFile_inFileViewerRootedAtPath_)
        self.assertResultIsBOOL(NSWorkspace.fileSystemChanged)
        self.assertResultIsBOOL(NSWorkspace.userDefaultsChanged)
        self.assertResultIsBOOL(NSWorkspace.getInfoForFile_application_type_)
        self.assertArgIsOut(NSWorkspace.getInfoForFile_application_type_, 1)
        self.assertArgIsOut(NSWorkspace.getInfoForFile_application_type_, 2)
        self.assertResultIsBOOL(NSWorkspace.isFilePackageAtPath_)
        self.assertResultIsBOOL(NSWorkspace.setIcon_forFile_options_)
        self.assertResultIsBOOL(NSWorkspace.getFileSystemInfoForPath_isRemovable_isWritable_isUnmountable_description_type_)
        self.assertArgHasType(NSWorkspace.getFileSystemInfoForPath_isRemovable_isWritable_isUnmountable_description_type_, 1, b'o^' + objc._C_NSBOOL)
        self.assertArgHasType(NSWorkspace.getFileSystemInfoForPath_isRemovable_isWritable_isUnmountable_description_type_, 2, b'o^' + objc._C_NSBOOL)
        self.assertArgHasType(NSWorkspace.getFileSystemInfoForPath_isRemovable_isWritable_isUnmountable_description_type_, 3, b'o^' + objc._C_NSBOOL)
        self.assertArgIsOut(NSWorkspace.getFileSystemInfoForPath_isRemovable_isWritable_isUnmountable_description_type_, 4)
        self.assertArgIsOut(NSWorkspace.getFileSystemInfoForPath_isRemovable_isWritable_isUnmountable_description_type_, 5)
        self.assertResultIsBOOL(NSWorkspace.performFileOperation_source_destination_files_tag_)
        self.assertArgIsOut(NSWorkspace.performFileOperation_source_destination_files_tag_, 4)
        self.assertResultIsBOOL(NSWorkspace.unmountAndEjectDeviceAtPath_)
        self.assertResultIsBOOL(NSWorkspace.launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_)
        self.assertArgIsOut(NSWorkspace.launchAppWithBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifier_, 3)
        self.assertResultIsBOOL(NSWorkspace.openURLs_withAppBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifiers_)
        self.assertArgIsOut(NSWorkspace.openURLs_withAppBundleIdentifier_options_additionalEventParamDescriptor_launchIdentifiers_, 4)
        self.assertArgIsOut(NSWorkspace.typeOfFile_error_, 1)
        self.assertResultIsBOOL(NSWorkspace.filenameExtension_isValidForType_)
        self.assertResultIsBOOL(NSWorkspace.type_conformsToType_)

        self.assertResultIsBOOL(NSWorkspace.selectFile_inFileViewerRootedAtPath_)
        self.assertArgHasType(NSWorkspace.slideImage_from_to_, 1, NSPoint.__typestr__)
        self.assertArgHasType(NSWorkspace.slideImage_from_to_, 2, NSPoint.__typestr__)

    @min_os_level('10.6')
    def testMethods10_6(self):
        self.assertArgIsOut(NSWorkspace.launchApplicationAtURL_options_configuration_error_, 3)
        self.assertResultIsBOOL(NSWorkspace.showSearchResultsForQueryString_)

        self.assertArgIsBlock(NSWorkspace.recycleURLs_completionHandler_, 1, b'v@@')
        self.assertArgIsBlock(NSWorkspace.duplicateURLs_completionHandler_, 1, b'v@@')

        self.assertResultIsBOOL(NSWorkspace.unmountAndEjectDeviceAtURL_error_)
        self.assertArgIsOut(NSWorkspace.unmountAndEjectDeviceAtURL_error_, 1)

        self.assertResultIsBOOL(NSWorkspace.setDesktopImageURL_forScreen_options_error_)
        self.assertArgIsOut(NSWorkspace.setDesktopImageURL_forScreen_options_error_, 3)

if __name__ == '__main__':
    main( )


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _TableCell = require('./TableCell');

var _TableCell2 = _interopRequireDefault(_TableCell);

var _ExpandIcon = require('./ExpandIcon');

var _ExpandIcon2 = _interopRequireDefault(_ExpandIcon);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var TableRow = function (_React$Component) {
  (0, _inherits3['default'])(TableRow, _React$Component);

  function TableRow() {
    var _ref;

    var _temp, _this, _ret;

    (0, _classCallCheck3['default'])(this, TableRow);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3['default'])(this, (_ref = TableRow.__proto__ || Object.getPrototypeOf(TableRow)).call.apply(_ref, [this].concat(args))), _this), _this.state = {
      hovered: false,
      height: null
    }, _this.onRowClick = function (event) {
      var _this$props = _this.props,
          record = _this$props.record,
          index = _this$props.index,
          onRowClick = _this$props.onRowClick,
          expandable = _this$props.expandable,
          expandRowByClick = _this$props.expandRowByClick,
          expanded = _this$props.expanded,
          onExpand = _this$props.onExpand;

      if (expandable && expandRowByClick) {
        onExpand(!expanded, record, event, index);
      }
      onRowClick(record, index, event);
    }, _this.onRowDoubleClick = function (event) {
      var _this$props2 = _this.props,
          record = _this$props2.record,
          index = _this$props2.index,
          onRowDoubleClick = _this$props2.onRowDoubleClick;

      onRowDoubleClick(record, index, event);
    }, _this.onMouseEnter = function () {
      var _this$props3 = _this.props,
          onHover = _this$props3.onHover,
          hoverKey = _this$props3.hoverKey;

      onHover(true, hoverKey);
    }, _this.onMouseLeave = function () {
      var _this$props4 = _this.props,
          onHover = _this$props4.onHover,
          hoverKey = _this$props4.hoverKey;

      onHover(false, hoverKey);
    }, _temp), (0, _possibleConstructorReturn3['default'])(_this, _ret);
  }

  (0, _createClass3['default'])(TableRow, [{
    key: 'componentDidMount',
    value: function componentDidMount() {
      var _this2 = this;

      var store = this.props.store;

      this.pushHeight();
      this.pullHeight();
      this.unsubscribe = store.subscribe(function () {
        _this2.setHover();
        _this2.pullHeight();
      });
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      var _props = this.props,
          record = _props.record,
          onDestroy = _props.onDestroy,
          index = _props.index;

      onDestroy(record, index);
      if (this.unsubscribe) {
        this.unsubscribe();
      }
    }
  }, {
    key: 'setHover',
    value: function setHover() {
      var _props2 = this.props,
          store = _props2.store,
          hoverKey = _props2.hoverKey;

      var _store$getState = store.getState(),
          currentHoverKey = _store$getState.currentHoverKey;

      if (currentHoverKey === hoverKey) {
        this.setState({ hovered: true });
      } else if (this.state.hovered === true) {
        this.setState({ hovered: false });
      }
    }
  }, {
    key: 'pullHeight',
    value: function pullHeight() {
      var _props3 = this.props,
          store = _props3.store,
          expandedRow = _props3.expandedRow,
          fixed = _props3.fixed,
          rowKey = _props3.rowKey;

      var _store$getState2 = store.getState(),
          expandedRowsHeight = _store$getState2.expandedRowsHeight;

      if (expandedRow && fixed && expandedRowsHeight[rowKey]) {
        this.setState({ height: expandedRowsHeight[rowKey] });
      }
    }
  }, {
    key: 'pushHeight',
    value: function pushHeight() {
      var _props4 = this.props,
          store = _props4.store,
          expandedRow = _props4.expandedRow,
          fixed = _props4.fixed,
          rowKey = _props4.rowKey;

      if (expandedRow && !fixed) {
        var _store$getState3 = store.getState(),
            expandedRowsHeight = _store$getState3.expandedRowsHeight;

        var height = this.trRef.getBoundingClientRect().height;
        expandedRowsHeight[rowKey] = height;
        store.setState({ expandedRowsHeight: expandedRowsHeight });
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      var _props5 = this.props,
          prefixCls = _props5.prefixCls,
          columns = _props5.columns,
          record = _props5.record,
          visible = _props5.visible,
          index = _props5.index,
          expandIconColumnIndex = _props5.expandIconColumnIndex,
          expandIconAsCell = _props5.expandIconAsCell,
          expanded = _props5.expanded,
          expandRowByClick = _props5.expandRowByClick,
          expandable = _props5.expandable,
          onExpand = _props5.onExpand,
          needIndentSpaced = _props5.needIndentSpaced,
          indent = _props5.indent,
          indentSize = _props5.indentSize;
      var className = this.props.className;

      if (this.state.hovered) {
        className += ' ' + prefixCls + '-hover';
      }

      var cells = [];

      var expandIcon = _react2['default'].createElement(_ExpandIcon2['default'], {
        expandable: expandable,
        prefixCls: prefixCls,
        onExpand: onExpand,
        needIndentSpaced: needIndentSpaced,
        expanded: expanded,
        record: record
      });

      for (var i = 0; i < columns.length; i++) {
        if (expandIconAsCell && i === 0) {
          cells.push(_react2['default'].createElement(
            'td',
            {
              className: prefixCls + '-expand-icon-cell',
              key: 'rc-table-expand-icon-cell'
            },
            expandIcon
          ));
        }
        var isColumnHaveExpandIcon = expandIconAsCell || expandRowByClick ? false : i === expandIconColumnIndex;
        cells.push(_react2['default'].createElement(_TableCell2['default'], {
          prefixCls: prefixCls,
          record: record,
          indentSize: indentSize,
          indent: indent,
          index: index,
          column: columns[i],
          key: columns[i].key,
          expandIcon: isColumnHaveExpandIcon ? expandIcon : null
        }));
      }
      var height = this.props.height || this.state.height;
      var style = { height: height };
      if (!visible) {
        style.display = 'none';
      }

      return _react2['default'].createElement(
        'tr',
        {
          ref: function ref(node) {
            return _this3.trRef = node;
          },
          onClick: this.onRowClick,
          onDoubleClick: this.onRowDoubleClick,
          onMouseEnter: this.onMouseEnter,
          onMouseLeave: this.onMouseLeave,
          className: prefixCls + ' ' + className + ' ' + prefixCls + '-level-' + indent,
          style: style
        },
        cells
      );
    }
  }]);
  return TableRow;
}(_react2['default'].Component);

TableRow.propTypes = {
  onDestroy: _propTypes2['default'].func,
  onRowClick: _propTypes2['default'].func,
  onRowDoubleClick: _propTypes2['default'].func,
  record: _propTypes2['default'].object,
  prefixCls: _propTypes2['default'].string,
  expandIconColumnIndex: _propTypes2['default'].number,
  onHover: _propTypes2['default'].func,
  columns: _propTypes2['default'].array,
  height: _propTypes2['default'].oneOfType([_propTypes2['default'].string, _propTypes2['default'].number]),
  visible: _propTypes2['default'].bool,
  index: _propTypes2['default'].number,
  hoverKey: _propTypes2['default'].any,
  expanded: _propTypes2['default'].bool,
  expandable: _propTypes2['default'].any,
  onExpand: _propTypes2['default'].func,
  needIndentSpaced: _propTypes2['default'].bool,
  className: _propTypes2['default'].string,
  indent: _propTypes2['default'].number,
  indentSize: _propTypes2['default'].number,
  expandIconAsCell: _propTypes2['default'].bool,
  expandRowByClick: _propTypes2['default'].bool,
  store: _propTypes2['default'].object.isRequired,
  expandedRow: _propTypes2['default'].bool,
  fixed: _propTypes2['default'].bool,
  rowKey: _propTypes2['default'].string
};
TableRow.defaultProps = {
  onRowClick: function onRowClick() {},
  onRowDoubleClick: function onRowDoubleClick() {},
  onDestroy: function onDestroy() {},

  expandIconColumnIndex: 0,
  expandRowByClick: false,
  onHover: function onHover() {}
};
exports['default'] = TableRow;
module.exports = exports['default'];


text:
using namespace std::placeholders;

namespace
{
class ErrorHttpRequest : public downloader::HttpRequest
{
public:
  explicit ErrorHttpRequest(std::string const & filePath)
  : HttpRequest(Callback(), Callback()), m_filePath(filePath)
  {
    m_status = downloader::DownloadStatus::Failed;
  }

  virtual std::string const & GetData() const { return m_filePath; }

private:
  std::string m_filePath;
};
}  // anonymous namespace

namespace storage
{
HttpMapFilesDownloader::~HttpMapFilesDownloader()
{
  CHECK_THREAD_CHECKER(m_checker, ());
}

void HttpMapFilesDownloader::Download(QueuedCountry & queuedCountry)
{
  CHECK_THREAD_CHECKER(m_checker, ());

  m_queue.Append(std::move(queuedCountry));

  if (m_queue.Count() != 1)
    return;

  for (auto const subscriber : m_subscribers)
    subscriber->OnStartDownloading();

  Download();
}

void HttpMapFilesDownloader::Download()
{
  CHECK_THREAD_CHECKER(m_checker, ());

  auto const & queuedCountry = m_queue.GetFirstCountry();

  auto const urls = MakeUrlList(queuedCountry.GetRelativeUrl());
  auto const path = queuedCountry.GetFileDownloadPath();
  auto const size = queuedCountry.GetDownloadSize();

  m_request.reset();

  if (IsDownloadingAllowed())
  {
    queuedCountry.OnStartDownloading();

    m_request.reset(downloader::HttpRequest::GetFile(
        urls, path, size,
        std::bind(&HttpMapFilesDownloader::OnMapFileDownloaded, this, queuedCountry, _1),
        std::bind(&HttpMapFilesDownloader::OnMapFileDownloadingProgress, this, queuedCountry, _1)));
  }
  else
  {
    ErrorHttpRequest error(path);
    auto const copy = queuedCountry;
    OnMapFileDownloaded(copy, error);
  }
}

void HttpMapFilesDownloader::Remove(CountryId const & id)
{
  CHECK_THREAD_CHECKER(m_checker, ());

  MapFilesDownloader::Remove(id);

  if (!m_queue.Contains(id))
    return;

  if (m_request && m_queue.GetFirstId() == id)
    m_request.reset();

  m_queue.Remove(id);

  if (m_queue.IsEmpty())
  {
    for (auto const subscriber : m_subscribers)
      subscriber->OnFinishDownloading();
  }
  else if (!m_request)
  {
    Download();
  }
}

void HttpMapFilesDownloader::Clear()
{
  CHECK_THREAD_CHECKER(m_checker, ());

  MapFilesDownloader::Clear();

  auto needNotify = m_request != nullptr;

  m_request.reset();
  m_queue.Clear();

  if (needNotify)
  {
    for (auto const subscriber : m_subscribers)
      subscriber->OnFinishDownloading();
  }
}

QueueInterface const & HttpMapFilesDownloader::GetQueue() const
{
  CHECK_THREAD_CHECKER(m_checker, ());

  if (m_queue.IsEmpty())
    return MapFilesDownloader::GetQueue();

  return m_queue;
}

void HttpMapFilesDownloader::OnMapFileDownloaded(QueuedCountry const & queuedCountry,
                                                 downloader::HttpRequest & request)
{
  CHECK_THREAD_CHECKER(m_checker, ());
  // Because this method is called deferred on original thread,
  // it is possible the country is already removed from queue.
  if (m_queue.IsEmpty() || m_queue.GetFirstId() != queuedCountry.GetCountryId())
    return;

  m_queue.PopFront();

  queuedCountry.OnDownloadFinished(request.GetStatus());

  m_request.reset();

  if (!m_queue.IsEmpty())
  {
    Download();
  }
  else
  {
    for (auto const subscriber : m_subscribers)
      subscriber->OnFinishDownloading();
  }
}

void HttpMapFilesDownloader::OnMapFileDownloadingProgress(QueuedCountry const & queuedCountry,
                                                          downloader::HttpRequest & request)
{
  CHECK_THREAD_CHECKER(m_checker, ());
  // Because of this method calls deferred on original thread,
  // it is possible the country is already removed from queue.
  if (m_queue.IsEmpty() || m_queue.GetFirstId() != queuedCountry.GetCountryId())
    return;

  queuedCountry.OnDownloadProgress(request.GetProgress());
}

std::unique_ptr<MapFilesDownloader> GetDownloader()
{
  return std::make_unique<HttpMapFilesDownloader>();
}
}  // namespace storage


text:
'use strict';

const pkgcloud = require('pkgcloud');
const CloudProviderClient = require('../../data-access-layer/iaas').CloudProviderClient;

describe('iaas', function () {
  describe('CloudProviderClient', function () {
    this.slow(200);

    const createClientSpy = sinon.spy(pkgcloud.storage, 'createClient');

    afterEach(function () {
      createClientSpy.reset();
    });

    describe('#deleteSnapshot', function () {
      it('bubbles up the error if cloudprovider throws error', function () {
        const client = new CloudProviderClient({
          name: 'aws',
          key: 'key',
          keyId: 'keyId',
          region: 'region'
        });
        const errorMessageExpected = 'fake-snap not found';
        const deleteSnapshotStub = sinon.stub(client.blockstorage, 'deleteSnapshot');
        deleteSnapshotStub.withArgs({
          SnapshotId: 'fake-snap'
        }).throws(Error(errorMessageExpected));
        client
          .deleteSnapshot('fake-snap')
          .catch(err => expect(err.message).to.equal(errorMessageExpected));
      });
      it('should throw error for openstack cloudprovider client', function () {
        const client = new CloudProviderClient({
          name: 'os',
          authUrl: 'https://keystone.org:5000/test/v3',
          keystoneAuthVersion: 'v3',
          domainName: 'domain',
          tenantName: 'service-fabrik',
          username: 'user',
          password: 'secret'
        });
        const errorMessageExpected = 'ComputeClient is not supported for openstack';
        client
          .deleteSnapshot('fake-snap')
          .catch(err => err)
          .then(err => {
            expect(err.status).to.equal(501);
            expect(err.message).to.equal(errorMessageExpected);
          });
      });
    });

    describe('#constructor', function () {

      it('should create an aws client instance', function () {
        const client = new CloudProviderClient({
          name: 'aws',
          key: 'key',
          keyId: 'keyId'
        });
        expect(client.provider).to.equal('amazon');
        expect(createClientSpy)
          .to.be.calledWith({
            provider: 'amazon',
            key: 'key',
            keyId: 'keyId'
          });
      });

      it('should create an aws client instance with max_retries', function () {
        const client = new CloudProviderClient({
          name: 'aws',
          key: 'key',
          keyId: 'keyId',
          max_retries: 12
        });
        expect(client.provider).to.equal('amazon');
        expect(createClientSpy)
          .to.be.calledWith({
            provider: 'amazon',
            key: 'key',
            keyId: 'keyId',
            max_retries: 12
          });
      });

      it('should create an openstack client instance', function () {
        const client = new CloudProviderClient({
          name: 'os',
          authUrl: 'https://keystone.org:5000/test/v3',
          keystoneAuthVersion: 'v3',
          domainName: 'domain',
          tenantName: 'service-fabrik',
          username: 'user',
          password: 'secret'
        });
        expect(client.provider).to.equal('openstack');
        expect(createClientSpy)
          .to.be.calledWithMatch({
            provider: 'openstack',
            authUrl: 'https://keystone.org:5000/test',
            keystoneAuthVersion: 'v3',
            domainName: 'domain',
            tenantName: 'service-fabrik',
            username: 'user',
            password: 'secret'
          });
      });
    });
  });
});


text:
ALTER TABLE [dbo].[RUNTIME_LINKING_MIGRATION_RESULTS]
	ADD CONSTRAINT [PK_RT_LinkingMigRslt]
	PRIMARY KEY (Id)


text:
package envelope_sender_test

import (
	"time"

	"github.com/cloudfoundry/sonde-go/events"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"google.golang.org/protobuf/proto"

	"testing"
)

func TestEnvelopeSender(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "EnvelopeSender Suite")
}

func createTestEnvelope(envOrigin string) *events.Envelope {
	return &events.Envelope{
		Origin:     proto.String(envOrigin),
		EventType:  events.Envelope_ValueMetric.Enum(),
		Timestamp:  proto.Int64(time.Now().Unix() * 1000),
		Deployment: proto.String("some-deployment"),
		Job:        proto.String("some-job"),
		Index:      proto.String("some-index"),
		ValueMetric: &events.ValueMetric{
			Name:  proto.String("metric-name"),
			Value: proto.Float64(42),
			Unit:  proto.String("answers"),
		},
	}
}


text:
<!DOCTYPE html>

		<title>three.js webgl - effects - anaglyph</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

three.js - effects - anaglyph. skybox by Paul Debevec


text:
<form action="mailto:you@yourdmainhere.com" method="post" enctype="text/plain" >
FirstName:<input type="text" name="FirstName">
Email:<input type="text" name="Email">
<input type="submit" name="submit" value="Submit">
</form>


text:
require 'jbuilder'

# ApiDef::Response means a response api returned
class ApiDef::Response < ApiDef::Element

  def body(&block)
    if block
      @body = Jbuilder.new(&block).attributes!
    else
      @body
    end
  end
end


text:
/*global define, Backbone */

define([
    'views/bin'
], function (BinView) {
    'use strict';
    var BinsView = Backbone.View.extend({

        tagName: "ul",
        className: "nav nav-pills nav-stacked",

        initialize: function () {
            this.collection.bind('reset', this.render, this);
            this.collection.bind('add', this.renderBin, this);

            this.collection.fetch();
        },

        render: function () {
            this.$el.empty();

            this.collection.each(function (bin) {
                this.renderBin(bin);
            }, this);

            return this;
        },

        renderBin: function (bin) {

            var binView = new BinView({
                model: bin
            });

            /*
             if(bin.get('isActive') === true) {
             binView.select();
             }
             */

            this.$el.append(binView.render().el);

            return this;
        }

    });

    return BinsView;
});


text:
using System.Linq;
using aoc.csharp._2017;
using Xunit;

namespace aoc.csharp.tests._2017
{
    public class Day16Tests
    {
        [Fact]
        public void Answer()
        {
            using var input = Input.Get(2017, 16);
            var (part1, part2) = Day16.GetAnswer(input);

            Assert.Equal("bkgcdefiholnpmja", part1);
            Assert.Equal("knmdfoijcbpghlea", part2);
        }

        [Fact]
        public void Sample()
        {
            var programs = Enumerable.Range(0, 5).ToArray();
            var dance = Day16.Parse("s1,x3/4,pe/b", programs.Length);
            Day16.RunDance(programs, dance);
            var result = Day16.ToString(programs);
            Assert.Equal("baedc", result);
        }
    }
}


text:
import { prop } from 'ramda'

export const getEnv = (env?: string) => env || process.env.NODE_ENV || 'test'

export const getConfig = config => (env?: string) => prop(getEnv(env), config)


text:
<?php

namespace ProxyManager\ProxyGenerator;

use ProxyManager\ProxyGenerator\NullObject\MethodGenerator\NullObjectMethodInterceptor;
use ProxyManager\ProxyGenerator\NullObject\MethodGenerator\Constructor;

use ProxyManager\ProxyGenerator\Util\ProxiedMethodsFilter;
use ReflectionClass;

use Zend\Code\Generator\ClassGenerator;
use Zend\Code\Reflection\MethodReflection;

/**
 * Generator for proxies implementing {@see \ProxyManager\Proxy\NullObjectInterface}
 *
 * {@inheritDoc}
 *
 * @author Vincent Blanchon <blanchon.vincent@gmail.com>
 * @license MIT
 */
class NullObjectGenerator implements ProxyGeneratorInterface
{
    /**
     * {@inheritDoc}
     */
    public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator)
    {
        $interfaces = array('ProxyManager\\Proxy\\NullObjectInterface');

        if ($originalClass->isInterface()) {
            $interfaces[] = $originalClass->getName();
        } else {
            foreach ($originalClass->getInterfaceNames() as $name) {
                $interfaces[] = $name;
            }
        }

        $classGenerator->setImplementedInterfaces($interfaces);

        foreach (ProxiedMethodsFilter::getProxiedMethods($originalClass) as $method) {
            $classGenerator->addMethodFromGenerator(
                NullObjectMethodInterceptor::generateMethod(
                    new MethodReflection($method->getDeclaringClass()->getName(), $method->getName())
                )
            );
        }

        $classGenerator->addMethodFromGenerator(new Constructor($originalClass));
    }
}