text:
"""Accesses the google.cloud.bigquery.datatransfer.v1 DataTransferService API."""

import functools
import pkg_resources
import warnings

from google.oauth2 import service_account
import google.api_core.gapic_v1.client_info
import google.api_core.gapic_v1.config
import google.api_core.gapic_v1.method
import google.api_core.path_template
import google.api_core.gapic_v1.routing_header
import google.api_core.grpc_helpers
import google.api_core.page_iterator
import google.api_core.path_template
import grpc

from google.cloud.bigquery_datatransfer_v1.gapic import data_transfer_service_client_config
from google.cloud.bigquery_datatransfer_v1.gapic import enums
from google.cloud.bigquery_datatransfer_v1.gapic.transports import data_transfer_service_grpc_transport
from google.cloud.bigquery_datatransfer_v1.proto import datatransfer_pb2
from google.cloud.bigquery_datatransfer_v1.proto import datatransfer_pb2_grpc
from google.cloud.bigquery_datatransfer_v1.proto import transfer_pb2
from google.protobuf import empty_pb2
from google.protobuf import field_mask_pb2
from google.protobuf import timestamp_pb2

_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution(
    'google-cloud-bigquery-datatransfer', ).version

class DataTransferServiceClient(object):
    """
    The Google BigQuery Data Transfer Service API enables BigQuery users to
    configure the transfer of their data from other Google Products into BigQuery.
    This service contains methods that are end user exposed. It backs up the
    frontend.
    """

    SERVICE_ADDRESS = 'bigquerydatatransfer.googleapis.com:443'
    """The default address of the service."""

    # The name of the interface for this client. This is the key used to
    # find the method configuration in the client_config dictionary.
    _INTERFACE_NAME = 'google.cloud.bigquery.datatransfer.v1.DataTransferService'

    @classmethod
    def from_service_account_file(cls, filename, *args, **kwargs):
        """Creates an instance of this client using the provided credentials
        file.

        Args:
            filename (str): The path to the service account private key json
                file.
            args: Additional arguments to pass to the constructor.
            kwargs: Additional arguments to pass to the constructor.

        Returns:
            DataTransferServiceClient: The constructed client.
        """
        credentials = service_account.Credentials.from_service_account_file(
            filename)
        kwargs['credentials'] = credentials
        return cls(*args, **kwargs)

    from_service_account_json = from_service_account_file

    @classmethod
    def project_data_source_path(cls, project, data_source):
        """Return a fully-qualified project_data_source string."""
        return google.api_core.path_template.expand(
            'projects/{project}/dataSources/{data_source}',
            project=project,
            data_source=data_source,
        )

    @classmethod
    def project_path(cls, project):
        """Return a fully-qualified project string."""
        return google.api_core.path_template.expand(
            'projects/{project}',
            project=project,
        )

    @classmethod
    def project_transfer_config_path(cls, project, transfer_config):
        """Return a fully-qualified project_transfer_config string."""
        return google.api_core.path_template.expand(
            'projects/{project}/transferConfigs/{transfer_config}',
            project=project,
            transfer_config=transfer_config,
        )

    @classmethod
    def project_run_path(cls, project, transfer_config, run):
        """Return a fully-qualified project_run string."""
        return google.api_core.path_template.expand(
            'projects/{project}/transferConfigs/{transfer_config}/runs/{run}',
            project=project,
            transfer_config=transfer_config,
            run=run,
        )

    def __init__(self,
                 transport=None,
                 channel=None,
                 credentials=None,
                 client_config=None,
                 client_info=None):
        """Constructor.

        Args:
            transport (Union[~.DataTransferServiceGrpcTransport,
                    Callable[[~.Credentials, type], ~.DataTransferServiceGrpcTransport]): A transport
                instance, responsible for actually making the API calls.
                The default transport uses the gRPC protocol.
                This argument may also be a callable which returns a
                transport instance. Callables will be sent the credentials
                as the first argument and the default transport class as
                the second argument.
            channel (grpc.Channel): DEPRECATED. A ``Channel`` instance
                through which to make calls. This argument is mutually exclusive
                with ``credentials``; providing both will raise an exception.
            credentials (google.auth.credentials.Credentials): The
                authorization credentials to attach to requests. These
                credentials identify this application to the service. If none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
                This argument is mutually exclusive with providing a
                transport instance to ``transport``; doing so will raise
                an exception.
            client_config (dict): DEPRECATED. A dictionary of call options for
                each method. If not specified, the default configuration is used.
            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're developing
                your own client library.
        """
        # Raise deprecation warnings for things we want to go away.
        if client_config is not None:
            warnings.warn(
                'The `client_config` argument is deprecated.',
                PendingDeprecationWarning,
                stacklevel=2)
        else:
            client_config = data_transfer_service_client_config.config

        if channel:
            warnings.warn(
                'The `channel` argument is deprecated; use '
                '`transport` instead.',
                PendingDeprecationWarning,
                stacklevel=2)

        # Instantiate the transport.
        # The transport is responsible for handling serialization and
        # deserialization and actually sending data to the service.
        if transport:
            if callable(transport):
                self.transport = transport(
                    credentials=credentials,
                    default_class=data_transfer_service_grpc_transport.
                    DataTransferServiceGrpcTransport,
                )
            else:
                if credentials:
                    raise ValueError(
                        'Received both a transport instance and '
                        'credentials; these are mutually exclusive.')
                self.transport = transport
        else:
            self.transport = data_transfer_service_grpc_transport.DataTransferServiceGrpcTransport(
                address=self.SERVICE_ADDRESS,
                channel=channel,
                credentials=credentials,
            )

        if client_info is None:
            client_info = google.api_core.gapic_v1.client_info.ClientInfo(
                gapic_version=_GAPIC_LIBRARY_VERSION, )
        else:
            client_info.gapic_version = _GAPIC_LIBRARY_VERSION
        self._client_info = client_info

        # Parse out the default settings for retry and timeout for each RPC
        # from the client configuration.
        # (Ordinarily, these are the defaults specified in the `*_config.py`
        # file next to this one.)
        self._method_configs = google.api_core.gapic_v1.config.parse_method_configs(
            client_config['interfaces'][self._INTERFACE_NAME], )

        # Save a dictionary of cached API call functions.
        # These are the actual callables which invoke the proper
        # transport methods, wrapped with `wrap_method` to add retry,
        # timeout, and the like.
        self._inner_api_calls = {}

    # Service calls
    def get_data_source(self,
                        name,
                        retry=google.api_core.gapic_v1.method.DEFAULT,
                        timeout=google.api_core.gapic_v1.method.DEFAULT,
                        metadata=None):
        """
        Retrieves a supported data source and returns its settings,
        which can be used for UI rendering.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> name = client.project_data_source_path('[PROJECT]', '[DATA_SOURCE]')
            >>>
            >>> response = client.get_data_source(name)

        Args:
            name (str): The field will contain name of the resource requested, for example:
                ``projects/{project_id}/dataSources/{data_source_id}``
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.bigquery_datatransfer_v1.types.DataSource` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'get_data_source' not in self._inner_api_calls:
            self._inner_api_calls[
                'get_data_source'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.get_data_source,
                    default_retry=self._method_configs['GetDataSource'].retry,
                    default_timeout=self._method_configs['GetDataSource'].
                    timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.GetDataSourceRequest(name=name, )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('name', name)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls['get_data_source'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def list_data_sources(self,
                          parent,
                          page_size=None,
                          retry=google.api_core.gapic_v1.method.DEFAULT,
                          timeout=google.api_core.gapic_v1.method.DEFAULT,
                          metadata=None):
        """
        Lists supported data sources and returns their settings,
        which can be used for UI rendering.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_data_sources(parent):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_data_sources(parent).pages:
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): The BigQuery project id for which data sources should be returned. Must
                be in the form: ``projects/{project_id}``
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.bigquery_datatransfer_v1.types.DataSource` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'list_data_sources' not in self._inner_api_calls:
            self._inner_api_calls[
                'list_data_sources'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.list_data_sources,
                    default_retry=self._method_configs['ListDataSources'].
                    retry,
                    default_timeout=self._method_configs['ListDataSources'].
                    timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.ListDataSourcesRequest(
            parent=parent,
            page_size=page_size,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('parent', parent)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls['list_data_sources'],
                retry=retry,
                timeout=timeout,
                metadata=metadata),
            request=request,
            items_field='data_sources',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator

    def create_transfer_config(self,
                               parent,
                               transfer_config,
                               authorization_code=None,
                               retry=google.api_core.gapic_v1.method.DEFAULT,
                               timeout=google.api_core.gapic_v1.method.DEFAULT,
                               metadata=None):
        """
        Creates a new data transfer configuration.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>> # TODO: Initialize `transfer_config`:
            >>> transfer_config = {}
            >>>
            >>> response = client.create_transfer_config(parent, transfer_config)

        Args:
            parent (str): The BigQuery project id where the transfer configuration should be
                created. Must be in the format
                /projects/{project\_id}/locations/{location\_id} If specified location
                and location of the destination bigquery dataset do not match - the
                request will fail.
            transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig`
            authorization_code (str): Optional OAuth2 authorization code to use with this transfer
                configuration. This is required if new credentials are needed, as
                indicated by ``CheckValidCreds``. In order to obtain
                authorization\_code, please make a request to
                https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=&redirect\_uri=

                -  client\_id should be OAuth client\_id of BigQuery DTS API for the
                   given data source returned by ListDataSources method.
                -  data\_source\_scopes are the scopes returned by ListDataSources
                   method.
                -  redirect\_uri is an optional parameter. If not specified, then
                   authorization code is posted to the opener of authorization flow
                   window. Otherwise it will be sent to the redirect uri. A special
                   value of urn:ietf:wg:oauth:2.0:oob means that authorization code
                   should be returned in the title bar of the browser, with the page
                   text prompting the user to copy the code and paste it in the
                   application.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'create_transfer_config' not in self._inner_api_calls:
            self._inner_api_calls[
                'create_transfer_config'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.create_transfer_config,
                    default_retry=self._method_configs['CreateTransferConfig'].
                    retry,
                    default_timeout=self.
                    _method_configs['CreateTransferConfig'].timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.CreateTransferConfigRequest(
            parent=parent,
            transfer_config=transfer_config,
            authorization_code=authorization_code,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('parent', parent)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls['create_transfer_config'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def update_transfer_config(self,
                               transfer_config,
                               update_mask,
                               authorization_code=None,
                               retry=google.api_core.gapic_v1.method.DEFAULT,
                               timeout=google.api_core.gapic_v1.method.DEFAULT,
                               metadata=None):
        """
        Updates a data transfer configuration.
        All fields must be set, even if they are not updated.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> # TODO: Initialize `transfer_config`:
            >>> transfer_config = {}
            >>>
            >>> # TODO: Initialize `update_mask`:
            >>> update_mask = {}
            >>>
            >>> response = client.update_transfer_config(transfer_config, update_mask)

        Args:
            transfer_config (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.TransferConfig]): Data transfer configuration to create.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig`
            update_mask (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.FieldMask]): Required list of fields to be updated in this request.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.bigquery_datatransfer_v1.types.FieldMask`
            authorization_code (str): Optional OAuth2 authorization code to use with this transfer
                configuration. If it is provided, the transfer configuration will be
                associated with the authorizing user. In order to obtain
                authorization\_code, please make a request to
                https://www.gstatic.com/bigquerydatatransfer/oauthz/auth?client\_id=&scope=&redirect\_uri=

                -  client\_id should be OAuth client\_id of BigQuery DTS API for the
                   given data source returned by ListDataSources method.
                -  data\_source\_scopes are the scopes returned by ListDataSources
                   method.
                -  redirect\_uri is an optional parameter. If not specified, then
                   authorization code is posted to the opener of authorization flow
                   window. Otherwise it will be sent to the redirect uri. A special
                   value of urn:ietf:wg:oauth:2.0:oob means that authorization code
                   should be returned in the title bar of the browser, with the page
                   text prompting the user to copy the code and paste it in the
                   application.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'update_transfer_config' not in self._inner_api_calls:
            self._inner_api_calls[
                'update_transfer_config'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.update_transfer_config,
                    default_retry=self._method_configs['UpdateTransferConfig'].
                    retry,
                    default_timeout=self.
                    _method_configs['UpdateTransferConfig'].timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.UpdateTransferConfigRequest(
            transfer_config=transfer_config,
            update_mask=update_mask,
            authorization_code=authorization_code,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('transfer_config.name', transfer_config.name)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls['update_transfer_config'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def delete_transfer_config(self,
                               name,
                               retry=google.api_core.gapic_v1.method.DEFAULT,
                               timeout=google.api_core.gapic_v1.method.DEFAULT,
                               metadata=None):
        """
        Deletes a data transfer configuration,
        including any associated transfer runs and logs.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> name = client.project_transfer_config_path('[PROJECT]', '[TRANSFER_CONFIG]')
            >>>
            >>> client.delete_transfer_config(name)

        Args:
            name (str): The field will contain name of the resource requested, for example:
                ``projects/{project_id}/transferConfigs/{config_id}``
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'delete_transfer_config' not in self._inner_api_calls:
            self._inner_api_calls[
                'delete_transfer_config'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.delete_transfer_config,
                    default_retry=self._method_configs['DeleteTransferConfig'].
                    retry,
                    default_timeout=self.
                    _method_configs['DeleteTransferConfig'].timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.DeleteTransferConfigRequest(name=name, )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('name', name)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        self._inner_api_calls['delete_transfer_config'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def get_transfer_config(self,
                            name,
                            retry=google.api_core.gapic_v1.method.DEFAULT,
                            timeout=google.api_core.gapic_v1.method.DEFAULT,
                            metadata=None):
        """
        Returns information about a data transfer config.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> name = client.project_transfer_config_path('[PROJECT]', '[TRANSFER_CONFIG]')
            >>>
            >>> response = client.get_transfer_config(name)

        Args:
            name (str): The field will contain name of the resource requested, for example:
                ``projects/{project_id}/transferConfigs/{config_id}``
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'get_transfer_config' not in self._inner_api_calls:
            self._inner_api_calls[
                'get_transfer_config'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.get_transfer_config,
                    default_retry=self._method_configs['GetTransferConfig'].
                    retry,
                    default_timeout=self._method_configs['GetTransferConfig'].
                    timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.GetTransferConfigRequest(name=name, )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('name', name)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls['get_transfer_config'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def list_transfer_configs(self,
                              parent,
                              data_source_ids=None,
                              page_size=None,
                              retry=google.api_core.gapic_v1.method.DEFAULT,
                              timeout=google.api_core.gapic_v1.method.DEFAULT,
                              metadata=None):
        """
        Returns information about all data transfers in the project.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> parent = client.project_path('[PROJECT]')
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_transfer_configs(parent):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_transfer_configs(parent).pages:
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): The BigQuery project id for which data sources should be returned:
                ``projects/{project_id}``.
            data_source_ids (list[str]): When specified, only configurations of requested data sources are returned.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferConfig` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'list_transfer_configs' not in self._inner_api_calls:
            self._inner_api_calls[
                'list_transfer_configs'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.list_transfer_configs,
                    default_retry=self._method_configs['ListTransferConfigs'].
                    retry,
                    default_timeout=self.
                    _method_configs['ListTransferConfigs'].timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.ListTransferConfigsRequest(
            parent=parent,
            data_source_ids=data_source_ids,
            page_size=page_size,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('parent', parent)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls['list_transfer_configs'],
                retry=retry,
                timeout=timeout,
                metadata=metadata),
            request=request,
            items_field='transfer_configs',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator

    def schedule_transfer_runs(self,
                               parent,
                               start_time,
                               end_time,
                               retry=google.api_core.gapic_v1.method.DEFAULT,
                               timeout=google.api_core.gapic_v1.method.DEFAULT,
                               metadata=None):
        """
        Creates transfer runs for a time range [start\_time, end\_time]. For
        each date - or whatever granularity the data source supports - in the
        range, one transfer run is created. Note that runs are created per UTC
        time in the time range.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> parent = client.project_transfer_config_path('[PROJECT]', '[TRANSFER_CONFIG]')
            >>>
            >>> # TODO: Initialize `start_time`:
            >>> start_time = {}
            >>>
            >>> # TODO: Initialize `end_time`:
            >>> end_time = {}
            >>>
            >>> response = client.schedule_transfer_runs(parent, start_time, end_time)

        Args:
            parent (str): Transfer configuration name in the form:
                ``projects/{project_id}/transferConfigs/{config_id}``.
            start_time (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.Timestamp]): Start time of the range of transfer runs. For example,
                ``"2017-05-25T00:00:00+00:00"``.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.bigquery_datatransfer_v1.types.Timestamp`
            end_time (Union[dict, ~google.cloud.bigquery_datatransfer_v1.types.Timestamp]): End time of the range of transfer runs. For example,
                ``"2017-05-30T00:00:00+00:00"``.

                If a dict is provided, it must be of the same form as the protobuf
                message :class:`~google.cloud.bigquery_datatransfer_v1.types.Timestamp`
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.bigquery_datatransfer_v1.types.ScheduleTransferRunsResponse` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'schedule_transfer_runs' not in self._inner_api_calls:
            self._inner_api_calls[
                'schedule_transfer_runs'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.schedule_transfer_runs,
                    default_retry=self._method_configs['ScheduleTransferRuns'].
                    retry,
                    default_timeout=self.
                    _method_configs['ScheduleTransferRuns'].timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.ScheduleTransferRunsRequest(
            parent=parent,
            start_time=start_time,
            end_time=end_time,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('parent', parent)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls['schedule_transfer_runs'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def get_transfer_run(self,
                         name,
                         retry=google.api_core.gapic_v1.method.DEFAULT,
                         timeout=google.api_core.gapic_v1.method.DEFAULT,
                         metadata=None):
        """
        Returns information about the particular transfer run.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> name = client.project_run_path('[PROJECT]', '[TRANSFER_CONFIG]', '[RUN]')
            >>>
            >>> response = client.get_transfer_run(name)

        Args:
            name (str): The field will contain name of the resource requested, for example:
                ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}``
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferRun` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'get_transfer_run' not in self._inner_api_calls:
            self._inner_api_calls[
                'get_transfer_run'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.get_transfer_run,
                    default_retry=self._method_configs['GetTransferRun'].retry,
                    default_timeout=self._method_configs['GetTransferRun'].
                    timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.GetTransferRunRequest(name=name, )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('name', name)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls['get_transfer_run'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def delete_transfer_run(self,
                            name,
                            retry=google.api_core.gapic_v1.method.DEFAULT,
                            timeout=google.api_core.gapic_v1.method.DEFAULT,
                            metadata=None):
        """
        Deletes the specified transfer run.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> name = client.project_run_path('[PROJECT]', '[TRANSFER_CONFIG]', '[RUN]')
            >>>
            >>> client.delete_transfer_run(name)

        Args:
            name (str): The field will contain name of the resource requested, for example:
                ``projects/{project_id}/transferConfigs/{config_id}/runs/{run_id}``
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'delete_transfer_run' not in self._inner_api_calls:
            self._inner_api_calls[
                'delete_transfer_run'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.delete_transfer_run,
                    default_retry=self._method_configs['DeleteTransferRun'].
                    retry,
                    default_timeout=self._method_configs['DeleteTransferRun'].
                    timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.DeleteTransferRunRequest(name=name, )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('name', name)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        self._inner_api_calls['delete_transfer_run'](
            request, retry=retry, timeout=timeout, metadata=metadata)

    def list_transfer_runs(self,
                           parent,
                           states=None,
                           page_size=None,
                           run_attempt=None,
                           retry=google.api_core.gapic_v1.method.DEFAULT,
                           timeout=google.api_core.gapic_v1.method.DEFAULT,
                           metadata=None):
        """
        Returns information about running and completed jobs.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> parent = client.project_transfer_config_path('[PROJECT]', '[TRANSFER_CONFIG]')
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_transfer_runs(parent):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_transfer_runs(parent).pages:
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): Name of transfer configuration for which transfer runs should be
                retrieved. Format of transfer configuration resource name is:
                ``projects/{project_id}/transferConfigs/{config_id}``.
            states (list[~google.cloud.bigquery_datatransfer_v1.types.TransferState]): When specified, only transfer runs with requested states are returned.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            run_attempt (~google.cloud.bigquery_datatransfer_v1.types.RunAttempt): Indicates how run attempts are to be pulled.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferRun` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'list_transfer_runs' not in self._inner_api_calls:
            self._inner_api_calls[
                'list_transfer_runs'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.list_transfer_runs,
                    default_retry=self._method_configs['ListTransferRuns'].
                    retry,
                    default_timeout=self._method_configs['ListTransferRuns'].
                    timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.ListTransferRunsRequest(
            parent=parent,
            states=states,
            page_size=page_size,
            run_attempt=run_attempt,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('parent', parent)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls['list_transfer_runs'],
                retry=retry,
                timeout=timeout,
                metadata=metadata),
            request=request,
            items_field='transfer_runs',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator

    def list_transfer_logs(self,
                           parent,
                           page_size=None,
                           message_types=None,
                           retry=google.api_core.gapic_v1.method.DEFAULT,
                           timeout=google.api_core.gapic_v1.method.DEFAULT,
                           metadata=None):
        """
        Returns user facing log messages for the data transfer run.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> parent = client.project_run_path('[PROJECT]', '[TRANSFER_CONFIG]', '[RUN]')
            >>>
            >>> # Iterate over all results
            >>> for element in client.list_transfer_logs(parent):
            ...     # process element
            ...     pass
            >>>
            >>>
            >>> # Alternatively:
            >>>
            >>> # Iterate over results one page at a time
            >>> for page in client.list_transfer_logs(parent).pages:
            ...     for element in page:
            ...         # process element
            ...         pass

        Args:
            parent (str): Transfer run name in the form:
                ``projects/{project_id}/transferConfigs/{config_Id}/runs/{run_id}``.
            page_size (int): The maximum number of resources contained in the
                underlying API response. If page streaming is performed per-
                resource, this parameter does not affect the return value. If page
                streaming is performed per-page, this determines the maximum number
                of resources in a page.
            message_types (list[~google.cloud.bigquery_datatransfer_v1.types.MessageSeverity]): Message types to return. If not populated - INFO, WARNING and ERROR
                messages are returned.
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.gax.PageIterator` instance. By default, this
            is an iterable of :class:`~google.cloud.bigquery_datatransfer_v1.types.TransferMessage` instances.
            This object can also be configured to iterate over the pages
            of the response through the `options` parameter.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'list_transfer_logs' not in self._inner_api_calls:
            self._inner_api_calls[
                'list_transfer_logs'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.list_transfer_logs,
                    default_retry=self._method_configs['ListTransferLogs'].
                    retry,
                    default_timeout=self._method_configs['ListTransferLogs'].
                    timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.ListTransferLogsRequest(
            parent=parent,
            page_size=page_size,
            message_types=message_types,
        )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('parent', parent)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        iterator = google.api_core.page_iterator.GRPCIterator(
            client=None,
            method=functools.partial(
                self._inner_api_calls['list_transfer_logs'],
                retry=retry,
                timeout=timeout,
                metadata=metadata),
            request=request,
            items_field='transfer_messages',
            request_token_field='page_token',
            response_token_field='next_page_token',
        )
        return iterator

    def check_valid_creds(self,
                          name,
                          retry=google.api_core.gapic_v1.method.DEFAULT,
                          timeout=google.api_core.gapic_v1.method.DEFAULT,
                          metadata=None):
        """
        Returns true if valid credentials exist for the given data source and
        requesting user.
        Some data sources doesn't support service account, so we need to talk to
        them on behalf of the end user. This API just checks whether we have OAuth
        token for the particular user, which is a pre-requisite before user can
        create a transfer config.

        Example:
            >>> from google.cloud import bigquery_datatransfer_v1
            >>>
            >>> client = bigquery_datatransfer_v1.DataTransferServiceClient()
            >>>
            >>> name = client.project_data_source_path('[PROJECT]', '[DATA_SOURCE]')
            >>>
            >>> response = client.check_valid_creds(name)

        Args:
            name (str): The data source in the form:
                ``projects/{project_id}/dataSources/{data_source_id}``
            retry (Optional[google.api_core.retry.Retry]):  A retry object used
                to retry requests. If ``None`` is specified, requests will not
                be retried.
            timeout (Optional[float]): The amount of time, in seconds, to wait
                for the request to complete. Note that if ``retry`` is
                specified, the timeout applies to each individual attempt.
            metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
                that is provided to the method.

        Returns:
            A :class:`~google.cloud.bigquery_datatransfer_v1.types.CheckValidCredsResponse` instance.

        Raises:
            google.api_core.exceptions.GoogleAPICallError: If the request
                    failed for any reason.
            google.api_core.exceptions.RetryError: If the request failed due
                    to a retryable error and retry attempts failed.
            ValueError: If the parameters are invalid.
        """
        # Wrap the transport method to add retry and timeout logic.
        if 'check_valid_creds' not in self._inner_api_calls:
            self._inner_api_calls[
                'check_valid_creds'] = google.api_core.gapic_v1.method.wrap_method(
                    self.transport.check_valid_creds,
                    default_retry=self._method_configs['CheckValidCreds'].
                    retry,
                    default_timeout=self._method_configs['CheckValidCreds'].
                    timeout,
                    client_info=self._client_info,
                )

        request = datatransfer_pb2.CheckValidCredsRequest(name=name, )
        if metadata is None:
            metadata = []
        metadata = list(metadata)
        try:
            routing_header = [('name', name)]
        except AttributeError:
            pass
        else:
            routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata(
                routing_header)
            metadata.append(routing_metadata)

        return self._inner_api_calls['check_valid_creds'](
            request, retry=retry, timeout=timeout, metadata=metadata)


text:
extern void* cfl_type_malloc(size_t size);
extern unsigned int cfl_type_get_next_id(void);

unsigned int cfl_generate_global_hypotheses(
        cfl_type_equations* equations,
        cfl_type_hypothesis_chain* hypothesis_head)
{
    cfl_type_hypothesis_chain* hypothesis =
            cfl_type_malloc(sizeof(cfl_type_hypothesis_chain));

    if(!hypothesis)
        return 0;

    unsigned int id = cfl_type_get_next_id();

    hypothesis->name = "random";
    hypothesis->id = id;
    hypothesis->next = hypothesis_head->next;

    hypothesis_head->next = hypothesis;

    cfl_type* integer_left = cfl_type_malloc(sizeof(cfl_type));

    if(!integer_left)
        return 0;

    cfl_create_type_integer(integer_left);

    cfl_type* integer_right = cfl_type_malloc(sizeof(cfl_type));

    if(!integer_right)
    {
        cfl_free_type(integer_left);

        return 0;
    }

    cfl_create_type_integer(integer_right);

    cfl_type* arrow = cfl_type_malloc(sizeof(cfl_type));

    if(!arrow)
    {
        cfl_free_type(integer_left);
        cfl_free_type(integer_right);

        return 0;
    }

    cfl_create_type_arrow(arrow, integer_left, integer_right);

    cfl_type* variable = cfl_type_malloc(sizeof(cfl_type));

    if(!variable)
    {
        cfl_free_type(arrow);

        return 0;
    }

    cfl_create_type_variable(variable, id);

    if(!cfl_add_type_equations(equations, variable, arrow))
    {
        cfl_free_type(arrow);
        cfl_free_type(variable);

        return 0;
    }

    return 1;
}

static cfl_type* cfl_run_hidden_typecheck(
        cfl_type_equations* equations,
        cfl_type_hypothesis_chain* hypothesis_head,
        char* name,
        cfl_node* node)
{
    cfl_type_equations* equations_copy = cfl_copy_type_equations(equations);

    if(!equations_copy)
        return 0;

    cfl_type* result = cfl_generate_type_equation_chain(equations_copy,
                                                        hypothesis_head,
                                                        node);

    if(!result)
    {
        cfl_delete_type_equations(equations_copy);
        free(equations_copy);

        return 0;
    }

    if(!cfl_close_type_equations(equations_copy))
    {
        cfl_delete_type_equations(equations_copy);
        free(equations_copy);
        cfl_free_type(result);

        return 0;
    }

    if(!cfl_are_type_equations_consistent(equations_copy))
    {
        cfl_type_error_bad_definition(name);

        cfl_delete_type_equations(equations_copy);
        free(equations_copy);
        cfl_free_type(result);

        return 0;
    }

    if(!cfl_simplify_type(equations_copy, result))
    {
        cfl_delete_type_equations(equations_copy);
        free(equations_copy);
        cfl_free_type(result);

        return 0;
    }

    cfl_delete_type_equations(equations_copy);
    free(equations_copy);

    return result;
}

unsigned int cfl_setup_definitions(
        cfl_type_equations* equations,
        cfl_type_hypothesis_chain* hypothesis_head,
        cfl_definition_list* definitions)
{
    unsigned int hypothesis_count = cfl_generate_global_hypotheses(equations,
                                                                   hypothesis_head);

    if(!hypothesis_count)
        return 0;

    cfl_definition_list* pos = definitions;

    while(pos)
    {
        pos->type = cfl_run_hidden_typecheck(equations,
                                             hypothesis_head,
                                             pos->name->data,
                                             pos->definition);

        if(!pos->type)
        {
            cfl_remove_n_hypotheses(hypothesis_head, hypothesis_count);

            return 0;
        }

        cfl_type_hypothesis_chain* hypothesis =
                cfl_type_malloc(sizeof(cfl_type_hypothesis_chain));

        if(!hypothesis)
        {
            cfl_remove_n_hypotheses(hypothesis_head, hypothesis_count);

            return 0;
        }

        unsigned int id = cfl_type_get_next_id();

        hypothesis->name = pos->name->data;
        hypothesis->id = id;
        hypothesis->next = hypothesis_head->next;

        hypothesis_head->next = hypothesis;

        ++hypothesis_count;

        cfl_type* result = cfl_type_malloc(sizeof(cfl_type));

        if(!result)
        {
            cfl_remove_n_hypotheses(hypothesis_head, hypothesis_count);

            return 0;
        }

        if(!cfl_copy_type(result, pos->type))
        {
            cfl_remove_n_hypotheses(hypothesis_head, hypothesis_count);
            free(result);

            return 0;
        }

        cfl_type* variable = cfl_type_malloc(sizeof(cfl_type));

        if(!variable)
        {
            cfl_remove_n_hypotheses(hypothesis_head, hypothesis_count);
            free(result);

            return 0;
        }

        cfl_create_type_variable(variable, id);

        if(!cfl_add_type_equations(equations, result, variable))
        {
            cfl_free_type(result);
            cfl_free_type(variable);

            return 0;
        }

        pos = pos->next;
    }

    return hypothesis_count;
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

<title>WebRTC Test</title>

WebRTC

You must have a WebRTC capable browser in order to make calls using this test
page.

 Local Preview
 Remote Video

  <video width="320" height="240" id="localView" autoplay="autoplay"></video>

  <video width="640" height="480" id="remoteView" autoplay="autoplay"></video>

   Server:

    <input type="text" id="server" size="30" value="http://localhost:8888"/>

   Name:	<input type="text" id="local" size="30" value="name"/>

  <button id="connect" onclick="connect();">Connect</button>

  <button id="disconnect" onclick="disconnect();" disabled="true">Disconnect
  </button>

  Connected peers:

  <select id="peers" size="5" disabled="true">
   <option value="-1">Not connected</option>
  </select>

  <button id="call" onclick="doCall();" disabled="true">Call</button>

  <button id="hangup" onclick="hangUp();" disabled="true">Hang up</button>

  <button onclick="toggleExtraButtons();">Toggle extra buttons (debug)</button>

  <button id="createPcBtn" onclick="createPeerConnection();" hidden="true">
  Create peer connection</button>

<button onclick="document.getElementById('debug').innerHTML='';">Clear log
</button>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
	<modelVersion>4.0.0</modelVersion>
	<groupId>JazzOMR</groupId>
	<artifactId>JazzOMR.core</artifactId>
	<packaging>jar</packaging>
	<name>Core - Classes Comuns</name>
	<parent>
		<groupId>JazzOMR</groupId>
		<artifactId>JazzOMR</artifactId>
		<version>1.0</version>
	</parent>

	<dependencies>

        <dependency>
            <groupId>javax.ejb</groupId>
            <artifactId>ejb-api</artifactId>
            <version>3.0</version>
           	<scope>provided</scope>
        </dependency>

		<!--
		<dependency>
			<groupId>javax.ejb</groupId>
			<artifactId>ejb</artifactId>
			<version>3.0</version>
			<scope>provided</scope>
		</dependency>
		 -->

		<dependency>
		    <groupId>com.google.code.gson</groupId>
		    <artifactId>gson</artifactId>
		    <version>1.7.1</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>imagej</groupId>
			<artifactId>ij</artifactId>
			<version>1.43</version>
		</dependency>

		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>5.14.6</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>3.0.5.RELEASE</version>
			<scope>test</scope>
		</dependency>

		<dependency>
		  <groupId>mysql</groupId>
		  <artifactId>mysql-connector-java</artifactId>
		  <version>5.1.18</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-clean-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<excludeDefaultDirectories>true</excludeDefaultDirectories>
					<filesets>
						<fileset>
							<directory>${project.build.directory}</directory>
							<excludes>
								<exclude>generated-resources/eclipse/**</exclude>
							</excludes>
						</fileset>
					</filesets>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
<?php

/*
 * GENERATED CODE WARNING
 * This file was automatically generated - do not edit!
 */

require_once __DIR__ . '/../../../vendor/autoload.php';

// [START lro_generated_BasicLro_Method1_sync]
use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Rpc\Status;
use Testing\BasicLro\BasicLroClient;
use Testing\BasicLro\LroResponse;

/**
 * To test method ordering; LRO methods referenced in gapic.yaml
 * file are always generated first; so this method will be emitted
 * before the above MethodNonLro1.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function method1_sample(): void
{
    // Create a client.
    $basicLroClient = new BasicLroClient();

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $basicLroClient->method1();
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var LroResponse $response */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}
// [END lro_generated_BasicLro_Method1_sync]


text:
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var pony = require('pony');
var ent = require('ent');

module.exports = function (opts) {
    if (typeof opts === 'string') {
        opts = { uri : opts };
    }

    var send = pony({
        host : opts.host || 'localhost',
        domain : opts.domain || opts.host || 'localhost',
        port : opts.port || 25,
        from : opts.from || 'password-robot@localhost',
    });

    var reset = new Forgot(opts);

    var self = function (email, cb) {
        var session = reset.generate();
        if (!session) return;

        var uri = session.uri = opts.uri + '?' + session.id;

        send({ to : email }, function (err, req) {
            if (err) {
                if (cb) cb(err);
                delete reset.sessions[session.id];
            }
            else {
                req.url = req.uri = uri;
                req.setHeader('content-type', 'text/html');
                req.setHeader(
                    'subject',
                    opts.subject || 'password reset confirmation'
                );
                if (cb) cb(null, req)
                if (cb && cb.length <= 1) {
                    req.end([
                        'Click this link to reset your password:\r\n',
                        '
',
                        '',
                        ent.encode(uri),
                        '',
                        ''
                    ].join('\r\n'));
                }
            }
        });

        return session;
    };

    self.middleware = reset.middleware.bind(reset);

    self.expire = function (id) {
        delete reset.sessions[id];
    };

    return self;
};

function Forgot (opts) {
    this.sessions = opts.sessions || {};
    this.mount = url.parse(opts.uri);
    this.mount.port = this.mount.port || 80;
}

Forgot.prototype.generate = function () {
    var buf = new Buffer(16);
    for (var i = 0; i < buf.length; i++) {
        buf[i] = Math.floor(Math.random() * 256);
    }
    var id = buf.toString('base64');

    var session = this.sessions[id] = new EventEmitter;
    session.id = id;
    return session;
};

Forgot.prototype.middleware = function (req, res, next) {
    if (!next) next = function (err) {
        if (err) res.end(err)
    }

    var u = url.parse('http://' + req.headers.host + req.url);
    u.port = u.port || 80;
    var id = u.query;

    if (u.hostname !== this.mount.hostname
    || parseInt(u.port, 10) !== parseInt(this.mount.port, 10)
    || u.pathname !== this.mount.pathname) {
        next()
    }
    else if (!id) {
        res.statusCode = 400;
        next('No auth token specified.');
    }
    else if (!this.sessions[id]) {
        res.statusCode = 410;
        next('auth token expired');
    }
    else {
        this.sessions[id].emit('request', req, res);
    }
};


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class NoDisksToCustomize extends CustomizationFault {
}


text:
Rails.application.routes.draw do
  root to: "simple_pages#main_page"

  devise_for :users, path_names: {sign_in: "log_in"}

  resources :senders, except: [:index, :show, :edit, :update]

  resources :receivers, except: [:edit, :update] do
    delete "remove_all", on: :collection
    get "download", on: :member
  end
end


text:
var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/course', function(err, db) {
    if(err) throw err;

    var query = { 'media.oembed.type' : 'video' };

    var projection = { 'media.oembed.url' : 1, '_id' : 0 };

    db.collection('reddit_front').find(query, projection).each(function(err, doc) {
        if(err) throw err;

        if(doc == null) {
            return db.close();
        }

        console.dir(doc);
    });
});


text:
handy-tools
===========

This project is no longer hosted here. The new location is: https://bitbucket.org/miguelfc/handy-tools

Sorry for the inconvenience.

MiguelFC


text:
package backend.distributor

import akka.actor._
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods.GET
import akka.http.scaladsl.model.StatusCodes.{NotFound, BadRequest}
import akka.http.scaladsl.model.ws.UpgradeToWebsocket
import akka.http.scaladsl.model._
import akka.stream._
import backend.shared.CodecStage
import com.typesafe.scalalogging.StrictLogging

import scala.language.postfixOps
import scala.util.{Failure, Success}

object Distributor {
  def start()(implicit sys: ActorSystem) = sys.actorOf(Props[Distributor], "distributor")
}

/**
  * Distributor component accepts websocket connections and integrates with Pricer component.
  */
private class Distributor extends Actor with StrictLogging {

  implicit val system = context.system
  implicit val executor = context.dispatcher

  var connectionCounter = 0

  // supervision strategy for all websocket handler streams
  val decider: Supervision.Decider = {
    case x => // If anything goes wrong, we terminate the stream and the connection
      logger.error("Stream terminated", x)
      Supervision.Stop
  }

  // Materializer turns stream spec into a runnable entity
  implicit val mat = ActorMaterializer(
    ActorMaterializerSettings(context.system)
      .withDebugLogging(enable = false)
      .withSupervisionStrategy(decider))

  val requestHandler: HttpRequest => HttpResponse = {

    // Handler for /
    case req@HttpRequest(GET, Uri.Path("/"), _, _, _) =>
      req.header[UpgradeToWebsocket] match {
        case Some(upgrade) =>
          connectionCounter += 1
          // initialise a stream...
          upgrade.handleMessages(buildFlow(connectionCounter))
        case None =>
          // not a websocket request
          HttpResponse(BadRequest, entity = "Not a valid websocket request!")
      }
    case _: HttpRequest => HttpResponse(NotFound, entity = "Unknown resource!")
  }

  // Initalise the listener and setup the handler
  val port = context.system.settings.config.getInt("distributor.port")
  val host = context.system.settings.config.getString("distributor.host")
  Http().bindAndHandleSync(handler = requestHandler, interface = host, port = port) onComplete {
    case Success(binding) => self ! SuccessfulBinding(binding)
    case Failure(x) => self ! BindingFailed(x)
  }

  // Flow spec
  def buildFlow(connectionId: Int) =
    WebsocketFrameStage() atop
      CodecStage() atop
      MetricsStage(connectionId) atop
      ShapingStage(1000) join // messages per second
      DistributorEndpointStage(connectionId, StreamRegistry.selection)

  private case class SuccessfulBinding(binding: Http.ServerBinding)

  private case class BindingFailed(x: Throwable)

  override def receive: Receive = {
    case SuccessfulBinding(binding) =>
      logger.info(s"Websocket server listening at $host:$port")
    case BindingFailed(x) =>
      // Here we just logging the result of the binding. Normally you may want to retry or terminate the process
      logger.error(s"Websocket server failed to bind to $host:$port", x)
  }

}


text:
/**
 * WebSocket Server Settings
 * (sails.config.sockets)
 *
 * These settings provide transparent access to the options for Sails'
 * encapsulated WebSocket server, as well as some additional Sails-specific
 * configuration layered on top.
 *
 * For more information on sockets configuration, including advanced config options, see:
 * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.sockets.html
 */
module.exports.sockets = {
  /***************************************************************************
   *                                                                          *
   * Node.js (and consequently Sails.js) apps scale horizontally. It's a      *
   * powerful, efficient approach, but it involves a tiny bit of planning. At *
   * scale, you'll want to be able to copy your app onto multiple Sails.js    *
   * servers and throw them behind a load balancer.                           *
   *                                                                          *
   * One of the big challenges of scaling an application is that these sorts  *
   * of clustered deployments cannot share memory, since they are on          *
   * physically different machines. On top of that, there is no guarantee     *
   * that a user will "stick" with the same server between requests (whether  *
   * HTTP or sockets), since the load balancer will route each request to the *
   * Sails server with the most available resources. However that means that  *
   * all room/pubsub/socket processing and shared memory has to be offloaded  *
   * to a shared, remote messaging queue (usually Redis)                      *
   *                                                                          *
   * Luckily, Socket.io (and consequently Sails.js) apps support Redis for    *
   * sockets by default. To enable a remote redis pubsub server, uncomment    *
   * the config below.                                                        *
   *                                                                          *
   * Worth mentioning is that, if `adapter` config is `redis`, but host/port  *
   * is left unset, Sails will try to connect to redis running on localhost   *
   * via port 6379                                                            *
   *                                                                          *
   ***************************************************************************/
  adapter: 'memory',

  //
  // -OR-
  //

  // adapter: 'redis',
  // host: '127.0.0.1',
  // port: 6379,
  // db: 'sails',
  // pass: '<redis auth password>'

  /***************************************************************************
   *                                                                          *
   * Whether to expose a 'get /__getcookie' route with CORS support that sets *
   * a cookie (this is used by the sails.io.js socket client to get access to *
   * a 3rd party cookie and to enable sessions).                              *
   *                                                                          *
   * Warning: Currently in this scenario, CORS settings apply to interpreted  *
   * requests sent via a socket.io connection that used this cookie to        *
   * connect, even for non-browser clients! (e.g. iOS apps, toasters, node.js *
   * unit tests)                                                              *
   *                                                                          *
   ***************************************************************************/
  grant3rdPartyCookie: true,

  /***************************************************************************
   *                                                                          *
   * `beforeConnect`                                                          *
   *                                                                          *
   * This custom beforeConnect function will be run each time BEFORE a new    *
   * socket is allowed to connect, when the initial socket.io handshake is    *
   * performed with the server.                                               *
   *                                                                          *
   * By default, when a socket tries to connect, Sails allows it, every time. *
   * (much in the same way any HTTP request is allowed to reach your routes.  *
   * If no valid cookie was sent, a temporary session will be created for the *
   * connecting socket.                                                       *
   *                                                                          *
   * If the cookie sent as part of the connetion request doesn't match any    *
   * known user session, a new user session is created for it.                *
   *                                                                          *
   * In most cases, the user would already have a cookie since they loaded    *
   * the socket.io client and the initial HTML pageyou're building.           *
   *                                                                          *
   * However, in the case of cross-domain requests, it is possible to receive *
   * a connection upgrade request WITHOUT A COOKIE (for certain transports)   *
   * In this case, there is no way to keep track of the requesting user       *
   * between requests, since there is no identifying information to link      *
   * him/her with a session. The sails.io.js client solves this by connecting *
   * to a CORS/jsonp endpoint first to get a 3rd party cookie(fortunately this*
   * works, even in Safari), then opening the connection.                     *
   *                                                                          *
   * You can also pass along a ?cookie query parameter to the upgrade url,    *
   * which Sails will use in the absense of a proper cookie e.g. (when        *
   * connecting from the client):                                             *
   * io.sails.connect('http://localhost:1337?cookie=smokeybear')              *
   *                                                                          *
   * Finally note that the user's cookie is NOT (and will never be) accessible*
   * from client-side javascript. Using HTTP-only cookies is crucial for your *
   * app's security.                                                          *
   *                                                                          *
   ***************************************************************************/
  // beforeConnect: function(handshake, cb) {
  //   // `true` allows the connection
  //   return cb(null, true);
  //
  //   // (`false` would reject the connection)
  // },

  /***************************************************************************
   *                                                                          *
   * This custom afterDisconnect function will be run each time a socket         *
   * disconnects                                                              *
   *                                                                          *
   ***************************************************************************/
  // afterDisconnect: function(session, socket, cb) {
  //   // By default: do nothing.
  //   return cb();
  // },

  transports: [
    'websocket',
    'htmlfile',
    'polling'
  ],

  origins: '*:*'

  // More configuration options for Sails+Socket.io:
  // http://sailsjs.org/#/documentation/reference/sails.config/sails.config.sockets.html
};


text:
What's next to learn after task queues?

            {% include "choices/buttons/logging.html" %}

            {% include "choices/buttons/web-analytics.html" %}

            {% include "choices/buttons/monitoring.html" %}


text:
namespace v8_inspector {

void SetMaxAsyncTaskStacksForTest(V8Inspector* inspector, int limit) {
  static_cast<V8InspectorImpl*>(inspector)
      ->debugger()
      ->setMaxAsyncTaskStacksForTest(limit);
}

}  //  v8_inspector


text:
select_input =
select id, name, mail_address from input_table


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>Snowball: /home/superuser/Snowball/snowball/body/body.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Snowball
    1.0.1

Self copying porgram

Main Page

Namespaces

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

 All Namespaces Files Functions

body

body.h

Go to the documentation of this file.

    1 //Author: 1nn3r5493

    2 #ifndef BODY_H

    3 #define BODY_H

    4 #include <fstream>

    5 #include <iostream>

    6 #include <string>

    7 #include <fstream>

    8 namespace body

    9 {

   10 void display();

   11 int propagate();

   12 } //namespace body

   13

   14 #endif

body::display

void display()

Definition: body.cpp:11

body::propagate

int propagate()

Definition: body.cpp:20

body

This namespace contais all the component functions of the body.

Definition: body.cpp:9

<address class="footer">
Generated on Mon Apr 3 2017 21:04:06 for Snowball by

 1.8.8
</address>


text:
module.exports = {
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  extends: ['plugin:@typescript-eslint/recommended'],
  rules: {
    // note you must disable the base rule as it can report incorrect errors
    'no-unused-vars': 'off',
    '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
    '@typescript-eslint/explicit-function-return-type': [
      'warn',
      { allowTypedFunctionExpressions: true, allowExpressions: true },
    ],
  },
};


text:
@implementation ICDURLCacheDAO

+ (instancetype)sharedManager {
    static id instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] initPrivate];
    });
    return instance;
}

