text:
#### [PATCH v5 00/14] KVM: Dirty ring interface
##### From: Peter Xu <peterx@redhat.com>

```c
From patchwork Wed Mar  4 17:49:33 2020
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Peter Xu <peterx@redhat.com>
X-Patchwork-Id: 11420541
Return-Path: <SRS0=VNnu=4V=vger.kernel.org=kvm-owner@kernel.org>
Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org
 [172.30.200.123])
	by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id A50CB1580
	for <patchwork-kvm@patchwork.kernel.org>;
 Wed,  4 Mar 2020 17:50:00 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [209.132.180.67])
	by mail.kernel.org (Postfix) with ESMTP id 7456721D56
	for <patchwork-kvm@patchwork.kernel.org>;
 Wed,  4 Mar 2020 17:50:00 +0000 (UTC)
Authentication-Results: mail.kernel.org;
	dkim=pass (1024-bit key) header.d=redhat.com header.i=@redhat.com
 header.b="A2WM+K5I"
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S2388158AbgCDRt7 (ORCPT
        <rfc822;patchwork-kvm@patchwork.kernel.org>);
        Wed, 4 Mar 2020 12:49:59 -0500
Received: from us-smtp-delivery-1.mimecast.com ([207.211.31.120]:28328 "EHLO
        us-smtp-1.mimecast.com" rhost-flags-OK-OK-OK-FAIL) by vger.kernel.org
        with ESMTP id S1729471AbgCDRt6 (ORCPT <rfc822;kvm@vger.kernel.org>);
        Wed, 4 Mar 2020 12:49:58 -0500
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com;
        s=mimecast20190719; t=1583344197;
        h=from:from:reply-to:subject:subject:date:date:message-id:message-id:
         to:to:cc:cc:mime-version:mime-version:
         content-transfer-encoding:content-transfer-encoding;
        bh=HRWK0p6I1LWStBHqfoAuFaTR2UJeOmXO70EvjnMwzKM=;
        b=A2WM+K5IEcnU+EUH/jcc08WxcanDfsnwA0tEL9a+3moXoB9p4acxZJ1Rg+8ssMCHj40EZZ
        t+To+2LkgmT2pblw0OqPyRzHZnXTIags2VrjKexDaAAFnCLx4BzhTfUhasT8FyBdlQTxYj
        1N973SVTIQ4cTxdwh3BUno54fJ483+4=
Received: from mail-qt1-f198.google.com (mail-qt1-f198.google.com
 [209.85.160.198]) (Using TLS) by relay.mimecast.com with ESMTP id
 us-mta-383--fhF8CU7NBuDv8F-CDc72g-1; Wed, 04 Mar 2020 12:49:51 -0500
X-MC-Unique: -fhF8CU7NBuDv8F-CDc72g-1
Received: by mail-qt1-f198.google.com with SMTP id h90so1946841qtd.23
        for <kvm@vger.kernel.org>; Wed, 04 Mar 2020 09:49:51 -0800 (PST)
X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;
        d=1e100.net; s=20161025;
        h=x-gm-message-state:from:to:cc:subject:date:message-id:mime-version
         :content-transfer-encoding;
        bh=HRWK0p6I1LWStBHqfoAuFaTR2UJeOmXO70EvjnMwzKM=;
        b=Sazjaikg0/mJhsgR2+3KCykLvEGzuDytJ543Zf4hzA1ZrvymVwLUrDi6m9Yz21gUVF
         tEUP+j43B0YH+KH04Axiwr+vgB34p7c9ZaDsAYbFgFdhlNJnk69TirxuXvUuPyxo0leb
         7jgd2eF03qZz0S8iYZ7D/gCYIRqOzX3BXciQRfl6JHaaLf0rdrMHGQ0jxqlAo88eTwVc
         OYxbWMb9kS/jP2BgvWoe1lC/WZKAyLZx8T+bu+gv33/+s660eP0w9alEVl8T1B8EeH+9
         ItizmIn2I22rzpm6WPSrli/Dk6RHYXDiLrs958FuYIFisAIPeYVnr7dpbou8qZPwVevT
         La5g==
X-Gm-Message-State: ANhLgQ3AC2bhPwRcRJVJACQvE7m/FgeQj8t2adQJx1qdVe3ccMKdNZKW
        OVo0P6fU/eqbJ44IQZHOkb7resaIjSc+4qamgKfiUVsUFY3g9ZVMTO9nNvzYLbN9s5ydYlF+jY7
        BsaQA4IQ7feqQ
X-Received: by 2002:a37:b48:: with SMTP id 69mr3966062qkl.362.1583344190876;
        Wed, 04 Mar 2020 09:49:50 -0800 (PST)
X-Google-Smtp-Source:
 ADFU+vuWUdHcDaT7gZYvMwEEbjQNEGppRVQg++TbU7MnlbDDq4RAg7RhEeWLqMwAEyYWemvBvvuA2Q==
X-Received: by 2002:a37:b48:: with SMTP id 69mr3966036qkl.362.1583344190549;
        Wed, 04 Mar 2020 09:49:50 -0800 (PST)
Received: from xz-x1.redhat.com ([2607:9880:19c0:32::2])
        by smtp.gmail.com with ESMTPSA id
 x184sm10337683qkb.128.2020.03.04.09.49.48
        (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256);
        Wed, 04 Mar 2020 09:49:49 -0800 (PST)
From: Peter Xu <peterx@redhat.com>
To: linux-kernel@vger.kernel.org, kvm@vger.kernel.org
Cc: Yan Zhao <yan.y.zhao@intel.com>, peterx@redhat.com,
        Vitaly Kuznetsov <vkuznets@redhat.com>,
        "Michael S . Tsirkin" <mst@redhat.com>,
        Alex Williamson <alex.williamson@redhat.com>,
        Sean Christopherson <sean.j.christopherson@intel.com>,
        "Dr . David Alan Gilbert" <dgilbert@redhat.com>,
        Jason Wang <jasowang@redhat.com>,
        Kevin Tian <kevin.tian@intel.com>,
        Paolo Bonzini <pbonzini@redhat.com>,
        Christophe de Dinechin <dinechin@redhat.com>
Subject: [PATCH v5 00/14] KVM: Dirty ring interface
Date: Wed,  4 Mar 2020 12:49:33 -0500
Message-Id: <20200304174947.69595-1-peterx@redhat.com>
X-Mailer: git-send-email 2.24.1
MIME-Version: 1.0
Sender: kvm-owner@vger.kernel.org
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

KVM branch:
  https://github.com/xzpeter/linux/tree/kvm-dirty-ring

QEMU branch for testing:
  https://github.com/xzpeter/qemu/tree/kvm-dirty-ring

v5:
- rebased to 5.6-rc4 (removed Paolo's r-b in patch 4 for context change)
- selftest: run all supported modes if mode not specified [Drew]
- selftest: expose vcpu->fd directly to test using vcpu_get_fd [Drew]

v4:
- refactor ring layout: remove indices, use bit 0/1 in the gfn.flags
  field to encode GFN status (invalid, dirtied, collected) [Michael,
  Paolo]
- patch memslot_valid_for_gpte() too to check against memslot flags
  rather than dirty_bitmap pointer
- fix build on non-x86 arch [syzbot]
- fix comment for kvm_dirty_gfn [Michael]
- check against VM_EXEC, VM_SHARED for mmaps [Michael]
- fix "KVM: X86: Don't track dirty for
  KVM_SET_[TSS_ADDR|IDENTITY_MAP_ADDR]" to unbreak
  unrestricted_guest=N [Sean]
- some rework in the test code, e.g., more comments

For previous versions, please refer to:

V1: https://lore.kernel.org/kvm/20191129213505.18472-1-peterx@redhat.com
V2: https://lore.kernel.org/kvm/20191221014938.58831-1-peterx@redhat.com
V3: https://lore.kernel.org/kvm/20200109145729.32898-1-peterx@redhat.com
V4: https://lore.kernel.org/kvm/20200205025105.367213-1-peterx@redhat.com

Overview
============

This is a continued work from Lei Cao <lei.cao@stratus.com> and Paolo
Bonzini on the KVM dirty ring interface.

The new dirty ring interface is another way to collect dirty pages for
the virtual machines. It is different from the existing dirty logging
interface in a few ways, majorly:

  - Data format: The dirty data was in a ring format rather than a
    bitmap format, so dirty bits to sync for dirty logging does not
    depend on the size of guest memory any more, but speed of
    dirtying.  Also, the dirty ring is per-vcpu, while the dirty
    bitmap is per-vm.

  - Data copy: The sync of dirty pages does not need data copy any more,
    but instead the ring is shared between the userspace and kernel by
    page sharings (mmap() on vcpu fd)

  - Interface: Instead of using the old KVM_GET_DIRTY_LOG,
    KVM_CLEAR_DIRTY_LOG interfaces, the new ring uses the new
    KVM_RESET_DIRTY_RINGS ioctl when we want to reset the collected
    dirty pages to protected mode again (works like
    KVM_CLEAR_DIRTY_LOG, but ring based).  To collecting dirty bits,
    we only need to read the ring data, no ioctl is needed.

Ring Layout
===========

KVM dirty ring is per-vcpu.  Each ring is an array of kvm_dirty_gfn
defined as:

struct kvm_dirty_gfn {
        __u32 flags;
        __u32 slot; /* as_id | slot_id */
        __u64 offset;
};

Each GFN is a state machine itself.  The state is embeded in the flags
field, as defined in the uapi header:

/*
 * KVM dirty GFN flags, defined as:
 *
 * |---------------+---------------+--------------|
 * | bit 1 (reset) | bit 0 (dirty) | Status       |
 * |---------------+---------------+--------------|
 * |             0 |             0 | Invalid GFN  |
 * |             0 |             1 | Dirty GFN    |
 * |             1 |             X | GFN to reset |
 * |---------------+---------------+--------------|
 *
 * Lifecycle of a dirty GFN goes like:
 *
 *      dirtied         collected        reset
 * 00 -----------> 01 -------------> 1X -------+
 *  ^                                          |
 *  |                                          |
 *  +------------------------------------------+
 *
 * The userspace program is only responsible for the 01->1X state
 * conversion (to collect dirty bits).  Also, it must not skip any
 * dirty bits so that dirty bits are always collected in sequence.
 */

Testing
=======

This series provided both the implementation of the KVM dirty ring and
the test case.  Also I've implemented the QEMU counterpart that can
run with the new KVM, link can be found at the top of the cover
letter.  However that's still a very initial version which is prone to
change and future optimizations.

I did some measurement with the new method with 24G guest running some
dirty workload, I don't see any speedup so far, even in some heavy
dirty load it'll be slower (e.g., when 800MB/s random dirty rate, kvm
dirty ring takes average of ~73s to complete migration while dirty
logging only needs average of ~55s).  However that's understandable
because 24G guest means only 1M dirty bitmap, that's still a suitable
case for dirty logging.  Meanwhile heavier workload means worst case
for dirty ring.

More tests are welcomed if there's bigger host/guest, especially on
COLO-like workload.

Please review, thanks.

Peter Xu (14):
  KVM: X86: Change parameter for fast_page_fault tracepoint
  KVM: Cache as_id in kvm_memory_slot
  KVM: X86: Don't track dirty for KVM_SET_[TSS_ADDR|IDENTITY_MAP_ADDR]
  KVM: Pass in kvm pointer into mark_page_dirty_in_slot()
  KVM: X86: Implement ring-based dirty memory tracking
  KVM: Make dirty ring exclusive to dirty bitmap log
  KVM: Don't allocate dirty bitmap if dirty ring is enabled
  KVM: selftests: Always clear dirty bitmap after iteration
  KVM: selftests: Sync uapi/linux/kvm.h to tools/
  KVM: selftests: Use a single binary for dirty/clear log test
  KVM: selftests: Introduce after_vcpu_run hook for dirty log test
  KVM: selftests: Add dirty ring buffer test
  KVM: selftests: Let dirty_log_test async for dirty ring test
  KVM: selftests: Add "-c" parameter to dirty log test

 Documentation/virt/kvm/api.rst                | 123 +++++
 arch/x86/include/asm/kvm_host.h               |   6 +-
 arch/x86/include/uapi/asm/kvm.h               |   1 +
 arch/x86/kvm/Makefile                         |   3 +-
 arch/x86/kvm/mmu/mmu.c                        |  10 +-
 arch/x86/kvm/mmutrace.h                       |   9 +-
 arch/x86/kvm/svm.c                            |   9 +-
 arch/x86/kvm/vmx/vmx.c                        |  85 +--
 arch/x86/kvm/x86.c                            |  49 +-
 include/linux/kvm_dirty_ring.h                |  50 ++
 include/linux/kvm_host.h                      |  21 +
 include/trace/events/kvm.h                    |  78 +++
 include/uapi/linux/kvm.h                      |  44 ++
 tools/include/uapi/linux/kvm.h                |  44 ++
 tools/testing/selftests/kvm/Makefile          |   2 -
 .../selftests/kvm/clear_dirty_log_test.c      |   2 -
 tools/testing/selftests/kvm/dirty_log_test.c  | 488 ++++++++++++++++--
 .../testing/selftests/kvm/include/kvm_util.h  |   4 +
 tools/testing/selftests/kvm/lib/kvm_util.c    |  67 +++
 .../selftests/kvm/lib/kvm_util_internal.h     |   4 +
 virt/kvm/dirty_ring.c                         | 176 +++++++
 virt/kvm/kvm_main.c                           | 236 ++++++++-
 22 files changed, 1386 insertions(+), 125 deletions(-)
 create mode 100644 include/linux/kvm_dirty_ring.h
 delete mode 100644 tools/testing/selftests/kvm/clear_dirty_log_test.c
 create mode 100644 virt/kvm/dirty_ring.c
```
#### [PATCH v5 00/23] irqchip/gic-v4: GICv4.1 architecture support
##### From: Marc Zyngier <maz@kernel.org>
X-SA-Exim-Mail-From: maz@kernel.org

