text:
"""
shared options and groups

The principle here is to define options once, but *not* instantiate them
globally. One reason being that options with action='append' can carry state
between parses. pip parses general options twice internally, and shouldn't
pass on state. To be consistent, all options will follow this design.
"""

# The following comment should be removed at some point in the future.
# mypy: strict-optional=False

from __future__ import absolute_import

import os
import textwrap
import warnings
from distutils.util import strtobool
from functools import partial
from optparse import SUPPRESS_HELP, Option, OptionGroup
from textwrap import dedent

from pip._internal.cli.progress_bars import BAR_TYPES
from pip._internal.exceptions import CommandError
from pip._internal.locations import USER_CACHE_DIR, get_src_prefix
from pip._internal.models.format_control import FormatControl
from pip._internal.models.index import PyPI
from pip._internal.models.target_python import TargetPython
from pip._internal.utils.hashes import STRONG_HASHES
from pip._internal.utils.typing import MYPY_CHECK_RUNNING

if MYPY_CHECK_RUNNING:
    from typing import Any, Callable, Dict, Optional, Tuple
    from optparse import OptionParser, Values
    from pip._internal.cli.parser import ConfigOptionParser

def raise_option_error(parser, option, msg):
    # type: (OptionParser, Option, str) -> None
    """
    Raise an option parsing error using parser.error().

    Args:
      parser: an OptionParser instance.
      option: an Option instance.
      msg: the error text.
    """
    msg = '{} error: {}'.format(option, msg)
    msg = textwrap.fill(' '.join(msg.split()))
    parser.error(msg)

def make_option_group(group, parser):
    # type: (Dict[str, Any], ConfigOptionParser) -> OptionGroup
    """
    Return an OptionGroup object
    group  -- assumed to be dict with 'name' and 'options' keys
    parser -- an optparse Parser
    """
    option_group = OptionGroup(parser, group['name'])
    for option in group['options']:
        option_group.add_option(option())
    return option_group

def check_install_build_global(options, check_options=None):
    # type: (Values, Optional[Values]) -> None
    """Disable wheels if per-setup.py call options are set.

    :param options: The OptionParser options to update.
    :param check_options: The options to check, if not supplied defaults to
        options.
    """
    if check_options is None:
        check_options = options

    def getname(n):
        # type: (str) -> Optional[Any]
        return getattr(check_options, n, None)
    names = ["build_options", "global_options", "install_options"]
    if any(map(getname, names)):
        control = options.format_control
        control.disallow_binaries()
        warnings.warn(
            'Disabling all use of wheels due to the use of --build-option '
            '/ --global-option / --install-option.', stacklevel=2,
        )

def check_dist_restriction(options, check_target=False):
    # type: (Values, bool) -> None
    """Function for determining if custom platform options are allowed.

    :param options: The OptionParser options.
    :param check_target: Whether or not to check if --target is being used.
    """
    dist_restriction_set = any([
        options.python_version,
        options.platform,
        options.abi,
        options.implementation,
    ])

    binary_only = FormatControl(set(), {':all:'})
    sdist_dependencies_allowed = (
        options.format_control != binary_only and
        not options.ignore_dependencies
    )

    # Installations or downloads using dist restrictions must not combine
    # source distributions and dist-specific wheels, as they are not
    # guaranteed to be locally compatible.
    if dist_restriction_set and sdist_dependencies_allowed:
        raise CommandError(
            "When restricting platform and interpreter constraints using "
            "--python-version, --platform, --abi, or --implementation, "
            "either --no-deps must be set, or --only-binary=:all: must be "
            "set and --no-binary must not be set (or must be set to "
            ":none:)."
        )

    if check_target:
        if dist_restriction_set and not options.target_dir:
            raise CommandError(
                "Can not use any platform or abi specific options unless "
                "installing via '--target'"
            )

def _path_option_check(option, opt, value):
    # type: (Option, str, str) -> str
    return os.path.expanduser(value)

class PipOption(Option):
    TYPES = Option.TYPES + ("path",)
    TYPE_CHECKER = Option.TYPE_CHECKER.copy()
    TYPE_CHECKER["path"] = _path_option_check

###########
# options #
###########

help_ = partial(
    Option,
    '-h', '--help',
    dest='help',
    action='help',
    help='Show help.',
)  # type: Callable[..., Option]

isolated_mode = partial(
    Option,
    "--isolated",
    dest="isolated_mode",
    action="store_true",
    default=False,
    help=(
        "Run pip in an isolated mode, ignoring environment variables and user "
        "configuration."
    ),
)  # type: Callable[..., Option]

require_virtualenv = partial(
    Option,
    # Run only if inside a virtualenv, bail if not.
    '--require-virtualenv', '--require-venv',
    dest='require_venv',
    action='store_true',
    default=False,
    help=SUPPRESS_HELP
)  # type: Callable[..., Option]

verbose = partial(
    Option,
    '-v', '--verbose',
    dest='verbose',
    action='count',
    default=0,
    help='Give more output. Option is additive, and can be used up to 3 times.'
)  # type: Callable[..., Option]

no_color = partial(
    Option,
    '--no-color',
    dest='no_color',
    action='store_true',
    default=False,
    help="Suppress colored output",
)  # type: Callable[..., Option]

version = partial(
    Option,
    '-V', '--version',
    dest='version',
    action='store_true',
    help='Show version and exit.',
)  # type: Callable[..., Option]

quiet = partial(
    Option,
    '-q', '--quiet',
    dest='quiet',
    action='count',
    default=0,
    help=(
        'Give less output. Option is additive, and can be used up to 3'
        ' times (corresponding to WARNING, ERROR, and CRITICAL logging'
        ' levels).'
    ),
)  # type: Callable[..., Option]

progress_bar = partial(
    Option,
    '--progress-bar',
    dest='progress_bar',
    type='choice',
    choices=list(BAR_TYPES.keys()),
    default='on',
    help=(
        'Specify type of progress to be displayed [' +
        '|'.join(BAR_TYPES.keys()) + '] (default: %default)'
    ),
)  # type: Callable[..., Option]

log = partial(
    PipOption,
    "--log", "--log-file", "--local-log",
    dest="log",
    metavar="path",
    type="path",
    help="Path to a verbose appending log."
)  # type: Callable[..., Option]

no_input = partial(
    Option,
    # Don't ask for input
    '--no-input',
    dest='no_input',
    action='store_true',
    default=False,
    help="Disable prompting for input."
)  # type: Callable[..., Option]

proxy = partial(
    Option,
    '--proxy',
    dest='proxy',
    type='str',
    default='',
    help="Specify a proxy in the form [user:passwd@]proxy.server:port."
)  # type: Callable[..., Option]

retries = partial(
    Option,
    '--retries',
    dest='retries',
    type='int',
    default=5,
    help="Maximum number of retries each connection should attempt "
         "(default %default times).",
)  # type: Callable[..., Option]

timeout = partial(
    Option,
    '--timeout', '--default-timeout',
    metavar='sec',
    dest='timeout',
    type='float',
    default=15,
    help='Set the socket timeout (default %default seconds).',
)  # type: Callable[..., Option]

def exists_action():
    # type: () -> Option
    return Option(
        # Option when path already exist
        '--exists-action',
        dest='exists_action',
        type='choice',
        choices=['s', 'i', 'w', 'b', 'a'],
        default=[],
        action='append',
        metavar='action',
        help="Default action when a path already exists: "
             "(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.",
    )

cert = partial(
    PipOption,
    '--cert',
    dest='cert',
    type='path',
    metavar='path',
    help="Path to alternate CA bundle.",
)  # type: Callable[..., Option]

client_cert = partial(
    PipOption,
    '--client-cert',
    dest='client_cert',
    type='path',
    default=None,
    metavar='path',
    help="Path to SSL client certificate, a single file containing the "
         "private key and the certificate in PEM format.",
)  # type: Callable[..., Option]

index_url = partial(
    Option,
    '-i', '--index-url', '--pypi-url',
    dest='index_url',
    metavar='URL',
    default=PyPI.simple_url,
    help="Base URL of the Python Package Index (default %default). "
         "This should point to a repository compliant with PEP 503 "
         "(the simple repository API) or a local directory laid out "
         "in the same format.",
)  # type: Callable[..., Option]

def extra_index_url():
    # type: () -> Option
    return Option(
        '--extra-index-url',
        dest='extra_index_urls',
        metavar='URL',
        action='append',
        default=[],
        help="Extra URLs of package indexes to use in addition to "
             "--index-url. Should follow the same rules as "
             "--index-url.",
    )

no_index = partial(
    Option,
    '--no-index',
    dest='no_index',
    action='store_true',
    default=False,
    help='Ignore package index (only looking at --find-links URLs instead).',
)  # type: Callable[..., Option]

def find_links():
    # type: () -> Option
    return Option(
        '-f', '--find-links',
        dest='find_links',
        action='append',
        default=[],
        metavar='url',
        help="If a URL or path to an html file, then parse for links to "
             "archives such as sdist (.tar.gz) or wheel (.whl) files. "
             "If a local path or file:// URL that's a directory,  "
             "then look for archives in the directory listing. "
             "Links to VCS project URLs are not supported.",
    )

def trusted_host():
    # type: () -> Option
    return Option(
        "--trusted-host",
        dest="trusted_hosts",
        action="append",
        metavar="HOSTNAME",
        default=[],
        help="Mark this host or host:port pair as trusted, even though it "
             "does not have valid or any HTTPS.",
    )

def constraints():
    # type: () -> Option
    return Option(
        '-c', '--constraint',
        dest='constraints',
        action='append',
        default=[],
        metavar='file',
        help='Constrain versions using the given constraints file. '
        'This option can be used multiple times.'
    )

def requirements():
    # type: () -> Option
    return Option(
        '-r', '--requirement',
        dest='requirements',
        action='append',
        default=[],
        metavar='file',
        help='Install from the given requirements file. '
        'This option can be used multiple times.'
    )

def editable():
    # type: () -> Option
    return Option(
        '-e', '--editable',
        dest='editables',
        action='append',
        default=[],
        metavar='path/url',
        help=('Install a project in editable mode (i.e. setuptools '
              '"develop mode") from a local project path or a VCS url.'),
    )

def _handle_src(option, opt_str, value, parser):
    # type: (Option, str, str, OptionParser) -> None
    value = os.path.abspath(value)
    setattr(parser.values, option.dest, value)

src = partial(
    PipOption,
    '--src', '--source', '--source-dir', '--source-directory',
    dest='src_dir',
    type='path',
    metavar='dir',
    default=get_src_prefix(),
    action='callback',
    callback=_handle_src,
    help='Directory to check out editable projects into. '
    'The default in a virtualenv is "<venv path>/src". '
    'The default for global installs is "<current dir>/src".'
)  # type: Callable[..., Option]

def _get_format_control(values, option):
    # type: (Values, Option) -> Any
    """Get a format_control object."""
    return getattr(values, option.dest)

def _handle_no_binary(option, opt_str, value, parser):
    # type: (Option, str, str, OptionParser) -> None
    existing = _get_format_control(parser.values, option)
    FormatControl.handle_mutual_excludes(
        value, existing.no_binary, existing.only_binary,
    )

def _handle_only_binary(option, opt_str, value, parser):
    # type: (Option, str, str, OptionParser) -> None
    existing = _get_format_control(parser.values, option)
    FormatControl.handle_mutual_excludes(
        value, existing.only_binary, existing.no_binary,
    )

def no_binary():
    # type: () -> Option
    format_control = FormatControl(set(), set())
    return Option(
        "--no-binary", dest="format_control", action="callback",
        callback=_handle_no_binary, type="str",
        default=format_control,
        help='Do not use binary packages. Can be supplied multiple times, and '
             'each time adds to the existing value. Accepts either ":all:" to '
             'disable all binary packages, ":none:" to empty the set (notice '
             'the colons), or one or more package names with commas between '
             'them (no colons). Note that some packages are tricky to compile '
             'and may fail to install when this option is used on them.',
    )