- (instancetype)init {
    @throw [NSException exceptionWithName:@"IllegalAccessExcetpion" reason:@"Use `+ (instancetype)sharedManager` instead" userInfo:nil];
}

- (instancetype)initPrivate {
    self = [super init];
    return self;
}

- (NSString *)urlCacheResponseJsonForRequest:(ICDBaseRequest *)request {
    NSString *cacheJson;
    NSDate *storeDate;
    NSString *path = [self cacheFilePath:request];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path isDirectory:nil] == YES) {
        id dic = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        if ([dic isKindOfClass:[NSString class]]) {
            return nil;
        }
        if ([dic isKindOfClass:[NSDictionary class]]) {
            cacheJson = dic[@"responseJson"];
            storeDate = dic[@"storeDate"];
        }
    }
    if ([self isValidCacheOfRequest:request storeDate:storeDate]) {
        return cacheJson;
    }
    return nil;
}

- (void)storeUrlCacheResponseJson:(NSString *)responseJson forRequest:(ICDBaseRequest *)request {
    NSDictionary *dic = @{@"responseJson":responseJson,
                          @"storeDate":[NSDate date]
                          };
    [NSKeyedArchiver archiveRootObject:dic toFile:[self cacheFilePath:request]];
}

#pragma mark - private methods
- (void)checkDirectory:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir;
    if (![fileManager fileExistsAtPath:path isDirectory:&isDir]) {
        [self createBaseDirectoryAtPath:path];
    } else {
        if (!isDir) {
            NSError *error = nil;
            [fileManager removeItemAtPath:path error:&error];
            [self createBaseDirectoryAtPath:path];
        }
    }
}