```c
From patchwork Wed Mar  4 20:33:07 2020
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Marc Zyngier <maz@kernel.org>
X-Patchwork-Id: 11420709
Return-Path: <SRS0=VNnu=4V=vger.kernel.org=kvm-owner@kernel.org>
Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org
 [172.30.200.123])
	by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id D47C01395
	for <patchwork-kvm@patchwork.kernel.org>;
 Wed,  4 Mar 2020 20:35:25 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [209.132.180.67])
	by mail.kernel.org (Postfix) with ESMTP id ACECB24654
	for <patchwork-kvm@patchwork.kernel.org>;
 Wed,  4 Mar 2020 20:35:25 +0000 (UTC)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org;
	s=default; t=1583354125;
	bh=EccRIJfqWszlojINoiDMmQQnsb0+rQyVI2xUVh/plgk=;
	h=From:To:Cc:Subject:Date:List-ID:From;
	b=ZBaQ727qIM/Xw5biYbq8Qj6D/WIfahN11bE/x6SeRAtpMeQevKz3y/CNGA3Qx3JWK
	 2D6F/Oj9Spu2h2AJPstuloYaIV1ho7A4xpyT6pKS0bYukC0ndQakN3bVyGVRCby/uc
	 CXAZZbfqOY+yOj99f766R2HdRvQxjk9UUiJiFGVA=
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S2387505AbgCDUel (ORCPT
        <rfc822;patchwork-kvm@patchwork.kernel.org>);
        Wed, 4 Mar 2020 15:34:41 -0500
Received: from mail.kernel.org ([198.145.29.99]:34682 "EHLO mail.kernel.org"
        rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP
        id S1728642AbgCDUel (ORCPT <rfc822;kvm@vger.kernel.org>);
        Wed, 4 Mar 2020 15:34:41 -0500
Received: from disco-boy.misterjones.org (disco-boy.misterjones.org
 [51.254.78.96])
        (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits))
        (No client certificate requested)
        by mail.kernel.org (Postfix) with ESMTPSA id 0590F2146E;
        Wed,  4 Mar 2020 20:34:40 +0000 (UTC)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kernel.org;
        s=default; t=1583354080;
        bh=EccRIJfqWszlojINoiDMmQQnsb0+rQyVI2xUVh/plgk=;
        h=From:To:Cc:Subject:Date:From;
        b=fMndKntSxrYcdIzHDf5W7dfxHX7dqrNrLDlG2f+x9yUL2diG3BWQOKaiiVgxGe50h
         fLicNAlpoKOsdxImuN6PZ5YKOB6t+hq5olmAvhEADhkqm2GLPousO7zHr+K0fQnHK8
         MYX+oVMUXX8qMT9N57gTTg233z6EuIl0rgDmxVeg=
Received: from 78.163-31-62.static.virginmediabusiness.co.uk ([62.31.163.78]
 helo=why.lan)
        by disco-boy.misterjones.org with esmtpsa
 (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256)
        (Exim 4.92)
        (envelope-from <maz@kernel.org>)
        id 1j9aiz-00A59R-EB; Wed, 04 Mar 2020 20:34:37 +0000
From: Marc Zyngier <maz@kernel.org>
To: linux-arm-kernel@lists.infradead.org, kvmarm@lists.cs.columbia.edu,
        kvm@vger.kernel.org, linux-kernel@vger.kernel.org
Cc: Lorenzo Pieralisi <lorenzo.pieralisi@arm.com>,
        Jason Cooper <jason@lakedaemon.net>,
        Robert Richter <rrichter@marvell.com>,
        Thomas Gleixner <tglx@linutronix.de>,
        Zenghui Yu <yuzenghui@huawei.com>,
        Eric Auger <eric.auger@redhat.com>,
        James Morse <james.morse@arm.com>,
        Julien Thierry <julien.thierry.kdev@gmail.com>,
        Suzuki K Poulose <suzuki.poulose@arm.com>
Subject: [PATCH v5 00/23] irqchip/gic-v4: GICv4.1 architecture support
Date: Wed,  4 Mar 2020 20:33:07 +0000
Message-Id: <20200304203330.4967-1-maz@kernel.org>
X-Mailer: git-send-email 2.20.1
MIME-Version: 1.0
X-SA-Exim-Connect-IP: 62.31.163.78
X-SA-Exim-Rcpt-To: linux-arm-kernel@lists.infradead.org,
 kvmarm@lists.cs.columbia.edu, kvm@vger.kernel.org,
 linux-kernel@vger.kernel.org, lorenzo.pieralisi@arm.com,
 jason@lakedaemon.net, rrichter@marvell.com, tglx@linutronix.de,
 yuzenghui@huawei.com, eric.auger@redhat.com, james.morse@arm.com,
 julien.thierry.kdev@gmail.com, suzuki.poulose@arm.com
X-SA-Exim-Mail-From: maz@kernel.org
X-SA-Exim-Scanned: No (on disco-boy.misterjones.org);
 SAEximRunCond expanded to false
Sender: kvm-owner@vger.kernel.org
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

This (now shorter) series expands the existing GICv4 support to deal
with the new GICv4.1 architecture, which comes with a set of major
improvements compared to v4.0:

- One architectural doorbell per vcpu, instead of one doorbell per VLPI

- Doorbell entirely managed by the HW, with an "at most once" delivery
  guarantee per non-residency phase and only when requested by the
  hypervisor

- A shared memory scheme between ITSs and redistributors, allowing for an
  optimised residency sequence (the use of VMOVP becomes less frequent)

- Support for direct virtual SGI delivery (the injection path still involves
  the hypervisor), at the cost of losing the active state on SGIs. It
  shouldn't be a big deal, but some guest operating systems might notice
  (Linux definitely won't care).

On the other hand, public documentation is not available yet, so that's a
bit annoying...

The series is roughly organised in 3 parts:

(0) Fixes
(1) v4.1 doorbell management
(2) Virtual SGI support
(3) Plumbing of virtual SGIs in KVM

Notes:

  - The whole thing is tested on a FVP model, which can be obtained
    free of charge on ARM's developer website. It requires you to
    create an account, unfortunately... You'll need a fix for the
    devicetree that is in the kernel tree (should be merged before
    the 5.6 release).

  - This series has uncovered a behaviour that looks like a HW bug on
    the Cavium ThunderX (aka TX1) platform. I'd very much welcome some
    clarification from the Marvell/Cavium folks on Cc, as well as an
    official erratum number if this happens to be an actual bug.

    [v3 update]
    People have ignored for two months now, and it is fairly obvious
    that support for this machine is slowly bit-rotting. Maybe I'll
    drop the patch and instead start the process of removing all TX1
    support from the kernel (we'd certainly be better off without it).

    [v4 update]
    TX1 is now broken in mainline, and nobody cares. Make of this what
    you want.

  - I'm extremely grateful for Zenghui Yu's huge effort in carefully
    reviewing this rather difficult series (if we ever get to meet
    face to face, drinks are definitely on me!).

  - Unless someone cries wolf, I plan to take this into 5.7.

* From v4 [4]
  - Rebased on v5.6-rc4
  - Fixed locking all over the shop now that we can bypass the ITS
  - Wait on INVALL at the RD level
  - Plentu of cleanups/fixes thanks to Zenghui's careful review effort

* From v3 [3]:
  - Rebased on v5.6-rc1
  - Considerably smaller thanks to the initial patches being merged
  - Small bug fix after the v5.6 merge window

* From v2 [2]:
  - Another bunch of fixes thanks to Zenghui Yu's very careful review
  - HW-accelerated SGIs are now optional thanks to new architected
    discovery/selection bits exposed by KVM and used by the guest kernel
  - Rebased on v5.5-rc2

* From v1 [1]:
  - A bunch of minor reworks after Zenghui Yu's review
  - A workaround for what looks like a new and unexpected TX1 bug
  - A subtle reorder of the series so that some patches can go in early

[1] https://lore.kernel.org/lkml/20190923182606.32100-1-maz@kernel.org/
[2] https://lore.kernel.org/lkml/20191027144234.8395-1-maz@kernel.org/
[3] https://lore.kernel.org/r/20191224111055.11836-1-maz@kernel.org/
[4] https://lore.kernel.org/r/20200214145736.18550-1-maz@kernel.org/

Marc Zyngier (22):
  irqchip/gic-v3: Use SGIs without active state if offered
  irqchip/gic-v4.1: Skip absent CPUs while iterating over redistributors
  irqchip/gic-v4.1: Ensure mutual exclusion between vPE affinity change
    and RD access
  irqchip/gic-v4.1: Ensure mutual exclusion betwen invalidations on the
    same RD
  irqchip/gic-v4.1: Advertise support v4.1 to KVM
  irqchip/gic-v4.1: Map the ITS SGIR register page
  irqchip/gic-v4.1: Plumb skeletal VSGI irqchip
  irqchip/gic-v4.1: Add initial SGI configuration
  irqchip/gic-v4.1: Plumb mask/unmask SGI callbacks
  irqchip/gic-v4.1: Plumb get/set_irqchip_state SGI callbacks
  irqchip/gic-v4.1: Plumb set_vcpu_affinity SGI callbacks
  irqchip/gic-v4.1: Move doorbell management to the GICv4 abstraction
    layer
  irqchip/gic-v4.1: Add VSGI allocation/teardown
  irqchip/gic-v4.1: Add VSGI property setup
  irqchip/gic-v4.1: Eagerly vmap vPEs
  KVM: arm64: GICv4.1: Let doorbells be auto-enabled
  KVM: arm64: GICv4.1: Add direct injection capability to SGI registers
  KVM: arm64: GICv4.1: Allow SGIs to switch between HW and SW interrupts
  KVM: arm64: GICv4.1: Plumb SGI implementation selection in the
    distributor
  KVM: arm64: GICv4.1: Reload VLPI configuration on distributor
    enable/disable
  KVM: arm64: GICv4.1: Allow non-trapping WFI when using HW SGIs
  KVM: arm64: GICv4.1: Expose HW-based SGIs in debugfs

Zenghui Yu (1):
  irqchip/gic-v4.1: Wait for completion of redistributor's INVALL
    operation

 arch/arm/include/asm/kvm_host.h        |   1 +
 arch/arm64/include/asm/kvm_emulate.h   |   3 +-
 arch/arm64/include/asm/kvm_host.h      |   1 +
 drivers/irqchip/irq-gic-v3-its.c       | 385 +++++++++++++++++++++++--
 drivers/irqchip/irq-gic-v3.c           |  13 +-
 drivers/irqchip/irq-gic-v4.c           | 134 ++++++++-
 include/kvm/arm_vgic.h                 |   4 +
 include/linux/irqchip/arm-gic-common.h |   2 +
 include/linux/irqchip/arm-gic-v3.h     |  20 +-
 include/linux/irqchip/arm-gic-v4.h     |  25 +-
 virt/kvm/arm/arm.c                     |   8 +
 virt/kvm/arm/vgic/vgic-debug.c         |  14 +-
 virt/kvm/arm/vgic/vgic-mmio-v3.c       |  68 ++++-
 virt/kvm/arm/vgic/vgic-mmio.c          |  88 +++++-
 virt/kvm/arm/vgic/vgic-v3.c            |   6 +-
 virt/kvm/arm/vgic/vgic-v4.c            | 137 +++++++--
 virt/kvm/arm/vgic/vgic.h               |   1 +
 17 files changed, 844 insertions(+), 66 deletions(-)
```