def only_binary():
    # type: () -> Option
    format_control = FormatControl(set(), set())
    return Option(
        "--only-binary", dest="format_control", action="callback",
        callback=_handle_only_binary, type="str",
        default=format_control,
        help='Do not use source packages. Can be supplied multiple times, and '
             'each time adds to the existing value. Accepts either ":all:" to '
             'disable all source packages, ":none:" to empty the set, or one '
             'or more package names with commas between them. Packages '
             'without binary distributions will fail to install when this '
             'option is used on them.',
    )

platform = partial(
    Option,
    '--platform',
    dest='platform',
    metavar='platform',
    default=None,
    help=("Only use wheels compatible with <platform>. "
          "Defaults to the platform of the running system."),
)  # type: Callable[..., Option]

# This was made a separate function for unit-testing purposes.
def _convert_python_version(value):
    # type: (str) -> Tuple[Tuple[int, ...], Optional[str]]
    """
    Convert a version string like "3", "37", or "3.7.3" into a tuple of ints.

    :return: A 2-tuple (version_info, error_msg), where `error_msg` is
        non-None if and only if there was a parsing error.
    """
    if not value:
        # The empty string is the same as not providing a value.
        return (None, None)

    parts = value.split('.')
    if len(parts) > 3:
        return ((), 'at most three version parts are allowed')

    if len(parts) == 1:
        # Then we are in the case of "3" or "37".
        value = parts[0]
        if len(value) > 1:
            parts = [value[0], value[1:]]

    try:
        version_info = tuple(int(part) for part in parts)
    except ValueError:
        return ((), 'each version part must be an integer')

    return (version_info, None)

def _handle_python_version(option, opt_str, value, parser):
    # type: (Option, str, str, OptionParser) -> None
    """
    Handle a provided --python-version value.
    """
    version_info, error_msg = _convert_python_version(value)
    if error_msg is not None:
        msg = (
            'invalid --python-version value: {!r}: {}'.format(
                value, error_msg,
            )
        )
        raise_option_error(parser, option=option, msg=msg)

    parser.values.python_version = version_info

python_version = partial(
    Option,
    '--python-version',
    dest='python_version',
    metavar='python_version',
    action='callback',
    callback=_handle_python_version, type='str',
    default=None,
    help=dedent("""\
    The Python interpreter version to use for wheel and "Requires-Python"
    compatibility checks. Defaults to a version derived from the running
    interpreter. The version can be specified using up to three dot-separated
    integers (e.g. "3" for 3.0.0, "3.7" for 3.7.0, or "3.7.3"). A major-minor
    version can also be given as a string without dots (e.g. "37" for 3.7.0).
    """),
)  # type: Callable[..., Option]

implementation = partial(
    Option,
    '--implementation',
    dest='implementation',
    metavar='implementation',
    default=None,
    help=("Only use wheels compatible with Python "
          "implementation <implementation>, e.g. 'pp', 'jy', 'cp', "
          " or 'ip'. If not specified, then the current "
          "interpreter implementation is used.  Use 'py' to force "
          "implementation-agnostic wheels."),
)  # type: Callable[..., Option]

abi = partial(
    Option,
    '--abi',
    dest='abi',
    metavar='abi',
    default=None,
    help=("Only use wheels compatible with Python "
          "abi <abi>, e.g. 'pypy_41'.  If not specified, then the "
          "current interpreter abi tag is used.  Generally "
          "you will need to specify --implementation, "
          "--platform, and --python-version when using "
          "this option."),
)  # type: Callable[..., Option]

def add_target_python_options(cmd_opts):
    # type: (OptionGroup) -> None
    cmd_opts.add_option(platform())
    cmd_opts.add_option(python_version())
    cmd_opts.add_option(implementation())
    cmd_opts.add_option(abi())

def make_target_python(options):
    # type: (Values) -> TargetPython
    target_python = TargetPython(
        platform=options.platform,
        py_version_info=options.python_version,
        abi=options.abi,
        implementation=options.implementation,
    )

    return target_python

def prefer_binary():
    # type: () -> Option
    return Option(
        "--prefer-binary",
        dest="prefer_binary",
        action="store_true",
        default=False,
        help="Prefer older binary packages over newer source packages."
    )

cache_dir = partial(
    PipOption,
    "--cache-dir",
    dest="cache_dir",
    default=USER_CACHE_DIR,
    metavar="dir",
    type='path',
    help="Store the cache data in <dir>."
)  # type: Callable[..., Option]

def _handle_no_cache_dir(option, opt, value, parser):
    # type: (Option, str, str, OptionParser) -> None
    """
    Process a value provided for the --no-cache-dir option.

    This is an optparse.Option callback for the --no-cache-dir option.
    """
    # The value argument will be None if --no-cache-dir is passed via the
    # command-line, since the option doesn't accept arguments.  However,
    # the value can be non-None if the option is triggered e.g. by an
    # environment variable, like PIP_NO_CACHE_DIR=true.
    if value is not None:
        # Then parse the string value to get argument error-checking.
        try:
            strtobool(value)
        except ValueError as exc:
            raise_option_error(parser, option=option, msg=str(exc))

    # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()
    # converted to 0 (like "false" or "no") caused cache_dir to be disabled
    # rather than enabled (logic would say the latter).  Thus, we disable
    # the cache directory not just on values that parse to True, but (for
    # backwards compatibility reasons) also on values that parse to False.
    # In other words, always set it to False if the option is provided in
    # some (valid) form.
    parser.values.cache_dir = False

no_cache = partial(
    Option,
    "--no-cache-dir",
    dest="cache_dir",
    action="callback",
    callback=_handle_no_cache_dir,
    help="Disable the cache.",
)  # type: Callable[..., Option]

no_deps = partial(
    Option,
    '--no-deps', '--no-dependencies',
    dest='ignore_dependencies',
    action='store_true',
    default=False,
    help="Don't install package dependencies.",
)  # type: Callable[..., Option]

def _handle_build_dir(option, opt, value, parser):
    # type: (Option, str, str, OptionParser) -> None
    if value:
        value = os.path.abspath(value)
    setattr(parser.values, option.dest, value)

build_dir = partial(
    PipOption,
    '-b', '--build', '--build-dir', '--build-directory',
    dest='build_dir',
    type='path',
    metavar='dir',
    action='callback',
    callback=_handle_build_dir,
    help='(DEPRECATED) '
         'Directory to unpack packages into and build in. Note that '
         'an initial build still takes place in a temporary directory. '
         'The location of temporary directories can be controlled by setting '
         'the TMPDIR environment variable (TEMP on Windows) appropriately. '
         'When passed, build directories are not cleaned in case of failures.'
)  # type: Callable[..., Option]

ignore_requires_python = partial(
    Option,
    '--ignore-requires-python',
    dest='ignore_requires_python',
    action='store_true',
    help='Ignore the Requires-Python information.'
)  # type: Callable[..., Option]

no_build_isolation = partial(
    Option,
    '--no-build-isolation',
    dest='build_isolation',
    action='store_false',
    default=True,
    help='Disable isolation when building a modern source distribution. '
         'Build dependencies specified by PEP 518 must be already installed '
         'if this option is used.'
)  # type: Callable[..., Option]

def _handle_no_use_pep517(option, opt, value, parser):
    # type: (Option, str, str, OptionParser) -> None
    """
    Process a value provided for the --no-use-pep517 option.

    This is an optparse.Option callback for the no_use_pep517 option.
    """
    # Since --no-use-pep517 doesn't accept arguments, the value argument
    # will be None if --no-use-pep517 is passed via the command-line.
    # However, the value can be non-None if the option is triggered e.g.
    # by an environment variable, for example "PIP_NO_USE_PEP517=true".
    if value is not None:
        msg = """A value was passed for --no-use-pep517,
        probably using either the PIP_NO_USE_PEP517 environment variable
        or the "no-use-pep517" config file option. Use an appropriate value
        of the PIP_USE_PEP517 environment variable or the "use-pep517"
        config file option instead.
        """
        raise_option_error(parser, option=option, msg=msg)

    # Otherwise, --no-use-pep517 was passed via the command-line.
    parser.values.use_pep517 = False

use_pep517 = partial(
    Option,
    '--use-pep517',
    dest='use_pep517',
    action='store_true',
    default=None,
    help='Use PEP 517 for building source distributions '
         '(use --no-use-pep517 to force legacy behaviour).'
)  # type: Any

no_use_pep517 = partial(
    Option,
    '--no-use-pep517',
    dest='use_pep517',
    action='callback',
    callback=_handle_no_use_pep517,
    default=None,
    help=SUPPRESS_HELP
)  # type: Any

install_options = partial(
    Option,
    '--install-option',
    dest='install_options',
    action='append',
    metavar='options',
    help="Extra arguments to be supplied to the setup.py install "
         "command (use like --install-option=\"--install-scripts=/usr/local/"
         "bin\"). Use multiple --install-option options to pass multiple "
         "options to setup.py install. If you are using an option with a "
         "directory path, be sure to use absolute path.",
)  # type: Callable[..., Option]

global_options = partial(
    Option,
    '--global-option',
    dest='global_options',
    action='append',
    metavar='options',
    help="Extra global options to be supplied to the setup.py "
         "call before the install command.",
)  # type: Callable[..., Option]

no_clean = partial(
    Option,
    '--no-clean',
    action='store_true',
    default=False,
    help="Don't clean up build directories."
)  # type: Callable[..., Option]

pre = partial(
    Option,
    '--pre',
    action='store_true',
    default=False,
    help="Include pre-release and development versions. By default, "
         "pip only finds stable versions.",
)  # type: Callable[..., Option]

disable_pip_version_check = partial(
    Option,
    "--disable-pip-version-check",
    dest="disable_pip_version_check",
    action="store_true",
    default=False,
    help="Don't periodically check PyPI to determine whether a new version "
         "of pip is available for download. Implied with --no-index.",
)  # type: Callable[..., Option]

def _handle_merge_hash(option, opt_str, value, parser):
    # type: (Option, str, str, OptionParser) -> None
    """Given a value spelled "algo:digest", append the digest to a list
    pointed to in a dict by the algo name."""
    if not parser.values.hashes:
        parser.values.hashes = {}
    try:
        algo, digest = value.split(':', 1)
    except ValueError:
        parser.error('Arguments to {} must be a hash name '  # noqa
                     'followed by a value, like --hash=sha256:'
                     'abcde...'.format(opt_str))
    if algo not in STRONG_HASHES:
        parser.error('Allowed hash algorithms for {} are {}.'.format(  # noqa
                     opt_str, ', '.join(STRONG_HASHES)))
    parser.values.hashes.setdefault(algo, []).append(digest)

hash = partial(
    Option,
    '--hash',
    # Hash values eventually end up in InstallRequirement.hashes due to
    # __dict__ copying in process_line().
    dest='hashes',
    action='callback',
    callback=_handle_merge_hash,
    type='string',
    help="Verify that the package's archive matches this "
         'hash before installing. Example: --hash=sha256:abcdef...',
)  # type: Callable[..., Option]

require_hashes = partial(
    Option,
    '--require-hashes',
    dest='require_hashes',
    action='store_true',
    default=False,
    help='Require a hash to check each requirement against, for '
         'repeatable installs. This option is implied when any package in a '
         'requirements file has a --hash option.',
)  # type: Callable[..., Option]

list_path = partial(
    PipOption,
    '--path',
    dest='path',
    type='path',
    action='append',
    help='Restrict to the specified installation path for listing '
         'packages (can be used multiple times).'
)  # type: Callable[..., Option]

def check_list_path_option(options):
    # type: (Values) -> None
    if options.path and (options.user or options.local):
        raise CommandError(
            "Cannot combine '--path' with '--user' or '--local'"
        )