- (void)createBaseDirectoryAtPath:(NSString *)path {
    __autoreleasing NSError *error = nil;
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES
                                               attributes:nil error:&error];
    if (error) {
        NSLog(@"ICDURLCacheDAO create cache directory failed, error = %@", error);
    } else {
        [ICDStringUtils addDoNotBackupAttribute:path];
    }
}

- (NSString *)cacheBasePath {
    NSString *pathOfLibrary = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [pathOfLibrary stringByAppendingPathComponent:@"LazyRequestCache"];
    [self checkDirectory:path];
    return path;
}

- (NSString *)cacheFileName:(ICDBaseRequest *)request {
    NSString *requestURI= request.requestURI;
    NSString *baseUrl = kICDServerBaseURL;
    NSString *requestJson = request.requestJson;
    NSString *requestMethod;
    if (request.requestMethod == ICDRequestMethodGET) {
        requestMethod = @"GET";
    } else {
        requestMethod = @"POST";
    }
    NSString *requestInfo = [NSString stringWithFormat:@"Method:%@ BaseUrl:%@ URI:%@ ArgumentJson:%@ AppVersion:%@",
                             requestMethod, baseUrl, requestURI,
                             requestJson, kAppVersion];
    NSString *cacheFileName = [ICDStringUtils md5StringFromString:requestInfo];
    return cacheFileName;
}