text:
using System;
using System.Net.Sockets;

namespace OrigoDB.Core.Utilities
{
	public static class SocketExtensions
	{
		public static bool IsConnected(this Socket socket)
		{
			try
			{
				return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
			}
			catch (SocketException) { return false; }
			catch (ObjectDisposedException)
			{
				return false;
			}
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.geekdos.client;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.9-b130926.1035
 * Generated source version: 2.2
 *
 */
@WebServiceClient(name = "HalimaService", targetNamespace = "http://service.geekdos.com/", wsdlLocation = "http://localhost:8088/SeyHello?wsdl")
public class HalimaService
    extends Service
{

    private final static URL HALIMASERVICE_WSDL_LOCATION;
    private final static WebServiceException HALIMASERVICE_EXCEPTION;
    private final static QName HALIMASERVICE_QNAME = new QName("http://service.geekdos.com/", "HalimaService");

    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("http://localhost:8088/SeyHello?wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        HALIMASERVICE_WSDL_LOCATION = url;
        HALIMASERVICE_EXCEPTION = e;
    }

    public HalimaService() {
        super(__getWsdlLocation(), HALIMASERVICE_QNAME);
    }

    public HalimaService(WebServiceFeature... features) {
        super(__getWsdlLocation(), HALIMASERVICE_QNAME, features);
    }

    public HalimaService(URL wsdlLocation) {
        super(wsdlLocation, HALIMASERVICE_QNAME);
    }

    public HalimaService(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, HALIMASERVICE_QNAME, features);
    }

    public HalimaService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public HalimaService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     *
     * @return
     *     returns Halima
     */
    @WebEndpoint(name = "HalimaPort")
    public Halima getHalimaPort() {
        return super.getPort(new QName("http://service.geekdos.com/", "HalimaPort"), Halima.class);
    }

    /**
     *
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the features parameter will have their default values.
     * @return
     *     returns Halima
     */
    @WebEndpoint(name = "HalimaPort")
    public Halima getHalimaPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://service.geekdos.com/", "HalimaPort"), Halima.class, features);
    }

    private static URL __getWsdlLocation() {
        if (HALIMASERVICE_EXCEPTION!= null) {
            throw HALIMASERVICE_EXCEPTION;
        }
        return HALIMASERVICE_WSDL_LOCATION;
    }

}


text:
class op_stddev
  {
  public:

  template<typename T1>
  inline static void apply(Mat<typename T1::pod_type>& out, const mtOp<typename T1::pod_type, T1, op_stddev>& in);
  };

//! @}


text:
@import "../tokens/tokens";
@import "custom-properties";
@import "custom-media";
@import "mixin";


text:
package com.miningpro.repository.slot;

import com.miningpro.core.event.Event;
import com.miningpro.core.event.AnalysisUnit;

/**
 * Slots que armazenam métricas para cada AnalysisUnit relacionada ao conjunto de eventos.
 *
 * @author gsantiago
 *
 * @param <N>
 *            Tipo da métrica, deve ser numérica
 * @param <E>
 *            Tipo do evento armazenado.
 */
public interface AnalysisUnitBasedMetricsSlot<N extends Number, E extends Event> extends AnalysisUnitBasedSlot<E> {

    N getMetric(AnalysisUnit m);

    N getDefaultMetricValue();
}


text:
/*global define, window */

;(function (factory) {
  'use strict'
  if (typeof define === 'function' && define.amd) {
    define([
      'jquery',
      './blueimp-gallery'
    ], factory)
  } else {
    factory(
      window.jQuery,
      window.blueimp.Gallery
    )
  }
}(function ($, Gallery) {
  'use strict'

  $.extend(Gallery.prototype.options, {
    useBootstrapModal: true
  })

  var close = Gallery.prototype.close
  var imageFactory = Gallery.prototype.imageFactory
  var videoFactory = Gallery.prototype.videoFactory
  var textFactory = Gallery.prototype.textFactory

  $.extend(Gallery.prototype, {
    modalFactory: function (obj, callback, factoryInterface, factory) {
      if (!this.options.useBootstrapModal || factoryInterface) {
        return factory.call(this, obj, callback, factoryInterface)
      }
      var that = this
      console.log(this)
      var modalTemplate = this.container.children('.modal')
      var modal = modalTemplate.clone().show().on('click', function (event) {
        // Close modal if click is outside of modal-content:
        if (event.target === modal[0] ||
          event.target === modal.children()[0]) {
          event.preventDefault()
          event.stopPropagation()
          that.close()
        }
      })
      var element = factory.call(this, obj, function (event) {
        callback({
          type: event.type,
          target: modal[0]
        })
        modal.addClass('in')
      }, factoryInterface)
      modal.find('.modal-title').text(element.title || String.fromCharCode(160))
      modal.find('.modal-body').append(element)

      return modal[0]
    },

    imageFactory: function (obj, callback, factoryInterface) {
      return this.modalFactory(obj, callback, factoryInterface, imageFactory)
    },

    videoFactory: function (obj, callback, factoryInterface) {
      return this.modalFactory(obj, callback, factoryInterface, videoFactory)
    },

    textFactory: function (obj, callback, factoryInterface) {
      return this.modalFactory(obj, callback, factoryInterface, textFactory)
    },

    close: function () {
      this.container.find('.modal').removeClass('in')
      close.call(this)
    }

  })
}))


text:
<!--
Copyright 2013 The Polymer Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<polymer-element name="polymer-layout" attributes="vertical">
  <template>
    <style>
      @host {
        * {
          display: none;
        }
      }
    </style>
  </template>
  <script>
    Polymer('polymer-layout', {
      vertical: false,
      ready: function() {
        this.setAttribute('nolayout', '');
      },
      inserted: function() {
        this.asyncMethod(function() {
          this.prepare();
          this.layout();
        });
      },
      prepare: function() {
        var parent = this.parentNode.host || this.parentNode;
        // may recalc
        var cs = window.getComputedStyle(parent);
        if (cs.position === 'static') {
          parent.style.position = 'relative';
        }
        parent.style.overflow = 'hidden';
        // changes will cause another recalc at next validation step
        var vertical;
        this.parentNode.childNodes.forEach(function(c, i) {
          if (c.nodeType === Node.ELEMENT_NODE && !c.hasAttribute('nolayout')) {
            stylize(c, {
              position: 'absolute',
              boxSizing: 'border-box',
              MozBoxSizing: 'border-box',
            });
            // test for auto-vertical
            if (vertical === undefined) {
              vertical = (c.offsetWidth == 0 && c.offsetHeight !== 0);
            }
          }
        });
        this.vertical = this.vertical || vertical;
      },
      layout: function() {
        var parent = this.parentNode.host || this.parentNode;
        var vertical = this.vertical;
        var ww = 0, hh = 0, pre = [], fit, post = [];
        var list = pre;
        // gather element information (at most one recalc)
        this.parentNode.childNodes.forEach(function(c, i) {
          if (c.nodeType===Node.ELEMENT_NODE && !c.hasAttribute('nolayout')) {
            var info = {
              element: c,
              w: c.offsetWidth,
              h: c.offsetHeight
            };
            if (!c.hasAttribute('fit')) {
              ww += c.offsetWidth;
              hh += c.offsetHeight;
              list.push(info);
            } else {
              fit = c;
              list = post;
              ww = hh = 0;
            }
          }
        });
        // update layout styles (invalidate, no recalc)
        var v = 0;
        var mxp = 0, myp = 0;
        pre.forEach(function(info) {
          if (vertical) {
            stylize(info.element, {
              top: v + 'px', right: mxp, height: info.h + 'px', left: mxp
            });
          } else {
            stylize(info.element, {
              top: myp, width: info.w + 'px', bottom: myp, left: v + 'px'
            });
          }
          v += vertical ? info.h : info.w;
        });
        if (fit) {
          if (vertical) {
            stylize(fit, {
              top: v + 'px', right: mxp, bottom: hh + 'px', left: mxp
            });
          } else {
            stylize(fit, {
              top: myp, right: ww + 'px', bottom: myp, left: v + 'px'
            });
          }
          v = vertical ? hh : ww;
          post.forEach(function(info) {
            v -= vertical ? info.h : info.w;
            if (vertical) {
              stylize(info.element, {
                height: info.h + 'px', right: mxp, bottom: v + 'px', left: mxp
              });
            } else {
              stylize(info.element, {
                top: myp, right: v + 'px', bottom: myp, width: info.w + 'px'
              });
            }
          });
        }
      }
    });
    function stylize(element, styles) {
      var style = element.style;
      Object.keys(styles).forEach(function(k){
        style[k] = styles[k];
      });
    }
  </script>
</polymer-element>


text:
namespace media {

// A class that keeps a callback registered. The callback will be unregistered
// upon destruction of this object.
class CallbackRegistration {
 public:
  CallbackRegistration() = default;

  CallbackRegistration(const CallbackRegistration&) = delete;
  CallbackRegistration& operator=(const CallbackRegistration&) = delete;

  virtual ~CallbackRegistration() = default;
};

template <typename Sig>
class CallbackRegistry;

// A helper class that can register, unregister callbacks, and notify registered
// callbacks. This class is thread safe: all methods can be called on any
// thread. The CallbackRegistry must outlive all CallbackRegistrations returned
// by Register().
// TODO(xhwang): This class is similar to base::RepeatingCallbackList, but is
// simpler, and provides thread safety. Consider merging these two.
template <typename... Args>
class CallbackRegistry<void(Args...)> {
 public:
  using CallbackType = base::RepeatingCallback<void(Args...)>;

  CallbackRegistry() = default;

  CallbackRegistry(const CallbackRegistry&) = delete;
  CallbackRegistry& operator=(const CallbackRegistry&) = delete;

  ~CallbackRegistry() = default;

  [[nodiscard]] std::unique_ptr<CallbackRegistration> Register(
      CallbackType cb) {
    base::AutoLock lock(lock_);
    DCHECK(cb);
    uint32_t registration_id = ++next_registration_id_;
    DVLOG(1) << __func__ << ": registration_id = " << registration_id;

    // Use BindToCurrentLoop so that the callbacks are always posted to the
    // thread where Register() is called. Also, this helps avoid reentrancy
    // and deadlock issues, e.g. Register() is called in one of the callbacks.
    callbacks_[registration_id] = BindToCurrentLoop(std::move(cb));

    return std::make_unique<RegistrationImpl>(this, registration_id);
  }

  void Notify(Args&&... args) {
    DVLOG(1) << __func__;
    base::AutoLock lock(lock_);
    for (auto const& [key_id, callback] : callbacks_)
      callback.Run(std::forward<Args>(args)...);
  }

 private:
  class RegistrationImpl : public CallbackRegistration {
   public:
    RegistrationImpl(CallbackRegistry<void(Args...)>* registry,
                     uint32_t registration_id)
        : registry_(registry), registration_id_(registration_id) {}

    RegistrationImpl(const RegistrationImpl&) = delete;
    RegistrationImpl& operator=(const RegistrationImpl&) = delete;

    ~RegistrationImpl() override { registry_->Unregister(registration_id_); }

   private:
    raw_ptr<CallbackRegistry<void(Args...)>> registry_ = nullptr;
    uint32_t registration_id_ = 0;
  };

  void Unregister(uint32_t registration_id) {
    DVLOG(1) << __func__ << ": registration_id = " << registration_id;
    base::AutoLock lock(lock_);
    size_t num_callbacks_removed = callbacks_.erase(registration_id);
    DCHECK_EQ(num_callbacks_removed, 1u);
  }