no_python_version_warning = partial(
    Option,
    '--no-python-version-warning',
    dest='no_python_version_warning',
    action='store_true',
    default=False,
    help='Silence deprecation warnings for upcoming unsupported Pythons.',
)  # type: Callable[..., Option]

unstable_feature = partial(
    Option,
    '--unstable-feature',
    dest='unstable_features',
    metavar='feature',
    action='append',
    default=[],
    choices=['resolver'],
    help=SUPPRESS_HELP,  # TODO: drop this in pip 20.3
)  # type: Callable[..., Option]

use_new_feature = partial(
    Option,
    '--use-feature',
    dest='features_enabled',
    metavar='feature',
    action='append',
    default=[],
    choices=['2020-resolver', 'fast-deps'],
    help='Enable new functionality, that may be backward incompatible.',
)  # type: Callable[..., Option]

use_deprecated_feature = partial(
    Option,
    '--use-deprecated',
    dest='deprecated_features_enabled',
    metavar='feature',
    action='append',
    default=[],
    choices=[],
    help=(
        'Enable deprecated functionality, that will be removed in the future.'
    ),
)  # type: Callable[..., Option]

##########
# groups #
##########

general_group = {
    'name': 'General Options',
    'options': [
        help_,
        isolated_mode,
        require_virtualenv,
        verbose,
        version,
        quiet,
        log,
        no_input,
        proxy,
        retries,
        timeout,
        exists_action,
        trusted_host,
        cert,
        client_cert,
        cache_dir,
        no_cache,
        disable_pip_version_check,
        no_color,
        no_python_version_warning,
        unstable_feature,
        use_new_feature,
        use_deprecated_feature,
    ]
}  # type: Dict[str, Any]

index_group = {
    'name': 'Package Index Options',
    'options': [
        index_url,
        extra_index_url,
        no_index,
        find_links,
    ]
}  # type: Dict[str, Any]


text:
#include <QtGui/QGuiApplication>
#include <QFont>

#include "controllerattached.h"
#include "controllermanager.h"
#include "qtquick2applicationviewer.h"

static FILE *logFile;

static void logMessageHandler(
    QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();

    if (!logFile) {
        return;
    }

    switch (type) {
    case QtDebugMsg:
        fprintf(logFile, "D/[%s@%s:%u] %s\n",
            context.function, context.file, context.line, localMsg.constData());
        break;
    case QtWarningMsg:
        fprintf(logFile, "W/[%s@%s:%u] %s\n",
            context.function, context.file, context.line, localMsg.constData());
        break;
    case QtCriticalMsg:
        fprintf(logFile, "C/[%s@%s:%u] %s\n",
            context.function, context.file, context.line, localMsg.constData());
        break;
    case QtFatalMsg:
        fprintf(logFile, "F/[%s@%s:%u] %s\n",
            context.function, context.file, context.line, localMsg.constData());
        break;
    }

    fflush(logFile);
}

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QtQuick2ApplicationViewer viewer;

    // Start logging
    logFile = fopen("/tmp/steamlink-qml-example.log", "w");
    qInstallMessageHandler(logMessageHandler);
    qWarning() << "Starting steamlink-qml-example.";

    // Move the mouse cursor off the screen so that it doesn't show on top
    // of the GUI.
    QCursor().setPos(0xFFFF, 0xFFFF);

    // Steam Link only has the Noto font family. Set it as the default font.
    app.setFont(QFont("Noto Sans"));

    // Setup controller input
    CControllerManager controllerManager(&app);
    app.installEventFilter(&controllerManager);
    ControllerAttached::initialize();

    viewer.setMainQmlFile(QStringLiteral("qml/steamlink-qml-example/main.qml"));
    viewer.showExpanded();

    return app.exec();
}

redpajama_set_name: RedPajamaGithub


text:
define(['jquery', 'time2Units'], function($, time2Units) {
    //将返回的json转化为html片段
    function createInnerBoxFragment(data, table) {
        var innerBoxHTML = "";
        $.each(data, function(index, value) {
            // alert(index);
            var title = $(value).attr("title");
            var img_url = $(value).attr("img_url");
            var content = $(value).attr("content");
            var from = $(value).attr("from");
            var time = $(value).attr("time");
            time = time.substring(0, 19).replace("T", " ");
            var newsdate = new Date(time);
            var datanow = new Date();
            //8小时的时间差,北京时间
            var differ = datanow.getTime() - 8 * 3600 * 1000 - newsdate.getTime();
            time = time2Units(differ) + "前";
            innerBoxHTML += '

' + title +
                '

' + content +
                '

' + time +
                '' + from +
                '

';
        });
        $(".selected").find(".loadMore").before(innerBoxHTML);
    }
    return createInnerBoxFragment;
});


text:
'use strict';

function enable(key) {
  this.set(key, true);
  return this;
}

module.exports = enable;


text:
Scx format was formed by Esemble Studios, [Microsoft] for their games, first time for [Age of Empires]  (1997) and second for [Age of Empires 2]  (1999), and for their last game on genie engine [Star Wars: Galactic Battlegrounds]. Format is used to store maps (scenarios). It's uses C++98 standart datatypes. Also scenario data are compressed with DEFLAT method. This document primary describes scx format used for Age of Empires 2, version 1.21.

## Format Standart

Most of this document originaly writen by DiGit's. specification with knowledge by AOHH and Iberico format and finally extend with me.

## List of Structures