- (NSString *)cacheFilePath:(ICDBaseRequest *)request {
    NSString *cacheFileName = [self cacheFileName:request];
    NSString *path = [self cacheBasePath];
    path = [path stringByAppendingPathComponent:cacheFileName];
    return path;
}

- (BOOL)isValidCacheOfRequest:(ICDBaseRequest *)request storeDate:(NSDate *)storeDate {
    NSDate *now = [NSDate date];
    NSDate *invalidDate = [NSDate dateWithTimeInterval:request.cacheValidTime sinceDate:storeDate];
    if ([[now laterDate:storeDate] isEqualToDate:now]
        && [[now laterDate:invalidDate] isEqualToDate:invalidDate]) {
        return YES;
    }
    return NO;
}

@end


text:
package cat.nyaa.nyaautils.elytra;

import cat.nyaa.nyaautils.I18n;
import cat.nyaa.nyaautils.NyaaUtils;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;

import java.util.*;

public class ElytraEnhanceListener implements Listener {
    public static List<UUID> FuelMode = new ArrayList<>();
    public static Set<UUID> disableFuelMode = new HashSet<>();
    public static Map<UUID, Long> duration = new HashMap<UUID, Long>();
    public NyaaUtils plugin;

    public ElytraEnhanceListener(NyaaUtils pl) {
        plugin = pl;
        plugin.getServer().getPluginManager().registerEvents(this, pl);
    }

