text:
"""
Module for running vmadm command on SmartOS
"""

import logging
import os
import shlex

import salt.utils.args
import salt.utils.files
import salt.utils.json
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
from salt.utils.odict import OrderedDict

log = logging.getLogger(__name__)

# Function aliases
__func_alias__ = {"list_vms": "list"}

# Define the module's virtual name
__virtualname__ = "vmadm"

def __virtual__():
    """
    Provides vmadm on SmartOS
    """
    if (
        salt.utils.platform.is_smartos_globalzone()
        and salt.utils.path.which("vmadm")
        and salt.utils.path.which("zfs")
    ):
        return __virtualname__
    return (
        False,
        "{} module can only be loaded on SmartOS compute nodes".format(__virtualname__),
    )

def _exit_status(retcode):
    """
    Translate exit status of vmadm
    """
    ret = {0: "Successful completion.", 1: "An error occurred.", 2: "Usage error."}[
        retcode
    ]
    return ret

def _create_update_from_file(mode="create", uuid=None, path=None):
    """
    Create vm from file
    """
    ret = {}
    if not os.path.isfile(path) or path is None:
        ret["Error"] = "File ({}) does not exists!".format(path)
        return ret
    # vmadm validate create|update [-f <filename>]
    cmd = "vmadm validate {mode} {brand} -f {path}".format(
        mode=mode, brand=get(uuid)["brand"] if uuid is not None else "", path=path
    )
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = _exit_status(retcode)
        if "stderr" in res:
            if res["stderr"][0] == "{":
                ret["Error"] = salt.utils.json.loads(res["stderr"])
            else:
                ret["Error"] = res["stderr"]
        return ret
    # vmadm create|update [-f <filename>]
    cmd = "vmadm {mode} {uuid} -f {path}".format(
        mode=mode, uuid=uuid if uuid is not None else "", path=path
    )
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = _exit_status(retcode)
        if "stderr" in res:
            if res["stderr"][0] == "{":
                ret["Error"] = salt.utils.json.loads(res["stderr"])
            else:
                ret["Error"] = res["stderr"]
        return ret
    else:
        if res["stderr"].startswith("Successfully created VM"):
            return res["stderr"][24:]
    return True

def _create_update_from_cfg(mode="create", uuid=None, vmcfg=None):
    """
    Create vm from configuration
    """
    ret = {}

    # write json file
    vmadm_json_file = __salt__["temp.file"](prefix="vmadm-")
    with salt.utils.files.fopen(vmadm_json_file, "w") as vmadm_json:
        salt.utils.json.dump(vmcfg, vmadm_json)

    # vmadm validate create|update [-f <filename>]
    cmd = "vmadm validate {mode} {brand} -f {vmadm_json_file}".format(
        mode=mode,
        brand=get(uuid)["brand"] if uuid is not None else "",
        vmadm_json_file=vmadm_json_file,
    )
    res = __salt__["cmd.run_all"](cmd, python_shell=True)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = _exit_status(retcode)
        if "stderr" in res:
            if res["stderr"][0] == "{":
                ret["Error"] = salt.utils.json.loads(res["stderr"])
            else:
                ret["Error"] = res["stderr"]
        return ret
    # vmadm create|update [-f <filename>]
    cmd = "vmadm {mode} {uuid} -f {vmadm_json_file}".format(
        mode=mode,
        uuid=uuid if uuid is not None else "",
        vmadm_json_file=vmadm_json_file,
    )
    res = __salt__["cmd.run_all"](cmd, python_shell=True)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = _exit_status(retcode)
        if "stderr" in res:
            if res["stderr"][0] == "{":
                ret["Error"] = salt.utils.json.loads(res["stderr"])
            else:
                ret["Error"] = res["stderr"]
        return ret
    else:
        # cleanup json file (only when successful to help troubleshooting)
        salt.utils.files.safe_rm(vmadm_json_file)

        # return uuid
        if res["stderr"].startswith("Successfully created VM"):
            return res["stderr"][24:]

    return True

def start(vm, options=None, key="uuid"):
    """
    Start a vm

    vm : string
        vm to be started
    options : string
        optional additional options
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.start 186da9ab-7392-4f55-91a5-b8f1fe770543
        salt '*' vmadm.start 186da9ab-7392-4f55-91a5-b8f1fe770543 'order=c,once=d cdrom=/path/to/image.iso,ide'
        salt '*' vmadm.start vm=nacl key=alias
        salt '*' vmadm.start vm=nina.example.org key=hostname
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    # vmadm start <uuid> [option=value ...]
    cmd = "vmadm start {uuid} {options}".format(
        uuid=vm, options=options if options else ""
    )
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

def stop(vm, force=False, key="uuid"):
    """
    Stop a vm

    vm : string
        vm to be stopped
    force : boolean
        force stop of vm if true
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.stop 186da9ab-7392-4f55-91a5-b8f1fe770543
        salt '*' vmadm.stop 186da9ab-7392-4f55-91a5-b8f1fe770543 True
        salt '*' vmadm.stop vm=nacl key=alias
        salt '*' vmadm.stop vm=nina.example.org key=hostname
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    # vmadm stop <uuid> [-F]
    cmd = "vmadm stop {force} {uuid}".format(force="-F" if force else "", uuid=vm)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = _exit_status(retcode)
        return ret
    return True