  base::Lock lock_;
  uint32_t next_registration_id_ GUARDED_BY(lock_) = 0;
  std::map<uint32_t, CallbackType> callbacks_ GUARDED_BY(lock_);
};

using ClosureRegistry = CallbackRegistry<void()>;

}  // namespace media

#endif  // MEDIA_BASE_CALLBACK_REGISTRY_H_


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

<title>ServletApiController (Spring Security 4.2.2.RELEASE API)</title>
<meta name="date" content="2017-10-31">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

ÄúµÄä¯ÀÀÆ÷ÒѽûÓà JavaScript¡£

Ìø¹ýµ¼º½Á´½Ó

³ÌÐò°ü

Àà

Ê÷

Òѹýʱ

Ë÷Òý

°ïÖú

spring-security-samples-xml-servletapi

ÉÏÒ»¸öÀà

ÏÂÒ»¸öÀà

¿ò¼Ü

ÎÞ¿ò¼Ü

ËùÓÐÀà

¸ÅÒª:

ǶÌ× |

×Ö¶Î |

¹¹ÔìÆ÷ |

·½·¨

Ïêϸ×ÊÁÏ:

×Ö¶Î |

¹¹ÔìÆ÷ |

·½·¨

org.springframework.security.samples.servletapi.mvc

Àà ServletApiController

java.lang.Object

org.springframework.security.samples.servletapi.mvc.ServletApiController

@Controller
public class ServletApiController
extends java.lang.Object

A Spring MVC Controller that demonstrates Spring Security's integration with the
 standard Servlet API's. Specifically it demonstrates the following:

authenticate(HttpServletRequest, HttpServletResponse) - Integration with
 HttpServletRequest.authenticate(HttpServletResponse)

login(HttpServletRequest, HttpServletResponse, LoginForm, BindingResult) -
 Integration with HttpServletRequest.login(String, String)

logout(HttpServletRequest, HttpServletResponse, RedirectAttributes) - Integration with
 HttpServletRequest.logout()

remoteUser(HttpServletRequest) - Integration with
 HttpServletRequest.getRemoteUser()

userPrincipal(HttpServletRequest) - Integration with
 HttpServletRequest.getUserPrincipal()

authentication(Authentication) - Spring MVC's ability to resolve the
 Authentication since it is found on
 HttpServletRequest.getUserPrincipal()

×÷Õß:

Rob Winch

¹¹ÔìÆ÷¸ÅÒª

¹¹ÔìÆ÷

¹¹ÔìÆ÷ºÍ˵Ã÷

ServletApiController()

·½·¨¸ÅÒª

ËùÓз½·¨ ʵÀý·½·¨ ¾ßÌå·½·¨

ÏÞ¶¨·ûºÍÀàÐÍ
·½·¨ºÍ˵Ã÷

void
asynch(javax.servlet.http.HttpServletRequest request,
      javax.servlet.http.HttpServletResponse response)

Demonstrates Spring Security with AsyncContext.start(Runnable).

java.lang.String
authenticate(javax.servlet.http.HttpServletRequest request,
            javax.servlet.http.HttpServletResponse response)

Demonstrates that HttpServletRequest.authenticate(HttpServletResponse) will
 send the user to the log in page configured within Spring Security if the user is
 not already authenticated.

org.springframework.security.core.Authentication
authentication(org.springframework.security.core.Authentication authentication)

Spring MVC will automatically resolve any object that implements Principal
 using HttpServletRequest.getUserPrincipal().

java.lang.String
login(javax.servlet.http.HttpServletRequest request,
     javax.servlet.http.HttpServletResponse response,
     LoginForm loginForm,
     org.springframework.validation.BindingResult result)

Demonstrates that you can authenticate with Spring Security using
 HttpServletRequest.login(String, String).

java.lang.String
login(LoginForm loginForm)

java.lang.String
logout(javax.servlet.http.HttpServletRequest request,
      javax.servlet.http.HttpServletResponse response,
      org.springframework.web.servlet.mvc.support.RedirectAttributes redirect)

Demonstrates that invoking HttpServletRequest.logout() will log the user
 out.

java.lang.String
remoteUser(javax.servlet.http.HttpServletRequest request)

Demonstrates that Spring Security automatically populates
 HttpServletRequest.getRemoteUser() with the current username.

java.security.Principal
userPrincipal(javax.servlet.http.HttpServletRequest request)

Demonstrates that Spring Security automatically populates
 HttpServletRequest.getUserPrincipal() with the Authentication that
 is present on SecurityContextHolder.getContext()

java.lang.String
welcome()

´ÓÀà¼Ì³ÐµÄ·½·¨ java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

¹¹ÔìÆ÷Ïêϸ×ÊÁÏ

ServletApiController

public ServletApiController()

·½·¨Ïêϸ×ÊÁÏ

authenticate

@RequestMapping(value="/authenticate")
public java.lang.String authenticate(javax.servlet.http.HttpServletRequest request,
                                                                             javax.servlet.http.HttpServletResponse response)
                                                                      throws javax.servlet.ServletException,
                                                                             java.io.IOException

Demonstrates that HttpServletRequest.authenticate(HttpServletResponse) will
 send the user to the log in page configured within Spring Security if the user is
 not already authenticated.

²ÎÊý:

request -

response -

·µ»Ø:

Å׳ö:

javax.servlet.ServletException

java.io.IOException

login

@RequestMapping(value="/login",
                method=POST)
public java.lang.String login(javax.servlet.http.HttpServletRequest request,
                                                                                javax.servlet.http.HttpServletResponse response,
                                                                                @ModelAttribute
                                                                                LoginForm loginForm,
                                                                                org.springframework.validation.BindingResult result)
                                                                                throws javax.servlet.ServletException

Demonstrates that you can authenticate with Spring Security using
 HttpServletRequest.login(String, String).

 If we fail to authenticate, a ServletException is thrown that wraps the
 original AuthenticationException from Spring Security. This means we can
 catch the ServletException to display the error message. Alternatively, we
 could allow the ServletException to propegate and Spring Security's
 ExceptionTranslationFilter would catch it and process it appropriately.

 In this method we choose to use Spring MVC's ModelAttribute to make things
 easier for our form. However, this is not necessary. We could have just as easily
 obtained the request parameters from the HttpServletRequest object.
 Remember all of these examples would work in a standard Servlet or anything
 with access to the HttpServletRequest and HttpServletResponse.

²ÎÊý:

request -

response -

loginForm -

result -

·µ»Ø:

Å׳ö:

javax.servlet.ServletException

logout

@RequestMapping(value="/logout")
public java.lang.String logout(javax.servlet.http.HttpServletRequest request,
                                                                 javax.servlet.http.HttpServletResponse response,
                                                                 org.springframework.web.servlet.mvc.support.RedirectAttributes redirect)
                                                          throws javax.servlet.ServletException

Demonstrates that invoking HttpServletRequest.logout() will log the user
 out. Note that the response does not get processed, so you need to write something
 to the response.

²ÎÊý:

request -

response -

redirect -

·µ»Ø:

Å׳ö:

javax.servlet.ServletException

asynch

@RequestMapping(value="/async")
public void asynch(javax.servlet.http.HttpServletRequest request,
                                                    javax.servlet.http.HttpServletResponse response)

Demonstrates Spring Security with AsyncContext.start(Runnable). Spring
 Security will automatically transfer the SecurityContext from the thread
 that AsyncContext.start(Runnable) is invoked to the new Thread that invokes
 the Runnable.

²ÎÊý:

request -

response -

remoteUser

@ModelAttribute(value="remoteUser")
public java.lang.String remoteUser(javax.servlet.http.HttpServletRequest request)

Demonstrates that Spring Security automatically populates
 HttpServletRequest.getRemoteUser() with the current username.

²ÎÊý:

request -

·µ»Ø:

userPrincipal

@ModelAttribute(value="userPrincipal")
public java.security.Principal userPrincipal(javax.servlet.http.HttpServletRequest request)

Demonstrates that Spring Security automatically populates
 HttpServletRequest.getUserPrincipal() with the Authentication that
 is present on SecurityContextHolder.getContext()

²ÎÊý:

request -

·µ»Ø:

authentication

@ModelAttribute
public org.springframework.security.core.Authentication authentication(org.springframework.security.core.Authentication authentication)

Spring MVC will automatically resolve any object that implements Principal
 using HttpServletRequest.getUserPrincipal(). This means you can easily
 resolve the Authentication just by adding it as an argument to your MVC
 controller. Alternatively, you could also have an argument of type
 Principal which would not couple your controller to Spring Security.

²ÎÊý:

authentication -

·µ»Ø:

welcome

@RequestMapping(value="/")
public java.lang.String welcome()

login

@RequestMapping(value="/login",
                method=GET)
public java.lang.String login(@ModelAttribute
                                                                                LoginForm loginForm)

Ìø¹ýµ¼º½Á´½Ó

³ÌÐò°ü

Àà

Ê÷

Òѹýʱ

Ë÷Òý

°ïÖú

spring-security-samples-xml-servletapi

ÉÏÒ»¸öÀà

ÏÂÒ»¸öÀà

¿ò¼Ü

ÎÞ¿ò¼Ü

ËùÓÐÀà

¸ÅÒª:

ǶÌ× |

×Ö¶Î |

¹¹ÔìÆ÷ |

·½·¨

Ïêϸ×ÊÁÏ:

×Ö¶Î |

¹¹ÔìÆ÷ |

·½·¨


text:
<?php

class ApiClientException extends Exception {}

?>


text:
package com.physphil.android.unitconverterultimate.test;

import com.physphil.android.unitconverterultimate.models.Conversion;
import com.physphil.android.unitconverterultimate.presenters.ConversionPresenter;
import com.physphil.android.unitconverterultimate.util.Conversions;

import org.junit.Before;
import org.junit.Test;
import org.mockito.AdditionalMatchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static com.physphil.android.unitconverterultimate.models.Unit.*;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;

/**
 * JUnit tests for unit conversions
 * Created by pshadlyn on 8/10/2015.
 */
public class ConversionTests
{
    @Mock ConversionPresenter.ConversionView view;

    private final double DELTA_4 = 0.0001;
    private final double DELTA_6 = 0.000001;
    private final double DELTA_7 = 0.0000001;
    private final double DELTA_9 = 0.000000001;
    private final double DELTA_10 = 0.0000000001;
    private Conversions mConversions;
    private ConversionPresenter mPresenter;

    @Before
    public void setup()
    {
        MockitoAnnotations.initMocks(this);
        mConversions = Conversions.getInstance();
        mPresenter = new ConversionPresenter(view);
    }