* [**Uncompressed Header**](#uncompressed-header) -basic information about scenario
* [**Compressed Data**](#compressed-data) -compressed information about scenario
* [Player Data 1](#player-data1) -
* [**Messages**](#messages) -messages like instructions and hints
* [**Cinematics**](#cinematics) -cinematics file names
* [Background Image](#background-image) -background image information
* [Bitmap Info Header](#bitmap-info-header) -image information (if image incldued)
* [Player Data 2](#player-2-data) -
* [AI Files](#struct-ai-files) -ai files included
* [Resources](#struct-resources) -resources for player (wo population)
* [**Global Victory**](#global-victory) -global victory information
* [**Diplomacy**](#diplomacy) -diplomacy for every player
* [Diplomacy per Player](#struct-diplomacy-per-player)
* [Disables](#disables) -disables tehnologies, units and buildings
* [**Map**](#map) -information about map
* [Terrain](#struct-terrain) -information about tile(s) (type and elevation)
* [Units Section](#units-section) -how many units section is described
* [Player Data 4](#struct-player-data-4) -
* [Player Units](#struct-player-units) -how many units are stored per player
* [**Unit**](#struct-unit) -all unit information
* [Player Data 3](#player-data-3) -
* [Player Data 3 Sub](#struct-player-data-3) -
* [Triggers Section](#triggers-section) -how many triggers
* [**Trigger**](#structure-trigger) -all stored triggers
* [**Efffect**](#structure-effect) -all stored effects for trigger
* [**Condition**](#structure-condition) -all stored conditoins for trigger
* [Included Files](#included-files) -included files
* [PER File Error](#per-file-error) -PER file error

## About Scenario

Here you will find interesting info about scenario files

### Coords

Coordinations [0, 0] starts from left point of map, continue to top of map [0, mapWidth]. Tiles are one dimension array, starting from position [0, 0].This image shows how are Tile[x, y] calculated.

![Map Coordinations](img/map_coords.png)

## Format

### Data Types

A note about data lengths: they specify both the length of the data and
how to interpret it. For example:

* **s32** is a signed 32-bit integer
* **u16** is an unsigned 16-bit integer
* **f32** is a 32-bit (single-precision) floating point number
* **c4** is a 4-byte character string
* **str16** is a variable-length character string (see below)
* **40** means 40 bytes of data
* **16*u16** means 16 unsigned 16-bit integers

Variable-length character strings are stored in the scenario as length/data
pairs. For example "str16" means there is a 16-bit length field with value n
followed by n bytes (characters). str32 is also used, but more rarely.

### Uncompressed Header ###

Length | Requires   | Description
-------|------------|----------------------------------------------------
c4     |            | Version (ASCII): 1.10, 1.18, 1.21
u32    |            | Length of header (excluding version and self)
s32    |            | Savable
u32    |Savable >= 2| Timestamp of last save
str32  |            | Scenario Instructions
u32    |            | Individual Victories Used
u32    |            | Player count (thanks iberico)

### Compressed DataIt uses Deflate method with *(-MAX_WBITS, for python)*

#### Header

Length | MinVer | Description
-------|--------|----------------------------------------------------
u32    |        | Next unit ID to place
f32    |        | Version 2
16*256 |        | ASCII player names
16*u32 | 1.18   | string table player names
16*16  |        | Player Data#1 see [sub-struct below](#player-data1)
u8     |        | Conquest Mode
u16    |        | Mission Items Counter = n
u16    |        | Mission Available
f32    |        | Mission Timeline
n*30   |        | Mision Item (each 30 bytes)
str16  |        | Original filename, created while first scenario save

##### Player Data#1

Length | MinVer | Description
-------|--------|----------------------------------------------------
u32    |        | Boolean: Active
u32    |        | Boolean: Human
u32    |        | Civilization, see IDs at this document
u32    |        | CTY Mode

#### Messages

Length | MinVer | Description
-------|--------|----------------------------------------------------
u32    | 1.18   | String table, Instructions
u32    | 1.18   | String table, Hints
u32    | 1.18   | String table, Victory
u32    | 1.18   | String table, Loss
u32    | 1.18   | String table, History
u32    | 1.22   | String table, Scouts
str16  |        | ASCII, Instructions
str16  |        | ASCII, Hints
str16  |        | ASCII, Victory
str16  |        | ASCII, Loss
str16  |        | ASCII, History
str16  | 1.22   | ASCII, Scouts

#### Cinematics

Length | MinVer | Description
-------|--------|----------------------------------------------------
str16  |        | ASCII, Pregame cinematic filename
str16  |        | ASCII, Victory cinematic filename
str16  |        | ASCII, Loss cinematic filename
1      |        | Separator (! in some version)

#### Background Image

Length | MinVer | Description
-------|--------|----------------------------------------------------
str16  |        | ASCII, Background filename
u32    |        | Picture Version
u32    |        | Bitmap width
s32    |        | Bitmap height
s16    |        | Picture Orientation
40+SIZE|        | [BITMAPINFOHEADER](#bitmap-info-header) (if width >= 0 && height >= 0)

#### Bitmap Info Header

**WARNING:** This section is readed only if above **Include** value is -1 or 2 !
Look at this [btmp info header article] about format spec for more information

Length     | MinVer | Description
-----------|--------|----------------------------------------------------
s32        |        | Size
u32        |        | Width
s32        |        | Height
s16        |        | Planes
s16        |        | BitCount
u32        |        | Compression
u32        |        | SizeImage **SIZ**
u32        |        | XPels
u32        |        | YPels
U32        |        | Colors Used **CLR**
u32        |        | Important Colors
u32***CLR**|        | Calculated: u32*ColorsUsed
u32***SIZ**|        | Calculated: u32*SizeImage

#### Player 2 Data

Length | MinVer | Description
-------|--------|----------------------------------------------------
32str16|        | Unknown strings (2 per player?)
16str16|        | AI names, one per player
16*var |        | AI files, see [sub-struct below](#struct-ai-files)
u8     |        | AI type, 0 = custom, 1 = standard, 2 = none. Thanks iberico.
u32    |        | Separator, 0xFFFFFF9D
16*24  |        | Resources, see [sub-struct below](#struct-resources)

##### Struct: AI Files

Length | MinVer | Description
-------|--------|----------------------------------------------------
u32    |        | unknown, always 0
u32    |        | unknown, always 0
str32  |        | AI .per file text

##### Struct: Resources

Length | MinVer | Description
-------|--------|----------------------------------------------------
u32    |        | Gold
u32    |        | Wood
u32    |        | Food
u32    |        | Stone
u32    |        | "Ore X", not used in AOK
u32    |        | Trade Goods

#### Global Victory

Length | MinVer | Description
-------|--------|----------------------------------------------------
u32    |        | Separator, 0xFFFFFF9D
u32    |        | Boolean: conquest required? (for custom vict)
u32    |        | Ruins
u32    |        | Artifacts
u32    |        | Discovery
u32    |        | Explored % of map required
u32    |        | Gold
u32    |        | Boolean: all custom conditions required?
u32    |        | Mode, see below
u32    |        | Required score for score victory
u32    |        | Time for timed game, in 10ths of a year (eg, 100 = 10yr)

#### Diplomacy

Length  | MinVer | Description
--------|--------|----------------------------------------------------
16*64   |        | Per-player diplomacy, see [sub-struct](#struct-diplomacy-per-player) below
16*12*60|        | Individual Victories (12 Conditions per 16 Players)
u32     |        | Separator, 0xFFFFFF9D
16*u32  |        | Boolean: Allied vict, per-player. Ignored (see PData3). Thanks iberico.

##### Struct: Diplomacy Per-player

Length | MinVer | Description
-------|--------|----------------------------------------------------
16*u32 |        | Stance with each player, 0 = allied, 1 = neutral, 3 = enemy

#### Disables

Length | MinVer | Description
-------|--------|----------------------------------------------------
16*u32 |        | Per-player, number of disabled techs
16*120 |        | Per-player, Disabled technology IDs (30*u32)
16*120 | 1.30   | Per-player, Extra disabled technologies (30*u32)
16*u32 |        | Per-player, number of disabled units
16*120 |        | Per-player, Disabled unit IDs (30*u32)
16*120 | 1.30   | Per-player, Extra disabled units (30*u32)
16*u32 |        | Per-player, number of disabled buildings
16*80  |        | Per-player, Disabled building IDs (20*u32)
16*160 | 1.30   | Per-player, Extra disabled buildings (40*u32)
u32    |        | Combat Mode
u32    |        | Naval Mode
u32    |        | Boolean: all techs
16*u32 |        | Per-player, starting age. See below. 0-8 Players, 9 - Gaia, 10-16 Unused players

#### Map

Length          | MinVer | Description
----------------|--------|-------------------------------------------
u32             |        | Separator, 0xFFFFFF9D
s32             |        | Player 1 camera, Y
s32             |        | Player 1 camera, X
s32             | 1.21   | AI Type (see list at bottom)
u32             |        | Map Width (AOK caps at 256), **W**
u32             |        | Map Height (AOK caps at 256), **H**
**W**\***H**\*3 |        | Terrain data, see [sub-struct](#struct-terrain) below

##### Struct: Terrain

Tiles are one dimensional array. There's not any X or Y. It's calculated internal. First tile[X:0, Y:0] starts at leftmost corner and continues at uppest corner of minimap. See [example image](#coords) how tiles are readed.

length | minver | description
-------|--------|----------------------------------------------------
u8     |        | terrain id, see list at bottom
u8     |        | elevation
u8     |        | unused = 0

#### Units Section

length    | minver | description
----------|--------|----------------------------------------------------
u32       |        | number of unit sections. I've always seen = 9. **P**
8*28      |        | Player Data 4, see [sub-struct](#struct-player-data-4) below
**P***var |        | Player Units, see [sub-struct](#struct-player-units) below. GAIA units come first.

##### Struct: Player Data 4

length | minver | description
-------|--------|----------------------------------------------------
f32    |        | Food, duplicate
f32    |        | Wood, duplicate
f32    |        | Gold, duplicate
f32    |        | Stone, duplicate
f32    |        | "Ore X", duplicate
f32    |        | Trade Goods Not in SW:GB.
f32    | 1.21   | Population limit

##### Struct: Player Units

length   | minver | description
---------|--------|----------------------------------------------------
u32      |        | Unit count, **N**
**N***29 |        | Units, see [sub-struct](#struct-unit) below

##### Struct: Unit

length | minver | description
-------|--------|----------------------------------------------------
f32    |        | X position
f32    |        | Y position
f32    |        | Z position
u32    |        | ID (for triggers, etc.)
u16    |        | Unit "constant", e.g. Archer, Man-at-arms
u8     |        | Status = 2
f32    |        | Rotation, in radians
u16    |        | Initial animation frame
u32    |        | Garrisonned in ID

#### Player Data 3

length | minver | description
-------|--------|----------------------------------------------------
u32    |        | Number of players? Always = 9
8*64   |        | Player Data 3, per player. See [sub-struct](#struct-player-data-3) below.
f64    |        | Trigger Version = 1.6

##### Struct: Player Data 3

length    | minver | description
----------|--------|----------------------------------------------------
str16     |        | Constant name, like "Player 1"
f32       |        | Initial Camera, X (for Player 1 = editor camera)
f32       |        | Initial Camera, Y
s16       |        | Unknown, similar to camera X
s16       |        | Unknown, similar to camera Y
u8        |        | Boolean: Allied Victory (AOK reads this one)
u16       |        | Player count for diplomacy, **P**
**P***u8  |        | Diplomacy for interaction: 0 = allied, 1 = neutral, 2 = ?, 3 = enemy
9*u32     |        | Diplomacy for AI system: 0=GAIA, 1=self, 2=allied, 3=neutral, 4=enemy
u32       |        | Color, see values below
f32       |        | Victory Version, TODO: below are Victory conditions and effects (need to clarify these structures):
u16       |        | Unknown, **DAT**
8*u8      |        | Only included if above f32 value == 2.0
**DAT***44|        | Unknown structure, found in Grand Theft Empires
7*u8      |        | Usually 0
s32       |        | Seems to be 0 if Unknown == 1.0, -1 if Unknown == 2.0

#### Triggers Section

length     | minver | description
-----------|--------|----------------------------------------------------
s8         |        | Trigger instructions start
s32        |        | Number of triggers = 0, **T**
**T**\*var |        | Trigger data, see [sub-struct](#structure-trigger) below
**T**\*u32 |        | Trigger display order array

##### Structure: Trigger

length     | minver | description
-----------|--------|----------------------------------------------------
u32        |        | Boolean: enabled?
s8         |        | Boolean: looping?
s32        |        | String Table ID = -1
u8         |        | Boolean: objective?
u32        |        | Description order (in objectives)
u32        |        | Trigger starting time
str32      |        | Trigger description
str32      |        | Trigger name (max 44 characters in UI)
s32        |        | Number of effects = **E**
**E**\*var |        | Effect data, see [sub-struct](#structure-effect) below
**E**\*s32 |        | Effect display order array
s32        |        | Number of conditions = **C**
**C**\*var |        | Condition data, see [sub-struct](#structure-condition) below
**C**\*s32 |        | Condition display order array

##### Structure: Effect

length    | minver | description
----------|--------|----------------------------------------------------
s32       |        | Effect type
s32       |        | Check, always = 0x17
s32       |        | AI script goal
s32       |        | Amount, used for hp and attack
s32       |        | Resource type
s32       |        | Diplomacy, state for change
s32       |        | N.o. units selected = **N**
s32       |        | Unit ID
s32       |        | Unit Name
s32       |        | Player Source
s32       |        | Player Target
s32       |        | Technology
s32       |        | String ID
s32       |        | Sound resource ID
s32       |        | Display Time (display instructions)
s32       |        | Trigger ID (activate/deactivate)
s32       |        | Location X
s32       |        | Location Y
s32       |        | Area 1 X
s32       |        | Area 1 Y
s32       |        | Area 2 X
s32       |        | Area 2 Y
s32       |        | Unit Group
s32       |        | Unit Type (Civilian, Military, Building, Other)
s32       |        | Instruction Panel
str32     |        | Instruction Text
str32     |        | Sound filename
s32***N** |        | Selected units IDs

##### Structure: Condition

length | minver | description
-------|--------|----------------------------------------------------
s32    |        | Condition Type
s32    |        | Check, always = 0x10
s32    |        | Amount (of Object, Diffculty)
s32    |        | Resource Type
s32    |        | Unit object
s32    |        | Unit ID
s32    |        | Unit Name
s32    |        | Player
s32    |        | Technology
s32    |        | Timer
s32    |        | Unknown
s32    |        | Area 1 X
s32    |        | Area 1 Y
s32    |        | Area 2 X
s32    |        | Area 2 Y
s32    |        | AI Signal

#### Included Files

length | minver | description
-------|--------|----------------------------------------------------
u32    |        | Boolean: files included?
u32    |        | Boolean: PER File Error, data included?
396    |        | PER File Error, if PER File Error included
var    |        | Included files

#### PER File Error

This data contains details about the last error occurrence in the PER files. This data is ignored during reading, but is written when saving a scenario with a PER file error.
The engine outputs the details on debug mode. The developers must have needed this feature to debug their AI scripting in scenarios. Normally, a dialog box contains a message about the details of the error. I don't see why they needed this; maybe they wanted to see the data in raw binary form.
*-by AOHH*

length | minver | description
-------|--------|----------------------------------------------------
256    |        | Name of corrupted PER File
u32    |        | Unknown ID (either PER file ID or Player ID)
u32    |        | Line of error in PER File
u32    |        | Interruption line in PER File
124    |        | Extracted code from PER File
u32    |        | Error Code

[Age of Empires]: http://en.wikipedia.org/wiki/Age_of_Empires
[Age of Empires 2]: http://en.wikipedia.org/wiki/Age_of_Empires_II:_The_Age_of_Kings
[Star Wars: Galactic Battlegrounds]: http://en.wikipedia.org/wiki/Star_Wars:_Galactic_Battlegrounds
[btmp info header article]: http://www.herdsoft.com/ti/davincie/davp3xo2.htm
[Microsoft]: http://www.microsoft.com


text:
title:  "Kako možemo izbeći zver?"
date:   20/03/2019
---

### Primena (Otkrivenje 17,3)

Otkrivenje pokazuje da je aždaja dodelila silu svojim predstavnicima širom sveta, sa kojima sarađuje kako bi prevarila Božji narod. Čak i među hrišćanima ima sinova i kćeri zla. Oni su kukolj koji raste zajedno sa žitom. Međutim, kad se navrši vreme, Hristos će poslati svoje anđele da sakupe kukolj i spale ga, a zatim da požanju žito (Matej 13,36-40).

Ali pre nego što Hristos dođe da bi nas poveo kući, moramo paziti da ne budemo deo duhovne truleži koja postoji u našim crkvama danas. U našem društvu dolazi do sve većeg odstupanja od vere. To se može pripisati delovanju aždaje, zveri i njihovih predstavnika, čiji su nastup, karakter i uticaj opisani u 17. poglavlju Otkrivenja.

Već dosta dugo postoje različiti oblici otpadništva koji su se uvukli u crkvu. Zato je potrebno da prepoznamo te lažne učitelje i njihova lažna učenja.

Za početak, lažna učenja odstupaju od ključnih i istinitih biblijskih doktrina, dodajući im svetovnu notu. Drugim rečima, ona zvuče kao istinita hrišćanska učenja, ali to nisu. Osim toga, otpadništvo se može javiti i u vidu potpunog odricanja od hrišćanske vere, pri čemu pojedinac postaje potpuni antihrist.

Jedna studija pod nazivom »Propovednici koji nisu vernici«, sprovedena 2010. godine, otkrila je da zaista postoje propovednici koji su »prihvativši jeretička učenja o hrišćanstvu, potpuno otpali od vere i sada su ili panteisti ili potajni ateisti«.1

Moramo se zaštititi od lažnih učenja smišljenih od strane zveri. A najbolji način da to učinimo jeste da upoznamo istinu. Da bismo prepoznali falsifikat, moramo proučavati original. Isus je govorio da ćemo drvo prepoznati po njegovom rodu (Matej 12,33). Evo nekih načina da prepoznamo lažne učitelje unutar hrišćanstva:

Njihova učenja o Hristu: Ako učenja ne podržavaju Hrista i Njegovo delo iskupljenja, onda im nešto nedostaje.

Njihovo razumevanje evanđelja: Pavle upozorava: »Ako vam neko propoveda evanđelje različito od onog koje ste primili, neka je proklet« (Galatima 1,9, SSP).

Njihove karakterne crte: Ako odbacuju Božji plan, proriču za novac, ili uzdižu sebe iznad Hrista, onda ne shvataju ono najbitnije (Matej 7,15-20; Juda 11).

**Odgovorite**

`1.	Možete li prepoznati neko lažno učenje u vašoj sredini?`

*Roz Ndanu, Matuu, Kenija*

_________
1	https://bit.ly/2GrOs7e


text:
tinyMCE.addToLang('',{
insert_advhr_desc : 'Horizontale lijn invoegen/bewerken',
insert_advhr_width : 'Breedte',
insert_advhr_size : 'Hoogte',
insert_advhr_noshade : 'Geen schaduw'
});


text:
<?php

final class PhabricatorDoubleExportField
  extends PhabricatorExportField {

  public function getNaturalValue($value) {
    if ($value === null) {
      return $value;
    }

    return (double)$value;
  }

  /**
   * @phutil-external-symbol class PHPExcel_Cell_DataType
   */
  public function formatPHPExcelCell($cell, $style) {
    $cell->setDataType(PHPExcel_Cell_DataType::TYPE_NUMERIC);
  }

  public function getCharacterWidth() {
    return 8;
  }

}


text:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MenuItem, DataTable, ConfirmationService,LazyLoadEvent,Message } from "primeng/primeng";
import Dexie from 'dexie';
import { Observable } from "rxjs";
import { Apollo } from 'apollo-angular';
import gql from 'graphql-tag';
import { FormBuilder, FormGroup, Validators } from "@angular/forms";

const MAX_EXAMPLE_RECORDS = 1000;

@Component({
  selector: 'at-alltimes',
  templateUrl: './alltimes.component.html',
  styleUrls: ['./alltimes.component.css']
})
export class AlltimesComponent implements OnInit {

  @ViewChild("dt") dt : DataTable;

    allTimesheetData = [];
    onTimeSheetDialog = false;

    allProjectNames = ['', 'Payroll App', 'Mobile App', 'Agile Times'];

    allProjects = this.allProjectNames.map((proj) => {
      return { label: proj, value: proj }
    });

    selectedRows: Array<any>;

    messages: Message[] = [];

    contextMenu: MenuItem[];

    mytimesheetform: FormGroup;
    recordCount : number;

    constructor(private apollo: Apollo,private confirmationService: ConfirmationService,private tsb: FormBuilder) {

     }

    ngOnInit() {

      const AllClientsQuery = gql`
      query allTimeSheets {
        allTimeSheets {
            id
            user
            project
            category
            startTime
            endTime
          }
      }`;

      const queryObservable = this.apollo.watchQuery({

        query: AllClientsQuery, pollInterval:200

      }).subscribe(({ data, loading }: any) => {

        console.log(data)
        this.allTimesheetData = data.allTimeSheets;
        this.recordCount = data.allTimeSheets.length;

      });

      this.mytimesheetform = this.tsb.group({
        user: ['', [Validators.required, Validators.minLength(5)]],
        project: ['', [Validators.required, Validators.maxLength(140)]],
        category: ['', Validators.required],
        startTime: ['',Validators.required],
        endTime:['',Validators.required],
        date:[new Date(),Validators.required]
      })

    }

    onEditComplete(editInfo) { }

    cancelNewTimeSheetDialog(){
      this.confirmationService.confirm({
        header: 'Cancel TimeSheet Creation',
        message: 'Cancel all changes. Are you sure?',
        accept: () => {
          this.onTimeSheetDialog = false;
          this.messages.push({ severity: 'info', summary: 'Edits Cancelled', detail: 'No changes were saved' });
        },
        reject: () => {
          this.messages.push({ severity: 'warn', summary: 'Cancelled the Cancel', detail: 'Please continue your editing' });
          console.log("False cancel. Just keep editing.");
        }
      });

    }

    hasFormErrors() {
      return !this.mytimesheetform.valid;
    }
    saveNewTimeSheetEntry(){
      this.onTimeSheetDialog = false;
  //    alert(JSON.stringify(this.mytimesheetform.value));

const user =this.mytimesheetform.value.user;
const project = this.mytimesheetform.value.project;
const category = this.mytimesheetform.value.category;
const startTime = this.mytimesheetform.value.startTime;
const endTime = this.mytimesheetform.value.endTime;

const createTimeSheet = gql`
  mutation createTimeSheet ($user: String!, $project: String!, $category: String!, $startTime: Int!, $endTime: Int!, $date: DateTime!) {
    createTimeSheet(user: $user, project: $project, category: $category, startTime: $startTime, endTime: $endTime, date: $date ) {
      id
    }
  }
`;

console.log(user);
this.apollo.mutate({
mutation: createTimeSheet,
  variables: {
    user: user,
    project: project,
    category: category,
    startTime: startTime,
    endTime: endTime,
    date: new Date()
  }
}).subscribe(({ data }) => {
  console.log('got data', data);

}, (error) => {
  console.log('there was an error sending the query', error);
});
           this.onTimeSheetDialog=false;
      this.messages.push({ severity: 'success', summary: 'Entry Created', detail: 'Your entry has been created' });
    }

    onNewTimeSheetSubmit() {
      alert(JSON.stringify(this.mytimesheetform.value));
    }
}


text:
/* note:
   This version of iUI has a partial implementation of the `busy` flag for Issue #191,
   it will not work with webapps that call `iui.showPage()` or `iui.showPageByHref()` directly.
   This issue will be resolved in a later version. */

(function() {

var slideSpeed = 20;
var slideInterval = 0;
var ajaxTimeoutVal = 30000;

var currentPage = null;
var currentDialog = null;
var currentWidth = 0;
var currentHeight = 0;
var currentHash = location.hash;
var hashPrefix = "#_";
var pageHistory = [];
var newPageCount = 0;
var checkTimer;
var hasOrientationEvent = false;
var portraitVal = "portrait";
var landscapeVal = "landscape";

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

/*
events:
iUI fires a number of custom events on your panel and dialog elements. Handling
these events is the recommended way to do any just-in-time transformations or
loading (besides the ajax pre-loading built into iUI).
*/

window.iui =
{
	/*
	property: iui.busy
	This is set to `true` if a slide animation is in progress.
	*/
	busy: false,

	/*
	property: iui.animOn
	Determines whether to do horizontal slide animations with CSS transitions
	(http://www.w3.org/TR/css3-2d-transforms/) where supported (defaults	to
	`true`). Otherwise, manual `setInterval()` style animations are performed
	(vertical slide animations are always done manually).
	*/
	animOn: true,

	/*
	property: iui.ajaxErrHandler
	If defined, this user-set function will be called when an AJAX call returns
	with an HTTP status other than `200` (currently all HTTP statuses other than
	`200`, even including 200-level statuses like `201 Created`, are seen as
	errors.  A status of `0` is treated as success for file:// URLs).
	*/
	ajaxErrHandler : null,

	/*
	property: iui.httpHeaders
	An object defining headers to be sent with Ajax requests. This defaults to:

	example:
	  { 'X-Requested-With': 'XMLHttpRequest' }
	*/
	httpHeaders: {
	    "X-Requested-With" : "XMLHttpRequest"
	},

	/*
	method: iui.showPage(page[, backwards=false])
	`showPage()` should probably be an internal function, outside callers should
	call `showPageById()` instead. `showPage()` doesn't set the busy flag because
	it is already set by the public-facing functions.

	`page` is the html element to show. If `backwards` is set to `true`, it will
	display a right-to-left animation instead of the default left-to-right.

	If the currently-displayed page is passed, iui will do nothing. `showPage()`
	is used for both panel-type pages and dialog-type pages (dialogs float on top
	of the panels, have a cancel button and do not participate in sliding
	animations). Panel-type pages receive blur/focus events and load/unload events,
	but dialog-type pages only receive blur/focus events.
	*/
	showPage: function(page, backwards)
	{
		if (page)
		{
//			if (window.iui_ext)	window.iui_ext.injectEventMethods(page);	// TG -- why was this comment left here??
			if (page == currentPage)
			{
				console.log("page = currentPage = " + page.id);
				iui.busy = false;	//  Don't do anything, just clear the busy flag and exit
				return;
			}

			if (currentDialog)
			{
				currentDialog.removeAttribute("selected");
				sendEvent("blur", currentDialog);					// EVENT: BLUR
				currentDialog = null;
			}

			/*
			events:
			Dialogs receive a `focus` event when they are shown and a `blur` event
			when hidden. Currently they don't receive any `load` or `unload` events.
			*/
			if (hasClass(page, "dialog"))
			{
				iui.busy = false;	// There's no slide transition, so clear busy flag
				// There's no LOAD/UNLOAD events for dialogs -- is that the way it should be??
				// Should the view the dialog is going over get a BLUR??
				sendEvent("focus", page);							// EVENT: FOCUS
				showDialog(page);
			}
			/*
			events:
			Panels receive `focus` and `blur` events and also receive a `load` event
			and (only when going backwards away from a panel) an `unload` event.
			*/
			else
			{
				sendEvent("load", page);    						// EVENT: LOAD
													// 127(stylesheet), 128(script), 129(onload)
													// 130(onFocus), 133(loadActionButton)
				var fromPage = currentPage;
				sendEvent("blur", currentPage);						// EVENT: BLUR
				currentPage = page;
				sendEvent("focus", page);							// EVENT: FOCUS

				if (fromPage)
				{
					setTimeout(slidePages, 0, fromPage, page, backwards);
				}
				else
				{
					updatePage(page, fromPage);
				}

			}
		}
	},

	/*
	method: iui.showPageById(pageId)
	Looks up the page element by the id and checks the internal history to
	determine if the page is on the stack -- if so, it will call `showPage()` with
	`backwards` set to `true`, reversing the direction of the animation.
	*/
	showPageById: function(pageId)
	{
		var page = $(pageId);
		if (page)
		{
			if (!iui.busy)
			{
				iui.busy = true;
				var index = pageHistory.indexOf(pageId);
				var backwards = index != -1;
				if (backwards)
				{
					// we're going back, remove history from index on
					// remember - pageId will be added again in updatePage
					pageHistory.splice(index);
				}

				iui.showPage(page, backwards);
			}
		}
	},

	/*
	method: iui.goBack()
	Navigates to the previous page in the history stack.
	*/
	goBack: function()
	{
		if (!iui.busy)
		{
			iui.busy = true;
			pageHistory.pop();	// pop current page
			var pageID = pageHistory.pop();  // pop/get parent
			var page = $(pageID);
			iui.showPage(page, true);
		}
	},

	/*
	method: iui.replacePage(pageId)
	Loads a new page at the same level in the history stack.
	Currently it will do a slide-in animation, but replaces
	the current page in the navStack.
	It should probably use a different animation (slide-up/slide-down).
	*/
	replacePage: function(pageId)
	{
		// Should probably take either an ID or an Element
		var page = $(pageId);
		if (page)
		{
			if (!iui.busy)
			{
				iui.busy = true;
				var index = pageHistory.indexOf(pageId);
				var backwards = index != -1;
				if (backwards)	// we're going back, shouldn't happen on replacePage()
					console.log("error: can't replace page with ancestor");

				pageHistory.pop();

				iui.showPage(page, false);
			}
		}
	},

	/*
	method: iui.showPageByHrefExt(href, args, method, replace, cb)
	Outside callers should use this version to do an ajax load programmatically
	from your webapp. In a future version, this will be renamed to
	`showPageByHref()` (once the old method and  all its calls are renamed).

	`href` is a URL string, `method` is the HTTP method (defaults to `GET`),
	`args` is an Object of key-value pairs that are used to generate the querystring,
	`replace` is an existing element that either is the panel or is a child of the
	panel that the incoming HTML will replace (if not supplied, iUI will append
	the incoming HTML to the `body`), and `cb` is a user-supplied callback function.
	*/
	showPageByHrefExt: function(href, args, method, replace, cb)
	{
		if (!iui.busy)
		{
			iui.busy = true;
			iui.showPageByHref(href, args, method, replace, cb);
		}
	},

	/*
	method: iui.showPageByHref(href, args, method, replace, cb)
	This one should only be used by iUI internally.  It should be renamed and
	possibly moved into the closure.
	*/
	showPageByHref: function(href, args, method, replace, cb)
	{
	  // I don't think we need onerror, because readstate will still go to 4 in that case
		function spbhCB(xhr)
		{
			console.log("xhr.readyState = " + xhr.readyState);
			if (xhr.readyState == 4)
			{
				if ((xhr.status == 200 || xhr.status == 0) && !xhr.aborted)
				{
				  // Add 'if (xhr.responseText)' to make sure we have something???
				  // Can't use createDocumentFragment() here because firstChild is null and childNodes is empty
				  var frag = document.createElement("div");
				  frag.innerHTML = xhr.responseText;
				  // EVENT beforeInsert->body
					/*
					events:
					When new pages are inserted into the DOM after an AJAX load, the `body`
					element receives a `beforeinsert` event with `{ fragment: frag }` parameters
					and afterwards receives an `afterinsert` event with `{insertedNode: docNode}` parameters.
					*/
				  sendEvent("beforeinsert", document.body, {fragment:frag})
				  if (replace)
				  {
					  replaceElementWithFrag(replace, frag);
					  iui.busy = false;
				  }
				  else
				  {
					  iui.insertPages(frag);
				  }
				}
				else
				{
					iui.busy = false;
					if (iui.ajaxErrHandler)
					{
						iui.ajaxErrHandler("Error contacting server, please try again later");
					}
				}
				if (cb)
				{
					setTimeout(cb, 1000, true);
				}
			}

		};
	  iui.ajax(href, args, method, spbhCB);
	},

	/*
	method: iui.ajax(url, args, method, cb)
	Handles ajax requests and also fires a `setTimeout()` call
	to abort the request if it takes longer than 30 seconds. See `showPageByHrefExt()`
	above for a description of the various arguments (`url` is the same as `href`).
	*/
	ajax: function(url, args, method, cb)
	{
        var xhr = new XMLHttpRequest();
        method = method ? method.toUpperCase() : "GET";
        if (args && method == "GET")
        {
          url =  url + "?" + iui.param(args);
        }
        xhr.open(method, url, true);
        if (cb)
        {
			xhr.onreadystatechange = function() { cb(xhr); };
        }
        var data = null;
        if (args && method != "GET")
        {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            data = iui.param(args);
        }
        for (var header in iui.httpHeaders)
        {
            xhr.setRequestHeader(header, iui.httpHeaders[header]);
        }
        xhr.send(data);
        xhr.requestTimer = setTimeout( ajaxTimeout, ajaxTimeoutVal );
		return xhr;
        function ajaxTimeout()
        {
			try{
		 		xhr.abort();
		   		xhr.aborted = true;
			}
		   	catch(err){
				console.log(err);
		 	}
		}
	},

	/*
	method: iui.param(o)
	Stripped-down, simplified object-only version of a jQuery function that
	converts an object of keys/values into a URL-encoded querystring.
	*/
	param: function( o )
	{
	  var s = [ ];

	  // Serialize the key/values
	  for ( var key in o )
		s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(o[key]);

	  // Return the resulting serialization
	  return s.join("&").replace(/%20/g, "+");
	},

	/*
	method: iui.insertPages(frag)
	If an AJAX call (`showPageByHref()`) is made without supplying a `replace`
	element, `insertPages()` is called to insert the newly-created element
	fragment into the page DOM. Each child-node of the HTML fragment is a panel
	and if any of them are already in the DOM, they will be replaced by the
	incoming elements.
	*/
	insertPages: function(frag)
	{
		var nodes = frag.childNodes;
		var targetPage;
		for (var i = 0; i < nodes.length; ++i)
		{
			var child = nodes[i];
			if (child.nodeType == 1)
			{
				if (!child.id)
					child.id = "__" + (++newPageCount) + "__";

				var clone = $(child.id);
				var docNode;
				if (clone) {
					clone.parentNode.replaceChild(child, clone);
				    docNode = $(child.id);
			    }
				else
					docNode = document.body.appendChild(child);

				sendEvent("afterinsert", document.body, {insertedNode:docNode});

				// First child becomes selected page/view by default unless
				// selected="true" is set
				// BUG: selected="true" results in a visually incorrect transition
				if (child.getAttribute("selected") == "true" || !targetPage)
					targetPage = child;

				--i;
			}
		}
		sendEvent("afterinsertend", document.body, {fragment:frag})

		if (targetPage)
			iui.showPage(targetPage);

	},

	/*
	method: iui.getSelectedPage()
	Returns the panel element that is currently being viewed. Each panel must be a
	direct child of the `body` element. A panel is set as the selected panel by
	setting the `selected` attribute to `true`.
	*/
	getSelectedPage: function()
	{
		for (var child = document.body.firstChild; child; child = child.nextSibling)
		{
			if (child.nodeType == 1 && child.getAttribute("selected") == "true")
				return child;
		}
	},

	/*
	method: iui.getAllViews()
	Returns all panels -- currently requires querySelectorAll() will be fixed
	*/
	getAllViews: function()
	{
		return document.querySelectorAll("body > *:not(.toolbar)");
	},

	/*
	method: iui.isNativeUrl(href)
	Determines whether the supplied URL string launches a native iPhone app (maps,
	YouTube, phone, email, etc). If so, iUI does nothing (doesn't attempt to load
	a page or slide to it) and allows the phone to handle it the click natively.
	*/
	isNativeUrl: function(href)
	{
		for(var i = 0; i < iui.nativeUrlPatterns.length; i++)
		{
			if(href.match(iui.nativeUrlPatterns[i])) return true;
		}
		return false;
	},
	nativeUrlPatterns: [
		new RegExp("^http:\/\/maps.google.com\/maps\?"),
		new RegExp("^mailto:"),
		new RegExp("^tel:"),
		new RegExp("^http:\/\/www.youtube.com\/watch\\?v="),
		new RegExp("^http:\/\/www.youtube.com\/v\/"),
		new RegExp("^javascript:"),

	],
	/*
	method: iui.hasClass(self, name)
	Convenience function to determine if the given element (`self`) has the
	class `name`.
	*/
	hasClass: function(self, name)
	{
		var re = new RegExp("(^|\\s)"+name+"($|\\s)");
		return re.exec(self.getAttribute("class")) != null;
	},

	/*
	method: iui.addClass(self, name)
	Convenience function to add the given class `name` to element `self`.
	*/
	addClass: function(self, name)
	{
	  if (!iui.hasClass(self,name)) self.className += " "+name;
	},

	/*
	method: iui.removeClass(self, name)
	Convenience function to remove the given class `name` to element `self`.
	*/
	removeClass: function(self, name)
	{
	  if (iui.hasClass(self,name)) {
		  var reg = new RegExp('(\\s|^)'+name+'(\\s|$)');
		self.className=self.className.replace(reg,' ');
	  }
	}
};

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

/*
load: On Load
On load, iUI will determine which page to display primarily based on
the anchor part of the URL (everything after `#_`) and secondarily based on the
top-level (child of the `body`) element with the `selected` attribute set to
`true`. If these both exist, iui.showPage() will be called twice, but the
anchor-based load will win because it is done second.
*/
addEventListener("load", function(event)
{
	var page = iui.getSelectedPage();
	var locPage = getPageFromLoc();

	if (page)
			iui.showPage(page);

	if (locPage && (locPage != page))
		iui.showPage(locPage);

	setTimeout(preloadImages, 0);
	if (typeof window.onorientationchange == "object")
	{
		window.onorientationchange=orientChangeHandler;
		hasOrientationEvent = true;
		setTimeout(orientChangeHandler, 0);
	}
	setTimeout(checkOrientAndLocation, 0);
	checkTimer = setInterval(checkOrientAndLocation, 300);
}, false);

addEventListener("unload", function(event)
{
	return;
}, false);

/*
click: Link Click Handling
iUI captures all clicks on `a` elements and goes through a series of checks to
determine what to do:

1. If the link has a `href="#..."`, iUI will navigate to the panel ID specified
   after the # (no underscore).
2. If the link's ID is `backButton`, iUI will navigate to the previous screen
   (see `iui.goBack()`).
3. If the link has a `type="submit"`, iUI will find the parent `form` element,
   gather up all the input values and submit the form via AJAX (see
   `iui.showPageByHref()`).
4. If the link has a `type="cancel"`, iUI will cancel the parent `form` element
   dialog.
5. If the link has a `target="_replace"`, iUI will do an AJAX call based on the
   href of the link and replace the panel that the link is in with the contents
   of the AJAX response.
6. If the link is a native URL (see `iui.isNativeURL()`), iUI will do nothing.
7. If the link has a `target="_webapp"`, iUI will perform a normal link,
   navigating completely away from the iUI app and pointing the browser to the
   linked-to webapp instead.
8. If there is no `target` attribute, iUI will perform a normal (non-replace)
   AJAX slide (see `iui.showPageByHref()`).
*/
addEventListener("click", function(event)
{
	var link = findParent(event.target, "a");
	if (link)
	{
		function unselect() { link.removeAttribute("selected"); }
		if (link.href && link.hash && link.hash != "#" && !link.target)
		{
			followAnchor(link);
		}
		else if (link == $("backButton"))
		{
			iui.goBack();
		}
		else if (link.getAttribute("type") == "submit")
		{
			var form = findParent(link, "form");
			if (form.target == "_self")
			{
				// Note: this will not call any onsubmit handlers!
			    form.submit();
			    return;  // allow default
			}
			submitForm(form);
		}
		else if (link.getAttribute("type") == "cancel")
		{
			cancelDialog(findParent(link, "form"));
		}
		else if (link.target == "_replace")
		{
			followAjax(link, link);
		}
		else if (iui.isNativeUrl(link.href))
		{
			return;
		}
		else if (link.target == "_webapp")
		{
			location.href = link.href;
		}
		else if (!link.target && link.href)
		{
			followAjax(link, null);
		}
		else
			return;

		event.preventDefault();
	}
}, true);

/*
click: Div.toggle Click Handling
iUI also captures `div.toggle` clicks and displays/hides the element via setting
a `toggled` attribute to true/false.
*/
addEventListener("click", function(event)
{
	var div = findParent(event.target, "div");
	if (div && hasClass(div, "toggle"))
	{
		div.setAttribute("toggled", div.getAttribute("toggled") != "true");
		event.preventDefault();
	}
}, true);

function followAnchor(link)
{
	function unselect() { link.removeAttribute("selected"); }

	if (!iui.busy)
	{
		iui.busy = true;
		link.setAttribute("selected", "true");
		// We need to check for backlinks here like in showPageID()
		// That backlink functionality needs to be in here somewhere
		iui.showPage($(link.hash.substr(1)));
		setTimeout(unselect, 500);
	}
}

function followAjax(link, replaceLink)
{
	function unselect() { link.removeAttribute("selected"); }

	if (!iui.busy)
	{
		iui.busy = true;
		link.setAttribute("selected", "progress");
		iui.showPageByHref(link.href, null, "GET", replaceLink, unselect);
	}
}

function sendEvent(type, node, props)
{
    if (node)
    {
        var event = document.createEvent("UIEvent");
        event.initEvent(type, false, false);  // no bubble, no cancel
        if (props)
        {
            for (i in props)
            {
                event[i] = props[i];
            }
        }
        node.dispatchEvent(event);
    }
}

function getPageFromLoc()
{
	var page;
	var result = location.hash.match(/#_([^\?_]+)/);
	if (result)
		page = result[1];
	if (page)
		page = $(page);
	return page;
}

function orientChangeHandler()
{
	var orientation=window.orientation;
	switch(orientation)
	{
	case 0:
		setOrientation(portraitVal);
		break;

	case 90:
	case -90:
		setOrientation(landscapeVal);
		break;
	}
}

function checkOrientAndLocation()
{
	if (!hasOrientationEvent)
	{
	  if ((window.innerWidth != currentWidth) || (window.innerHeight != currentHeight))
	  {
		  currentWidth = window.innerWidth;
		  currentHeight = window.innerHeight;
		  var orient = (currentWidth < currentHeight) ? portraitVal : landscapeVal;
		  setOrientation(orient);
	  }
	}

	if (location.hash != currentHash)
	{
		var pageId = location.hash.substr(hashPrefix.length);
		iui.showPageById(pageId);
	}
}

function setOrientation(orient)
{
	document.body.setAttribute("orient", orient);
//  Set class in addition to orient attribute:
	if (orient == portraitVal)
	{
		iui.removeClass(document.body, landscapeVal);
		iui.addClass(document.body, portraitVal);
	}
	else if (orient == landscapeVal)
	{
		iui.removeClass(document.body, portraitVal);
		iui.addClass(document.body, landscapeVal);
	}
	else
	{
		iui.removeClass(document.body, portraitVal);
		iui.removeClass(document.body, landscapeVal);
	}
	setTimeout(scrollTo, 100, 0, 1);
}

function showDialog(page)
{
	currentDialog = page;
	page.setAttribute("selected", "true");

	if (hasClass(page, "dialog"))
		showForm(page);
}

function showForm(form)
{
	form.onsubmit = function(event)
	{
//  submitForm and preventDefault are called in the click handler
//  when the user clicks the submit a.button
//
		event.preventDefault();
		submitForm(form);
	};

	form.onclick = function(event)
	{
// Why is this code needed?  cancelDialog is called from
// the click hander.  When will this be called?
		if (event.target == form && hasClass(form, "dialog"))
			cancelDialog(form);
	};
}

function cancelDialog(form)
{
	form.removeAttribute("selected");
}

function updatePage(page, fromPage)
{
	if (!page.id)
		page.id = "__" + (++newPageCount) + "__";

	location.hash = currentHash = hashPrefix + page.id;
	pageHistory.push(page.id);

	var pageTitle = $("pageTitle");
	if (page.title)
		pageTitle.innerHTML = page.title;
	var ttlClass = page.getAttribute("ttlclass");
	pageTitle.className = ttlClass ? ttlClass : "";

	if (page.localName.toLowerCase() == "form" && !page.target)
		showForm(page);

	var backButton = $("backButton");
	if (backButton)
	{
		var prevPage = $(pageHistory[pageHistory.length-2]);
		if (prevPage && !page.getAttribute("hideBackButton"))
		{
			backButton.style.display = "inline";
			backButton.innerHTML = prevPage.title ? prevPage.title : "Back";
			var bbClass = prevPage.getAttribute("bbclass");
			backButton.className = (bbClass) ? 'button ' + bbClass : 'button';
		}
		else
			backButton.style.display = "none";
	}
	iui.busy = false;
}
/*
events:
Both panels involved in a slide animation receive `beforetransition` and
`aftertransition` events. The panel being navigated from receives event
parameters `{ out :true }`, the panel being navigated to receives `{ out: false }`.
*/
function slidePages(fromPage, toPage, backwards)
{
	var axis = (backwards ? fromPage : toPage).getAttribute("axis");

	clearInterval(checkTimer);

	sendEvent("beforetransition", fromPage, {out:true});
	sendEvent("beforetransition", toPage, {out:false});
	if (canDoSlideAnim() && axis != 'y')
	{
	  slide2(fromPage, toPage, backwards, slideDone);
	}
	else
	{
	  slide1(fromPage, toPage, backwards, axis, slideDone);
	}

	function slideDone()
	{
	  if (!hasClass(toPage, "dialog"))
		  fromPage.removeAttribute("selected");
	  checkTimer = setInterval(checkOrientAndLocation, 300);
	  setTimeout(updatePage, 0, toPage, fromPage);
	  fromPage.removeEventListener('webkitTransitionEnd', slideDone, false);
	  sendEvent("aftertransition", fromPage, {out:true});
      sendEvent("aftertransition", toPage, {out:false});
	  if (backwards) sendEvent("unload", fromPage);	// EVENT: UNLOAD
	}
}

function canDoSlideAnim()
{
  return (iui.animOn) && (typeof WebKitCSSMatrix == "object");
}

function slide1(fromPage, toPage, backwards, axis, cb)
{
	if (axis == "y")
		(backwards ? fromPage : toPage).style.top = "100%";
	else
		toPage.style.left = "100%";

	scrollTo(0, 1);
	toPage.setAttribute("selected", "true");
	var percent = 100;
	slide();
	var timer = setInterval(slide, slideInterval);

	function slide()
	{
		percent -= slideSpeed;
		if (percent <= 0)
		{
			percent = 0;
			clearInterval(timer);
			cb();
		}

		if (axis == "y")
		{
			backwards
				? fromPage.style.top = (100-percent) + "%"
				: toPage.style.top = percent + "%";
		}
		else
		{
			fromPage.style.left = (backwards ? (100-percent) : (percent-100)) + "%";
			toPage.style.left = (backwards ? -percent : percent) + "%";
		}
	}
}

function slide2(fromPage, toPage, backwards, cb)
{
	toPage.style.webkitTransitionDuration = '0ms'; // Turn off transitions to set toPage start offset
	// fromStart is always 0% and toEnd is always 0%
	// iPhone won't take % width on toPage
	var toStart = 'translateX(' + (backwards ? '-' : '') + window.innerWidth +	'px)';
	var fromEnd = 'translateX(' + (backwards ? '100%' : '-100%') + ')';
	toPage.style.webkitTransform = toStart;
	toPage.setAttribute("selected", "true");
	toPage.style.webkitTransitionDuration = '';	  // Turn transitions back on
	function startTrans()
	{
		fromPage.style.webkitTransform = fromEnd;
		toPage.style.webkitTransform = 'translateX(0%)'; //toEnd
	}
	fromPage.addEventListener('webkitTransitionEnd', cb, false);
	setTimeout(startTrans, 0);
}

function preloadImages()
{
	var preloader = document.createElement("div");
	preloader.id = "preloader";
	document.body.appendChild(preloader);
}

function submitForm(form)
{
 	if (!iui.busy)
	{
		iui.busy = true;
		iui.addClass(form, "progress");
		iui.showPageByHref(form.action, encodeForm(form), form.method || "GET", null, clear);
	}
    function clear() {   iui.removeClass(form, "progress"); }
}

function encodeForm(form)
{
	function encode(inputs)
	{
		for (var i = 0; i < inputs.length; ++i)
		{
	        if (inputs[i].name)
		        args[inputs[i].name] = inputs[i].value;
		}
	}

    var args = {};
    encode(form.getElementsByTagName("input"));
    encode(form.getElementsByTagName("textarea"));
    encode(form.getElementsByTagName("select"));
    encode(form.getElementsByTagName("button"));
    return args;
}

function findParent(node, localName)
{
	while (node && (node.nodeType != 1 || node.localName.toLowerCase() != localName))
		node = node.parentNode;
	return node;
}

function hasClass(self, name)
{
	return iui.hasClass(self,name);
}

function replaceElementWithFrag(replace, frag)
{
	var page = replace.parentNode;
	var parent = replace;
	while (page.parentNode != document.body)
	{
		page = page.parentNode;
		parent = parent.parentNode;
	}
	page.removeChild(parent);

    var docNode;
	while (frag.firstChild) {
		docNode = page.appendChild(frag.firstChild);
		sendEvent("afterinsert", document.body, {insertedNode:docNode});
    }
	sendEvent("afterinsertend", document.body, {fragment:frag})
}

function $(id) { return document.getElementById(id); }
function ddd() { console.log.apply(console, arguments); }

})();


text:
/**
 *

 *    A cc.SpriteFrame has:

 *      - texture: A cc.Texture2D that will be used by the cc.Sprite

 *      - rectangle: A rectangle of the texture

 *

 *    You can modify the frame of a cc.Sprite by doing:

 *

 * @class
 * @extends cc.Class
 *
 * @example
 * var texture = cc.TextureCache.getInstance().addImage(s_dragon_animation);
 * var frame0 = cc.SpriteFrame.createWithTexture(texture, cc.rect(132 * 0, 132 * 0, 132, 132));
 */
cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
    _offset:null,
    _originalSize:null,
    _rectInPixels:null,
    _rotated:null,
    _rect:null,
    _offsetInPixels:null,
    _originalSizeInPixels:null,
    _texture:null,
    _textureFilename:"",

    ctor:function () {
        this._offset = cc.p(0, 0);
        this._offsetInPixels = cc.p(0, 0);
        this._originalSize = cc.size(0, 0);
        this._rectInPixels = cc.rect(0, 0, 0, 0);
        this._rect = cc.rect(0, 0, 0, 0);
        this._originalSizeInPixels = cc.size(0, 0);
        this._textureFilename = "";
    },

    // attributes
    /**
     * @return {cc.Rect}
     */
    getRectInPixels:function () {
        return this._rectInPixels;
    },

    /**
     * @param {cc.Rect} rectInPixels
     */
    setRectInPixels:function (rectInPixels) {
        this._rectInPixels = rectInPixels;
        this._rect = cc.RECT_PIXELS_TO_POINTS(rectInPixels);
    },

    /**
     *

     *     return is rotated of SpriteFrame.

     *

     * @return {Boolean}
     */
    isRotated:function () {
        return this._rotated;
    },

    /**
     * set SpriteFrame is rotated
     * @param {Boolean} bRotated
     */
    setRotated:function (bRotated) {
        this._rotated = bRotated;
    },

    /**
     * get rect of the frame
     * @return {cc.Rect}
     */
    getRect:function () {
        return this._rect;
    },

    /**
     * set rect of the frame
     * @param {cc.Rect} rect
     */
    setRect:function (rect) {
        this._rect = rect;
        this._rectInPixels = cc.RECT_POINTS_TO_PIXELS(this._rect);
    },

    /**
     * get offset of the frame
     * @return {cc.Point}
     */
    getOffsetInPixels:function () {
        return cc.p(this._offsetInPixels.x, this._offsetInPixels.y);
    },

    /**
     * set offset of the frame
     * @param {cc.Point} offsetInPixels
     */
    setOffsetInPixels:function (offsetInPixels) {
        this._offsetInPixels = offsetInPixels;
        this._offset = cc.POINT_PIXELS_TO_POINTS(this._offsetInPixels);
    },

    /**
     * get original size of the trimmed image
     * @return {cc.Size}
     */
    getOriginalSizeInPixels:function () {
        return this._originalSizeInPixels;
    },

    /**
     * set original size of the trimmed image
     * @param {cc.Size} sizeInPixels
     */
    setOriginalSizeInPixels:function (sizeInPixels) {
        this._originalSizeInPixels = sizeInPixels;
    },

    /**
     * get original size of the trimmed image
     * @return {cc.Size}
     */
    getOriginalSize:function () {
        return cc.size(this._originalSize.width, this._originalSize.height);
    },

    /**
     * set original size of the trimmed image
     * @param {cc.Size} sizeInPixels
     */
    setOriginalSize:function (sizeInPixels) {
        this._originalSize = sizeInPixels;
    },

    /**
     * get texture of the frame
     * @return {cc.Texture2D|HTMLImageElement}
     */
    getTexture:function () {
        if (this._texture)
            return this._texture;
        if (this._textureFilename !== "")
            return cc.TextureCache.getInstance().addImage(this._textureFilename);
        return null;
    },

    /**
     * set texture of the frame, the texture is retained
     * @param {cc.Texture2D|HTMLImageElement} texture
     */
    setTexture:function (texture) {
        if (this._texture != texture) {
            this._texture = texture;
        }
    },

    /**
     * Offset getter
     * @return {cc.Point}
     */
    getOffset:function () {
        return cc.p(this._offset.x, this._offset.y);
    },

    /**
     * offset setter
     * @param {cc.Point} offsets
     */
    setOffset:function (offsets) {
        this._offset = offsets;
    },

    /**
     * copy a new SpriteFrame
     * @return {cc.SpriteFrame}
     */
    copyWithZone:function () {
        var copy = new cc.SpriteFrame();
        copy.initWithTextureFilename(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels);
        copy.setTexture(this._texture);
        return copy;
    },

    copy:function () {
        return this.copyWithZone();
    },

    /**
     * Initializes SpriteFrame with Texture, rect, rotated, offset and originalSize in pixels.
     * @param {cc.Texture2D|HTMLImageElement} texture
     * @param {cc.Rect} rect
     * @param {Boolean} rotated
     * @param {cc.Point} offset
     * @param {cc.Size} originalSize
     * @return {Boolean}
     */
    initWithTexture:function (texture, rect, rotated, offset, originalSize) {
        var argnum = arguments.length;
        switch (argnum) {
        /** Initializes a cc.SpriteFrame with a texture, rect in points.
         It is assumed that the frame was not trimmed.
         */
            case 2:
                var rectInPixels = cc.RECT_POINTS_TO_PIXELS(rect);
                return this.initWithTexture(texture, rectInPixels, false, cc.PointZero(), rectInPixels.size);
                break;

        /** Initializes a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
         The originalSize is the size in points of the frame before being trimmed.
         */
            case 5:
                this._texture = texture;
                this._rectInPixels = rect;
                this._rect = cc.RECT_PIXELS_TO_POINTS(rect);
                this._offsetInPixels = offset;
                this._offset = cc.POINT_PIXELS_TO_POINTS(this._offsetInPixels);
                this._originalSizeInPixels = originalSize;
                this._originalSize = cc.SIZE_PIXELS_TO_POINTS(this._originalSizeInPixels);
                this._rotated = rotated;
                return true;
                break;
            default:
                throw "Argument must be non-nil ";
                break;
        }
    },

    /**
     *

     *    Initializes a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.

     *    The originalSize is the size in pixels of the frame before being trimmed.
     *

     * @param {string} filename
     * @param {cc.Rect} rect
     * @param {Boolean} rotated
     * @param {cc.Point} offset
     * @param {cc.Size} originalSize
     */
    initWithTextureFilename:function (filename, rect, rotated, offset, originalSize) {
        var rectInPixels = cc.RECT_POINTS_TO_PIXELS(rect);
        offset = offset || cc.size(0, 0);
        originalSize = originalSize || rectInPixels.size;

        this._texture = null;
        this._textureFilename = filename;
        this._rectInPixels = rectInPixels;
        this._rect = cc.RECT_PIXELS_TO_POINTS(rectInPixels);
        this._rotated = rotated || false;
        this._offsetInPixels = offset;
        this._offset = cc.POINT_PIXELS_TO_POINTS(offset);
        this._originalSizeInPixels = originalSize;
        this._originalSize = cc.SIZE_PIXELS_TO_POINTS(originalSize);

        return true;
    }
});

/**
 *

 *    Create a cc.SpriteFrame with a texture filename, rect, rotated, offset and originalSize in pixels.

 *    The originalSize is the size in pixels of the frame before being trimmed.
 *

 * @param {string} filename
 * @param {cc.Rect} rect
 * @param {Boolean} rotated
 * @param {cc.Point} offset
 * @param {cc.Size} originalSize
 * @return {cc.SpriteFrame}
 */
cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) {
    var spriteFrame = new cc.SpriteFrame();
    switch (arguments.length) {
        case 2:
            spriteFrame.initWithTextureFilename(filename, rect);
            break;
        case 5:
            spriteFrame.initWithTextureFilename(filename, rect, rotated, offset, originalSize);
            break;
        default:
            throw "Argument must be non-nil ";
            break;
    }
    return spriteFrame;
};

/**
 * Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
 * @param {cc.Texture2D|HTMLImageElement} texture
 * @param {cc.Rect} rect
 * @param {Boolean} rotated
 * @param {cc.Point} offset
 * @param {cc.Size} originalSize
 * @return {cc.SpriteFrame}
 * @example
 * //Create a cc.SpriteFrame with a texture, rect in texture.
 * var frame1 = cc.SpriteFrame.createWithTexture("grossini_dance.png",cc.rect(0,0,90,128));
 *
 * //Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
 * var frame2 = cc.SpriteFrame.createWithTexture(texture, frameRect, rotated, offset, sourceSize);
 */
cc.SpriteFrame.createWithTexture = function (texture, rect, rotated, offset, originalSize) {
    var argnum = arguments.length;
    var spriteFrame = new cc.SpriteFrame();
    switch (argnum) {
    /** Create a cc.SpriteFrame with a texture, rect in points.
     It is assumed that the frame was not trimmed.
     */
        case 2:
            spriteFrame.initWithTexture(texture, rect);
            break;
    /** Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
     The originalSize is the size in points of the frame before being trimmed.
     */
        case 5:
            spriteFrame.initWithTexture(texture, rect, rotated, offset, originalSize);
            break;
        default:
            throw "Argument must be non-nil ";
            break;
    }
    return spriteFrame;
};

cc.SpriteFrame._frameWithTextureForCanvas = function (texture, rect, rotated, offset, originalSize) {
    var spriteFrame = new cc.SpriteFrame();
    spriteFrame._texture = texture;
    spriteFrame._rectInPixels = rect;
    spriteFrame._rect = cc.RECT_PIXELS_TO_POINTS(rect);
    spriteFrame._offsetInPixels = offset;
    spriteFrame._offset = cc.POINT_PIXELS_TO_POINTS(spriteFrame._offsetInPixels);
    spriteFrame._originalSizeInPixels = originalSize;
    spriteFrame._originalSize = cc.SIZE_PIXELS_TO_POINTS(spriteFrame._originalSizeInPixels);
    spriteFrame._rotated = rotated;
    return spriteFrame;
};


text:
<!doctype html>

		<meta charset="utf-8">

		<title>Desenvolvendo serviços web com Redstone.dart</title>

		<meta name="description" content="A framework for easily creating beautiful presentations using HTML">
		<meta name="author" content="Hakim El Hattab">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/simple.css" id="theme">

		<link rel="stylesheet" href="lib/css/googlecode.css">

Desenvolvendo serviços web com Redstone.dart

						Luiz Henrique Farcic Mineo / @lhfmineo

O que é Dart?

Plataforma para desenvolvimento de aplicações web

100% open source (BSD)

Pode ser executada no navegador web e no servidor

Como Dart funciona?

dart2js: Compila código Dart para Javascript

							DartVM: Permite a execução de código Dart no servidor

Oferece APIs para acesso a recursos do sistema operacional

Por que usar Dart para criar serviços web?

							Produtividade

Dart é uma linguagem moderna e flexível

							Desempenho

A DartVM possui um desempenho competitivo

							Suporte

Dart possui uma incrível e ativa comunidade

							Integração

Compartilhe código com sua aplicação cliente

A linguagem Dart

Tipagem opcional

//tipos não são obrigatórios
var resposta = 42;

//mas podem ser usados quando desejado
int resposta = 42;

Orientada a objetos, com suporte a classes

class Pessoa {

  String nome;
  int idade;
  String endereco;

  Pessoa([this.nome, this.idade, this.endereco]);
}

var pessoa = new Pessoa("José", 35);

A linguagem Dart

Programação assíncrona, com fila de eventos

Suporte nativo ao promise pattern

Future future = operacaoAssincrona();
future..then((resp) => print(resp))
      ..catchError((e) => print("erro: $e"));

A linguagem Dart

Parâmetros opcionais (posicionais e nomeados)

Herança múltipla com mixins

Getters e setters implícitos

Interface implícita

Funções como objetos de primeira classe

Módulos

Metadados

O que é Redstone.dart?

Framework para criação de serviços web

Motivação: lidar com o protocolo HTTP diretamente é chato e cansativo

import 'dart:io';

void main() {
  HttpServer.bind('0.0.0.0', 8080).then((server) {
    server.listen((HttpRequest request) {
      request.response
        ..headers.contentType =
             new ContentType("text", "plain", charset: "utf-8")
        ..write('Olá, mundo!')
        ..close();
    });
  });
}

O que é Redstone.dart?

Redstone usa metadados para definir serviços

import 'package:redstone/server.dart' as app;

@app.Route("/")
olaMundo() => "Olá, mundo!";

main() {
  app.start();
}

Inspiração: Flask framework (Python)

Criando serviços

//Ex.: http://localhost:8080/ola/luiz
@app.Route("/ola/:usuario")
olaUsuario(String usuario) => "Olá, $usuario";

//Ex.: http://localhost:8080/usuario?id=1234
@app.Route("/usuario")
buscaUsuario(@app.QueryParam("id") int id) {
  ...
};

//Suporte a JSON
@app.Route("/usuario", methods: const [app.POST])
salvaUsuario(@app.Body(app.JSON) Map json) {
  ...
};

//Suporte ao objeto Future
@app.Route("/usuario/:id")
Future<Map> buscaUsuario(int id) =>
  database.find(id);

Interceptadores

Podem ser usados para aplicar um comportamento comum a um conjunto de serviços

Similares aos filtros do JEE, porém com uma API assíncrona

Exemplo: configuração do cabeçalho de resposta

@app.Interceptor(r'/.*')
handleResponseHeader() {

  app.chain.next(()
    => app.response.change(headers:
       {"Access-Control-Allow-Origin": "*"}));

}

Tratadores de erro

Erros são interceptados através do código HTTP

@app.ErrorHandler(404)
recursoNaoEncontrado() => app.redirect("/error/not_found.html");

Se um serviço lança uma exceção, o código 500 é associado a requisição

@app.ErrorHandler(500)
erroInterno() {
  //exceção gerada
  print(app.chain.error);
}

Grupos

Grupos são usados para agrupar serviços, interceptadores e tratadores de erro

@Group("/usuario")
class Usuario {

  //Ex.: http://localhost:8080/usuario/buscar?n=luiz
  @app.Route("/buscar")
  buscar(@app.QueryParam("n") String nome) {
    ...
  }

  @app.Route("/salvar", methods: const [app.POST])
  salvar(@app.Body(app.JSON) Map json) {
    ...
  }
}

Plugin redstone_mapper

Permite serializar facilmente objetos Dart para JSON

class Usuario {

  @Field() String nome;
  @Field() int idade;

}

//conteúdo da requisição é convertido
//de JSON para Usuario
@app.Route('/usuario', methods = const[app.POST])
salvaUsuario(@Decode() Usuario usuario) {
  ...
}

Plugin redstone_mapper

Oferece integração com banco de dados

MongoDB

//Retorno da função é convertido para JSON
@app.Route("/usuarios")
@Encode()
Future<List<Usuario>> buscaUsuarios() =>
  //busca documentos da coleção 'usuarios',
  //e os converte para List<Usuario>
  mongoDb.find("usuarios", Usuario);

PostgreSQL

//Retorno da função é convertido para JSON
@app.Route("/usuarios")
@Encode()
Future<List<Usuario>> buscaUsuarios() =>
  //busca registros da tabela 'usuario',
  //e os converte para List<Usuario>
  postgreSql.query("select * from usuario",
      Usuario);

Outros recursos

Suporte a injeção de dependências

Suporte a testes unitários

Integrado ao Shelf framework

Suporte a web sockets (plugin redstone_web_socket)

Pode ser implantado facilmente no Heroku e outras soluções de cloud computing

Obrigado!

Dart: http://dartlang.org

Redstone.dart: http://redstonedart.org

GitHub: https://github.com/luizmineo/redstone.dart