def reboot(vm, force=False, key="uuid"):
    """
    Reboot a vm

    vm : string
        vm to be rebooted
    force : boolean
        force reboot of vm if true
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.reboot 186da9ab-7392-4f55-91a5-b8f1fe770543
        salt '*' vmadm.reboot 186da9ab-7392-4f55-91a5-b8f1fe770543 True
        salt '*' vmadm.reboot vm=nacl key=alias
        salt '*' vmadm.reboot vm=nina.example.org key=hostname
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    # vmadm reboot <uuid> [-F]
    cmd = "vmadm reboot {force} {uuid}".format(force="-F" if force else "", uuid=vm)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

def list_vms(search=None, sort=None, order="uuid,type,ram,state,alias", keyed=True):
    """
    Return a list of VMs

    search : string
        vmadm filter property
    sort : string
        vmadm sort (-s) property
    order : string
        vmadm order (-o) property -- Default: uuid,type,ram,state,alias
    keyed : boolean
        specified if the output should be an array (False) or dict (True)
            For a dict the key is the first item from the order parameter.
            Note: If key is not unique last vm wins.

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.list
        salt '*' vmadm.list order=alias,ram,cpu_cap sort=-ram,-cpu_cap
        salt '*' vmadm.list search='type=KVM'
    """
    ret = {}
    # vmadm list [-p] [-H] [-o field,...] [-s field,...] [field=value ...]
    cmd = "vmadm list -p -H {order} {sort} {search}".format(
        order="-o {}".format(order) if order else "",
        sort="-s {}".format(sort) if sort else "",
        search=search if search else "",
    )
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    result = OrderedDict() if keyed else []
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret

    fields = order.split(",")

    for vm in res["stdout"].splitlines():
        vm_data = OrderedDict()
        vm = vm.split(":")
        if keyed:
            for field in fields:
                if fields.index(field) == 0:
                    continue
                vm_data[field.strip()] = vm[fields.index(field)].strip()
            result[vm[0]] = vm_data
        else:
            if len(vm) > 1:
                for field in fields:
                    vm_data[field.strip()] = vm[fields.index(field)].strip()
            else:
                vm_data = vm[0]
            result.append(vm_data)
    return result

def lookup(search=None, order=None, one=False):
    """
    Return a list of VMs using lookup

    search : string
        vmadm filter property
    order : string
        vmadm order (-o) property -- Default: uuid,type,ram,state,alias
    one : boolean
        return only one result (vmadm's -1)

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.lookup search='state=running'
        salt '*' vmadm.lookup search='state=running' order=uuid,alias,hostname
        salt '*' vmadm.lookup search='alias=nacl' one=True
    """
    ret = {}
    # vmadm lookup [-j|-1] [-o field,...] [field=value ...]
    cmd = "vmadm lookup {one} {order} {search}".format(
        one="-1" if one else "-j",
        order="-o {}".format(order) if order else "",
        search=search if search else "",
    )
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    result = []
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret

    if one:
        result = res["stdout"]
    else:
        for vm in salt.utils.json.loads(res["stdout"]):
            result.append(vm)

    return result

def sysrq(vm, action="nmi", key="uuid"):
    """
    Send non-maskable interrupt to vm or capture a screenshot

    vm : string
        vm to be targeted
    action : string
        nmi or screenshot -- Default: nmi
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.sysrq 186da9ab-7392-4f55-91a5-b8f1fe770543 nmi
        salt '*' vmadm.sysrq 186da9ab-7392-4f55-91a5-b8f1fe770543 screenshot
        salt '*' vmadm.sysrq nacl nmi key=alias
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    if action not in ["nmi", "screenshot"]:
        ret["Error"] = "Action must be either nmi or screenshot"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    # vmadm sysrq <uuid> <nmi|screenshot>
    cmd = "vmadm sysrq {uuid} {action}".format(uuid=vm, action=action)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

def delete(vm, key="uuid"):
    """
    Delete a vm

    vm : string
        vm to be deleted
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.delete 186da9ab-7392-4f55-91a5-b8f1fe770543
        salt '*' vmadm.delete nacl key=alias
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    # vmadm delete <uuid>
    cmd = "vmadm delete {}".format(vm)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

def get(vm, key="uuid"):
    """
    Output the JSON object describing a VM

    vm : string
        vm to be targeted
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.get 186da9ab-7392-4f55-91a5-b8f1fe770543
        salt '*' vmadm.get nacl key=alias
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    # vmadm get <uuid>
    cmd = "vmadm get {}".format(vm)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return salt.utils.json.loads(res["stdout"])

def info(vm, info_type="all", key="uuid"):
    """
    Lookup info on running kvm

    vm : string
        vm to be targeted
    info_type : string [all|block|blockstats|chardev|cpus|kvm|pci|spice|version|vnc]
        info type to return
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543
        salt '*' vmadm.info 186da9ab-7392-4f55-91a5-b8f1fe770543 vnc
        salt '*' vmadm.info nacl key=alias
        salt '*' vmadm.info nacl vnc key=alias
    """
    ret = {}
    if info_type not in [
        "all",
        "block",
        "blockstats",
        "chardev",
        "cpus",
        "kvm",
        "pci",
        "spice",
        "version",
        "vnc",
    ]:
        ret["Error"] = "Requested info_type is not available"
        return ret
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    # vmadm info <uuid> [type,...]
    cmd = "vmadm info {uuid} {type}".format(uuid=vm, type=info_type)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return salt.utils.json.loads(res["stdout"])

def create_snapshot(vm, name, key="uuid"):
    """
    Create snapshot of a vm

    vm : string
        vm to be targeted
    name : string
        snapshot name
            The snapname must be 64 characters or less
            and must only contain alphanumeric characters and
            characters in the set [-_.:%] to comply with ZFS restrictions.
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.create_snapshot 186da9ab-7392-4f55-91a5-b8f1fe770543 baseline
        salt '*' vmadm.create_snapshot nacl baseline key=alias
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    vmobj = get(vm)
    if "datasets" in vmobj:
        ret["Error"] = "VM cannot have datasets"
        return ret
    if vmobj["brand"] in ["kvm"]:
        ret["Error"] = "VM must be of type OS"
        return ret
    if vmobj["zone_state"] not in ["running"]:  # work around a vmadm bug
        ret["Error"] = "VM must be running to take a snapshot"
        return ret
    # vmadm create-snapshot <uuid> <snapname>
    cmd = "vmadm create-snapshot {uuid} {snapshot}".format(snapshot=name, uuid=vm)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

def delete_snapshot(vm, name, key="uuid"):
    """
    Delete snapshot of a vm

    vm : string
        vm to be targeted
    name : string
        snapshot name
            The snapname must be 64 characters or less
            and must only contain alphanumeric characters and
            characters in the set [-_.:%] to comply with ZFS restrictions.
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.delete_snapshot 186da9ab-7392-4f55-91a5-b8f1fe770543 baseline
        salt '*' vmadm.delete_snapshot nacl baseline key=alias
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    vmobj = get(vm)
    if "datasets" in vmobj:
        ret["Error"] = "VM cannot have datasets"
        return ret
    if vmobj["brand"] in ["kvm"]:
        ret["Error"] = "VM must be of type OS"
        return ret
    # vmadm delete-snapshot <uuid> <snapname>
    cmd = "vmadm delete-snapshot {uuid} {snapshot}".format(snapshot=name, uuid=vm)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

def rollback_snapshot(vm, name, key="uuid"):
    """
    Rollback snapshot of a vm

    vm : string
        vm to be targeted
    name : string
        snapshot name
            The snapname must be 64 characters or less
            and must only contain alphanumeric characters and
            characters in the set [-_.:%] to comply with ZFS restrictions.
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.rollback_snapshot 186da9ab-7392-4f55-91a5-b8f1fe770543 baseline
        salt '*' vmadm.rollback_snapshot nacl baseline key=alias
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    vmobj = get(vm)
    if "datasets" in vmobj:
        ret["Error"] = "VM cannot have datasets"
        return ret
    if vmobj["brand"] in ["kvm"]:
        ret["Error"] = "VM must be of type OS"
        return ret
    # vmadm rollback-snapshot <uuid> <snapname>
    cmd = "vmadm rollback-snapshot {uuid} {snapshot}".format(snapshot=name, uuid=vm)
    res = __salt__["cmd.run_all"](cmd)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

def reprovision(vm, image, key="uuid"):
    """
    Reprovision a vm

    vm : string
        vm to be reprovisioned
    image : string
        uuid of new image
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.reprovision 186da9ab-7392-4f55-91a5-b8f1fe770543 c02a2044-c1bd-11e4-bd8c-dfc1db8b0182
        salt '*' vmadm.reprovision nacl c02a2044-c1bd-11e4-bd8c-dfc1db8b0182 key=alias
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    if image not in __salt__["imgadm.list"]():
        ret["Error"] = "Image ({}) is not present on this host".format(image)
        return ret
    # vmadm reprovision <uuid> [-f <filename>]
    cmd = "echo {image} | vmadm reprovision {uuid}".format(
        uuid=salt.utils.stringutils.to_unicode(vm),
        image=shlex.quote(salt.utils.json.dumps({"image_uuid": image})),
    )
    res = __salt__["cmd.run_all"](cmd, python_shell=True)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

def create(from_file=None, **kwargs):
    """
    Create a new vm

    from_file : string
        json file to create the vm from -- if present, all other options will be ignored
    kwargs : string|int|...
        options to set for the vm

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.create from_file=/tmp/new_vm.json
        salt '*' vmadm.create image_uuid='...' alias='...' nics='[{ "nic_tag": "admin", "ip": "198.51.100.123", ...}, {...}]' [...]
    """
    ret = {}
    # prepare vmcfg
    vmcfg = {}
    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    for k, v in kwargs.items():
        vmcfg[k] = v

    if from_file:
        return _create_update_from_file("create", path=from_file)
    else:
        return _create_update_from_cfg("create", vmcfg=vmcfg)

def update(vm, from_file=None, key="uuid", **kwargs):
    """
    Update a new vm

    vm : string
        vm to be updated
    from_file : string
        json file to update the vm with -- if present, all other options will be ignored
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter
    kwargs : string|int|...
        options to update for the vm

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.update vm=186da9ab-7392-4f55-91a5-b8f1fe770543 from_file=/tmp/new_vm.json
        salt '*' vmadm.update vm=nacl key=alias from_file=/tmp/new_vm.json
        salt '*' vmadm.update vm=186da9ab-7392-4f55-91a5-b8f1fe770543 max_physical_memory=1024
    """
    ret = {}
    # prepare vmcfg
    vmcfg = {}
    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    for k, v in kwargs.items():
        vmcfg[k] = v

    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    uuid = lookup("{}={}".format(key, vm), one=True)
    if "Error" in uuid:
        return uuid

    if from_file:
        return _create_update_from_file("update", uuid, path=from_file)
    else:
        return _create_update_from_cfg("update", uuid, vmcfg=vmcfg)

def send(vm, target, key="uuid"):
    """
    Send a vm to a directory

    vm : string
        vm to be sent
    target : string
        target directory
    key : string [uuid|alias|hostname]
        value type of 'vm' parameter

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.send 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups
        salt '*' vmadm.send vm=nacl target=/opt/backups key=alias
    """
    ret = {}
    if key not in ["uuid", "alias", "hostname"]:
        ret["Error"] = "Key must be either uuid, alias or hostname"
        return ret
    if not os.path.isdir(target):
        ret["Error"] = "Target must be a directory or host"
        return ret
    vm = lookup("{}={}".format(key, vm), one=True)
    if "Error" in vm:
        return vm
    # vmadm send <uuid> [target]
    cmd = "vmadm send {uuid} > {target}".format(
        uuid=vm, target=os.path.join(target, "{}.vmdata".format(vm))
    )
    res = __salt__["cmd.run_all"](cmd, python_shell=True)
    retcode = res["retcode"]
    if retcode != 0:
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    vmobj = get(vm)
    if "datasets" not in vmobj:
        return True
    log.warning("one or more datasets detected, this is not supported!")
    log.warning("trying to zfs send datasets...")
    for dataset in vmobj["datasets"]:
        name = dataset.split("/")
        name = name[-1]
        cmd = "zfs send {dataset} > {target}".format(
            dataset=dataset,
            target=os.path.join(target, "{}-{}.zfsds".format(vm, name)),
        )
        res = __salt__["cmd.run_all"](cmd, python_shell=True)
        retcode = res["retcode"]
        if retcode != 0:
            ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
            return ret
    return True

def receive(uuid, source):
    """
    Receive a vm from a directory

    uuid : string
        uuid of vm to be received
    source : string
        source directory

    CLI Example:

    .. code-block:: bash

        salt '*' vmadm.receive 186da9ab-7392-4f55-91a5-b8f1fe770543 /opt/backups
    """
    ret = {}
    if not os.path.isdir(source):
        ret["Error"] = "Source must be a directory or host"
        return ret
    if not os.path.exists(os.path.join(source, "{}.vmdata".format(uuid))):
        ret["Error"] = "Unknow vm with uuid in {}".format(source)
        return ret
    # vmadm receive
    cmd = "vmadm receive < {source}".format(
        source=os.path.join(source, "{}.vmdata".format(uuid))
    )
    res = __salt__["cmd.run_all"](cmd, python_shell=True)
    retcode = res["retcode"]
    if retcode != 0 and not res["stderr"].endswith("datasets"):
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    vmobj = get(uuid)
    if "datasets" not in vmobj:
        return True
    log.warning("one or more datasets detected, this is not supported!")
    log.warning("trying to restore datasets, mountpoints will need to be set again...")
    for dataset in vmobj["datasets"]:
        name = dataset.split("/")
        name = name[-1]
        cmd = "zfs receive {dataset} < {source}".format(
            dataset=dataset,
            source=os.path.join(source, "{}-{}.zfsds".format(uuid, name)),
        )
        res = __salt__["cmd.run_all"](cmd, python_shell=True)
        retcode = res["retcode"]
        if retcode != 0:
            ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
            return ret
    cmd = "vmadm install {}".format(uuid)
    res = __salt__["cmd.run_all"](cmd, python_shell=True)
    retcode = res["retcode"]
    if retcode != 0 and not res["stderr"].endswith("datasets"):
        ret["Error"] = res["stderr"] if "stderr" in res else _exit_status(retcode)
        return ret
    return True

# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>ConsumeKinesisStream</title>
    <link rel="stylesheet" href="../../../../../css/component-usage.css" type="text/css"/>

Streaming Versus Batch Processing

    ConsumeKinesisStream retrieves all Kinesis Records that it encounters in the configured Kinesis Stream.
    There are two common, broadly defined use cases.

Per-Message Use Case

    By default, the Processor will create a separate FlowFile for each Kinesis Record (message) in the Stream
    and add attributes for shard id, sequence number, etc.

Per-Batch Use Case

    Another common use case is the desire to process all Kinesis Records retrieved from the Stream in a batch as a single FlowFile.

    The ConsumeKinesisStream Processor can optionally be configured with a Record Reader and Record Writer.
    When a Record Reader and Record Writer are configured, a single FlowFile will be created that will contain a Record
    for each Record within the batch of Kinesis Records (messages), instead of a separate FlowFile per Kinesis Record.

    The FlowFiles emitted in this mode will include the standard record.* attributes along with the same
    Kinesis Shard ID, Sequence Number and Approximate Arrival Timestamp; but the values will relate to the last
    Kinesis Record that was processed in the batch of messages constituting the content of the FlowFile.

redpajama_set_name: RedPajamaGithub


text:
package com.adms.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import com.pff.PSTAttachment;
import com.pff.PSTException;
import com.pff.PSTFile;
import com.pff.PSTFolder;
import com.pff.PSTMessage;

public class TestApp {

	private static int depth = -1;

	public static void main(String[] args) {

		try {
			System.out.println("start");
			String outDir = "D:/project/reports/MGL/in/zip/201505";
			File outfile = new File(outDir);
			if(!outfile.exists()) outfile.mkdirs();

			PSTFile pstFile = new PSTFile("D:/Email/Archive_PataweeCha_2015.pst");

			System.out.println(pstFile.getMessageStore().getDisplayName());

			processFolder(pstFile.getRootFolder(), outDir);

			System.out.println("finish");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void processFolder(PSTFolder folder, String outDir) throws PSTException,
			IOException {
		depth++;
		// the root folder doesn't have a display name
		if (depth > 0) {
			printDepth();
			System.out.println(folder.getDisplayName());
		}

		// go through the folders...
		if (folder.hasSubfolders()) {
			Vector<PSTFolder> childFolders = folder.getSubFolders();
			for (PSTFolder childFolder : childFolders) {
				processFolder(childFolder, outDir);
			}
		}

		// and now the emails for this folder
		if(folder.getDisplayName().equalsIgnoreCase("daily report")
				|| folder.getDisplayName().equalsIgnoreCase("autorpt")) {
			if (folder.getContentCount() > 0) {
				depth++;
				PSTMessage email = (PSTMessage) folder.getNextChild();
				while (email != null) {
					if(email.getSubject().toLowerCase().contains("confirmrpt")
							|| email.getSubject().toLowerCase().contains(" : report")
							|| (email.getSubject().toLowerCase().contains("autorpt_")
									&& !email.getSubject().toLowerCase().contains("app")
									&& !email.getSubject().toLowerCase().contains("yesfiles"))) {

						printDepth();
						System.out.println("Email: " + email.getSubject() + " | from: " + email.getSenderEmailAddress());

//						@tele-intel.com for TELE, @onetoonecontacts.com for OTO
						getAttachments(email, outDir + "/" + (email.getSenderEmailAddress().endsWith("@tele-intel.com") ? "TELE" : "OTO"));
					}
					email = (PSTMessage) folder.getNextChild();
				}
				depth--;
			}
		}
		depth--;
	}

	private static void getAttachments(PSTMessage email, String outDir) {
		try {
			File f = new File(outDir);
			if(!f.exists()) f.mkdirs();
			int numberOfAttachments = email.getNumberOfAttachments();
			for (int x = 0; x < numberOfAttachments; x++) {
				PSTAttachment attach = email.getAttachment(x);
				InputStream attachmentStream = attach.getFileInputStream();
				// both long and short filenames can be used for attachments
				String filename = attach.getLongFilename();
				if (filename.isEmpty()) {
					filename = attach.getFilename();
				}

				if(filename.toLowerCase().contains(".zip")) {
					FileOutputStream out = new FileOutputStream(outDir + "/" + filename);
					// 8176 is the block size used internally and should give the
					// best performance
					int bufferSize = 8176;
					byte[] buffer = new byte[bufferSize];
					int count = attachmentStream.read(buffer);
					while (count == bufferSize) {
						out.write(buffer);
						count = attachmentStream.read(buffer);
					}
					byte[] endBuffer = new byte[count];
					System.arraycopy(buffer, 0, endBuffer, 0, count);
					out.write(endBuffer);
					out.close();
				}

				attachmentStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void printDepth() {
		for (int x = 0; x < depth - 1; x++) {
			System.out.print(" | ");
		}
		System.out.print(" |- ");
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.java.a35.newsapp.NewsListActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
                <android.support.design.widget.TabLayout
                    android:id="@+id/tabLayout"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="@dimen/category_height"
                    android:background="@color/backgroundHoloLight"
                    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                    app:elevation="4dp"
                    app:tabIndicatorColor="@color/colorPrimary"
                    app:tabIndicatorHeight="5dp"
                    app:tabTextColor="@color/primaryTextDark"
                    app:tabSelectedTextColor="@color/colorPrimary"
                    app:tabMode="scrollable" />

                <ImageButton
                    android:id="@+id/addCategory"
                    android:layout_width="@dimen/category_width"
                    android:layout_height="@dimen/category_height"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_centerVertical="true"
                    android:scaleType="center"
                    android:background="@color/backgroundHoloLight"
                    android:elevation="10dp"
                    app:srcCompat="@drawable/ic_add" />
        </LinearLayout>

    </android.support.design.widget.AppBarLayout>

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

    </FrameLayout>

</android.support.design.widget.CoordinatorLayout>


text:
Small, simple C# animation library built using the reactive extensions framework, utilizing Robert Penner's easing functions. Does not make use of reflection, instead allowing the caller to use a function/monad/observer to update their desired object.

Available as a NuGet package at https://www.nuget.org/packages/ReactiveAnimation/

## Why use reactive extensions?
Observables are very useful, because it allows you to easily react to events like resizes or repositions etc.  For example, you can animate an object to chase another object that is being animated, and have the animations scale automatically when the Form they are on changes size.
All the hard work is being done on separate threads, so you don't have to worry about it.  For Windows Forms, Rx can ensure that your subscribed observer executes on the Control thread, so it's super easy to update properties etc. without worrying about using Invoke.

## Principles
- The Animation sets the duration and (optionally) the easing function.
- Then you specify what values you want to animate, which you then subscribe to, essentially registering an observer that will update the desired object.
- Then you start the animation.
- Animations can be paused, cancelled, or skipped to completion etc.

## Examples
- Create an Animation that will last for 3 seconds and ease in and out using the quadratic curve
```cs
var a = new Animation {
  DurationInFrames = Animation.FromTimeSpanToDurationInFrames(3),
  EasingFunction = ef => Easing.EaseInOut(ef, EasingType.Quadratic)
};
```
- Using this animation, register an observer to animate a float from 0.8 to 1.0 and use the value to set the opacity of a form
```cs
a.AnimateOnControlThread(
  form,
  ObservableHelper.FixedValue((float)0.8),
  ObservableHelper.FixedValue((float)1),
  v => f.Opacity = v.CurrentValue
);
```
- Start the animation
```cs
a.Start();
```

- Or, if you want to animate a Windows Form Control without an easing function, and you want a specific speed as opposed to a set duration, you can use the LinearAnimation static class.
```cs
var cts = LinearAnimation.AnimateControl(
  button, // control to animate
  ObservableHelper.FixedValue(new Point(0, 150)), // animate until at this position
  ObservableHelper.FixedValue(5), // speed to move at
  true); // keep in same relative position when the control's parent resizes
// returns a CancellationTokenSource that you can use to cancel the animation
```

[![MyGet Build Status](https://www.myget.org/BuildSource/Badge/progamer-me?identifier=e8f7d0bd-e97a-4f4d-be10-e3d80f613a26)](https://www.myget.org/)


text:
package cn.jsprun.dao;
import java.util.List;
import cn.jsprun.domain.Mythreads;
public interface MythreadDao {
	public boolean deleteMythreadByUid(int uid);
	public boolean insertMythread(Mythreads mythread);
	public List<Mythreads>findMythreadByUid(int uid);
	public void deleteMythread(Integer tid);
}


text:
/**
 *
 */
package com.zimbra.qa.selenium.projects.admin.ui;

import com.zimbra.qa.selenium.framework.ui.AbsApplication;
import com.zimbra.qa.selenium.framework.ui.AbsPage;
import com.zimbra.qa.selenium.framework.ui.AbsTab;
import com.zimbra.qa.selenium.framework.ui.Action;
import com.zimbra.qa.selenium.framework.ui.Button;
import com.zimbra.qa.selenium.framework.util.HarnessException;

/**
 * @author Matt Rhoades
 *
 */
public class PageEditMailQueue extends AbsTab {

	public PageEditMailQueue(AbsApplication application) {
		super(application);
		// TODO Auto-generated constructor stub
	}

	/* (non-Javadoc)
	 * @see projects.admin.ui.AbsTab#isActive()
	 */
	@Override
	public boolean zIsActive() throws HarnessException {
		throw new HarnessException("implement me");
	}

	/* (non-Javadoc)
	 * @see projects.admin.ui.AbsTab#myPageName()
	 */
	@Override
	public String myPageName() {
		return (this.getClass().getName());
	}

	/* (non-Javadoc)
	 * @see projects.admin.ui.AbsTab#navigateTo()
	 */
	@Override
	public void zNavigateTo() throws HarnessException {
		throw new HarnessException("implement me");
	}

	@Override
	public AbsPage zListItem(Action action, String item)
			throws HarnessException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public AbsPage zListItem(Action action, Button option, String item)
			throws HarnessException {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public AbsPage zListItem(Action action, Button option, Button subOption ,String item)
			throws HarnessException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public AbsPage zToolbarPressButton(Button button) throws HarnessException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public AbsPage zToolbarPressPulldown(Button pulldown, Button option)
			throws HarnessException {
		// TODO Auto-generated method stub
		return null;
	}

}


text:
angular.module('pmpBrowser.controllers', [])
.controller('DocCtrl', function ($scope, doc) {
  $scope.doc = doc;
})
.controller('AppCtrl', function ($scope, $pmp, $ionicLoading, CollectionDoc, metadata) {

  $scope.items = [];

  $scope.search = {};

  window.search = $scope.search;

  $scope.totalItems = function () {
    if ($scope.search && $scope.search.result && $scope.search.result.hasLink('self')) {
      return $scope.search.result.findLink('self').totalitems;
    }
    return 0;
  }

  $scope.orgFor = function (doc) {
    return metadata.orgInfo(doc.links.creator[0].href);
  }

  $scope.$watch('search.string', function (newValue, oldValue) {
    debouncedSearch(newValue, oldValue);
  });

  var debouncedSearch = ionic.debounce(function (newValue, oldValue) {
    $scope.$apply(function (){
      if ((newValue || '') != (oldValue || '')) {
        $scope.search.result = null;
        $scope.items = [];
        $scope.pmpSearch($scope.search.string);
      }
    });
  }, 400, false);

  $scope.moreDataCanBeLoaded = function () {
    var loadMore = false;

    if (!$scope.search || !$scope.search.result) {
      loadMore = true;
    } else {
      loadMore = $scope.search.result.hasLink('next');
    }
    return loadMore;
  };

  $scope.loadMore = function () {
    if ($scope.search && $scope.search.result) {
      $scope.search.result.next().then(
        function (doc) {
          if (doc) {
            $scope.search.result = doc;
            $scope.items = $scope.items.concat(doc.items);
            $scope.$broadcast('scroll.infiniteScrollComplete');
          }
        }
      );
    } else {
      $scope.pmpSearch($scope.search.string).then( function() {
        $scope.$broadcast('scroll.infiniteScrollComplete');
      });
    }
  };

  $scope.pmpSearch = function (query, options) {
    $ionicLoading.show({ template: '<i class="icon ion-loading-d icon-refreshing"></i> Loading...', noBackdrop: true });
    var vars = options || {};
    if (query) {
      vars['text'] = query;
    }

    return CollectionDoc.search(vars).then(
      function (doc) {
        $scope.search.result = doc;
        $scope.items = $scope.items.concat(doc.items);
        $ionicLoading.hide();
      },
      function (data) {
        $scope.search.result = null;
        $ionicLoading.hide();
      }
    );
  };

});


text:
package com.namelessdev.mpdroid;

import com.namelessdev.mpdroid.helpers.MPDControl;
import com.namelessdev.mpdroid.service.MPDroidService;
import com.namelessdev.mpdroid.service.NotificationHandler;
import com.namelessdev.mpdroid.service.StreamHandler;
import com.namelessdev.mpdroid.tools.Tools;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.IBinder;
import android.util.Log;
import android.view.KeyEvent;

/**
 * RemoteControlReceiver receives media player button stuff. Most of
 * the code was taken from the Android Open Source Project music app.
 *
 * @author Arnaud Barisain Monrose (Dream_Team)
 */
public class RemoteControlReceiver extends BroadcastReceiver {

    private static final boolean DEBUG = false;

    private static final String TAG = "RemoteControlReceiver";

    private static final MPDApplication sApp = MPDApplication.getInstance();

    @Override
    public final void onReceive(final Context context, final Intent intent) {
        final String action = intent.getAction();
        final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

        Log.d(TAG, "Intent: " + intent + " received with context: " + context + " with action: "
                + action);

        if (event != null && event.getAction() == KeyEvent.ACTION_DOWN &&
                Intent.ACTION_MEDIA_BUTTON.equals(action)) {
            final int eventKeyCode = event.getKeyCode();
            Log.d(TAG, "with keycode: " + eventKeyCode);
            switch (eventKeyCode) {
                case KeyEvent.KEYCODE_MEDIA_STOP:
                    MPDControl.run(MPDControl.ACTION_STOP);
                    break;
                case KeyEvent.KEYCODE_HEADSETHOOK:
                case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
                    MPDControl.run(MPDControl.ACTION_TOGGLE_PLAYBACK);
                    break;
                case KeyEvent.KEYCODE_MEDIA_NEXT:
                    MPDControl.run(MPDControl.ACTION_NEXT);
                    break;
                case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
                    MPDControl.run(MPDControl.ACTION_PREVIOUS);
                    break;
                default:
                    break;
            }
        } else {
            switch (action) {
                case AudioManager.ACTION_AUDIO_BECOMING_NOISY:
                    if (Tools.isServerLocalhost()) {
                        MPDControl.run(MPDControl.ACTION_PAUSE);
                    } else {
                        redirectIntentToService(false, intent);
                    }
                    break;
                case Intent.ACTION_BOOT_COMPLETED:
                    if (sApp.isNotificationPersistent()) {
                        redirectIntentToService(true, intent);
                    }
                    break;
                case MPDroidService.ACTION_STOP:
                    sApp.setPersistentOverride(true);
                    /** Fall Through */
                case NotificationHandler.ACTION_START:
                case StreamHandler.ACTION_START:
                    redirectIntentToService(true, intent);
                    break;
                default:
                    MPDControl.run(action);
                    break;
            }
        }
    }

    /**
     * This method redirects the incoming broadcast intent to the service, if it's alive. The
     * service cannot be communicated through messages in this class because this BroadcastReceiver
     * is registered through the AndroidManifest {@code <receiver>} tag which results in this
     * BroadcastReceiver will no longer exist after return from {@code onReceive()}.
     *
     * @param forceService Force the action, even if the service isn't active.
     * @param intent       The incoming intent through {@code onReceive()}.
     * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
     * android.content.Intent)
     */
    private void redirectIntentToService(final boolean forceService, final Intent intent) {
        intent.setClass(sApp, MPDroidService.class);
        final IBinder iBinder = peekService(sApp, intent);
        if (forceService || iBinder != null && iBinder.isBinderAlive()) {
            if (DEBUG) {
                Log.d(TAG, "Redirecting action " + intent.getAction() + " to the service.");
            }

            sApp.startService(intent);
        }
    }
}


text:
add_rules("mode.debug", "mode.release")

target("${TARGETNAME}")
    set_kind("shared")
    add_files("src/interfaces.d")
    add_includedirs("src", {public = true})

target("${TARGETNAME}_demo")
    set_kind("binary")
    add_deps("${TARGETNAME}")
    add_files("src/main.d")

${FAQ}


text:
var Runtime = require('../lib/runtime');
var assert = require('assert');
var Registry = require('./fixture/mem_registry');
var EventEmitter = require('events').EventEmitter;

describe('Runtime', function(){
  describe('Reactive', function(done){
    var runtime = null;
    beforeEach(function() {
      var reg = new Registry();
      runtime = new Runtime({registry: reg});
    });

    it('implements the filter method.', function() {
      assert.ok(runtime.filter);
    });

    it('implements the map method.', function() {
      assert.ok(runtime.map);
    });

    it('implements the zip method.', function() {
      assert.ok(runtime.zip);
    });

    it('implements the subscribe method.', function() {
      assert.ok(runtime.subscribe);
    });

    it('implements the observe method.', function() {
      assert.ok(runtime.observe);
    });

    it('calls the calls the filter method on deviceready', function() {
      var d = { type: 'test' };

      runtime
        .filter(function(e) {
          assert.equal(e.type, 'test');
          done();
        });

      runtime.emit('deviceready', d);
    });

    it('calls subscribe when the observable chain is complete.', function(done) {
      var d = { type: 'test' };
      runtime
        .subscribe(function(d) {
          assert.equal(d.type, 'test');
          done();
        });

      runtime.emit('deviceready', d);
    });

    it('calls map on the observable chain when an event occurs', function(done) {
      var d = { type: 'test' };
      runtime
        .map(function(d) {
          assert.equal(d.type, 'test');
          return d;
        })
        .subscribe(function(x) {
          assert.equal(x.type, 'test');
          done();
        });

      runtime.emit('deviceready', d);

    });

    it('only calls zip when all conditions are fulfilled.', function(done) {
      var d1 = { type: 'test' };
      var d2 = { type: 'test2' };

      var filter2 = runtime.filter(function(d) {
        return d.type == 'test2';
      });

      runtime
        .filter(function(d) {
          return d.type == 'test';
        }).zip(filter2, function(){
          return arguments;
        })
        .subscribe(function(x) {
          assert.equal(x[0].type, 'test');
          assert.equal(x[1].type, 'test2');
          done();
        });

      runtime.emit('deviceready', d1);
      runtime.emit('deviceready', d2);
    });

    describe('Runtime#observe', function() {
      it('returns a Subscription when a subscribe function is provided', function() {
        var q = runtime.where({ type: 'test' });

        var sub = runtime.observe(q, function(device) {
          // do nothing
        });

        assert(typeof(sub.dispose) === 'function');
      });

      it('returns an Observable when a subscribe function is not provided', function() {
        var q = runtime.where({ type: 'test' });

        var obs = runtime.observe(q);

        assert(typeof(obs.subscribe) === 'function');
      });

      it('will take a single query as the first argument', function(done) {
        var q = runtime.where({ type: 'test' });
        var d = { type: 'test' };

        runtime.observe(q, function(device) {
          assert.equal(device.type, 'test');
          done();
        });

        runtime.emit('deviceready', d);
      });

      it('will call the observe callback when the query is fullfilled.', function(done) {
        var q = runtime.where({type: 'test'});
        var d = { type: 'test' };
        runtime.observe([q], function(device) {
          assert.equal(device.type, 'test');
          done();
        });

        runtime.emit('deviceready', d);
      });

      it('will call the observe callback when all queries are fullfilled.', function(done) {
          var q1 = runtime.where({ type: 'test1' });
          var q2 = runtime.where({ type: 'test2' });

          var d1 = { type: 'test1' };
          var d2 = { type: 'test2' };

          runtime.observe([q1, q2], function(one, two) {
            assert.equal(one.type, 'test1');
            assert.equal(two.type, 'test2');
            done();
          });

          runtime.emit('deviceready', d1);
          runtime.emit('deviceready', d2);
      });

      it('will call the observe callback when all queries are fullfilled, and when events happen in any order', function(done) {
          var q1 = runtime.where({ type: 'test1' });
          var q2 = runtime.where({ type: 'test2' });

          var d1 = { type: 'test1' };
          var d2 = { type: 'test2' };

          runtime.observe([q1, q2], function(one, two) {
            assert.equal(one.type, 'test1');
            assert.equal(two.type, 'test2');
            done();
          });

          runtime.emit('deviceready', d2);
          runtime.emit('deviceready', d1);
      });

      it('will fire if a device exists in the registry and doesn\'t call deviceready', function(done) {
        runtime._jsDevices['1'] = { id: '1', type: 'test1' };

        var q1 = runtime.where({ type: 'test1' });
        var q2 = runtime.where({ type: 'test2' });

        var d2 = { type: 'test2' };

        runtime.observe([q1, q2], function(one, two) {
          assert.equal(one.type, 'test1');
          assert.equal(two.type, 'test2');
          done();
        });

        runtime.emit('deviceready', d2);
      });
  });

  describe('Extended reactive syntax', function() {
    it('will respond the same way using the extended reactive syntax.', function(done) {
      runtime
        .filter(function(d) {
          return d.type === 'test1';
        })
        .zip(runtime.filter(function(d){
          return d.type === 'test2';
        }), function() {
          return Array.prototype.slice.call(arguments);
        })
        .subscribe(function(x) {
          var devOne = x[0];
          var devTwo = x[1];
          assert.equal(devOne.type, 'test1');
          assert.equal(devTwo.type, 'test2');
          done();
        });

        var d1 = { type: 'test1' };
        var d2 = { type: 'test2' };

        runtime.emit('deviceready', d1);
        runtime.emit('deviceready', d2);
    });

    it('take will only fire with one pair.', function(done) {
      var emitter = new EventEmitter();
      var fired = 0;
      runtime
        .filter(function(d) {
          return d.type === 'test1';
        })
        .zip(runtime.filter(function(d){
          return d.type === 'test2';
        }), function() {
          return Array.prototype.slice.call(arguments);
        })
        .take(1)
        .subscribe(function(x) {
          var devOne = x[0];
          var devTwo = x[1];
          assert.equal(devOne.type, 'test1');
          assert.equal(devTwo.type, 'test2');
          fired++;
          emitter.on('complete', function() {
            assert.equal(fired, 1);
            done();
          });
        });

        var d1 = { type: 'test1' };
        var d2 = { type: 'test2' };

        runtime.emit('deviceready', d1);
        runtime.emit('deviceready', d2);
        runtime.emit('deviceready', d1);
        runtime.emit('deviceready', d2);
        emitter.emit('complete');
      });

      it('will only fire take one time', function(done) {
        var d = { type: 'test' };
        var fired = 0;
        var emitter = new EventEmitter();
        runtime
          .take(1)
          .subscribe(function(x) {
            assert.equal(x.type, 'test');
            fired++;
            emitter.on('complete', function(){
              assert.equal(fired, 1);
              done();
            });
          });

        runtime.emit('deviceready', d);
        emitter.emit('complete');
      });

      it('will only fire take twice.', function(done) {
        var d = { type: 'test' };
        var fired = 0;
        var emitter = new EventEmitter();
        runtime
          .take(2)
          .subscribe(function(x) {
            assert.equal(x.type, 'test');
            fired++;
            if(fired > 1) {
              emitter.on('complete', function(){
                assert.equal(fired, 2);
                done();
              });
            }
          });

        runtime.emit('deviceready', d);
        runtime.emit('deviceready', d);
        runtime.emit('deviceready', d);
        emitter.emit('complete');
      });

    });
  });
});


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.android.build.api.artifact Class Hierarchy (Android Gradle API)</title>
<meta name="date" content="2018-09-20">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.android.build.api.artifact

Package Hierarchies:

All Packages

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

com.android.build.api.artifact.BuildArtifactType (implements com.android.build.api.artifact.ArtifactType)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
module RequestRefinery
	class Customer < ActiveRecord::Base
		has_and_belongs_to_many :users
	end
end


text:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class AtbashTest {

    @ParameterizedTest
    @CsvSource({
            "foobar, ullyzi",
            "wizard, draziw",
            "/r/dailyprogrammer, /i/wzrobkiltiznnvi",
            "gsrh rh zm vcznkov lu gsv zgyzhs xrksvi, this is an example of the atbash cipher",
    })
    void test(String input, String output) {
        Assertions.assertEquals(output, new Atbash().run(input));
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.chmod = chmod;
exports.readdir = readdir;
exports.readdirForCompilable = readdirForCompilable;
exports.isCompilableExtension = isCompilableExtension;
exports.addSourceMappingUrl = addSourceMappingUrl;
exports.transform = transform;
exports.compile = compile;
exports.deleteDir = deleteDir;
exports.requireChokidar = requireChokidar;
exports.adjustRelative = adjustRelative;

function _fsReaddirRecursive() {
  const data = _interopRequireDefault(require("fs-readdir-recursive"));

  _fsReaddirRecursive = function () {
    return data;
  };

  return data;
}

function babel() {
  const data = _interopRequireWildcard(require("@babel/core"));

  babel = function () {
    return data;
  };

  return data;
}

function _includes() {
  const data = _interopRequireDefault(require("lodash/includes"));

  _includes = function () {
    return data;
  };

  return data;
}

function _path() {
  const data = _interopRequireDefault(require("path"));

  _path = function () {
    return data;
  };

  return data;
}

function _fs() {
  const data = _interopRequireDefault(require("fs"));

  _fs = function () {
    return data;
  };

  return data;
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }

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

function chmod(src, dest) {
  _fs().default.chmodSync(dest, _fs().default.statSync(src).mode);
}

function readdir(dirname, includeDotfiles, filter) {
  return (0, _fsReaddirRecursive().default)(dirname, (filename, _index, currentDirectory) => {
    const stat = _fs().default.statSync(_path().default.join(currentDirectory, filename));

    if (stat.isDirectory()) return true;
    return (includeDotfiles || filename[0] !== ".") && (!filter || filter(filename));
  });
}

function readdirForCompilable(dirname, includeDotfiles) {
  return readdir(dirname, includeDotfiles, isCompilableExtension);
}

function isCompilableExtension(filename, altExts) {
  const exts = altExts || babel().DEFAULT_EXTENSIONS;

  const ext = _path().default.extname(filename);

  return (0, _includes().default)(exts, ext);
}

function addSourceMappingUrl(code, loc) {
  return code + "\n//# sourceMappingURL=" + _path().default.basename(loc);
}

const CALLER = {
  name: "@babel/cli"
};

function transform(filename, code, opts) {
  opts = Object.assign({}, opts, {
    caller: CALLER,
    filename
  });
  return new Promise((resolve, reject) => {
    babel().transform(code, opts, (err, result) => {
      if (err) reject(err);else resolve(result);
    });
  });
}

function compile(filename, opts) {
  opts = Object.assign({}, opts, {
    caller: CALLER
  });
  return new Promise((resolve, reject) => {
    babel().transformFile(filename, opts, (err, result) => {
      if (err) reject(err);else resolve(result);
    });
  });
}

function deleteDir(path) {
  if (_fs().default.existsSync(path)) {
    _fs().default.readdirSync(path).forEach(function (file) {
      const curPath = path + "/" + file;

      if (_fs().default.lstatSync(curPath).isDirectory()) {
        deleteDir(curPath);
      } else {
        _fs().default.unlinkSync(curPath);
      }
    });

    _fs().default.rmdirSync(path);
  }
}

process.on("uncaughtException", function (err) {
  console.error(err);
  process.exit(1);
});

function requireChokidar() {
  try {
    return require("chokidar");
  } catch (err) {
    console.error("The optional dependency chokidar failed to install and is required for " + "--watch. Chokidar is likely not supported on your platform.");
    throw err;
  }
}

function adjustRelative(relative, keepFileExtension) {
  if (keepFileExtension) {
    return relative;
  }

  return relative.replace(/\.(\w*?)$/, "") + ".js";
}


text:
@interface Journey : NSManagedObject

@property (nonatomic) double calculatedFare;
@property (nonatomic) double travelledDistance;
@property (nonatomic, retain) NSString * endLocationId;
@property (nonatomic, retain) NSString * journeyDate;
@property (nonatomic, retain) NSString * providerId;
@property (nonatomic, retain) NSString * selfId;
@property (nonatomic, retain) NSString * serviceId;
@property (nonatomic, retain) NSString * startLocationId;
@property (nonatomic, retain) NSString * subCategoryId;

@end


text:
package com.otv.user.dao;

import java.util.List;

import com.otv.model.User;

/**
 *
 * User DAO Interface
 *
 * @author onlinetechvision.com
 * @since 25 Mar 2012
 * @version 1.0.0
 *
 */
public interface IUserDAO {

	/**
	 * Add User
	 *
	 * @param  User user
	 */
	public void addUser(User user);

	/**
	 * Update User
	 *
	 * @param  User user
	 */
	public void updateUser(User user);

	/**
	 * Delete User
	 *
	 * @param  User user
	 */
	public void deleteUser(User user);

	/**
	 * Get User
	 *
	 * @param  int User Id
	 */
	public User getUserById(int id);

	/**
	 * Get User List
	 *
	 */
	public List<User> getUsers();
}


text:
require 'spec_helper'
require 'date'
require 'time'

require_relative '../lib/ally/detector/date'

today = Date.today()
wday = today.wday

weekdays = %w[
  sunday
  monday
  tuesday
  wednesday
  thursday
  friday
  saturday
]

describe Ally::Detector::Date do
  context 'detect date' do
    it 'simple case' do
      r = subject.inquiry('now').detect
      r.day.should == today.day
      r.month.should == today.month
      r.year.should == today.year
    end

    it 'when no date exists' do
      subject.inquiry('No date here, should be nil')
        .detect.should == nil
    end

    it 'simple sentence referring to today' do
      r = subject.inquiry('whats the date today').detect
      r.day.should == today.day
      r.month.should == today.month
      r.year.should == today.year
    end

    it 'when referencing yesterday' do
      r = subject.inquiry('yesterday i had a great day').detect
      d = today - 1
      r.day.should == d.day
      r.month.should == d.month
      r.year.should == d.year
    end

    it 'when referencing tomorrow' do
      r = subject.inquiry('there is always another day tomorrow').detect
      d = today + 1
      r.day.should == d.day
      r.month.should == d.month
      r.year.should == d.year
    end

    it 'when referencing a week from today' do
      r = subject.inquiry("I have a doctor's appointment #{Date.today.strftime("%A")}").detect
      d = today + 7
      r.day.should == d.day
      r.month.should == d.month
      r.year.should == d.year
    end

    context 'past tense day references' do
      weekdays.each_with_index do |weekday,i|
        if wday == i
          x = -7
        elsif wday < i
          x = -(wday + (7 - i))
        elsif wday > i
          x = -(wday - i)
        end
        it "to #{weekday}" do
          r = subject.inquiry("i had a test last #{weekday}").detect
          d = today + x
          r.day.should == d.day
          r.month.should == d.month
          r.year.should == d.year
        end
      end
    end

    context 'future tense day references' do
      weekdays.each_with_index do |weekday,i|
        if wday == i
          x = 7
        elsif wday < i
          x = i - wday
        elsif wday > i
          x = (7 - wday) + i
        end
        it "to #{weekday}" do
          r = subject.inquiry("i have a test #{weekday}").detect
          d = today + x
          r.day.should == d.day
          r.month.should == d.month
          r.year.should == d.year
          r = subject.inquiry("i have a test this #{weekday}").detect
          d = today + x
          r.day.should == d.day
          r.month.should == d.month
          r.year.should == d.year
        end
      end
    end

    it 'reference a specific date' do
      r = subject.inquiry('i have an appointment on dec 30th').detect
      if today.month < 12
        year = today.year
      elsif today.day >= 30
        year = today.year + 1
      end
      r.should satisfy { |d| d.day == 30 }
      r.should satisfy { |d| d.month == 12 }
      r.should satisfy { |d| d.year == year }
    end

    it 'the next month by name' do
      r = subject.inquiry('august is going to be a hot one').detect
      year = today.month >= 8 ? today.year + 1 : today.year
      r.should satisfy { |d| d.month == 8 }
      r.should satisfy { |d| d.year == year }
    end

    it 'the last month by name' do
      r = subject.inquiry('last february was really cold').detect
      year = today.month < 2 ? today.year - 1 : today.year
      r.should satisfy { |d| d.month == 2 }
      r.should satisfy { |d| d.year == year }
    end

    it 'specific date' do
      r = subject.inquiry('2014-10-01').detect
      r.should satisfy { |d| d.day == 1 }
      r.should satisfy { |d| d.month == 10 }
      r.should satisfy { |d| d.year == 2014 }
    end

    it 'unix timestamp' do
      r = subject.inquiry('1412292987').detect
      r.should satisfy { |d| d.day == 2 }
      r.should satisfy { |d| d.month == 10 }
      r.should satisfy { |d| d.year == 2014 }
      r.should satisfy { |d| d.hour == 23 }
      r.should satisfy { |d| d.min == 36 }
    end

    it 'iso8601' do
      r = subject.inquiry('2011-10-19T04:01:52').detect
      r.should satisfy { |d| d.day == 19 }
      r.should satisfy { |d| d.month == 10 }
      r.should satisfy { |d| d.year == 2011 }
      r.should satisfy { |d| d.hour == 4 }
      r.should satisfy { |d| d.min == 1 }
      r.should satisfy { |d| d.sec == 52 }
    end
  end
end


text:
package org.springframework.cloud.stream.binder.kafka.streams;

import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.streams.errors.DeserializationExceptionHandler;
import org.apache.kafka.streams.processor.ProcessorContext;

/**
 *
 * {@link DeserializationExceptionHandler} that allows to silently skip
 * deserialization exceptions and continue processing.
 *
 * @author Soby Chakco
 * @since 3.1.2
 */
public class SkipAndContinueExceptionHandler implements DeserializationExceptionHandler {

	@Override
	public DeserializationExceptionHandler.DeserializationHandlerResponse handle(final ProcessorContext context,
																				final ConsumerRecord<byte[], byte[]> record,
																				final Exception exception) {
		return DeserializationExceptionHandler.DeserializationHandlerResponse.CONTINUE;
	}

	@Override
	public void configure(final Map<String, ?> configs) {
		// ignore
	}
}


text:
var RxOld = require('rx');
var RxNew = require('../../../../index');

module.exports = function interval(suite) {
  var oldIntervalWithImmediateScheduler = RxOld.Observable.interval(25, RxOld.Scheduler.immediate).take(5);
  var newIntervalWithImmediateScheduler = RxNew.Observable.interval(25).take(5);

  function _next(x) { }
  function _error(e) { }
  function _complete() { }
  return suite
    .add('old interval with immediate scheduler', function () {
      oldIntervalWithImmediateScheduler.subscribe(_next, _error, _complete);
    })
    .add('new interval with immediate scheduler', function () {
      newIntervalWithImmediateScheduler.subscribe(_next, _error, _complete);
    });
};


text:
import 'ie-shim';

// Core-JS
import 'core-js/es6/array';
import 'core-js/es6/map';
import 'core-js/es6/set';
import 'core-js/es6/string';
import 'core-js/es6/symbol';
import 'core-js/es7/reflect';
import 'core-js/fn/array/includes';
import 'core-js/fn/object/assign';

// Zone
import 'zone.js/dist/zone';

// Typescript helpers
import 'ts-helpers';


text:
package auth

// HTTPAuth http 授权
type HTTPAuth interface {
	// HTTPHeaders 根据 @url 获取 http 授权请求头
	HTTPHeaders(url string, appID string, secret string) map[string][]string
}


text:
class CreateGroups < ActiveRecord::Migration
  def self.up
    create_table :groups do |t|
      t.string :name
      t.text :desc
      t.integer :owner_id
      t.timestamps
    end
    create_table :groups_users, :id => false do |t|
      t.integer :user_id
      t.integer :group_id
    end
  end

  def self.down
    drop_table :groups
    drop_table :groups_users
  end
end


text:
package org.michenux.yourappidea.aroundme;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import org.lucasr.twowayview.ItemClickSupport;
import org.lucasr.twowayview.widget.DividerItemDecoration;
import org.lucasr.twowayview.widget.TwoWayView;
import org.michenux.drodrolib.db.utils.CursorUtils;
import org.michenux.yourappidea.R;

public class CityListFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, ItemClickSupport.OnItemClickListener {

    public static final String CITY_NAME = "city_name";
    public static final String CITY_COUNTRY = "city_country";
    public static final String CITY_LONGITUDE = "city_longitude";
    public static final String CITY_LATITUDE = "city_latitude";

    private CityRecyclerAdapter mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        this.mAdapter = new CityRecyclerAdapter(null);
        this.getLoaderManager().initLoader(0, null, this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.city_fragment, container, false);
        TwoWayView recyclerView = (TwoWayView) view.findViewById(R.id.city_listview);
        recyclerView.setAdapter(this.mAdapter);
        recyclerView.setHasFixedSize(true);
        final Drawable divider = getResources().getDrawable(R.drawable.divider);
        recyclerView.addItemDecoration(new DividerItemDecoration(divider));
        final ItemClickSupport itemClick = ItemClickSupport.addTo(recyclerView);
        itemClick.setOnItemClickListener(this);
        return view;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        String[] projection = { CityContentProvider.ID_COLUMN,
                CityContentProvider.NAME_COLUMN, CityContentProvider.COUNTRY_COLUMN, CityContentProvider.LATITUDE_COLUMN, CityContentProvider.LONGITUDE_COLUMN };
        CursorLoader cursorLoader = new CursorLoader(this.getActivity(),
                CityContentProvider.CONTENT_URI, projection, null, null, CityContentProvider.NAME_COLUMN);
        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        this.mAdapter.changeCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        this.mAdapter.changeCursor(null);
    }

    @Override
    public void onItemClick(RecyclerView recyclerView, View view, int position, long id) {
        Intent returnIntent = new Intent();
        Cursor cursor = this.mAdapter.getCursor();
        cursor.moveToPosition(position);
        returnIntent.putExtra(CITY_NAME, CursorUtils.getString(CityContentProvider.NAME_COLUMN, cursor));
        returnIntent.putExtra(CITY_COUNTRY, CursorUtils.getString(CityContentProvider.COUNTRY_COLUMN, cursor));
        returnIntent.putExtra(CITY_LONGITUDE, CursorUtils.getDouble(CityContentProvider.LONGITUDE_COLUMN, cursor));
        returnIntent.putExtra(CITY_LATITUDE, CursorUtils.getDouble(CityContentProvider.LATITUDE_COLUMN, cursor));
        getActivity().setResult(Activity.RESULT_OK, returnIntent);
        getActivity().supportFinishAfterTransition();
    }
}


text:
package de.doe300.activerecord.util;

import de.doe300.activerecord.AssertException;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author doe300
 * @since 0.8
 */
public class MutablePairTest extends Assert implements AssertException
{
	private static final MutablePair<String, String> firstNull = new MutablePair<>(null, "Dummy");
	private static final MutablePair<String, String> secondNull = new MutablePair<>("Dummy", null);

	public MutablePairTest()
	{
	}

	@Test
	public void testGetFirst()
	{
		assertNull( firstNull.getFirst());
		assertNotNull( secondNull.getFirst());
	}

	@Test
	public void testGetSecond()
	{
		assertNotNull( firstNull.getSecond());
		assertNull( secondNull.getSecond());
	}

	@Test
	public void testHasFirst()
	{
		assertFalse( firstNull.hasFirst());
		assertTrue( secondNull.hasFirst());
	}

	@Test
	public void testHasSecond()
	{
		assertTrue( firstNull.hasSecond());
		assertFalse( secondNull.hasSecond());
	}

	@Test
	public void testGetFirstOrThrow()
	{
		assertNotNull( secondNull.getFirstOrThrow());
		assertThrows( NullPointerException.class, () -> firstNull.getFirstOrThrow());
	}

	@Test
	public void testGetSecondOrThrow()
	{
		assertNotNull( firstNull.getSecondOrThrow());
		assertThrows( NullPointerException.class, () -> secondNull.getSecondOrThrow());
	}

	@Test
	public void testSetFirst()
	{
		secondNull.setFirst( "Test");
		assertEquals( "Test", secondNull.getFirst());
	}

	@Test
	public void testSetSecond()
	{
		firstNull.setSecond("Test");
		assertEquals( "Test", firstNull.getSecond());
	}

	@Test
	public void testEquals()
	{
		final MutablePair<String, String> testEq = new MutablePair<>(firstNull.getFirst(), firstNull.getSecond());
		assertFalse( firstNull.equals( secondNull));
		assertTrue( firstNull.equals( testEq));
	}

	@Test
	public void testHashCode()
	{
		final MutablePair<String, String> p1 = new MutablePair<>(firstNull.getFirst(), firstNull.getSecond());
		assertEquals( p1.hashCode(), p1.hashCode());
		assertEquals( firstNull.hashCode(), p1.hashCode());
	}
}


text:
// MIT License. Copyright (c) 2016 Maxim Kuzmin. Contacts: https://github.com/maxim-kuzmin

// Author: Maxim Kuzmin

using Makc2017.Core.Authorize;
using System;
using System.Security.Principal;

namespace Makc2017.Core.Web.Authorize
{
    /// <summary>
    /// Ядро. Веб. Авторизация. Сервис.
    /// </summary>
    public class CoreWebAuthorizeService : ICoreAuthorizeService
    {
        #region Properties

        private Func<IPrincipal> FuncUserGetting { get; set; }

        /// <summary>
        /// Получить принципала.
        /// </summary>
        /// <returns>Принципал.</returns>
        public IPrincipal GetPrincipal()
        {
            return FuncUserGetting.Invoke();
        }

        #endregion Properties

        #region Constructors

        /// <summary>
        /// Конструктор.
        /// </summary>
        /// <param name="funcUserGetting">Функция получения пользователя.</param>
        public CoreWebAuthorizeService(Func<IPrincipal> funcUserGetting)
        {
            FuncUserGetting = funcUserGetting;
        }

        #endregion Constructors
    }
}


text:
package rx.android.samples.demo.skill;

import android.view.View;
import android.widget.Button;

import rx.Observable;
import rx.Subscriber;
import rx.android.samples.demo.BaseFragment;
import rx.functions.Action1;

/**
 * Created by Lin on 2017/2/20.
 */

public class Fragment_Merge extends BaseFragment {

    private Button btn1;
    private Button btn2;
    private Button btn3;

    @Override
    protected void init() {
        super.init();

        btn1 = new Button(getActivity());
        btn1.setText("text1");
        container.addView(btn1);

        btn2 = new Button(getActivity());
        btn2.setText("text2");
        container.addView(btn2);

        btn3 = new Button(getActivity());
        btn3.setText("text3");
        container.addView(btn3);

        Observable obs1 = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                btn1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        subscriber.onNext("1");
                    }
                });
            }
        });
        Observable obs2 = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                btn2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        subscriber.onNext("2");
                    }
                });
            }
        });
        Observable obs3 = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(final Subscriber<? super String> subscriber) {
                btn3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        subscriber.onNext("3");
                    }
                });
            }
        });
        Observable.merge(obs1,obs2,obs3)
                .subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object s) {
                        println("click:" + s);
                    }
                });
    }

}


text:
require 'spec_helper'

describe Wingman::Stat do
  subject { Wingman::Stat.new :foo_bar }

  before do
    subject.initial_value 'Not foo bar'
    subject.replace_value 'Definitely foo bar'
  end

  its( :name   ){ should eq( :foo_bar  ) }
  its( :title  ){ should eq( 'Foo Bar' ) }
  its( :value  ){ should eq( 'Not foo bar' ) }
  its( :render ){ should eq( <<-EOS
<script type='text/javascript'>
$( function( ){ $( 'input#feedback_foo_bar' ).val( 'Definitely foo bar' ); } );
</script>
  EOS
  ) }
end