    @Test
    public void testArea()
    {
        Conversion area = mConversions.getById(Conversion.AREA);

        // Test each fromBase and toBase value
        mPresenter.convert(5.5, area.getUnitById(SQ_KILOMETRES), area.getUnitById(SQ_METRES));
        verify(view, atLeastOnce()).showResult(eq(5500000.0));
        mPresenter.convert(5.5, area.getUnitById(SQ_METRES), area.getUnitById(SQ_CENTIMETRES));
        verify(view, atLeastOnce()).showResult(eq(55000.0));
        mPresenter.convert(5.5, area.getUnitById(SQ_CENTIMETRES), area.getUnitById(HECTARE));
        verify(view, atLeastOnce()).showResult(eq(0.000000055));
        mPresenter.convert(5.5, area.getUnitById(HECTARE), area.getUnitById(SQ_MILE));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(0.0212, DELTA_4));
        mPresenter.convert(5.5, area.getUnitById(SQ_MILE), area.getUnitById(SQ_YARD));
        verify(view, atLeastOnce()).showResult(eq(17036800.0));
        mPresenter.convert(5.5, area.getUnitById(SQ_YARD), area.getUnitById(SQ_FOOT));
        verify(view, atLeastOnce()).showResult(eq(49.5));
        mPresenter.convert(5.5, area.getUnitById(SQ_FOOT), area.getUnitById(SQ_INCH));
        verify(view, atLeastOnce()).showResult(eq(792.0));
        mPresenter.convert(5.5, area.getUnitById(SQ_INCH), area.getUnitById(ACRE));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(0.0000008768, DELTA_10));
        mPresenter.convert(5.5, area.getUnitById(ACRE), area.getUnitById(SQ_KILOMETRES));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(0.0223, DELTA_4));
    }

    @Test
    public void testStorage()
    {
        Conversion storage = mConversions.getById(Conversion.STORAGE);

        mPresenter.convert(4.0, storage.getUnitById(BYTE), storage.getUnitById(BIT));
        verify(view, atLeastOnce()).showResult(eq(32.0));
        mPresenter.convert(4.0, storage.getUnitById(KILOBIT), storage.getUnitById(BYTE));
        verify(view, atLeastOnce()).showResult(eq(512.0));
        mPresenter.convert(4.0, storage.getUnitById(KILOBYTE), storage.getUnitById(KILOBIT));
        verify(view, atLeastOnce()).showResult(eq(32.0));
        mPresenter.convert(4.0, storage.getUnitById(MEGABIT), storage.getUnitById(KILOBYTE));
        verify(view, atLeastOnce()).showResult(eq(512.0));
        mPresenter.convert(4.0, storage.getUnitById(MEGABYTE), storage.getUnitById(MEGABIT));
        verify(view, atLeastOnce()).showResult(eq(32.0));
        mPresenter.convert(4.0, storage.getUnitById(GIGABIT), storage.getUnitById(MEGABYTE));
        verify(view, atLeastOnce()).showResult(eq(512.0));
        mPresenter.convert(4.0, storage.getUnitById(GIGABYTE), storage.getUnitById(GIGABIT));
        verify(view, atLeastOnce()).showResult(eq(32.0));
        mPresenter.convert(4.0, storage.getUnitById(TERABIT), storage.getUnitById(GIGABYTE));
        verify(view, atLeastOnce()).showResult(eq(512.0));
        mPresenter.convert(4.0, storage.getUnitById(TERABIT), storage.getUnitById(TERABYTE));
        verify(view, atLeastOnce()).showResult(eq(0.5));
        mPresenter.convert(4.0, storage.getUnitById(BIT), storage.getUnitById(BYTE));
        verify(view, atLeastOnce()).showResult(eq(0.5));
        mPresenter.convert(1.0, storage.getUnitById(GIGABYTE), storage.getUnitById(MEGABYTE));
        verify(view, atLeastOnce()).showResult(eq(1024.0));
    }

    @Test
    public void testEnergy()
    {
        Conversion energy = mConversions.getById(Conversion.ENERGY);

        mPresenter.convert(5.5, energy.getUnitById(JOULE), energy.getUnitById(KILOJOULE));
        verify(view).showResult(eq(0.0055));
        mPresenter.convert(5.5, energy.getUnitById(KILOJOULE), energy.getUnitById(CALORIE));
        verify(view).showResult(AdditionalMatchers.eq(1314.5315, DELTA_4));
        mPresenter.convert(5.5, energy.getUnitById(CALORIE), energy.getUnitById(KILOCALORIE));
        verify(view, atLeastOnce()).showResult(eq(0.0055));
        mPresenter.convert(5.5, energy.getUnitById(KILOCALORIE), energy.getUnitById(BTU));
        verify(view).showResult(AdditionalMatchers.eq(21.8112, DELTA_4));
        mPresenter.convert(5.5, energy.getUnitById(BTU), energy.getUnitById(FT_LBF));
        verify(view).showResult(AdditionalMatchers.eq(4279.9309, DELTA_4));
        mPresenter.convert(5.5, energy.getUnitById(FT_LBF), energy.getUnitById(IN_LBF));
        verify(view).showResult(AdditionalMatchers.eq(66.0000000161, DELTA_10));
        mPresenter.convert(5555555.0, energy.getUnitById(IN_LBF), energy.getUnitById(KILOWATT_HOUR));
        verify(view).showResult(AdditionalMatchers.eq(0.1744, DELTA_4));
        mPresenter.convert(5.5, energy.getUnitById(KILOWATT_HOUR), energy.getUnitById(JOULE));
        verify(view).showResult(eq(19800000.0));
    }

    @Test
    public void testFuelConsumption()
    {
        Conversion fuel = mConversions.getById(Conversion.FUEL);

        mPresenter.convertFuelValue(5.5, fuel.getUnitById(MPG_US), fuel.getUnitById(MPG_UK));
        verify(view).showResult(AdditionalMatchers.eq(6.6052245905, DELTA_10));
        mPresenter.convertFuelValue(5.5, fuel.getUnitById(MPG_UK), fuel.getUnitById(L_100K));
        verify(view).showResult(AdditionalMatchers.eq(51.3601699525, DELTA_10));
        mPresenter.convertFuelValue(5.5, fuel.getUnitById(L_100K), fuel.getUnitById(KM_L));
        verify(view).showResult(AdditionalMatchers.eq(18.1818180813, DELTA_10));
        mPresenter.convertFuelValue(5.5, fuel.getUnitById(KM_L), fuel.getUnitById(MILES_L));
        verify(view).showResult(AdditionalMatchers.eq(3.4175415522, DELTA_10));
        mPresenter.convertFuelValue(5.5, fuel.getUnitById(MILES_L), fuel.getUnitById(MPG_US));
        verify(view).showResult(AdditionalMatchers.eq(20.8197649, DELTA_10));
        mPresenter.convertFuelValue(0, fuel.getUnitById(L_100K), fuel.getUnitById(MPG_UK));
        verify(view, atLeastOnce()).showResult(0.0);
        mPresenter.convertFuelValue(0, fuel.getUnitById(MPG_UK), fuel.getUnitById(L_100K));
        verify(view, atLeastOnce()).showResult(0.0);
    }

    @Test
    public void testLength()
    {
        Conversion length = mConversions.getById(Conversion.LENGTH);

        mPresenter.convert(5.5, length.getUnitById(KILOMETRE), length.getUnitById(MILE));
        verify(view).showResult(AdditionalMatchers.eq(3.4175415573, DELTA_10));
        mPresenter.convert(5.5, length.getUnitById(MILE), length.getUnitById(METRE));
        verify(view).showResult(eq(8851.392));
        mPresenter.convert(5.5, length.getUnitById(METRE), length.getUnitById(CENTIMETRE));
        verify(view).showResult(eq(550.0));
        mPresenter.convert(5.5, length.getUnitById(CENTIMETRE), length.getUnitById(MILLIMETRE));
        verify(view).showResult(eq(55.0));
        mPresenter.convert(5.5, length.getUnitById(MILLIMETRE), length.getUnitById(MICROMETRE));
        verify(view).showResult(eq(5500.0));
        mPresenter.convert(5.5, length.getUnitById(MICROMETRE), length.getUnitById(NANOMETRE));
        verify(view, atLeastOnce()).showResult(eq(5500.0));
        mPresenter.convert(5558, length.getUnitById(NANOMETRE), length.getUnitById(YARD));
        verify(view).showResult(AdditionalMatchers.eq(0.0000060783, DELTA_10));
        mPresenter.convert(5.5, length.getUnitById(YARD), length.getUnitById(FEET));
        verify(view).showResult(eq(16.5));
        mPresenter.convert(5.5, length.getUnitById(FEET), length.getUnitById(INCH));
        verify(view).showResult(AdditionalMatchers.eq(66.0, DELTA_10));
        mPresenter.convert(5.5, length.getUnitById(MILLIMETRE), length.getUnitById(MICROMETRE));
        verify(view, atLeastOnce()).showResult(eq(5500.0));
        mPresenter.convert(5.5, length.getUnitById(INCH), length.getUnitById(NAUTICAL_MILE));
        verify(view).showResult(AdditionalMatchers.eq(0.000075432, DELTA_10));
        mPresenter.convert(5.5, length.getUnitById(NAUTICAL_MILE), length.getUnitById(FURLONG));
        verify(view).showResult(AdditionalMatchers.eq(50.634295713, DELTA_10));
        mPresenter.convert(123456789.0, length.getUnitById(FURLONG), length.getUnitById(LIGHT_YEAR));
        verify(view).showResult(AdditionalMatchers.eq(0.0000026251, DELTA_10));
        mPresenter.convert(5.5, length.getUnitById(LIGHT_YEAR), length.getUnitById(KILOMETRE));
        verify(view).showResult(eq(52034017599194.4));
    }

    @Test
    public void testMass()
    {
        Conversion mass = mConversions.getById(Conversion.MASS);

        mPresenter.convert(5.5, mass.getUnitById(KILOGRAM), mass.getUnitById(POUND));
        verify(view).showResult(AdditionalMatchers.eq(12.1254244202, DELTA_10));
        mPresenter.convert(5.5, mass.getUnitById(POUND), mass.getUnitById(GRAM));
        verify(view).showResult(AdditionalMatchers.eq(2494.758035, DELTA_6));
        mPresenter.convert(5.5, mass.getUnitById(GRAM), mass.getUnitById(MILLIGRAM));
        verify(view).showResult(eq(5500.0));
        mPresenter.convert(5.5, mass.getUnitById(MILLIGRAM), mass.getUnitById(OUNCE));
        verify(view).showResult(AdditionalMatchers.eq(0.0001940068, DELTA_10));
        mPresenter.convert(5.5, mass.getUnitById(OUNCE), mass.getUnitById(GRAIN));
        verify(view).showResult(eq(2406.25));
        mPresenter.convert(5.5, mass.getUnitById(GRAIN), mass.getUnitById(STONE));
        verify(view).showResult(AdditionalMatchers.eq(0.0000561224, DELTA_10));
        mPresenter.convert(5.5, mass.getUnitById(STONE), mass.getUnitById(METRIC_TON));
        verify(view).showResult(AdditionalMatchers.eq(0.0349266125, DELTA_10));
        mPresenter.convert(5.5, mass.getUnitById(METRIC_TON), mass.getUnitById(SHORT_TON));
        verify(view).showResult(AdditionalMatchers.eq(6.0627122101, DELTA_10));
        mPresenter.convert(5.5, mass.getUnitById(SHORT_TON), mass.getUnitById(LONG_TON));
        verify(view).showResult(AdditionalMatchers.eq(4.9107142857, DELTA_10));
        mPresenter.convert(5.5, mass.getUnitById(LONG_TON), mass.getUnitById(KILOGRAM));
        verify(view).showResult(AdditionalMatchers.eq(5588.2579984, DELTA_7));
    }

    @Test
    public void testPower()
    {
        Conversion power = mConversions.getById(Conversion.POWER);

        mPresenter.convert(5.5, power.getUnitById(WATT), power.getUnitById(KILOWATT));
        verify(view).showResult(eq(0.0055));
        mPresenter.convert(5.5, power.getUnitById(KILOWATT), power.getUnitById(MEGAWATT));
        verify(view, atLeastOnce()).showResult(eq(0.0055));
        mPresenter.convert(5.5, power.getUnitById(MEGAWATT), power.getUnitById(HP));
        verify(view).showResult(AdditionalMatchers.eq(7477.9188951715, DELTA_10));
        mPresenter.convert(5.5, power.getUnitById(HP), power.getUnitById(HP_UK));
        verify(view).showResult(AdditionalMatchers.eq(5.4247603884, DELTA_10));
        mPresenter.convert(5.5, power.getUnitById(HP_UK), power.getUnitById(FT_LBF_S));
        verify(view).showResult(eq(3025.0));
        mPresenter.convert(5.5, power.getUnitById(FT_LBF_S), power.getUnitById(CALORIE_S));
        verify(view).showResult(AdditionalMatchers.eq(1.7810735444, DELTA_10));
        mPresenter.convert(5.5, power.getUnitById(CALORIE_S), power.getUnitById(BTU_S));
        verify(view).showResult(AdditionalMatchers.eq(0.021825764, DELTA_9));
        mPresenter.convert(5.5, power.getUnitById(BTU_S), power.getUnitById(KVA));
        verify(view).showResult(AdditionalMatchers.eq(5.8028071894, DELTA_10));
        mPresenter.convert(5.5, power.getUnitById(KVA), power.getUnitById(WATT));
        verify(view).showResult(eq(5500.0));
    }

    @Test
    public void testPressure()
    {
        Conversion pressure = mConversions.getById(Conversion.PRESSURE);

        mPresenter.convert(5.5, pressure.getUnitById(MEGAPASCAL), pressure.getUnitById(KILOPASCAL));
        verify(view).showResult(eq(5500.0));
        mPresenter.convert(5.5, pressure.getUnitById(KILOPASCAL), pressure.getUnitById(PASCAL));
        verify(view, atLeastOnce()).showResult(eq(5500.0));
        mPresenter.convert(5.5, pressure.getUnitById(PASCAL), pressure.getUnitById(BAR));
        verify(view).showResult(eq(0.000055));
        mPresenter.convert(5.5, pressure.getUnitById(BAR), pressure.getUnitById(PSI));
        verify(view).showResult(AdditionalMatchers.eq(79.7707557516, DELTA_10));
        mPresenter.convert(5.5, pressure.getUnitById(PSI), pressure.getUnitById(PSF));
        verify(view).showResult(eq(792.0));
        mPresenter.convert(5.5, pressure.getUnitById(PSF), pressure.getUnitById(ATMOSPHERE));
        verify(view).showResult(AdditionalMatchers.eq(0.0025989778, DELTA_10));
        mPresenter.convert(5.5, pressure.getUnitById(ATMOSPHERE), pressure.getUnitById(MMHG));
        verify(view).showResult(AdditionalMatchers.eq(4179.9994044909, DELTA_10));
        mPresenter.convert(5.5, pressure.getUnitById(MMHG), pressure.getUnitById(TORR));
        verify(view).showResult(AdditionalMatchers.eq(5.5000007836, DELTA_10));
        mPresenter.convert(5.5, pressure.getUnitById(TORR), pressure.getUnitById(TECHNICAL_ATMOSPHERE));
        verify(view).showResult(AdditionalMatchers.eq(0.007477303934736015598438, DELTA_10));
        mPresenter.convert(5.5, pressure.getUnitById(TECHNICAL_ATMOSPHERE), pressure.getUnitById(MEGAPASCAL));
        verify(view).showResult((0.53936575));
    }

    @Test
    public void testSpeed()
    {
        Conversion speed = mConversions.getById(Conversion.SPEED);

        mPresenter.convert(5.5, speed.getUnitById(KM_HR), speed.getUnitById(MPH));
        verify(view).showResult(AdditionalMatchers.eq(3.4175415573, DELTA_10));
        mPresenter.convert(5.5, speed.getUnitById(MPH), speed.getUnitById(M_S));
        verify(view).showResult(eq(2.45872));
        mPresenter.convert(5.5, speed.getUnitById(M_S), speed.getUnitById(FPS));
        verify(view).showResult(AdditionalMatchers.eq(18.0446194226, DELTA_10));
        mPresenter.convert(5.5, speed.getUnitById(FPS), speed.getUnitById(KNOT));
        verify(view).showResult(AdditionalMatchers.eq(3.2586609071, DELTA_10));
        mPresenter.convert(5.5, speed.getUnitById(KNOT), speed.getUnitById(KM_HR));
        verify(view).showResult(AdditionalMatchers.eq(10.1860, DELTA_4));
    }

    @Test
    public void testTemperature()
    {
        Conversion temp = mConversions.getById(Conversion.TEMPERATURE);

        mPresenter.convertTemperatureValue(5.5, temp.getUnitById(CELSIUS), temp.getUnitById(FAHRENHEIT));
        verify(view).showResult(eq(41.9));
        mPresenter.convertTemperatureValue(5.5, temp.getUnitById(FAHRENHEIT), temp.getUnitById(KELVIN));
        verify(view).showResult(AdditionalMatchers.eq(258.4277777778, DELTA_10));
        mPresenter.convertTemperatureValue(5.5, temp.getUnitById(KELVIN), temp.getUnitById(RANKINE));
        verify(view).showResult(eq(9.9));
        mPresenter.convertTemperatureValue(5.5, temp.getUnitById(RANKINE), temp.getUnitById(DELISLE));
        verify(view).showResult(AdditionalMatchers.eq(555.1416666667, DELTA_10));
        mPresenter.convertTemperatureValue(5.5, temp.getUnitById(DELISLE), temp.getUnitById(NEWTON));
        verify(view).showResult(eq(31.79));
        mPresenter.convertTemperatureValue(5.5, temp.getUnitById(NEWTON), temp.getUnitById(REAUMUR));
        verify(view).showResult(AdditionalMatchers.eq(13.3333333333, DELTA_10));
        mPresenter.convertTemperatureValue(5.5, temp.getUnitById(REAUMUR), temp.getUnitById(ROMER));
        verify(view).showResult(eq(11.109375));
        mPresenter.convertTemperatureValue(10.0, temp.getUnitById(GAS_MARK), temp.getUnitById(CELSIUS));
        verify(view).showResult(eq(260.0));
    }

    @Test
    public void testTime()
    {
        Conversion time = mConversions.getById(Conversion.TIME);

        mPresenter.convert(5.0, time.getUnitById(YEAR), time.getUnitById(MONTH));
        verify(view).showResult(AdditionalMatchers.eq(59.9999994, DELTA_7));
        mPresenter.convert(5.0, time.getUnitById(MONTH), time.getUnitById(WEEK));
        verify(view).showResult(AdditionalMatchers.eq(21.7261904762, DELTA_10));
        mPresenter.convert(5.0, time.getUnitById(WEEK), time.getUnitById(DAY));
        verify(view).showResult(eq(35.0));
        mPresenter.convert(5.0, time.getUnitById(DAY), time.getUnitById(HOUR));
        verify(view).showResult(eq(120.0));
        mPresenter.convert(5.0, time.getUnitById(HOUR), time.getUnitById(MINUTE));
        verify(view).showResult(eq(300.0));
        mPresenter.convert(5.0, time.getUnitById(MINUTE), time.getUnitById(SECOND));
        verify(view, atLeastOnce()).showResult(eq(300.0));
        mPresenter.convert(5.0, time.getUnitById(SECOND), time.getUnitById(MILLISECOND));
        verify(view).showResult(eq(5000.0));
        mPresenter.convert(5.0, time.getUnitById(MILLISECOND), time.getUnitById(NANOSECOND));
        verify(view).showResult(eq(5000000.0));
        mPresenter.convert(5.0, time.getUnitById(NANOSECOND), time.getUnitById(MILLISECOND));
        verify(view).showResult(AdditionalMatchers.eq(0.000005, DELTA_7));
        mPresenter.convert(5.0, time.getUnitById(MONTH), time.getUnitById(YEAR));
        verify(view).showResult(AdditionalMatchers.eq(0.4166666667, DELTA_10));
    }

    @Test
    public void testTorque()
    {
        Conversion torque = mConversions.getById(Conversion.TORQUE);

        mPresenter.convert(5.5, torque.getUnitById(N_M), torque.getUnitById(FT_LBF));
        verify(view).showResult(AdditionalMatchers.eq(4.056591822, DELTA_10));
        mPresenter.convert(5.5, torque.getUnitById(FT_LBF), torque.getUnitById(IN_LBF));
        verify(view).showResult(AdditionalMatchers.eq(66.0000000161, DELTA_10));
        mPresenter.convert(5.5, torque.getUnitById(IN_LBF), torque.getUnitById(N_M));
        verify(view).showResult(AdditionalMatchers.eq(0.6214165597, DELTA_10));
    }

    @Test
    public void testVolume()
    {
        Conversion volume = mConversions.getById(Conversion.VOLUME);

        mPresenter.convert(5.5, volume.getUnitById(TEASPOON), volume.getUnitById(TABLESPOON));
        verify(view).showResult(AdditionalMatchers.eq(1.8333333334, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(TABLESPOON), volume.getUnitById(CUP));
        verify(view).showResult(AdditionalMatchers.eq(0.34375, DELTA_6));
        mPresenter.convert(5.5, volume.getUnitById(CUP), volume.getUnitById(FLUID_OUNCE));
        verify(view).showResult(eq(44.0));
        mPresenter.convert(5.5, volume.getUnitById(FLUID_OUNCE), volume.getUnitById(FLUID_OUNCE_UK));
        verify(view).showResult(AdditionalMatchers.eq(5.7246350193, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(FLUID_OUNCE_UK), volume.getUnitById(PINT));
        verify(view).showResult(AdditionalMatchers.eq(0.3302612295, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(PINT), volume.getUnitById(PINT_UK));
        verify(view).showResult(AdditionalMatchers.eq(4.5797080155, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(PINT_UK), volume.getUnitById(QUART));
        verify(view).showResult(AdditionalMatchers.eq(3.3026122951, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(QUART), volume.getUnitById(QUART_UK));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(4.5797080155, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(QUART_UK), volume.getUnitById(GALLON));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(1.6513061476, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(GALLON), volume.getUnitById(GALLON_UK));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(4.5797080155, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(GALLON_UK), volume.getUnitById(BARREL));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(0.2096896695, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(BARREL), volume.getUnitById(BARREL_UK));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(4.0072445135, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(BARREL_UK), volume.getUnitById(MILLILITRE));
        verify(view).showResult(AdditionalMatchers.eq(900125.82, DELTA_6));
        mPresenter.convert(5.5, volume.getUnitById(MILLILITRE), volume.getUnitById(LITRE));
        verify(view).showResult(eq(0.0055));
        mPresenter.convert(5.5, volume.getUnitById(LITRE), volume.getUnitById(CUBIC_CM));
        verify(view).showResult(eq(5500.0));
        mPresenter.convert(5.5, volume.getUnitById(CUBIC_CM), volume.getUnitById(CUBIC_M));
        verify(view).showResult(eq(0.0000055));
        mPresenter.convert(5.5, volume.getUnitById(CUBIC_M), volume.getUnitById(CUBIC_INCH));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(335630.592521028, DELTA_9));
        mPresenter.convert(5.5, volume.getUnitById(CUBIC_INCH), volume.getUnitById(CUBIC_FOOT));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(0.0031828704, DELTA_9));
        mPresenter.convert(5.5, volume.getUnitById(CUBIC_FOOT), volume.getUnitById(CUBIC_YARD));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(0.2037037007, DELTA_10));
        mPresenter.convert(5.5, volume.getUnitById(CUBIC_YARD), volume.getUnitById(TEASPOON));
        verify(view, atLeastOnce()).showResult(AdditionalMatchers.eq(853138.298312504, DELTA_9));
    }
}


text:
/* $chaos: return_values.h,v 1.1 2002/07/06 08:29:46 per Exp $ */
/* Abstract: Return values returned by the block library. */
/* Author: Per Lundberg <per@chaosdev.org> */

/* Copyright 2002 chaos development. */
/* Use freely under the terms listed in the file LICENSE. */

#ifndef __BLOCK_RETURN_VALUES_H__
#define __BLOCK_RETURN_VALUES_H__

enum
{
    /* The function returnes successfully. */
    BLOCK_RETURN_SUCCESS,

    /* The service was not available. */
    BLOCK_RETURN_SERVICE_UNAVAILABLE
};

#endif /* !__BLOCK_RETURN_VALUES_H__ */


text:
import datetime

import boto
import sure  # noqa

from moto import mock_ec2
from moto.backends import get_model
from moto.core.utils import iso_8601_datetime

@mock_ec2
def test_request_spot_instances():
    conn = boto.connect_ec2()

    conn.create_security_group('group1', 'description')
    conn.create_security_group('group2', 'description')

    start = iso_8601_datetime(datetime.datetime(2013, 1, 1))
    end = iso_8601_datetime(datetime.datetime(2013, 1, 2))

    request = conn.request_spot_instances(
        price=0.5, image_id='ami-abcd1234', count=1, type='one-time',
        valid_from=start, valid_until=end, launch_group="the-group",
        availability_zone_group='my-group', key_name="test",
        security_groups=['group1', 'group2'], user_data="some test data",
        instance_type='m1.small', placement='us-east-1c',
        kernel_id="test-kernel", ramdisk_id="test-ramdisk",
        monitoring_enabled=True, subnet_id="subnet123",
    )

    requests = conn.get_all_spot_instance_requests()
    requests.should.have.length_of(1)
    request = requests[0]

    request.state.should.equal("open")
    request.price.should.equal(0.5)
    request.launch_specification.image_id.should.equal('ami-abcd1234')
    request.type.should.equal('one-time')
    request.valid_from.should.equal(start)
    request.valid_until.should.equal(end)
    request.launch_group.should.equal("the-group")
    request.availability_zone_group.should.equal('my-group')
    request.launch_specification.key_name.should.equal("test")
    security_group_names = [group.name for group in request.launch_specification.groups]
    set(security_group_names).should.equal(set(['group1', 'group2']))
    request.launch_specification.instance_type.should.equal('m1.small')
    request.launch_specification.placement.should.equal('us-east-1c')
    request.launch_specification.kernel.should.equal("test-kernel")
    request.launch_specification.ramdisk.should.equal("test-ramdisk")
    request.launch_specification.subnet_id.should.equal("subnet123")

@mock_ec2
def test_request_spot_instances_default_arguments():
    """
    Test that moto set the correct default arguments
    """
    conn = boto.connect_ec2()

    request = conn.request_spot_instances(
        price=0.5, image_id='ami-abcd1234',
    )

    requests = conn.get_all_spot_instance_requests()
    requests.should.have.length_of(1)
    request = requests[0]

    request.state.should.equal("open")
    request.price.should.equal(0.5)
    request.launch_specification.image_id.should.equal('ami-abcd1234')
    request.type.should.equal('one-time')
    request.valid_from.should.equal(None)
    request.valid_until.should.equal(None)
    request.launch_group.should.equal(None)
    request.availability_zone_group.should.equal(None)
    request.launch_specification.key_name.should.equal(None)
    security_group_names = [group.name for group in request.launch_specification.groups]
    security_group_names.should.equal(["default"])
    request.launch_specification.instance_type.should.equal('m1.small')
    request.launch_specification.placement.should.equal(None)
    request.launch_specification.kernel.should.equal(None)
    request.launch_specification.ramdisk.should.equal(None)
    request.launch_specification.subnet_id.should.equal(None)

@mock_ec2
def test_cancel_spot_instance_request():
    conn = boto.connect_ec2()

    conn.request_spot_instances(
        price=0.5, image_id='ami-abcd1234',
    )

    requests = conn.get_all_spot_instance_requests()
    requests.should.have.length_of(1)

    conn.cancel_spot_instance_requests([requests[0].id])

    requests = conn.get_all_spot_instance_requests()
    requests.should.have.length_of(0)

@mock_ec2
def test_request_spot_instances_fulfilled():
    """
    Test that moto correctly fullfills a spot instance request
    """
    conn = boto.connect_ec2()

    request = conn.request_spot_instances(
        price=0.5, image_id='ami-abcd1234',
    )

    requests = conn.get_all_spot_instance_requests()
    requests.should.have.length_of(1)
    request = requests[0]

    request.state.should.equal("open")

    get_model('SpotInstanceRequest')[0].state = 'active'

    requests = conn.get_all_spot_instance_requests()
    requests.should.have.length_of(1)
    request = requests[0]

    request.state.should.equal("active")


text:
    Method:

    <select name="methods[]" class="form-control">
        <optgroup label="Methods">
        {% for item in methods %}
        <option value="{{item}}" {% if current.method == item %}selected{% endif %} >{{item}}</option>
        {% endfor %}
        </optgroup>
     </select>

    <button  class="remove btn btn-default btn-sm"></button>


text:
<com.sqisland.android.sliding_pane_layout.CrossFadeSlidingPaneLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sliding_pane_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  <FrameLayout
      android:layout_width="@dimen/side_pane_width"
      android:layout_height="match_parent"
      android:background="@color/purple">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/full"/>
    <TextView
        android:layout_width="@dimen/partial_pane_width"
        android:layout_height="match_parent"
        android:background="@color/blue"
        android:text="@string/partial"/>
  </FrameLayout>
  <TextView
      android:layout_width="@dimen/main_pane_width"
      android:layout_height="match_parent"
      android:layout_weight="1"
      android:layout_marginLeft="@dimen/partial_pane_width"
      android:background="@color/light_blue"
      android:text="@string/pane_2"/>
</com.sqisland.android.sliding_pane_layout.CrossFadeSlidingPaneLayout>


text:
@extends('layouts.app')

@section('content')

                #
                Описание

                {{ $equiptype->id }}
                {{ $equiptype->equiptype_desc }}

            Внесите правки в форму ниже

        @include('common.errors')
        <form action="{{ url('equiptype/'.$equiptype->id ) }}" method="post" class="form-horizontal">
            {{ method_field('put') }}
            {{ csrf_field() }}

                описание:

                    <input type="text" name="equiptype_desc" id="equiptype_desc" class="form-control" value="{{ trim($equiptype->equiptype_desc ? $equiptype->equiptype_desc : old('equiptype_desc')) }}">

                    <button type="submit" class="btn btn-primary">Исправить</button>

        </form>

@endsection


text:
package guitests;

import static seedu.task.logic.commands.DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS;

import org.junit.Test;

//import org.junit.Test;

import seedu.task.testutil.TestTask;
import seedu.task.testutil.TestUtil;

public class DeleteCommandTest extends TaskManagerGuiTest {

    @Test
    public void delete() {
        try {
            setup();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // delete the first in the list
        TestTask[] currentList = td.getTypicalTasks();
        int targetIndex = 1;
        commandBox.runCommand("clear");
        for (int i = 0; i < currentList.length; i++)
            commandBox.runCommand(currentList[i].getAddCommand());

        assertDeleteSuccess(targetIndex, currentList);

        // delete the last in the list
        currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
        targetIndex = currentList.length;
        assertDeleteSuccess(targetIndex, currentList);

        // delete from the middle of the list
        currentList = TestUtil.removeTaskFromList(currentList, targetIndex);
        targetIndex = currentList.length / 2;
        assertDeleteSuccess(targetIndex, currentList);

        // invalid index
        commandBox.runCommand("delete " + currentList.length + 1);
        assertResultMessage("The task index provided is invalid");

    }

    /**
     * Runs the delete command to delete the task at specified index and
     * confirms the result is correct.
     *
     * @param targetIndexOneIndexed
     *            e.g. index 1 to delete the first task in the list,
     * @param currentList
     *            A copy of the current list of tasks (before deletion).
     */
    private void assertDeleteSuccess(int targetIndexOneIndexed, final TestTask[] currentList) {
        TestTask taskToDelete = currentList[targetIndexOneIndexed - 1];
        TestTask[] expectedRemainder = TestUtil.removeTaskFromList(currentList, targetIndexOneIndexed);

        commandBox.runCommand("delete " + targetIndexOneIndexed);

        // confirm the result message is correct
        assertResultMessage(String.format(MESSAGE_DELETE_TASK_SUCCESS, taskToDelete.getTaskName().fullTaskName + '\n'));
    }

}


text:
@implementation GLGIRCBrokerProvider

@end


text:
package lib;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class AbstractCrfModel implements CrfModel {

    protected static final int VERSION = 100;

    private static final String[] BosArray = { "_B-1", "_B-2", "_B-3", "_B-4", "_B-5", "_B-6", "_B-7", "_B-8" };

    private static final String[] EosArray = { "_B+1", "_B+2", "_B+3", "_B+4", "_B+5", "_B+6", "_B+7", "_B+8" };

    private static final Pattern P_REF = Pattern.compile(
                    "%x\\[(-?\\d+?),(\\d+?)\\]"
    );

    protected int version = 0;

    protected double costFactor = 0.0;

    protected int xSize = 0;

    protected int maxId = 0;

    protected String templs = "";

    protected List<Double> alphaList = new ArrayList<Double>();

    protected List<String> unigramTemplsList = new ArrayList<String>();

    protected List<String> bigramTemplsList = new ArrayList<String>();

    protected List<String> yList = new ArrayList<String>();

    protected Map<String, Integer> featureAlphaIndexMap = new HashMap<String, Integer>();

    private boolean getFeatureList(List<String> templsList, InputSequence seq, int curIndex, List<Integer> featureList) {

        featureList.clear();
        boolean success = true;
        for (int i = 0; i < templsList.size(); ++i) {
            String templ = templsList.get(i);
            List<String[]> x = seq.getXList();
            StringBuffer sb = new StringBuffer();
            Matcher mRef = P_REF.matcher(templ);
            while (mRef.find()) {
                try {
                    int row = Integer.parseInt(mRef.group(1)) + curIndex;
                    int column = Integer.parseInt(mRef.group(2));
                    if (row >= 0 && row < x.size()) {
                        mRef.appendReplacement(sb, Matcher.quoteReplacement(x.get(row)[column]));
                    }
                    else if (row < 0) {
                        row = -row - 1;
                        mRef.appendReplacement(sb, Matcher.quoteReplacement(BosArray[row]));
                    }
                    else {
                        row = row - x.size();
                        mRef.appendReplacement(sb, Matcher.quoteReplacement(EosArray[row]));
                    }
                }
                catch (Exception e) {
                    success = false;
                }
            }
            mRef.appendTail(sb);
            String featureStr = sb.toString();
            Integer feature = featureAlphaIndexMap.get(featureStr);
            if (feature != null) {
                featureList.add(feature);
            }
        }
        return success;
    }

    private double getUnigramCost(List<Integer> unigramFeatureList, int yIndex) {
        double cost = 0.0;
        for (int i = 0; i < unigramFeatureList.size(); ++i) {
            cost += alphaList.get(unigramFeatureList.get(i) + yIndex);
        }
        return cost;
    }

    private double getBigramCost(List<Integer> bigramFeatureList, int yLeftIndex, int yRightIndex) {
        double cost = 0.0;
        for (int i = 0; i < bigramFeatureList.size(); ++i) {
            cost += alphaList.get(bigramFeatureList.get(i) + yLeftIndex * yList.size() + yRightIndex);
        }
        return cost;
    }

    protected void initialize() {

        version = 0;
        costFactor = 0.0;
        maxId = 0;
        xSize = 0;
        templs = "";
        alphaList.clear();
        unigramTemplsList.clear();
        bigramTemplsList.clear();
        yList.clear();
        featureAlphaIndexMap.clear();
    }

    public int getSize() {
        return maxId;
    }

    public int getXSize() {
        return xSize;
    }

    public int getYSize() {
        return yList.size();
    }

    public String getY(int i) {
        return yList.get(i);
    }

    public List<String> getYList() {
        return yList;
    }

    public double getCostFactor() {
        return costFactor;
    }

    public boolean setLatticeCost(Lattice lattice) {

        if (lattice == null || !yList.equals(lattice.yList)) {
            return false;
        }
        InputSequence inputSequence = lattice.inputSequence;
        if (inputSequence == null || xSize != inputSequence.getXSize()) {
            return false;
        }

        List<List<Node>> node2dList = lattice.node2dList;
        if (node2dList == null) {
            return false;
        }

        int sequenceSize = inputSequence.getSequenceSize();
        int ySize = yList.size();
        List<Integer> unigramFeatureList = new ArrayList<Integer>();
        List<Integer> bigramFeatureList = new ArrayList<Integer>();
        for (int i = 0; i < sequenceSize; ++i) {
            if (!getFeatureList(unigramTemplsList, inputSequence, i, unigramFeatureList)) {
                return false;
            }
            List<Node> yNodeList = node2dList.get(i);
            for (int j = 0; j < ySize; ++j) {
                Node node = yNodeList.get(j);
                node.cost = getUnigramCost(unigramFeatureList, j);
                if (i > 0) {
                    if (!getFeatureList(bigramTemplsList, inputSequence, i, bigramFeatureList)) {
                        return false;
                    }
                    for (int k = 0; k < ySize; ++k) {
                        Node leftNode = node2dList.get(i - 1).get(k);
                        Node rightNode = node;
                        double pathCost = getBigramCost(bigramFeatureList, k, j);
                        leftNode.rightPathList.get(j).cost = pathCost;
                        rightNode.leftPathList.get(k).cost = pathCost;
                    }
                }
            }
        }
        return true;
    }
}


text:
package vpc

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// CreateBgpGroup invokes the vpc.CreateBgpGroup API synchronously
func (client *Client) CreateBgpGroup(request *CreateBgpGroupRequest) (response *CreateBgpGroupResponse, err error) {
	response = CreateCreateBgpGroupResponse()
	err = client.DoAction(request, response)
	return
}

// CreateBgpGroupWithChan invokes the vpc.CreateBgpGroup API asynchronously
func (client *Client) CreateBgpGroupWithChan(request *CreateBgpGroupRequest) (<-chan *CreateBgpGroupResponse, <-chan error) {
	responseChan := make(chan *CreateBgpGroupResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.CreateBgpGroup(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// CreateBgpGroupWithCallback invokes the vpc.CreateBgpGroup API asynchronously
func (client *Client) CreateBgpGroupWithCallback(request *CreateBgpGroupRequest, callback func(response *CreateBgpGroupResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *CreateBgpGroupResponse
		var err error
		defer close(result)
		response, err = client.CreateBgpGroup(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// CreateBgpGroupRequest is the request struct for api CreateBgpGroup
type CreateBgpGroupRequest struct {
	*requests.RpcRequest
	AuthKey                  string           `position:"Query" name:"AuthKey"`
	ResourceOwnerId          requests.Integer `position:"Query" name:"ResourceOwnerId"`
	ClientToken              string           `position:"Query" name:"ClientToken"`
	Description              string           `position:"Query" name:"Description"`
	PeerAsn                  requests.Integer `position:"Query" name:"PeerAsn"`
	IsFakeAsn                requests.Boolean `position:"Query" name:"IsFakeAsn"`
	IpVersion                string           `position:"Query" name:"IpVersion"`
	ResourceOwnerAccount     string           `position:"Query" name:"ResourceOwnerAccount"`
	OwnerAccount             string           `position:"Query" name:"OwnerAccount"`
	RouteQuota               requests.Integer `position:"Query" name:"RouteQuota"`
	OwnerId                  requests.Integer `position:"Query" name:"OwnerId"`
	RouteUsageAlarmThreshold requests.Integer `position:"Query" name:"RouteUsageAlarmThreshold"`
	RouterId                 string           `position:"Query" name:"RouterId"`
	Name                     string           `position:"Query" name:"Name"`
	LocalAsn                 requests.Integer `position:"Query" name:"LocalAsn"`
}

// CreateBgpGroupResponse is the response struct for api CreateBgpGroup
type CreateBgpGroupResponse struct {
	*responses.BaseResponse
	BgpGroupId string `json:"BgpGroupId" xml:"BgpGroupId"`
	RequestId  string `json:"RequestId" xml:"RequestId"`
}

// CreateCreateBgpGroupRequest creates a request to invoke CreateBgpGroup API
func CreateCreateBgpGroupRequest() (request *CreateBgpGroupRequest) {
	request = &CreateBgpGroupRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Vpc", "2016-04-28", "CreateBgpGroup", "vpc", "openAPI")
	request.Method = requests.POST
	return
}

// CreateCreateBgpGroupResponse creates a response to parse from CreateBgpGroup response
func CreateCreateBgpGroupResponse() (response *CreateBgpGroupResponse) {
	response = &CreateBgpGroupResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
<?php

namespace   Splash\Models\Helpers;

use Splash\Core\SplashCore      as Splash;

/**
 * Helper for Images Fields Management
 */
class ImagesHelper extends FilesHelper
{
    //====================================================================//
    //  IMAGE FIELDS MANAGEMENT
    //====================================================================//

    /**
     * Build a new image field array
     *
     * @param string $name      Image Name
     * @param string $fileName  Image Filename with Extension
     * @param string $filePath  Image Full path on local system
     * @param string $publicUrl Complete Public Url of this image if available
     *
     * @return array|false Splash Image Array or False
     */
    public static function encode($name, $fileName, $filePath, $publicUrl = null)
    {
        //====================================================================//
        // Safety Checks - Validate Inputs
        $fullPath = self::verifyInputs($name, $fileName, $filePath);
        if (false == $fullPath) {
            return false;
        }
        //====================================================================//
        // Safety Checks - Validate is An Image
        $dimensions = getimagesize($fullPath);
        if (empty($dimensions)) {
            return Splash::log()->err("ErrImgNotAnImage", __FUNCTION__, $fullPath);
        }
        //====================================================================//
        // Build Image Array
        $image = array();
        //====================================================================//
        // ADD MAIN INFOS
        //====================================================================//
        // Image Name
        $image["name"] = $name;
        //====================================================================//
        // Image Filename
        $image["filename"] = $fileName;
        //====================================================================//
        // Image Full Path
        $image["path"] = $fullPath;
        //====================================================================//
        // Image Publics Url
        $image["url"] = $publicUrl;
        //====================================================================//
        // ADD COMPUTED INFOS
        //====================================================================//
        // Images Informations
        $image["width"] = $dimensions[0];
        $image["height"] = $dimensions[1];
        $image["md5"] = md5_file($fullPath);
        $image["size"] = filesize($fullPath);
        //====================================================================//
        // Safety Check
        if (empty($image["md5"])) {
            return Splash::log()->err("Unable to read Remote File Md5");
        }

        return $image;
    }

    /**
     * Build a new image field array
     *
     * @param string $name        Image Name
     * @param string $absoluteUrl Image Absolute Url
     * @param string $publicUrl   Complete Public Url of this image if available
     *
     * @return array|false Splash Image Array or False
     */
    public static function encodeFromUrl($name, $absoluteUrl, $publicUrl = null)
    {
        //====================================================================//
        // Safety Checks - Validate Inputs
        if (!is_string($name) || empty($name)) {
            return Splash::log()->err("ErrImgNoName", __FUNCTION__);
        }
        if (!is_string($absoluteUrl) || empty($absoluteUrl)) {
            return Splash::log()->err("ErrImgNoPath", __FUNCTION__);
        }
        //====================================================================//
        // Safety Checks - Validate Image
        $dimensions = getimagesize($absoluteUrl);
        if (empty($dimensions)) {
            return Splash::log()->err("ErrImgNotAnImage", __FUNCTION__, $absoluteUrl);
        }
        //====================================================================//
        // Build Image Array
        $image = array();
        //====================================================================//
        // ADD MAIN INFOS
        //====================================================================//
        // Image Name
        $image["name"] = $name;
        //====================================================================//
        // Image Filename
        $image["filename"] = basename((string) parse_url($absoluteUrl, PHP_URL_PATH));
        //====================================================================//
        // Image Full Path
        $image["path"] = $absoluteUrl;
        //====================================================================//
        // Image Publics Url
        $image["url"] = $publicUrl;
        //====================================================================//
        // ADD COMPUTED INFOS
        //====================================================================//
        // Images Informations
        $image["width"] = $dimensions[0];
        $image["height"] = $dimensions[1];
        $image["md5"] = md5_file($absoluteUrl);
        $image["size"] = self::getRemoteFileSize($absoluteUrl);
        //====================================================================//
        // Safety Check
        if (empty($image["md5"])) {
            return Splash::log()->err("Unable to read Remote File Md5");
        }

        return $image;
    }
}


text:
/**
 * @implements {UI.Searchable}
 * @unrestricted
 */
Extensions.ExtensionPanel = class extends UI.Panel {
  /**
   * @param {!Extensions.ExtensionServer} server
   * @param {string} panelName
   * @param {string} id
   * @param {string} pageURL
   */
  constructor(server, panelName, id, pageURL) {
    super(panelName);
    this._server = server;
    this._id = id;
    this.setHideOnDetach();
    this._panelToolbar = new UI.Toolbar('hidden', this.element);

    this._searchableView = new UI.SearchableView(this);
    this._searchableView.show(this.element);

    var extensionView = new Extensions.ExtensionView(server, this._id, pageURL, 'extension');
    extensionView.show(this._searchableView.element);
  }

  /**
   * @param {!UI.ToolbarItem} item
   */
  addToolbarItem(item) {
    this._panelToolbar.element.classList.remove('hidden');
    this._panelToolbar.appendToolbarItem(item);
  }

  /**
   * @override
   */
  searchCanceled() {
    this._server.notifySearchAction(this._id, Extensions.extensionAPI.panels.SearchAction.CancelSearch);
    this._searchableView.updateSearchMatchesCount(0);
  }

  /**
   * @override
   * @return {!UI.SearchableView}
   */
  searchableView() {
    return this._searchableView;
  }

  /**
   * @override
   * @param {!UI.SearchableView.SearchConfig} searchConfig
   * @param {boolean} shouldJump
   * @param {boolean=} jumpBackwards
   */
  performSearch(searchConfig, shouldJump, jumpBackwards) {
    var query = searchConfig.query;
    this._server.notifySearchAction(this._id, Extensions.extensionAPI.panels.SearchAction.PerformSearch, query);
  }

  /**
   * @override
   */
  jumpToNextSearchResult() {
    this._server.notifySearchAction(this._id, Extensions.extensionAPI.panels.SearchAction.NextSearchResult);
  }

  /**
   * @override
   */
  jumpToPreviousSearchResult() {
    this._server.notifySearchAction(this._id, Extensions.extensionAPI.panels.SearchAction.PreviousSearchResult);
  }

  /**
   * @override
   * @return {boolean}
   */
  supportsCaseSensitiveSearch() {
    return false;
  }

  /**
   * @override
   * @return {boolean}
   */
  supportsRegexSearch() {
    return false;
  }
};

/**
 * @unrestricted
 */
Extensions.ExtensionButton = class {
  /**
   * @param {!Extensions.ExtensionServer} server
   * @param {string} id
   * @param {string} iconURL
   * @param {string=} tooltip
   * @param {boolean=} disabled
   */
  constructor(server, id, iconURL, tooltip, disabled) {
    this._id = id;

    this._toolbarButton = new UI.ToolbarButton('', '');
    this._toolbarButton.addEventListener(
        UI.ToolbarButton.Events.Click, server.notifyButtonClicked.bind(server, this._id));
    this.update(iconURL, tooltip, disabled);
  }

  /**
   * @param {string} iconURL
   * @param {string=} tooltip
   * @param {boolean=} disabled
   */
  update(iconURL, tooltip, disabled) {
    if (typeof iconURL === 'string')
      this._toolbarButton.setBackgroundImage(iconURL);
    if (typeof tooltip === 'string')
      this._toolbarButton.setTitle(tooltip);
    if (typeof disabled === 'boolean')
      this._toolbarButton.setEnabled(!disabled);
  }

  /**
   * @return {!UI.ToolbarButton}
   */
  toolbarButton() {
    return this._toolbarButton;
  }
};

/**
 * @unrestricted
 */
Extensions.ExtensionSidebarPane = class extends UI.SimpleView {
  /**
   * @param {!Extensions.ExtensionServer} server
   * @param {string} panelName
   * @param {string} title
   * @param {string} id
   */
  constructor(server, panelName, title, id) {
    super(title);
    this.element.classList.add('fill');
    this._panelName = panelName;
    this._server = server;
    this._id = id;
  }

  /**
   * @return {string}
   */
  id() {
    return this._id;
  }

  /**
   * @return {string}
   */
  panelName() {
    return this._panelName;
  }

  /**
   * @param {!Object} object
   * @param {string} title
   * @param {function(?string=)} callback
   */
  setObject(object, title, callback) {
    this._createObjectPropertiesView();
    this._setObject(SDK.RemoteObject.fromLocalObject(object), title, callback);
  }

  /**
   * @param {string} expression
   * @param {string} title
   * @param {!Object} evaluateOptions
   * @param {string} securityOrigin
   * @param {function(?string=)} callback
   */
  setExpression(expression, title, evaluateOptions, securityOrigin, callback) {
    this._createObjectPropertiesView();
    this._server.evaluate(
        expression, true, false, evaluateOptions, securityOrigin, this._onEvaluate.bind(this, title, callback));
  }

  /**
   * @param {string} url
   */
  setPage(url) {
    if (this._objectPropertiesView) {
      this._objectPropertiesView.detach();
      delete this._objectPropertiesView;
    }
    if (this._extensionView)
      this._extensionView.detach(true);

    this._extensionView = new Extensions.ExtensionView(this._server, this._id, url, 'extension fill');
    this._extensionView.show(this.element);

    if (!this.element.style.height)
      this.setHeight('150px');
  }

  /**
   * @param {string} height
   */
  setHeight(height) {
    this.element.style.height = height;
  }

  /**
   * @param {string} title
   * @param {function(?string=)} callback
   * @param {?Protocol.Error} error
   * @param {?SDK.RemoteObject} result
   * @param {boolean=} wasThrown
   */
  _onEvaluate(title, callback, error, result, wasThrown) {
    if (error)
      callback(error.toString());
    else
      this._setObject(/** @type {!SDK.RemoteObject} */ (result), title, callback);
  }

  _createObjectPropertiesView() {
    if (this._objectPropertiesView)
      return;
    if (this._extensionView) {
      this._extensionView.detach(true);
      delete this._extensionView;
    }
    this._objectPropertiesView = new Extensions.ExtensionNotifierView(this._server, this._id);
    this._objectPropertiesView.show(this.element);
  }

  /**
   * @param {!SDK.RemoteObject} object
   * @param {string} title
   * @param {function(?string=)} callback
   */
  _setObject(object, title, callback) {
    // This may only happen if setPage() was called while we were evaluating the expression.
    if (!this._objectPropertiesView) {
      callback('operation cancelled');
      return;
    }
    this._objectPropertiesView.element.removeChildren();
    var section = new Components.ObjectPropertiesSection(object, title);
    if (!title)
      section.titleLessMode();
    section.expand();
    section.editable = false;
    this._objectPropertiesView.element.appendChild(section.element);
    callback();
  }
};


text:
@interface PDSPageViewControllerDataSource : NSObject <UIPageViewControllerDataSource>

@property (nonatomic, readonly) NSUInteger numberOfViewControllers;

@property (nonatomic, copy) UIViewController *(^instantiateViewControllerBlock)(NSInteger index, id itemAtIndex);

@property (nonatomic, copy) void (^configureViewControllerBlock)(UIViewController *viewController, NSInteger index, id itemAtIndex);

- (instancetype)initWithDataSource:(id <PDSDataSource>)dataSource placeholderViewController:(UIViewController *)placeholder NS_DESIGNATED_INITIALIZER;

- (UIViewController *)viewControllerAtIndex:(NSInteger)index;

+ (instancetype)pageViewControllerDataSourceWithDataSource:(id <PDSDataSource>)dataSource placeholderViewController:(UIViewController *)placeholder;

@end

@interface PDSPageViewControllerDataSource (ReadOnly)

@property (nonatomic, readonly) id <PDSDataSource> dataSource;

@property (nonatomic, readonly) UIViewController *placeholderViewController;

@end