    @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
    public void playerMove(PlayerMoveEvent e) {
        Player player = e.getPlayer();
        if (player.isGliding() &&
                plugin.cfg.elytra_enhance_enabled &&
                !plugin.cfg.disabled_world.contains(player.getWorld().getName()) &&
                player.getLocation().getBlock().isEmpty() &&
                player.getEyeLocation().getBlock().isEmpty() &&
                !disableFuelMode.contains(player.getUniqueId()) &&
                !player.isSneaking()) {
            if (!FuelMode.contains(player.getUniqueId()) &&
                    player.getVelocity().length() >= 0.75 &&
                    plugin.fuelManager.getFuelAmount(player, false) > 0) {
                FuelMode.add(player.getUniqueId());
            }
            if (duration.containsKey(player.getUniqueId()) &&
                    duration.get(player.getUniqueId()) >= System.currentTimeMillis()) {
                player.setVelocity(player.getEyeLocation().getDirection().multiply(plugin.cfg.elytra_max_velocity));
            }
            if (FuelMode.contains(player.getUniqueId()) &&
                    player.getVelocity().length() <= plugin.cfg.elytra_min_velocity &&
                    player.getLocation().getBlockY() <= plugin.cfg.elytra_boost_max_height &&
                    player.getLocation().getPitch() < 50) {
                if (player.getInventory().getChestplate() != null &&
                        player.getInventory().getChestplate().getType() == Material.ELYTRA) {
                    int durability = player.getInventory().getChestplate().getType().getMaxDurability() -
                                             ((Damageable)player.getInventory().getChestplate().getItemMeta()).getDamage();
                    if (durability <= plugin.cfg.elytra_durability_notify) {
                        player.sendMessage(I18n.format("user.elytra_enhance.durability_notify", durability));
                    }
                }
                if (!plugin.fuelManager.useFuel(player)) {
                    FuelMode.remove(player.getUniqueId());
                    if (duration.containsKey(player.getUniqueId())) {
                        duration.remove(player.getUniqueId());
                    }
                    return;
                } else {
                    duration.put(player.getUniqueId(), System.currentTimeMillis() + (plugin.cfg.elytra_power_duration * 1000));
                    player.setVelocity(player.getEyeLocation().getDirection().multiply(plugin.cfg.elytra_max_velocity));
                }
                int fuelAmount = plugin.fuelManager.getFuelAmount(player, false);
                if (fuelAmount <= plugin.cfg.elytra_fuel_notify) {
                    player.sendMessage(I18n.format("user.elytra_enhance.fuel_notify", fuelAmount));
                }
            }
            return;
        } else if (FuelMode.contains(player.getUniqueId())) {
            FuelMode.remove(player.getUniqueId());
        }
    }

    @EventHandler(ignoreCancelled = true)
    public void onInventoryClickEvent(InventoryClickEvent event) {
        if (!event.getWhoClicked().isGliding() && event.getCurrentItem() != null && plugin.fuelManager.getFuelID(event.getCurrentItem()) != -1) {
            ItemStack item = event.getCurrentItem();
            int id = plugin.fuelManager.getFuelID(item);
            int durability = plugin.fuelManager.getFuelDurability(item);
            plugin.fuelManager.updateItem(item, id, durability);
            event.setCurrentItem(item);
        }
    }
}