text:
/* $Id: UIGDetailsSet.cpp $ */
/** @file
 * VBox Qt GUI - UIGDetailsSet class implementation.
 */

/*
 * Copyright (C) 2012 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

#ifdef VBOX_WITH_PRECOMPILED_HEADERS
# include <precomp.h>
#else  /* !VBOX_WITH_PRECOMPILED_HEADERS */

/* GUI includes: */
# include "UIGDetailsSet.h"
# include "UIGDetailsModel.h"
# include "UIGDetailsElements.h"
# include "UIVMItem.h"
# include "UIVirtualBoxEventHandler.h"
# include "VBoxGlobal.h"

/* COM includes: */
# include "CUSBController.h"
# include "CUSBDeviceFilters.h"

#endif /* !VBOX_WITH_PRECOMPILED_HEADERS */

UIGDetailsSet::UIGDetailsSet(UIGDetailsItem *pParent)
    : UIGDetailsItem(pParent)
    , m_pMachineItem(0)
    , m_fHasDetails(false)
    , m_configurationAccessLevel(ConfigurationAccessLevel_Null)
    , m_fFullSet(true)
    , m_pBuildStep(0)
    , m_iLastStepNumber(-1)
{
    /* Add set to the parent group: */
    parentItem()->addItem(this);

    /* Prepare set: */
    prepareSet();

    /* Prepare connections: */
    prepareConnections();
}

UIGDetailsSet::~UIGDetailsSet()
{
    /* Cleanup items: */
    clearItems();

    /* Remove set from the parent group: */
    parentItem()->removeItem(this);
}

void UIGDetailsSet::buildSet(UIVMItem *pMachineItem, bool fFullSet, const QMap<DetailsElementType, bool> &settings)
{
    /* Remember passed arguments: */
    m_pMachineItem = pMachineItem;
    m_machine = m_pMachineItem->machine();
    m_fHasDetails = m_pMachineItem->hasDetails();
    m_fFullSet = fFullSet;
    m_settings = settings;

    /* Cleanup superfluous items: */
    if (!m_fFullSet || !m_fHasDetails)
    {
        int iFirstItem = m_fHasDetails ? DetailsElementType_Display : DetailsElementType_General;
        int iLastItem = DetailsElementType_Description;
        bool fCleanupPerformed = false;
        for (int i = iFirstItem; i <= iLastItem; ++i)
            if (m_elements.contains(i))
            {
                delete m_elements[i];
                fCleanupPerformed = true;
            }
        if (fCleanupPerformed)
            updateGeometry();
    }

    /* Make sure we have details: */
    if (!m_fHasDetails)
    {
        /* Reset last-step number: */
        m_iLastStepNumber = -1;
        /* Notify parent group we are built: */
        emit sigBuildDone();
        return;
    }

    /* Choose last-step number: */
    m_iLastStepNumber = m_fFullSet ? DetailsElementType_Description : DetailsElementType_Preview;

    /* Fetch USB controller restrictions: */
    const CUSBDeviceFilters &filters = m_machine.GetUSBDeviceFilters();
    if (filters.isNull() || !m_machine.GetUSBProxyAvailable())
        m_settings.remove(DetailsElementType_USB);

    /* Start building set: */
    rebuildSet();
}

void UIGDetailsSet::sltBuildStep(QString strStepId, int iStepNumber)
{
    /* Cleanup build-step: */
    delete m_pBuildStep;
    m_pBuildStep = 0;

    /* Is step id valid? */
    if (strStepId != m_strSetId)
        return;

    /* Step number feats the bounds: */
    if (iStepNumber >= 0 && iStepNumber <= m_iLastStepNumber)
    {
        /* Load details settings: */
        DetailsElementType elementType = (DetailsElementType)iStepNumber;
        /* Should the element be visible? */
        bool fVisible = m_settings.contains(elementType);
        /* Should the element be opened? */
        bool fOpen = fVisible && m_settings[elementType];

        /* Check if element is present already: */
        UIGDetailsElement *pElement = element(elementType);
        if (pElement && fOpen)
            pElement->open(false);
        /* Create element if necessary: */
        bool fJustCreated = false;
        if (!pElement)
        {
            fJustCreated = true;
            pElement = createElement(elementType, fOpen);
        }

        /* Show element if necessary: */
        if (fVisible && !pElement->isVisible())
        {
            /* Show the element: */
            pElement->show();
            /* Recursively update size-hint: */
            pElement->updateGeometry();
            /* Update layout: */
            model()->updateLayout();
        }
        /* Hide element if necessary: */
        else if (!fVisible && pElement->isVisible())
        {
            /* Hide the element: */
            pElement->hide();
            /* Recursively update size-hint: */
            updateGeometry();
            /* Update layout: */
            model()->updateLayout();
        }
        /* Update model if necessary: */
        else if (fJustCreated)
            model()->updateLayout();

        /* For visible element: */
        if (pElement->isVisible())
        {
            /* Create next build-step: */
            m_pBuildStep = new UIBuildStep(this, pElement, strStepId, iStepNumber + 1);

            /* Build element: */
            pElement->updateAppearance();
        }
        /* For invisible element: */
        else
        {
            /* Just build next step: */
            sltBuildStep(strStepId, iStepNumber + 1);
        }
    }
    /* Step number out of bounds: */
    else
    {
        /* Update model: */
        model()->updateLayout();
        /* Repaint all the items: */
        foreach (UIGDetailsItem *pItem, items())
            pItem->update();
        /* Notify listener about build done: */
        emit sigBuildDone();
    }
}

void UIGDetailsSet::sltMachineStateChange(QString strId)
{
    /* Is this our VM changed? */
    if (m_machine.GetId() != strId)
        return;

    /* Update appearance: */
    rebuildSet();
}

void UIGDetailsSet::sltMachineAttributesChange(QString strId)
{
    /* Is this our VM changed? */
    if (m_machine.GetId() != strId)
        return;

    /* Update appearance: */
    rebuildSet();
}

void UIGDetailsSet::sltUpdateAppearance()
{
    /* Update appearance: */
    rebuildSet();
}

QVariant UIGDetailsSet::data(int iKey) const
{
    /* Provide other members with required data: */
    switch (iKey)
    {
        /* Layout hints: */
        case SetData_Margin: return 0;
        case SetData_Spacing: return 3;
        /* Default: */
        default: break;
    }
    return QVariant();
}

void UIGDetailsSet::addItem(UIGDetailsItem *pItem)
{
    switch (pItem->type())
    {
        case UIGDetailsItemType_Element:
        {
            UIGDetailsElement *pElement = pItem->toElement();
            DetailsElementType type = pElement->elementType();
            AssertMsg(!m_elements.contains(type), ("Element already added!"));
            m_elements.insert(type, pItem);
            break;
        }
        default:
        {
            AssertMsgFailed(("Invalid item type!"));
            break;
        }
    }
}

void UIGDetailsSet::removeItem(UIGDetailsItem *pItem)
{
    switch (pItem->type())
    {
        case UIGDetailsItemType_Element:
        {
            UIGDetailsElement *pElement = pItem->toElement();
            DetailsElementType type = pElement->elementType();
            AssertMsg(m_elements.contains(type), ("Element do not present (type = %d)!", (int)type));
            m_elements.remove(type);
            break;
        }
        default:
        {
            AssertMsgFailed(("Invalid item type!"));
            break;
        }
    }
}

QList<UIGDetailsItem*> UIGDetailsSet::items(UIGDetailsItemType type /* = UIGDetailsItemType_Element */) const
{
    switch (type)
    {
        case UIGDetailsItemType_Element: return m_elements.values();
        case UIGDetailsItemType_Any: return items(UIGDetailsItemType_Element);
        default: AssertMsgFailed(("Invalid item type!")); break;
    }
    return QList<UIGDetailsItem*>();
}

bool UIGDetailsSet::hasItems(UIGDetailsItemType type /* = UIGDetailsItemType_Element */) const
{
    switch (type)
    {
        case UIGDetailsItemType_Element: return !m_elements.isEmpty();
        case UIGDetailsItemType_Any: return hasItems(UIGDetailsItemType_Element);
        default: AssertMsgFailed(("Invalid item type!")); break;
    }
    return false;
}

void UIGDetailsSet::clearItems(UIGDetailsItemType type /* = UIGDetailsItemType_Element */)
{
    switch (type)
    {
        case UIGDetailsItemType_Element:
        {
            foreach (int iKey, m_elements.keys())
                delete m_elements[iKey];
            AssertMsg(m_elements.isEmpty(), ("Set items cleanup failed!"));
            break;
        }
        case UIGDetailsItemType_Any:
        {
            clearItems(UIGDetailsItemType_Element);
            break;
        }
        default:
        {
            AssertMsgFailed(("Invalid item type!"));
            break;
        }
    }
}

UIGDetailsElement* UIGDetailsSet::element(DetailsElementType elementType) const
{
    UIGDetailsItem *pItem = m_elements.value(elementType, 0);
    if (pItem)
        return pItem->toElement();
    return 0;
}

void UIGDetailsSet::prepareSet()
{
    /* Setup size-policy: */
    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed);
}

void UIGDetailsSet::prepareConnections()
{
    /* Global-events connections: */
    connect(gVBoxEvents, SIGNAL(sigMachineStateChange(QString, KMachineState)), this, SLOT(sltMachineStateChange(QString)));
    connect(gVBoxEvents, SIGNAL(sigMachineDataChange(QString)), this, SLOT(sltMachineAttributesChange(QString)));
    connect(gVBoxEvents, SIGNAL(sigSessionStateChange(QString, KSessionState)), this, SLOT(sltMachineAttributesChange(QString)));
    connect(gVBoxEvents, SIGNAL(sigSnapshotTake(QString, QString)), this, SLOT(sltMachineAttributesChange(QString)));
    connect(gVBoxEvents, SIGNAL(sigSnapshotDelete(QString, QString)), this, SLOT(sltMachineAttributesChange(QString)));
    connect(gVBoxEvents, SIGNAL(sigSnapshotChange(QString, QString)), this, SLOT(sltMachineAttributesChange(QString)));
    connect(gVBoxEvents, SIGNAL(sigSnapshotRestore(QString, QString)), this, SLOT(sltMachineAttributesChange(QString)));

    /* Meidum-enumeration connections: */
    connect(&vboxGlobal(), SIGNAL(sigMediumEnumerationStarted()), this, SLOT(sltUpdateAppearance()));
    connect(&vboxGlobal(), SIGNAL(sigMediumEnumerationFinished()), this, SLOT(sltUpdateAppearance()));
}

int UIGDetailsSet::minimumWidthHint() const
{
    /* Zero if has no details: */
    if (!hasDetails())
        return 0;

    /* Prepare variables: */
    int iMargin = data(SetData_Margin).toInt();
    int iSpacing = data(SetData_Spacing).toInt();
    int iMinimumWidthHint = 0;

    /* Take into account all the elements: */
    foreach (UIGDetailsItem *pItem, items())
    {
        /* Skip hidden: */
        if (!pItem->isVisible())
            continue;

        /* For each particular element: */
        UIGDetailsElement *pElement = pItem->toElement();
        switch (pElement->elementType())
        {
            case DetailsElementType_General:
            case DetailsElementType_System:
            case DetailsElementType_Display:
            case DetailsElementType_Storage:
            case DetailsElementType_Audio:
            case DetailsElementType_Network:
            case DetailsElementType_Serial:
#ifdef VBOX_WITH_PARALLEL_PORTS
            case DetailsElementType_Parallel:
#endif /* VBOX_WITH_PARALLEL_PORTS */
            case DetailsElementType_USB:
            case DetailsElementType_SF:
            case DetailsElementType_UI:
            case DetailsElementType_Description:
            {
                iMinimumWidthHint = qMax(iMinimumWidthHint, pItem->minimumWidthHint());
                break;
            }
            case DetailsElementType_Preview:
            {
                UIGDetailsItem *pGeneralItem = element(DetailsElementType_General);
                UIGDetailsItem *pSystemItem = element(DetailsElementType_System);
                int iGeneralElementWidth = pGeneralItem ? pGeneralItem->minimumWidthHint() : 0;
                int iSystemElementWidth = pSystemItem ? pSystemItem->minimumWidthHint() : 0;
                int iFirstColumnWidth = qMax(iGeneralElementWidth, iSystemElementWidth);
                iMinimumWidthHint = qMax(iMinimumWidthHint, iFirstColumnWidth + iSpacing + pItem->minimumWidthHint());
                break;
            }
        }
    }

    /* And two margins finally: */
    iMinimumWidthHint += 2 * iMargin;

    /* Return result: */
    return iMinimumWidthHint;
}

int UIGDetailsSet::minimumHeightHint() const
{
    /* Zero if has no details: */
    if (!hasDetails())
        return 0;

    /* Prepare variables: */
    int iMargin = data(SetData_Margin).toInt();
    int iSpacing = data(SetData_Spacing).toInt();
    int iMinimumHeightHint = 0;

    /* Take into account all the elements: */
    foreach (UIGDetailsItem *pItem, items())
    {
        /* Skip hidden: */
        if (!pItem->isVisible())
            continue;

        /* For each particular element: */
        UIGDetailsElement *pElement = pItem->toElement();
        switch (pElement->elementType())
        {
            case DetailsElementType_General:
            case DetailsElementType_System:
            case DetailsElementType_Display:
            case DetailsElementType_Storage:
            case DetailsElementType_Audio:
            case DetailsElementType_Network:
            case DetailsElementType_Serial:
#ifdef VBOX_WITH_PARALLEL_PORTS
            case DetailsElementType_Parallel:
#endif /* VBOX_WITH_PARALLEL_PORTS */
            case DetailsElementType_USB:
            case DetailsElementType_SF:
            case DetailsElementType_UI:
            case DetailsElementType_Description:
            {
                iMinimumHeightHint += (pItem->minimumHeightHint() + iSpacing);
                break;
            }
            case DetailsElementType_Preview:
            {
                iMinimumHeightHint = qMax(iMinimumHeightHint, pItem->minimumHeightHint() + iSpacing);
                break;
            }
        }
    }

    /* Minus last spacing: */
    iMinimumHeightHint -= iSpacing;

    /* And two margins finally: */
    iMinimumHeightHint += 2 * iMargin;

    /* Return result: */
    return iMinimumHeightHint;
}

void UIGDetailsSet::updateLayout()
{
    /* Prepare variables: */
    int iMargin = data(SetData_Margin).toInt();
    int iSpacing = data(SetData_Spacing).toInt();
    int iMaximumWidth = geometry().size().toSize().width();
    int iVerticalIndent = iMargin;

    /* Layout all the elements: */
    foreach (UIGDetailsItem *pItem, items())
    {
        /* Skip hidden: */
        if (!pItem->isVisible())
            continue;

        /* For each particular element: */
        UIGDetailsElement *pElement = pItem->toElement();
        switch (pElement->elementType())
        {
            case DetailsElementType_General:
            case DetailsElementType_System:
            case DetailsElementType_Display:
            case DetailsElementType_Storage:
            case DetailsElementType_Audio:
            case DetailsElementType_Network:
            case DetailsElementType_Serial:
#ifdef VBOX_WITH_PARALLEL_PORTS
            case DetailsElementType_Parallel:
#endif /* VBOX_WITH_PARALLEL_PORTS */
            case DetailsElementType_USB:
            case DetailsElementType_SF:
            case DetailsElementType_UI:
            case DetailsElementType_Description:
            {
                /* Move element: */
                pElement->setPos(iMargin, iVerticalIndent);
                /* Calculate required width: */
                int iWidth = iMaximumWidth - 2 * iMargin;
                if (pElement->elementType() == DetailsElementType_General ||
                    pElement->elementType() == DetailsElementType_System)
                    if (UIGDetailsElement *pPreviewElement = element(DetailsElementType_Preview))
                        if (pPreviewElement->isVisible())
                            iWidth -= (iSpacing + pPreviewElement->minimumWidthHint());
                /* If element width is wrong: */
                if (pElement->geometry().width() != iWidth)
                {
                    /* Resize element to required width: */
                    pElement->resize(iWidth, pElement->geometry().height());
                }
                /* Acquire required height: */
                int iHeight = pElement->minimumHeightHint();
                /* If element height is wrong: */
                if (pElement->geometry().height() != iHeight)
                {
                    /* Resize element to required height: */
                    pElement->resize(pElement->geometry().width(), iHeight);
                }
                /* Layout element content: */
                pItem->updateLayout();
                /* Advance indent: */
                iVerticalIndent += (iHeight + iSpacing);
                break;
            }
            case DetailsElementType_Preview:
            {
                /* Prepare variables: */
                int iWidth = pElement->minimumWidthHint();
                int iHeight = pElement->minimumHeightHint();
                /* Move element: */
                pElement->setPos(iMaximumWidth - iMargin - iWidth, iMargin);
                /* Resize element: */
                pElement->resize(iWidth, iHeight);
                /* Layout element content: */
                pItem->updateLayout();
                /* Advance indent: */
                iVerticalIndent = qMax(iVerticalIndent, iHeight + iSpacing);
                break;
            }
        }
    }
}

void UIGDetailsSet::rebuildSet()
{
    /* Make sure we have details: */
    if (!m_fHasDetails)
        return;

    /* Recache properties: */
    m_configurationAccessLevel = m_pMachineItem->configurationAccessLevel();

    /* Cleanup build-step: */
    delete m_pBuildStep;
    m_pBuildStep = 0;

    /* Generate new set-id: */
    m_strSetId = QUuid::createUuid().toString();

    /* Request to build first step: */
    emit sigBuildStep(m_strSetId, DetailsElementType_General);
}

UIGDetailsElement* UIGDetailsSet::createElement(DetailsElementType elementType, bool fOpen)
{
    /* Element factory: */
    switch (elementType)
    {
        case DetailsElementType_General:     return new UIGDetailsElementGeneral(this, fOpen);
        case DetailsElementType_System:      return new UIGDetailsElementSystem(this, fOpen);
        case DetailsElementType_Preview:     return new UIGDetailsElementPreview(this, fOpen);
        case DetailsElementType_Display:     return new UIGDetailsElementDisplay(this, fOpen);
        case DetailsElementType_Storage:     return new UIGDetailsElementStorage(this, fOpen);
        case DetailsElementType_Audio:       return new UIGDetailsElementAudio(this, fOpen);
        case DetailsElementType_Network:     return new UIGDetailsElementNetwork(this, fOpen);
        case DetailsElementType_Serial:      return new UIGDetailsElementSerial(this, fOpen);
#ifdef VBOX_WITH_PARALLEL_PORTS
        case DetailsElementType_Parallel:    return new UIGDetailsElementParallel(this, fOpen);
#endif /* VBOX_WITH_PARALLEL_PORTS */
        case DetailsElementType_USB:         return new UIGDetailsElementUSB(this, fOpen);
        case DetailsElementType_SF:          return new UIGDetailsElementSF(this, fOpen);
        case DetailsElementType_UI:          return new UIGDetailsElementUI(this, fOpen);
        case DetailsElementType_Description: return new UIGDetailsElementDescription(this, fOpen);
    }
    return 0;
}


text:
<?php

namespace Klimesf\RequestMapping;

class EntityMetadataFactory
{

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef CPU_JIT_AVX512_CORE_X8S8S32X_CONVOLUTION_HPP
#define CPU_JIT_AVX512_CORE_X8S8S32X_CONVOLUTION_HPP

#include "c_types_map.hpp"
#include "memory_tracking.hpp"
#include "mkldnn_thread.hpp"
#include "utils.hpp"

#include "cpu_convolution_pd.hpp"
#include "cpu_primitive.hpp"

#include "jit_avx512_core_x8s8s32x_conv_kernel.hpp"

namespace mkldnn {
namespace impl {
namespace cpu {

template <impl::data_type_t src_type, impl::data_type_t dst_type>
struct jit_avx512_core_x8s8s32x_convolution_fwd_t : public cpu_primitive_t {
    struct pd_t : public cpu_convolution_fwd_pd_t {
        pd_t(engine_t *engine, const convolution_desc_t *adesc,
                const primitive_attr_t *attr,
                const typename pd_t::base_class *hint_fwd_pd)
            : cpu_convolution_fwd_pd_t(engine, adesc, attr, hint_fwd_pd)
            , jcp_()
        {}

        DECLARE_COMMON_PD_T(
                JIT_IMPL_NAME_HELPER("jit_int8:", ((jcp_.ver == ver_vnni)
                    ? avx512_core_vnni : avx512_core), ""),
                jit_avx512_core_x8s8s32x_convolution_fwd_t<src_type, dst_type>);

        status_t init() {
            bool ok = true
                && is_fwd()
                && set_default_alg_kind(alg_kind::convolution_direct)
                && expect_data_types(src_type, data_type::s8, data_type::undef,
                        dst_type, data_type::s32)
                && IMPLICATION(with_bias(), utils::one_of(bias_md_.data_type,
                            data_type::f32, data_type::s32, data_type::s8,
                            data_type::u8))
                && !has_zero_dim_memory();
            if (!ok) return status::unimplemented;

            status_t status = jit_avx512_core_x8s8s32x_fwd_kernel::init_conf(
                    jcp_, *desc(), src_md_, weights_md_, dst_md_, bias_md_,
                    *attr(), mkldnn_get_max_threads());
            if (status != status::success) return status;

            auto scratchpad = scratchpad_registry().registrar();
            jit_avx512_core_x8s8s32x_fwd_kernel::init_scratchpad(scratchpad,
                    jcp_, *attr());

            return status;
        }

        jit_conv_conf_t jcp_;
    };

    jit_avx512_core_x8s8s32x_convolution_fwd_t(const pd_t *apd)
        : cpu_primitive_t(apd)
    {
        kernel_ = new jit_avx512_core_x8s8s32x_fwd_kernel(pd()->jcp_,
                    *pd()->attr());
    }

    ~jit_avx512_core_x8s8s32x_convolution_fwd_t() { delete kernel_; }

    typedef typename prec_traits<src_type>::type src_data_t;
    typedef typename prec_traits<data_type::s8>::type wei_data_t;
    typedef typename prec_traits<dst_type>::type dst_data_t;

    virtual status_t execute(const exec_ctx_t &ctx) const override
    {
        const auto &_pd = pd();
        if (_pd->ndims() == 3)
            execute_forward_1d(ctx);
        else if (_pd->jcp_.is_depthwise)
            execute_forward_2d_dw(ctx);
        else
            execute_forward_2d(ctx);
        return status::success;
    }

private:
    void execute_forward_1d(const exec_ctx_t &ctx) const;
    void execute_forward_2d(const exec_ctx_t &ctx) const;
    void execute_forward_2d_dw(const exec_ctx_t &ctx) const;
    const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); }

    jit_avx512_core_x8s8s32x_fwd_kernel *kernel_;
};

}
}
}

#endif

// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s


text:
angular.module('sample.widgets.linklist')
.controller('linklistCtrl', function ($scope, config) {
  if (!config.links) {
    config.links = [];
  }
  $scope.links = config.links;
}).controller('linklistEditCtrl', function ($scope) {
  function getLinks() {
    if (!$scope.config.links) {
      $scope.config.links = [];
    }
    return $scope.config.links;
  }
  $scope.addLink = function () {
    getLinks().push({});
  };
  $scope.removeLink = function (index) {
    getLinks().splice(index, 1);
  };
})


text: int compress_yuyv_to_jpeg(struct vdIn *vd, unsigned char *buffer, int size, int quality);


text:
layout: post
title:  "Day 7: Our brains hurt from learning so much"
date:   2016-07-12
categories: [log]
comments: false
tags: [log, rust, servo]
authors: Jeena and Malisa
---

## Things we did:
- Re-organized a lot of our validate function we wrote yesterday.
    - We had misinterpreted the HeadersAPI spec. We were thinking way too far ahead.
    - But, the code we wrote yesterday will be useful in the near future, so :thumbsup:.
- We understood better what we need to do for validating Header name and value.
    - We will have to write parsers to do so.
- Started writing different components for the parsers.
- We added `guard` to our `Headers` struct.
- We created `enum Guard` for `guard`.
- We got a lot of practice using `Result<>`.
- We filed an [issue] (https://github.com/whatwg/fetch/issues/332) at whatwg/fetch.

## Things we learned:
- How to add crate dependencies (assuming `script` is the root directory of our files):
    - In `components/script/lib.rs`, add `extern crate unicase;`.
    - In `components/script/Cargo.toml`, add `use unicase="1.4.0"`.
- `Cow` automatically handles copy and writing when you have a borrowed immutable reference.
- Emacs tip "defining macro":
    - `C-x (` (define macro) `C-x )` `C-e` (execute macro)
- `String` is guaranteed to be UTF8 and is heap-allocated (and therefore growable). `&str` is a `string-slice`. `dom::bindings::str::ByteString` is not guaranteed to be UTF8.
- If `Result` only returns an error, use `Result<(), Error>`.
- For Boolean matching in Rust, use `&&`.
- Because the Headers API interacts with JS, JS garbage collector must be able to trace Headers API's elements. In order to allow that, above a struct or enum that declares, add `#[derive(JSTraceable, HeapSizeOf)]`.
- Crate `regex` supports pattern matching on bytes. Add `use regex::bytes` to the code.

## TODO:
- Finish writing field name and field content parsers.
- Figure out how to wrap our Headers struct around `hyper::headers::Headers`. Ask jdm!
- Continue writing `Append` method.


text:
box.cfg {
    ------------------------
    -- Network configuration
    ------------------------

    -- The read/write data port number or URI
    -- Has no default value, so must be specified if
    -- connections will occur from remote clients
    -- that do not use "admin address"

    -- listen = 'localhost:3301';
    listen = '*:{{PORT}}';

    -- The server is considered to be a Tarantool replica
    -- it will try to connect to the master
    -- which replication_source specifies with a URI
    -- for example konstantin:secret_password@tarantool.org:3301
    -- by default username is "guest"
    -- replication_source="127.0.0.1:3102";

    -- The server will sleep for io_collect_interval seconds
    -- between iterations of the event loop
    io_collect_interval = nil;

    -- The size of the read-ahead buffer associated with a client connection
    readahead = 16320;

    ----------------------
    -- Memtx configuration
    ----------------------

    -- An absolute path to directory where snapshot (.snap) files are stored.
    -- If not specified, defaults to /var/lib/tarantool/INSTANCE
    memtx_dir = "{{DBDIR}}";

    -- How much memory Memtx engine allocates
    -- to actually store tuples, in bytes.
    memtx_memory = 128 * 1024 * 1024; -- 10Mb

    -- Size of the smallest allocation unit, in bytes.
    -- It can be tuned up if most of the tuples are not so small
    memtx_min_tuple_size = 16;

    -- Size of the largest allocation unit, in bytes.
    -- It can be tuned up if it is necessary to store large tuples
    memtx_max_tuple_size = 1 * 1024 * 1024; -- 1Mb

    -- Reduce the throttling effect of box.snapshot() on
    -- INSERT/UPDATE/DELETE performance by setting a limit
    -- on how many megabytes per second it can write to disk
    memtx_snap_io_rate_limit = nil;

    ----------------------
    -- Vinyl configuration
    ----------------------

    -- An absolute path to directory where Vinyl files are stored.
    -- If not specified, defaults to /var/lib/tarantool/INSTANCE

    vinyl_dir = "{{DBDIR}}";

    -- How much memory Vinyl engine can use for in-memory level, in bytes.
    vinyl_memory = 128 * 1024 * 1024; -- 128Mb

    -- How much memory Vinyl engine can use for caches, in bytes.
    vinyl_cache = 128 * 1024 * 1024; -- 128Mb

    -- Size of the largest allocation unit, in bytes.
    -- It can be tuned up if it is necessary to store large tuples
    -- vinyl_max_tuple_size = 10 * 1024 * 1024; -- 10Mb

    -- The maximum number of background workers for compaction.
    vinyl_write_threads = 2;

    ------------------------------
    -- Binary logging and recovery
    ------------------------------

    -- An absolute path to directory where write-ahead log (.xlog) files are
    -- stored. If not specified, defaults to /var/lib/tarantool/INSTANCE

    wal_dir = "{{DBDIR}}";

    -- Specify fiber-WAL-disk synchronization mode as:
    -- "none": write-ahead log is not maintained;
    -- "write": fibers wait for their data to be written to the write-ahead log;
    -- "fsync": fibers wait for their data, fsync follows each write;
    wal_mode = "write";

    -- The maximal size of a single write-ahead log file
    wal_max_size = 256 * 1024 * 1024;

    -- The interval between actions by the checkpoint daemon, in seconds
    checkpoint_interval = 60 * 60; -- one hour

    -- The maximum number of checkpoints that the daemon maintans
    -- checkpoint_count = 6;

    -- Don't abort recovery if there is an error while reading
    -- files from the disk at server start.
    force_recovery = true;

    ----------
    -- Logging
    ----------

    -- How verbose the logging is. There are six log verbosity classes:
    -- 1 – SYSERROR
    -- 2 – ERROR
    -- 3 – CRITICAL
    -- 4 – WARNING
    -- 5 – INFO
    -- 6 – VERBOSE
    -- 7 – DEBUG
    log_level = 5;

    -- By default, the log is sent to /var/log/tarantool/INSTANCE.log
    -- If logger is specified, the log is sent to the file named in the string

    log = "{{DBDIR}}/instance.log";

    -- If true, tarantool does not block on the log file descriptor
    -- when it's not ready for write, and drops the message instead
    log_nonblock = true;

    -- If processing a request takes longer than
    -- the given value (in seconds), warn about it in the log
    too_long_threshold = 0.5;

    -- Inject the given string into server process title
    -- custom_proc_title = 'example';
}

local function bootstrap()
    -- local space = box.schema.create_space("main")
    -- space:create_index('primary')
    -- Comment this if you need fine grained access control (without it, guest
    -- will have access to everything)
    -- box.schema.user.grant('guest', 'read,write,execute', 'universe')

    -- Keep things safe by default
    box.schema.user.create('root', { password = '{{SECRET}}' })
    box.schema.user.grant('root', 'read,write,execute', 'universe')
    --  box.schema.user.grant('example', 'replication')
    --  box.schema.user.grant('example', 'read,write,execute', 'space', 'example')
end

-- for first run create a space and add set up grants
box.once('bootstrap_{{NAME}}', bootstrap)

-----------------------
-- Automatinc sharding
-----------------------
-- N.B. you need install tarantool-shard package to use shadring
-- Docs: https://github.com/tarantool/shard/blob/master/README.md
-- Example:
--  local shard = require('shard')
--  local shards = {
--      servers = {
--          { uri = [[host1.com:4301]]; zone = [[0]]; };
--          { uri = [[host2.com:4302]]; zone = [[1]]; };
--      };
--      login = 'tester';
--      password = 'pass';
--      redundancy = 2;
--      binary = '127.0.0.1:3301';
--      monitor = false;
--  }
--  shard.init(shards)

-----------------
-- Message queue
-----------------
-- N.B. you need to install tarantool-queue package to use queue
-- Docs: https://github.com/tarantool/queue/blob/master/README.md
-- Example:
--  local queue = require('queue')
--  queue.create_tube(tube_name, 'fifottl')

-------------------
-- Data expiration
-------------------
-- N.B. you need to install tarantool-expirationd package to use expirationd
-- Docs: https://github.com/tarantool/expirationd/blob/master/README.md
-- Example (deletion of all tuples):
--  local expirationd = require('expirationd')
--  local function is_expired(args, tuple)
--    return true
--  end
--  expirationd.start("clean_all", space.id, is_expired {
--    tuple_per_item = 50,
--    full_scan_time = 3600
--  })

package.path = '/tmp/lua/?.lua;' .. package.path


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

describe DeliveryDate do
  before(:each) do
    @delivery_date = DeliveryDate.new
  end
  describe "validateチェック" do
    it "データがただしい" do
      @delivery_date.should be_valid
    end
  end
end


text:
<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(Classie\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'remember_token' => str_random(10),
    ];
});

$factory->define(Classie\Post::class, function (Faker\Generator $faker) {
    return [
        'user_id' => function () {
            return factory(Classie\User::class)->create()->id;
        },
        'title' => $faker->sentence,
        'body' => $faker->paragraph
    ];
});


text:
@interface ANEPExpression : NSObject {
	NSMutableArray * subcomponents;
	ANEPNumber * number;
}

// CALL THESE METHODS TO PARSE AN EXPRESSION
+ (ANEPExpression *)expressionFromString:(NSString *)str variables:(NSArray *)vars;
- (ANEPNumber *)numberValue;

// methods not to be called
+ (ANEPExpression *)expressionWithNumber:(ANEPNumber *)_number;

@end


text:
int PositiveDivide( unsigned int dividend, unsigned int divisor )
{
    int Q = 0;
	while (dividend >= divisor)
	{
		unsigned int ShiftedDividend = dividend;
		unsigned int ShiftedBit = 0;
		while (divisor <= ShiftedDividend)
		{
			ShiftedDividend >>= 1;
			ShiftedBit++;
		}
		--ShiftedBit;
		dividend -= (divisor << ShiftedBit);
		Q |= (1 << ShiftedBit);
	}
	return Q;
}

int divide(int dividend, int divisor)
{
    if( !divisor || !dividend )return 0;
    if( dividend == divisor )return 1;
    if( dividend == INT_MAX && abs(divisor) == 1 )return (abs(divisor) == divisor) ? MAX_INT : -2147483647;
    if( abs(dividend) < 0 && abs(divisor) == 1 )return (abs(divisor) == divisor) ?  -2147483648 : MAX_INT;
    int ret = 0;
    unsigned int OverflowDividend = abs(dividend) < 0 ? INT_MAX+1 : dividend;
    if( dividend > 0 && divisor > 0 || dividend < 0 && divisor < 0 )
    {
        if( dividend < 0 && abs(dividend) < 0)
            ret += PositiveDivide(OverflowDividend, abs(divisor));
        else
            ret += PositiveDivide(abs(dividend), abs(divisor));
    }
    else
    {
        if( dividend < 0 && abs(dividend) < 0)
            ret -= PositiveDivide(OverflowDividend, abs(divisor));
        else
            ret -= PositiveDivide(abs(dividend), abs(divisor));
    }
    return ret;
}


text:
These pseudo data flow diagrams show how the data flow from input through the three modules of the implementation. These are high level overview of the internal operation of the modules that should ease the process of reading into the source code.

**Notation**
* **B**: the batch size.
* **T**: the sequence length.
* **the rest** follows the paper notation.

*No data flow diagram is shown for the memory module as it would be unnecessarily complicated; given that , unlike the other two modules, the memory model is not doing anything more than what is described in the paper*.

## DNC Module

![DNC-pDFD](/assets/DNC-DFD.png)

## Controller Module

![Controller-pDFD](/assets/Controller-DFD.png)


text:
namespace galaxy
{
	Editor::Editor() noexcept
		:m_window(nullptr)
	{
	}

	Editor::Editor(sf::RenderWindow* window)
		:m_window(nullptr)
	{
		init(window);
	}

	Editor::~Editor()
	{
		shutdown();
	}

	void Editor::init(sf::RenderWindow* window)
	{
		m_window = window;

		// Setup Dear ImGui context and SFML.
		ImGui::SFML::Init(*m_window, true);
		ImGuiIO& io = ImGui::GetIO();
		io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;

		// Setup style.
		ImGui::StyleColorsDark();
	}

	void Editor::event(const sf::Event& event)
	{
		ImGui::SFML::ProcessEvent(event);
	}

	void Editor::update(sf::Time& dt)
	{
		ImGui::SFML::Update(*m_window, dt);
	}

	void Editor::render()
	{
		ImGui::SFML::Render();
	}

	void Editor::shutdown()
	{
		ImGui::SFML::Shutdown();
	}

	void Editor::display(bool* restart)
	{
		// Set up stateless variables.
		static bool s_showEditor = false;
		static bool s_showLuaConsole = false;

		// BEGIN UI.
		ImGui::Begin("Galaxy Editor", (bool*)false, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_AlwaysUseWindowPadding);
		ImGui::SetWindowSize(ImVec2(640, 480), ImGuiCond_FirstUseEver);

		// Define the gui layout.
		if (ImGui::BeginMenuBar())
		{
			// This is the code used by the app to restart it.
			if (ImGui::MenuItem("Restart"))
			{
				*restart = true;
				galaxy::ServiceLocator::get().window()->close();
			}

			// Option to close game.
			if (ImGui::MenuItem("Quit"))
			{
				*restart = false;
				galaxy::ServiceLocator::get().window()->close();
			}

			ImGui::EndMenuBar();
		}

		ImGui::Separator();
		ImGui::Spacing();

		// Open script m_editor.
		if (ImGui::Button("Script Editor"))
		{
			s_showEditor = true;
		}

		// Open Lua console.
		if (ImGui::Button("Show Console"))
		{
			s_showLuaConsole = true;
		}

		if (s_showEditor)
		{
			static const std::array<const char*, 2> filter = {
				"*.json", "*.lua"
			};

			auto cpos = m_editor.GetCursorPosition();

			// BEGIN WINDOW.
			ImGui::Begin("Script Editor", &s_showEditor, ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_AlwaysVerticalScrollbar);
			ImGui::SetWindowSize(ImVec2(800, 600), ImGuiCond_FirstUseEver);

			// BEGIN MENU BAR.
			if (ImGui::BeginMenuBar())
			{
				if (ImGui::BeginMenu("File"))
				{
					if (ImGui::MenuItem("Open", "Ctrl-O"))
					{
						// https://github.com/BalazsJako/ColorTextEditorDemo/blob/master/main.cpp
						// make only json or lua.
						auto openFileName = tinyfd_openFileDialog(
							"Open",
							PHYSFS_getBaseDir(),
							0,
							filter.data(),
							"JSON or Lua.",
							false);

						if (openFileName != nullptr)
						{
							// Convert to C++17 path.
							std::filesystem::path filePath = std::filesystem::path(openFileName);
							m_currentFile = openFileName;

							if (filePath.extension() == ".json")
							{
								m_editor.SetLanguageDefinition(galaxy::getJsonDefinition());
							}
							else if (filePath.extension() == ".lua")
							{
								m_editor.SetLanguageDefinition(TextEditor::LanguageDefinition::Lua());
							}
							else
							{
								PL_LOG(pl::Log::Level::ERROR_, "Tried to load unsupported file.");
							}

							std::ifstream text(filePath.string());
							if (!text.fail())
							{
								std::string str((std::istreambuf_iterator<char>(text)), std::istreambuf_iterator<char>());
								m_editor.SetText(str);
							}
							else
							{
								PL_LOG(pl::Log::Level::ERROR_, "Failed to read file: " + filePath.string());
							}

							text.close();
						}
						else
						{
							PL_LOG(pl::Log::Level::ERROR_, "Failed to open file with tfd.");
						}
					}

					if (ImGui::MenuItem("Save", "Ctrl-S"))
					{
						m_editor.GetCursorPosition();
						auto text = m_editor.GetText();
						std::ofstream out(m_currentFile, std::ios::out | std::ios::trunc);
						out << text;
						out.close();
					}

					if (ImGui::MenuItem("Close", "Ctrl-Q"))
					{
						s_showEditor = false;
						m_editor.SetText("");
					}

					ImGui::EndMenu();
				}

				if (ImGui::BeginMenu("Edit"))
				{
					bool ro = m_editor.IsReadOnly();
					if (ImGui::MenuItem("Read-only mode", nullptr, &ro))
						m_editor.SetReadOnly(ro);
					ImGui::Separator();

					if (ImGui::MenuItem("Undo", "ALT-Backspace", nullptr, !ro && m_editor.CanUndo()))
						m_editor.Undo();
					if (ImGui::MenuItem("Redo", "Ctrl-Y", nullptr, !ro && m_editor.CanRedo()))
						m_editor.Redo();

					ImGui::Separator();

					if (ImGui::MenuItem("Copy", "Ctrl-C", nullptr, m_editor.HasSelection()))
						m_editor.Copy();
					if (ImGui::MenuItem("Cut", "Ctrl-X", nullptr, !ro && m_editor.HasSelection()))
						m_editor.Cut();
					if (ImGui::MenuItem("Delete", "Del", nullptr, !ro && m_editor.HasSelection()))
						m_editor.Delete();
					if (ImGui::MenuItem("Paste", "Ctrl-V", nullptr, !ro && ImGui::GetClipboardText() != nullptr))
						m_editor.Paste();

					ImGui::Separator();

					if (ImGui::MenuItem("Select all", nullptr, nullptr))
						m_editor.SetSelection(TextEditor::Coordinates(), TextEditor::Coordinates(m_editor.GetTotalLines(), 0));

					ImGui::EndMenu();
				}

				if (ImGui::BeginMenu("View"))
				{
					if (ImGui::MenuItem("Dark palette"))
						m_editor.SetPalette(TextEditor::GetDarkPalette());
					if (ImGui::MenuItem("Light palette"))
						m_editor.SetPalette(TextEditor::GetLightPalette());
					if (ImGui::MenuItem("Retro blue palette"))
						m_editor.SetPalette(TextEditor::GetRetroBluePalette());
					ImGui::EndMenu();
				}

				ImGui::EndMenuBar();
				// END MENU BAR.
			}

			m_editor.Render("TextEditor");

			ImGui::End();
			// END WINDOW.
		}

		if (s_showLuaConsole)
		{
			// Create and show console.
			static galaxy::LuaConsole s_console;
			s_console.draw(&s_showLuaConsole);
		}

		ImGui::End();
		// END UI.
	}
}


text:
Full changelog for Zend Framework 3 view helpers library.

## v1.02.2 - Code coverage - 2018-05-16

* Added code coverage reporting.
* Updated dependencies and tested.

## v1.02.1 - Dependency - 2018-01-20

* Removed deanblackborough/zf3-view-helpers-code-completion from require, added to suggest

## v1.02.0 - Row and Column view helper - 2018-01-20

* Added a Bootstrap 4 row view helper.
* Added a Bootstrap 4 column view helper.
* Updated dependencies, zendframework/zend-view v2.10

## v1.01.2 - Minor corrections - 2018-01-05

* Require PHP 7, suggest PHP 7.2.
* Removed unused property.
* Testing against PHP7.2.
* Updated dependencies.
* Spelling corrections.

## v1.01.1 - Minor corrections - 2017-12-04

* Type hints missing.
* Unused property.

## v1.01.0 - Alert component - 2017-12-02

* Added a Bootstrap 4 alert view helper.
* Removed a redundant property in the button view helper.
* Type hints missing.
* Added missing dates in CHANGELOG.

## v1.00.0 - Card component (Official release) - 2017-10-13

Official v1.00.0 release, tests in place for all the Bootstrap 4 view helpers.

* Card view helper extends Bootstrap4Helper.
* Card view helper supports setTextStyle() and setBgStyle().
* Added tests for card view helper.
* setFooter() in card view helper broken, incorrect property being used to generated HTML.
* Fixed a couple of bugs with the navbar view helper.
* Added tests for the navbar view helper.

## v0.66.0 - Minor updates - 2017-10-11

* Updated Bootstrap 4 jumbotron view helper, extends Bootstrap4Helper.
* Updated Bootstrap 4 multiple progress bar view helper, extends Bootstrap4Helper.
* Updated Bootstrap 4 badge view helper, extends Bootstrap4Helper.
* Updated Bootstrap 4 button view helper, extends Bootstrap4Helper.
* Added combined tests to view helpers.
* Corrected README.

## v0.65.0 - Base class - 2017-10-11

* Additional tests for Bootstrap 4 Progress bar view helper.
* Added a base class for Bootstrap 4 view helpers, Progress bar now extends it for base functionality.
* Minor changes to method names.

## v0.64.0 - Tests and Jumbotron - 2017-10-11

* Added tests for Bootstrap 4 Jumbotron view helper.
* Added setBGStyle() and setTextStyle() to Jumbotron view helper.
* Jumbotron headings default to heading-1 for the H1.
* Added tests for Bootstrap 4 Progress bar view helper.
* Bootstrap 4 progress bar view helper now supports all the bg-* utility classes.

## v0.63.0 - Tests - 2017-10-08

* Removing call to default escape plugins, assumption now is developer will escape their own data.
* Added tests for Bootstrap 4 Badge view helper.
* Added tests for Bootstrap 4 Button view helper.

## v0.62.1 - Beta 4.0.0 updates/fixes

* Badge view helper updated, classes match beta-4.0.0 of Bootstrap.
* Updated supported styles for badge and button view helpers.

## v0.62.0 - Cards: First body element only

* Updated addCustomBodyAttr() and addCustomBodyClass(), only apply custom class or attribute to the first body element
of the given type.

## v0.61.1 - Navbar view helper

* Updated navbar view helper to take account of changes between the alpha and beta.
* Updated the background schemes.

## v0.61 - Card view helper: Custom body attributes and classes - 2017-08-25

* Custom attributes and classes can be assigned to body section.
* Comment corrections/updates.

## v0.60 - Card - 2017-08-22

* Added a Bootstrap 4 card view helper.
* Updated README, changed order of sections.

## v0.51 - Progress bar - 2017-08-14

* Added Bootstrap 3 progress bar view helper.
* Switched back to require, if you use the view helpers you need the completion, you don't need the completion to develop the view helpers.

## v0.50 - Progress bar - 2017-07-26

* Added progress bar and multiple progress bar Bootstrap 4 view helpers.

## v0.40.3 - Readme - 2017-05-30

* Updated readme with details on code completion package.

## v0.40.2 - Dependency - 2017-05-30

* Code completion package is now a dependency.

## v0.40.2 - Dependency - 2017-05-30

* Code completion package is now a dependency.

## v0.40.1 - Escape - 2017-05-26

* View helpers were not calling the escape helpers.

## v0.40 - Navbar - 2017-05-24

* Added a Bootstrap 4 navbar view helper.

## v0.30 - Badges and labels - 2017-05-22

* Added Bootstrap 3 badge view helper.
* Added Bootstrap 3 label view helper.
* Added Bootstrap 4 badge view helper.
* Minor fixes.

## v0.25 - Buttons - 2017-05-22

* Added Bootstrap 3 button view helper.
* customClass method was incorrectly private.

## v0.20 - Buttons - 2017-05-19

* Added Bootstrap 4 button view helper.

## v0.10.1 - Icons - 2017-05-16

* Added missing icons to README.

## v0.10 (Initial release) - 2017-05-16

* Added Bootstrap 3 Jumbotron view helper.
* Added Bootstrap 4 Jumbotron view helper.


text:
class WorkbinsViewModel : public QAbstractItemModel
{
    Q_OBJECT

public:
    explicit WorkbinsViewModel(QObject *parent = 0);
    ~WorkbinsViewModel();

    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
    Qt::ItemFlags flags(const QModelIndex &index) const;
    QModelIndex index(int row, int column,
                      const QModelIndex &parent = QModelIndex()) const;
    QModelIndex parent(const QModelIndex &index) const;
    int rowCount(const QModelIndex &parent = QModelIndex()) const;
    int columnCount(const QModelIndex &parent = QModelIndex()) const;

    bool setData(const QModelIndex &index, const QVariant &value, int role);

    WorkbinsViewItem* invisibleRootItem();
    QModelIndex& rootIndex();

public slots:
    void childAddedSlot(WorkbinsViewItem*);
    void childCheckBoxChanged();

private:
    WorkbinsViewItem *rootItem;
};

#endif // WORKBINSVIEWMODEL_H


text:
      {{ activeComponent.name }} extends {{ activeComponent.extends }}({{ activeComponent.module }} module){{ activeComponent.file }} at line #{{ activeComponent.line }}

    <input id="component-search" class="component-search" ng-model="searchComponentText" ng-keydown="clearOnEscape($event, 'searchComponentText')" ng-mouseup="searchMouseUp($event)" placeholder="Filter Component Items" />

        HTML Attributes{{ activeComponent.nghtmlattributes.length }}

        Methods{{ activeComponent.methods.length }}

        Properties{{ activeComponent.properties.length }}

        Events{{ activeComponent.events.length + activeComponent.respondTos.length }}

        Watches{{ activeComponent.ngWatches.length }}

    HTML Attributes

        {{ htmlAttribute.name }} : {{ htmlAttribute.type }}

      No items available.

    Methods

{{ method.ngtype }}

          {{ method.name }}([ 0">, {{ parameter.type }} {{ parameter.name }} = {{ parameter.optdefault }}])
         : {{ method.return.type }} {{ method.file }} at line #{{ method.line }}

          Returns : {{ method.return.type }}

          Examples

      No items available.

    Properties

{{ property.ngtype }}

        {{ property.name }} : {{ property.type }}{{ property.file }} at line #{{ property.line }}

          Sub-Properties

                {{ property.name }}.{{ subProperty.name }} : {{ subProperty.type }}

Default: {{ subProperty.optdefault }}

      No items available.

    Events

Broadcasts

          {{ event.eventlevel }} - {{ event.name }}File: {{ event.file }} at line #{{ event.line }}

        No items available.

Listens

          {{ respondTo.name }}File: {{ respondTo.file }} at line #{{ respondTo.line }} : {{ respondTo.eventlevel }}

        No items available.

    Watches

{{ ngwatch.ngtype }}

        {{ ngwatch.name }}{{ ngwatch.file }} at line #{{ ngwatch.line }}

      No items available.


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

<title>404 Not Found</title>

Not Found

The requested URL /~kurmasz/Teaching/Courses/S17/CS371/Assignments/HtmlCss/week1.css was not found on this server.


text:
http://localhost:8080/ssmmv0x

http://localhost:8080/ssmmv0x/user/register?username=admin1&password=admin1
http://localhost:8080/ssmmv0x/user/login?username=admin&password=admin
http://localhost:8080/ssmmv0x/user/login?username=admin&password=admin1

1
mvn archetype:generate -DgroupId=com.vsked -DartifactId=ssmmv0 -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false -DarchetypeCatalog=internal

2
cd ssmmv0
mvn eclipse:eclipse

right click->configue->cover to maven project

3
fixed the web.xml version

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

fixed the junit version to 4.12

4
mvn install

本实例抄自
http://www.cnblogs.com/java-zhao/p/5096811.html


text:
<!DOCTYPE html>

<title>
Autocorrelation
</title>
<link rel="stylesheet" type="text/css" href="help.css">

Definition

Correlations between two values of the same variable at equispaced times.

The 95% confidence level is indicated by two horizontal lines. If the series is completely random, the probability is roughly 95% that the correlation falls within the lines. The ordinates of the lines are at `2/sqrt(N)` , where N is the number of data points.

Parameters

In the top slot, the qualitative field to be analayzed. The values must be sorted by the time.


text:
package org.apache.jmeter.engine.event;

import org.apache.jmeter.testelement.TestElement;

/**
 * An iteration event provides information about the iteration number and the
 * source of the event.
 */
public class LoopIterationEvent {
    private final int iteration;

    private final TestElement source;

    public LoopIterationEvent(TestElement source, int iter) {
        iteration = iter;
        this.source = source;
    }

    /**
     * Returns the iteration.
     *
     * @return int
     */
    public int getIteration() {
        return iteration;
    }

    /**
     * Returns the source.
     *
     * @return TestElement
     */
    public TestElement getSource() {
        return source;
    }

}


text:
import max from 'mout/object/max';

import CanvasOffscreenBuffer from '../../../Common/Misc/CanvasOffscreenBuffer';
import WebGlUtil from '../../../Common/Misc/WebGl';
import PingPong from '../../../Common/Misc/PingPong';

import vertexShader from '../../../Common/Misc/WebGl/shaders/vertex/basic.c';
import fragmentShaderDisplay from './shaders/fragment/display.c';
import fragmentShaderComposite from './shaders/fragment/composite.c';

export default class RGBACompositor {
  // ------------------------------------------------------------------------

  constructor({ queryDataModel, imageBuilder }) {
    this.queryDataModel = queryDataModel;
    this.imageBuilder = imageBuilder;
    this.rgbdSprite = null;
    this.offsetList = [];
    this.spriteSize = max(
      this.queryDataModel.originalData.CompositePipeline.offset
    );
    this.removeLoadCallback = false;
    this.closureRenderMethod = () => {
      this.render();
    };

    this.dataSubscription = queryDataModel.onDataChange((data, envelope) => {
      this.rgbdSprite = data.rgbdSprite.image;

      if (this.rgbdSprite.complete) {
        this.render();
      } else {
        this.removeLoadCallback = true;
        this.rgbdSprite.addEventListener('load', this.closureRenderMethod);
      }
    });

    this.width = this.queryDataModel.originalData.CompositePipeline.dimensions[0];
    this.height = this.queryDataModel.originalData.CompositePipeline.dimensions[1];
    this.glCanvas = new CanvasOffscreenBuffer(this.width, this.height);
    this.compositeCanvas = new CanvasOffscreenBuffer(this.width, this.height);
    this.compositeCtx = this.compositeCanvas.get2DContext();

    // Inialize GL context
    this.gl = this.glCanvas.get3DContext();
    if (!this.gl) {
      console.error('Unable to get WebGl context');
      return;
    }

    // Set clear color to white, fully transparent
    this.gl.clearColor(1.0, 1.0, 1.0, 0.0);

    // Set up GL resources
    this.glConfig = {
      programs: {
        displayProgram: {
          vertexShader,
          fragmentShader: fragmentShaderDisplay,
          mapping: 'default',
        },
        compositeProgram: {
          vertexShader,
          fragmentShader: fragmentShaderComposite,
          mapping: 'default',
        },
      },
      resources: {
        buffers: [
          {
            id: 'texCoord',
            data: new Float32Array([
              0.0,
              0.0,
              1.0,
              0.0,
              0.0,
              1.0,
              0.0,
              1.0,
              1.0,
              0.0,
              1.0,
              1.0,
            ]),
          },
          {
            id: 'posCoord',
            data: new Float32Array([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
          },
        ],
        textures: [
          {
            id: 'texture2D',
            pixelStore: [['UNPACK_FLIP_Y_WEBGL', true]],
            texParameter: [
              ['TEXTURE_MAG_FILTER', 'NEAREST'],
              ['TEXTURE_MIN_FILTER', 'NEAREST'],
              ['TEXTURE_WRAP_S', 'CLAMP_TO_EDGE'],
              ['TEXTURE_WRAP_T', 'CLAMP_TO_EDGE'],
            ],
          },
          {
            id: 'ping',
            pixelStore: [['UNPACK_FLIP_Y_WEBGL', true]],
            texParameter: [
              ['TEXTURE_MAG_FILTER', 'NEAREST'],
              ['TEXTURE_MIN_FILTER', 'NEAREST'],
              ['TEXTURE_WRAP_S', 'CLAMP_TO_EDGE'],
              ['TEXTURE_WRAP_T', 'CLAMP_TO_EDGE'],
            ],
          },
          {
            id: 'pong',
            pixelStore: [['UNPACK_FLIP_Y_WEBGL', true]],
            texParameter: [
              ['TEXTURE_MAG_FILTER', 'NEAREST'],
              ['TEXTURE_MIN_FILTER', 'NEAREST'],
              ['TEXTURE_WRAP_S', 'CLAMP_TO_EDGE'],
              ['TEXTURE_WRAP_T', 'CLAMP_TO_EDGE'],
            ],
          },
        ],
        framebuffers: [
          {
            id: 'ping',
            width: this.width,
            height: this.height,
          },
          {
            id: 'pong',
            width: this.width,
            height: this.height,
          },
        ],
      },
      mappings: {
        default: [
          {
            id: 'posCoord',
            name: 'positionLocation',
            attribute: 'a_position',
            format: [2, this.gl.FLOAT, false, 0, 0],
          },
          {
            id: 'texCoord',
            name: 'texCoordLocation',
            attribute: 'a_texCoord',
            format: [2, this.gl.FLOAT, false, 0, 0],
          },
        ],
      },
    };

    this.glResources = WebGlUtil.createGLResources(this.gl, this.glConfig);

    this.pingPong = new PingPong(
      this.gl,
      [this.glResources.framebuffers.ping, this.glResources.framebuffers.pong],
      [this.glResources.textures.ping, this.glResources.textures.pong]
    );
  }

  // ------------------------------------------------------------------------

  updateQuery(query) {
    const layers = this.queryDataModel.originalData.CompositePipeline.layers;
    const count = layers.length;
    const offsets = this.queryDataModel.originalData.CompositePipeline.offset;

    this.offsetList = [];
    for (let idx = 0; idx < count; idx++) {
      const fieldCode = query[idx * 2 + 1];
      if (fieldCode !== '_') {
        this.offsetList.push(
          this.spriteSize - offsets[layers[idx] + fieldCode]
        );
      }
    }
  }

  // ------------------------------------------------------------------------

  render() {
    if (!this.rgbdSprite || !this.rgbdSprite.complete) {
      return;
    }

    // Handle image decoding
    if (this.removeLoadCallback) {
      this.rgbdSprite.removeEventListener('load', this.closureRenderMethod);
      this.removeLoadCallback = false;
    }

    // Compute composite
    this.pingPong.clearFbo();
    this.offsetList.forEach((layerIdx) => {
      const srcY = layerIdx * this.height;

      // Because the png has transparency, we need to clear the canvas, or else
      // we end up with some blending when we draw the next image
      this.compositeCtx.clearRect(0, 0, this.width, this.height);
      this.compositeCtx.drawImage(
        this.rgbdSprite,
        0,
        srcY,
        this.width,
        this.height,
        0,
        0,
        this.width,
        this.height
      );

      this.drawCompositePass();
    });

    // Draw to display
    this.drawDisplayPass();

    const readyImage = {
      canvas: this.glCanvas.el,
      area: [0, 0, this.width, this.height],
      outputSize: [this.width, this.height],
      builder: this.imageBuilder,
    };

    this.imageBuilder.imageReady(readyImage);
  }

  // ------------------------------------------------------------------------

  destroy() {
    this.glCanvas.destroy();
    this.glCanvas = null;

    this.dataSubscription.unsubscribe();
    this.dataSubscription = null;

    this.glResources.destroy();
    this.glResources = null;

    this.pingPong = null;
  }

  // ------------------------------------------------------------------------

  drawDisplayPass() {
    // Draw to the screen framebuffer
    this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null);

    // Using the display shader program
    this.gl.useProgram(this.glResources.programs.displayProgram);

    this.gl.clear(this.gl.COLOR_BUFFER_BIT);
    this.gl.viewport(0, 0, this.width, this.height);

    // Set up the sampler uniform and bind the rendered texture
    const uImage = this.gl.getUniformLocation(
      this.glResources.programs.displayProgram,
      'u_image'
    );
    this.gl.uniform1i(uImage, 0);
    this.gl.activeTexture(this.gl.TEXTURE0 + 0);
    this.gl.bindTexture(
      this.gl.TEXTURE_2D,
      this.pingPong.getRenderingTexture()
    );

    // Draw the rectangle.
    this.gl.drawArrays(this.gl.TRIANGLES, 0, 6);

    this.gl.finish();
  }

  // ------------------------------------------------------------------------

  drawCompositePass() {
    // Draw to the fbo on this pass
    this.gl.bindFramebuffer(
      this.gl.FRAMEBUFFER,
      this.pingPong.getFramebuffer()
    );

    // Using the compositing shader program
    this.gl.useProgram(this.glResources.programs.compositeProgram);

    // this.gl.clear(this.gl.COLOR_BUFFER_BIT);
    this.gl.viewport(0, 0, this.width, this.height);

    // Set up the layer texture
    const layer = this.gl.getUniformLocation(
      this.glResources.programs.compositeProgram,
      'layerSampler'
    );
    this.gl.uniform1i(layer, 0);
    this.gl.activeTexture(this.gl.TEXTURE0 + 0);
    this.gl.bindTexture(
      this.gl.TEXTURE_2D,
      this.glResources.textures.texture2D
    );
    this.gl.texImage2D(
      this.gl.TEXTURE_2D,
      0,
      this.gl.RGBA,
      this.gl.RGBA,
      this.gl.UNSIGNED_BYTE,
      this.compositeCanvas.el
    );

    // Set up the sampler uniform and bind the rendered texture
    const composite = this.gl.getUniformLocation(
      this.glResources.programs.compositeProgram,
      'compositeSampler'
    );
    this.gl.uniform1i(composite, 1);
    this.gl.activeTexture(this.gl.TEXTURE0 + 1);
    this.gl.bindTexture(
      this.gl.TEXTURE_2D,
      this.pingPong.getRenderingTexture()
    );

    // Draw the rectangle.
    this.gl.drawArrays(this.gl.TRIANGLES, 0, 6);

    this.gl.finish();

    // Ping-pong
    this.pingPong.swap();
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using ServiceStack.Text.Jsv;

namespace ServiceStack.Text.Tests.JsvTests
{
    [TestFixture]
    public class InheritanceTests
    {
        public class TestParent
        {
            public string Parameter { get; private set; }

            public TestParent(string parameter)
            {
                Parameter = parameter;
            }
        }

        public class TestChild : TestParent
        {
            public TestChild(string parameter)
                : base(parameter)
            { }
        }

        [Test]
        public void Should_set_property_of_parent_class()
        {
            var serializer = new JsvSerializer<TestChild>();
            var serialized = serializer.SerializeToString(new TestChild("Test Value"));
            var deserialized = serializer.DeserializeFromString(serialized);
            Assert.That(deserialized.Parameter, Is.EqualTo("Test Value"));
        }
    }
}


text:
.PHONY: clean clean-build clean-pyc clean-test lint test test-doc docs

help:
	@echo "clean - remove all build, test, coverage and Python artifacts"
	@echo "clean-build - remove build artifacts"
	@echo "clean-pyc - remove Python file artifacts"
	@echo "clean-test - remove test and coverage artifacts"
	@echo "lint - check style with flake8"
	@echo "test - run tests quickly with the default Python"
	@echo "test-doc - run Sphinx documentation integrity check"
	@echo "docs - generate Sphinx HTML documentation, including API docs"

clean: clean-build clean-pyc clean-test

clean-build:
	rm -fr build/
	rm -fr dist/
	rm -fr .eggs/
	find . -name '*.egg-info' -exec rm -fr {} +
	find . -name '*.egg' -exec rm -f {} +

clean-pyc:
	find . -name '*.pyc' -exec rm -f {} +
	find . -name '*.pyo' -exec rm -f {} +
	find . -name '*~' -exec rm -f {} +
	find . -name '__pycache__' -exec rm -fr {} +

clean-test:
	rm -f .coverage

lint:
	flake8 snoPlowPy

test: clean-pyc
	pytest snoPlowPy

test-doc:
	sphinx-build -b html -d docs/_build/doctrees docs docs/_build/html

docs:
	rm -f docs/snoPlowPy.rst
	rm -f docs/modules.rst
	sphinx-apidoc -o docs/ snoPlowPy
	$(MAKE) -C docs clean
	$(MAKE) -C docs html


text:
layout: page
title: Fuck everything about 2016
---

![Are you thinking what I'm thinking?](./2016.jpg)

# Fuck everything about 2016


text:
{% load sitetree %}

    {% for item in sitetree_items %}
    {% if item.has_children %}

        {{ item.title_resolved }}

        {% sitetree_children of item for menu template "base/dropdown-menu.html" %}

    {% else %}

        {{ item.title_resolved }}
    {% endif %}

    {% endfor %}


text:
using Xamarin.Forms;

namespace HydrantWiki.Controls
{
    public abstract class AbstractListView : ListView
    {
        public AbstractListView()
        {
            VerticalOptions = LayoutOptions.FillAndExpand;
            BackgroundColor = Color.Transparent;
            HasUnevenRows = false;
        }
    }
}


text:
<?php
namespace Application\Models\Domain;

class CrimeStatisticType
{
    public $id;
    public $name;
    public $abbreviation;
}
?>


text:
<?php

namespace ServiceGraph\Tests\Service;

use ServiceGraph\Action\Action;
use ServiceGraph\Service\Service;

class ServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Service
     */
    protected $service;

    public function setUp()
    {
        parent::setUp();
        $this->service = new Service;
    }

    public function tearDown()
    {
        parent::tearDown();
        unset($this->service);
    }

    /**
     * @param string $callbackName
     * @return PHPUnit_Framework_Mock_Object
     */
    protected function getMockAction($callbackName)
    {
        $mock = $this->getMockBuilder('ServiceGraph\Tests\Resources\FakeAction')
            ->setMethods(array(
                $callbackName,
            ))
            ->getMock();
        $mock->setCallbackName($callbackName);
        return $mock;
    }

    public function testHasAction()
    {
        $mockAction = $this->getMockAction('newInTown');
        $result = $this->service->hasAction('newInTown');
        $this->assertFalse($result);

        $this->service->register('hello', $mockAction);
        $result = $this->service->hasAction('hello');
        $this->assertTrue($result);
    }

    public function testRegister()
    {
        $mockAction = $this->getMockAction('doStuff');

        // Ensure we can assign an action to our service.
        $this->service->register('doStuff', $mockAction);
        $actionList = $this->service->getActionList();
        $this->assertSame($mockAction, end($actionList));
    }

    public function testRegisterThrowsExceptionIfAliasIsNotCallable()
    {
        $mockAction = $this->getMockAction('doStuff');

        $this->setExpectedException('InvalidArgumentException', 'Cannot register an Action without a useful name.');
        $this->service->register(909, $mockAction);
    }

    public function testRegisterThrowsExceptionIfCallbackIsNotCallable()
    {
        $mockAction = $this->getMockAction('doStuff');
        $mockAction->setCallbackName('theresNoWayThisWillWork');
        $this->setExpectedException('LogicException', 'Cannot register an Action without a valid callback');
        $this->service->register('doStuff', $mockAction);
    }

    public function testRegisterThrowsExceptionIfActionExists()
    {
        $mockAction = $this->getMockAction('doStuff');
        $this->service->register('doStuff', $mockAction);

        // Ensure the action can't be unexpectedly replaced.
        $this->setExpectedException('LogicException', 'Action "doStuff" is already registered!');
        $this->service->register('doStuff', $mockAction);
    }

    public function testCall()
    {
        /**
         * A fake callback to use.
         * We expect to get the two numbers added together.
         */
        $fakeCall = function ($arg1, $arg2) {
            return $arg1 + $arg2;
        };
        $arguments = array(
            1,
            2,
        );
        $mockAction = $this->getMockAction('addNumbers');
        $mockAction->expects($this->once())
            ->method('addNumbers')
            ->with($arguments[0], $arguments[1])
            ->will($this->returnCallback($fakeCall));
        $this->service->register('addNumbers', $mockAction);
        $result = $this->service->addNumbers($arguments[0], $arguments[1]);
        $this->assertSame(3, $result, 'Unexpected result returned from Service::fakeAction');
    }

    public function testCallThrowsException()
    {
        $this->setExpectedException('DomainException', 'Action "cantFindMe" not found on service "ServiceGraph\Service\Service"');
        $this->service->cantFindMe();
    }

    public function testRemove()
    {
        $mockAction = $this->getMockAction('helpMe');
        $this->service->register('helpMe', $mockAction);
        $this->service->remove('helpMe');
        $result = $this->service->hasAction('helpMe');
        $this->assertFalse($result, 'Service still has "helpMe" action.');
    }
}


text:
In `Go`, the length is also a part of array type. So the following code declares an array:

	var array [3]int
while "`var slice []int`" defines a slice. Because of this characteristic, arrays with the same array element type but different length can't assign values each other. I.E.:

	package main

	import "fmt"

	func main() {
		var a1 [2]int
		var a2 [3]int
		a2 = a1
		fmt.Println(a2)
	}
The compiler will complain:

	cannot use a1 (type [2]int) as type [3]int in assignment

Changing "`var a1 [2]int`" to "`var a1 [3]int`" will make it work.

Another caveat you should pay attention to is the following code declares an array, not a slice:

	array := [...]int {1, 2, 3}
You can verify it by the following code:

	package main

	import (
		"fmt"
		"reflect"
	)

	func main() {
		array := [...]int {1, 2, 3}
		slice := []int{1, 2, 3}
		fmt.Println(reflect.TypeOf(array), reflect.TypeOf(slice))
	}

The output is:

	[3]int []int

Additionally, since in `Go`, the function argument is passed by "value", so if you use an array as a function argument, the function just does the operations on the copy of the original copy. Check the following code:

	package main

	import (
		"fmt"
	)

	func changeArray(array [3]int) {
		for i, _ := range array {
			array[i] = 1
		}
		fmt.Printf("In changeArray function, array address is %p, value is %v\n", &array, array)
	}

	func main() {
		var array [3]int

		fmt.Printf("Original array address is %p, value is %v\n", &array, array)
		changeArray(array)
		fmt.Printf("Changed array address is %p, value is %v\n", &array, array)
	}

The output is:

	Original array address is 0xc082008680, value is [0 0 0]
	In changeArray function, array address is 0xc082008700, value is [1 1 1]
	Changed array address is 0xc082008680, value is [0 0 0]

From the log, you can see the array's address in `changeArray` function is not the same with array's address in `main` function, so the content of original array will definitely not be modified. Furthermore, if the array is very large, copying them when passing argument to function may generate more overhead than you want, you should know about it.


text:
<!--
    Copyright 2015 CBS Interactive Inc.

    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.

    CBS Interactive accepts contributions to software products and free
    and open-source projects owned, licensed, managed, or maintained by
    CBS Interactive submitted under the terms of the CBS Interactive
    Contribution License Agreement (the "Contribution Agreement"); you may
    not submit software to CBS Interactive for inclusion in a CBS
    Interactive product or project unless you agree to the terms of the
    CBS Interactive Contribution License Agreement or have executed a
    separate agreement with CBS Interactive governing the use of such
    submission. A copy of the Contribution Agreement should have been
    included with the software. You may also obtain a copy of the
    Contribution Agreement at
    http://www.cbsinteractive.com/cbs-interactive-software-grant-and-contribution-license-agreement/.
-->

<RumConf>

  <!--
      Lua chunks used to load external modules and to define global
      variables; executed right after the creation of each Lua VM; the
      "rum" module is not available to chunks at this stage. First,
      chunks in all <Script> sections are executed in order, and then
      chunks in all <ScriptFile> sections are executed in order.
    -->
  <Definitions>

    <Script>
      <![CDATA[
         -- define some global variables
         someglobal1 = 1
         someglobal2 = 2

         -- load bitlib module
         require("bit")
      ]]>
    </Script>

    <Script>
      <![CDATA[
         -- global variables defined in definition chunks already
         -- executed are available
         someglobal3 = someglobal1 + someglobal2

         -- load Lua chunk; entries for the path specified using the
         -- RumBaseDir httpd.conf directive are added to package.path
         -- and package.cpath, so relative paths can be used; note,
         -- the ".lua" or ".so" extensions must be left off
         require("conf/map-table-1")
      ]]>
    </Script>

    <!--
        Load a Lua chunk from a file; when relative paths are used,
        they are relative to the directory specified using the
        RumBaseDir httpd.conf directive.
      -->
    <ScriptFile>
      conf/map-table-2.lua
    </ScriptFile>

    <ScriptFile>
      conf/dump-request.lua
    </ScriptFile>

  </Definitions>

  <!--
      Lua chunks executed before each Lua action
    -->
  <CommonPreAction>

    <Script>
      <![CDATA[
        rum.core.log_info("BEG common-pre-action")

        -- shorthand
        r = rum.request
        puts = rum.core.puts

        rum.core.log_info("END common-pre-action")
      ]]>
    </Script>

    <ScriptFile>
      conf/common-pre-action.lua
    </ScriptFile>

  </CommonPreAction>

  <!--
      optional custom error handler; this is identical to the default
      error handler and is therefore unnecessary; only shown to serve
      as an example
  -->
  <ErrorHandler>
    <Script>
      <![CDATA[
         return debug.traceback(..., 2)
      ]]>
    </Script>
  </ErrorHandler>

  <Rules>

    <!--
        rule which sets the IP address of the remote client in the
        request from the X-X-FORWARDED-FOR header
      -->
    <Rule>
      <Actions>
        <Script>
          <![CDATA[
             local rum = rum
             local rum_core = rum.core
             rum_core.log_info("BEG deforward action")

             local request = rum.request
             local ip = request.headers_in:get("X-X-FORWARDED-FOR")
             if ip then
                request.connection.remote_ip = ip
                rum_core.log_info("deforwarded IP: " .. ip)
             end

             rum_core.log_info("END deforward action")
          ]]>
        </Script>
      </Actions>
    </Rule>

    <!--
        rule which demonstrates getting various info about the request
        and the matched conditions using the RUM API
      -->
    <Rule>
      <Conditions>
        <Path>
          <Pattern trailingSlashOptional="true">
            showme/**
          </Pattern>
          <RegEx>
            .*/(everything.*)$
          </RegEx>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          <![CDATA[
             rum.core.log_info("BEG showme action")

             -- set the content-type for this generated page
             rum.core.set_content_type("text/plain")

             -- be polite and say hello
             puts("hello world from RUM!!!")

             -- show the RUM state if the showstate query arg is present
             if rum.queryarg.get("showstate") then
                puts("\n\n" .. rum.core.state());
             end

             -- define function to print out the request's fields
             function rshow(f)
                puts("rum.request." .. f .. ": " .. tostring(r[f]))
             end

             -- define function to print out the request's functions
             function rfshow(f)
                puts("rum.request:" .. f .. "(): " .. tostring(r[f](r)))
             end

             -- define function to print out the connection's fields
             function cshow(f)
                puts("rum.request.connection." .. f .. ": " ..
                     tostring(r.connection[f]))
             end

             -- define function to print out the server's fields
             function sshow(f)
                puts("rum.request.server." .. f .. ": " ..
                     tostring(r.server[f]))
             end

             -- print some stuff from the request
             puts("\n\nrequest functions:")
             rfshow("is_internal_redirect")
             rfshow("is_subrequest")
             rfshow("is_initial_req")
             rfshow("get_server_name")
             rfshow("get_server_port")
             rfshow("http_scheme")

             puts("\n\nrequest fields:")
             rshow("the_request")
             rshow("protocol")
             rshow("hostname")
             rshow("method")
             rshow("unparsed_uri")
             rshow("uri")
             rshow("args")

             puts("\n\nconnection fields:")
             cshow("remote_ip")
             cshow("keepalives")

             puts("\n\nserver fields:")
             sshow("defn_name")
             sshow("defn_line_number")
             sshow("server_admin")
             sshow("server_hostname")
             sshow("loglevel")
             sshow("is_virtual")
             sshow("keep_alive")
             sshow("keep_alive_max")
             sshow("keep_alive_timeout")
             sshow("timeout")

             -- was there a trailing slash?
             if rum.path.trailing_slash() then
                 puts("\n\ntrailing slash is present")
             else
                 puts("\n\ntrailing slash is absent")
             end

             -- print out request headers
             puts("\n\nrequest headers:")
             keys = rum.request.headers_in:keys()
             for i, v in ipairs(keys) do
                puts("  " .. v .. ":")
                a = rum.request.headers_in:mget(v)
                for j, v2 in ipairs(a) do
                   puts("    " .. tostring(v2))
                end
             end

             -- print out raw request headers
             puts("\n\nraw request headers:")
             keys = rum.request.headers_in:keys()
             for i, v in ipairs(keys) do
                puts("  " .. v .. ":")
                a = rum.request.headers_in:raw_mget(v)
                for j, v2 in ipairs(a) do
                   puts("    " .. tostring(v2))
                end
             end

             -- print all cookie names and values
             puts("\n\ncookie names and values:")
             cookies = rum.request.headers_in:get("Cookie")
             if cookies then
                for k, v in string.gmatch(cookies, "([^;, =]+)=([^;, =]+)") do
                   puts("  " .. k .. ": " .. v)
                end
             else
                puts("sorry, no cookies for you")
             end

             -- print out query args
             puts("\n\nquery args:")
             qa = rum.queryarg
             keys = qa.keys()
             for i, v in ipairs(keys) do
                s = ""
                a = qa.mget(v)
                for j, v2 in ipairs(a) do
                   if string.len(s) > 0 then
                      s = s .. ", "
                   end
                   s = s .. tostring(v2)
                end
                puts("  " .. tostring(v) .. " = " .. s)
             end

             -- print out raw (undecoded) query args
             qa = rum.queryarg
             puts("\n\nraw (undecoded) query args:")
             keys = qa.keys()
             for i, v in ipairs(keys) do
                s = ""
                a = qa.raw_mget(v)
                for j, v2 in ipairs(a) do
                   if string.len(s) > 0 then
                      s = s .. ", "
                   end
                   s = s .. tostring(v2)
                end
                puts("  " .. tostring(v) .. " = " .. s)
             end

             -- print out path tokens
             puts("\n\npath tokens:")
             for i = 1, #rum.path.tokens do
                puts("rum.path.tokens[" .. i .. "]: " ..
                     rum.path.tokens[i])
             end

             -- print out match captures of first Path condition
             puts("\n\nfirst path captures:")
             for i = 1, #rum.path.captures do
                puts("rum.path.captures[" .. i .. "]: " ..
                     rum.path.captures[i])
             end

             -- print out match captures of all Path conditions
             puts("\n\nall path captures:")
             for i = 1, #rum.path.mcaptures do
                puts("  path condition " .. i .. ":")
                caps = rum.path.mcaptures[i]
                for j = 1, #caps do
                   puts("    " .. caps[j])
                end
             end

             -- print out subrequest call chain
             puts("\n\nsubrequest call chain:")
             r2 = rum.request
             repeat
                puts("  " .. r2.uri)
                r2 = r2.main
             until not r2

             -- print out internal redirect call chain
             puts("\n\ninternal redirect call chain:")
             r2 = rum.request
             repeat
                puts("  " .. r2.uri)
                r2 = r2.prev
             until not r2

             -- print out some global variables defined in
             -- the <Definitions> section
             puts("\n\nsome global variables:")
             puts("  someglobal1: " .. tostring(someglobal1))
             puts("  someglobal2: " .. tostring(someglobal2))
             puts("  someglobal3: " .. tostring(someglobal3))
             if map1 then
                puts("  map1[3]: " .. tostring(map1[3]))
             else
                puts("  map1: nil")
             end
             if map2 then
                puts("  map2.scorpion: " .. tostring(map2.scorpion))
             else
                puts("  map2: nil")
             end

             -- have some interactive RUM fun when running with rumtest
             rum.core.interactive_lua()

             rum.core.log_info("END showme action")
          ]]>
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /file5
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          <![CDATA[
             rum.core.log_info("BEG file5 action")

             -- set a cookie
             if rum.queryarg.get("cookie_me") then
                rum.request.headers_out:add("Set-Cookie", "rum_last_access=" ..
                                            tostring(os.time()))
             end

             rum.core.log_info("END file5 action")
          ]]>
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /bikes/tricycles
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <InternalRedirect>
          /file1
        </InternalRedirect>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /bikes/mopeds
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <ExternalRedirect>
          /file2
        </ExternalRedirect>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /*/scooters
          </Pattern>
        </Path>
        <QueryArg>
          <Name>
            color
          </Name>
          <NameVal>
            shape=square
          </NameVal>
        </QueryArg>
      </Conditions>
      <Actions>
        <Script>
          new_uri = "/file7?type=" .. rum.path.captures[1]
          if rum.queryarg.get("color") == "red" then
             -- default is 301 (HTTP_MOVED_PERMANENTLY)
             rum.core.external_redirect(new_uri)
          else
             -- explicitly specify 302 (HTTP_MOVED_TEMPORARILY)
             rum.core.external_redirect(new_uri, 302)
          end
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /file3
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          -- variables defined in an action's script element are not
          -- visible in other script elements
          mycolor = "purple"
        </Script>
        <Script>
          -- here the mycolor variable starts out as nil
          if not mycolor then
             mycolor = "green"
          end
          rum.request.headers_out:add("X-Color", mycolor)
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <RegEx>
            ^/file[0-9]$
          </RegEx>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          -- set some custom header
          r.headers_out:add("X-Temperature", "cold")
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <RegEx>
            (file[7-9])$
          </RegEx>
          <Pattern>
            /(AAA|Aaa|aaa)/*
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          new_uri = "/" .. rum.path.captures[1]
          rum.core.internal_redirect(new_uri)
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /proxyme/*
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          url = "http://factory-" .. rum.path.tokens[2] .. ".cnet.com/"
          path = rum.queryarg.get("path")
          if path then
             url = url .. path
          end
          rum.core.proxy(url)
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /file4
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          if rum.queryarg.get("last") then
             rum.core.last_action = true
          end
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /file4
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          if not rum.request.notes:get("been_here") then
             rum.request.notes:set("been_here", 1)
             rum.core.relookup = true
          else
             rum.core.external_redirect("/file6")
          end
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /groundhog/day
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <ScriptFile>
          conf/groundhog.lua
        </ScriptFile>
        <Script>
          <![CDATA[
             rum.core.log_info("BEG groundhog/day action")

             rum.core.log_info("END groundhog/day action")
          ]]>
        </Script>
      </Actions>
    </Rule>

    <Rule>
      <Conditions>
        <Path>
          <Pattern>
            /dump-request
          </Pattern>
        </Path>
      </Conditions>
      <Actions>
        <Script>
          <![CDATA[
             dump_request_rec(rum.request, "rum.request", ": ", "[", "]")
          ]]>
        </Script>
      </Actions>
    </Rule>

  </Rules>

</RumConf>


text:
<!doctype html>

    <title>Code coverage report for All files</title>
    <meta charset="utf-8">

    <link rel="stylesheet" href="prettify.css">

Code coverage report for All files

        Statements: 77.5% (658 / 849)

        Branches: 65.8% (329 / 500)

        Functions: 76.43% (107 / 140)

        Lines: 77.96% (651 / 835)

   File

   Statements

   Branches

   Functions

   Lines

	lib/

	59.29%
	(67 / 113)
	36.54%
	(19 / 52)
	83.33%
	(15 / 18)
	59.46%
	(66 / 111)

	lib/cli/

	89.47%
	(85 / 95)
	83.84%
	(83 / 99)
	100%
	(6 / 6)
	89.13%
	(82 / 92)

	lib/config/

	80.98%
	(166 / 205)
	69.03%
	(78 / 113)
	76.47%
	(26 / 34)
	81.19%
	(164 / 202)

	lib/help/

	91.67%
	(11 / 12)
	75%
	(3 / 4)
	100%
	(1 / 1)
	91.67%
	(11 / 12)

	lib/monitor/

	71.2%
	(178 / 250)
	55.63%
	(79 / 142)
	64.58%
	(31 / 48)
	72.65%
	(178 / 245)

	lib/rules/

	88.89%
	(48 / 54)
	76.92%
	(20 / 26)
	100%
	(7 / 7)
	88.89%
	(48 / 54)

	lib/utils/

	85.83%
	(103 / 120)
	73.44%
	(47 / 64)
	80.77%
	(21 / 26)
	85.71%
	(102 / 119)

Generated by istanbul at Sun Jan 05 2014 01:50:14 GMT+0000 (GMT)


text:
"use strict";

var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

//----------------------------------------------------------------------
//
// This source file is part of the Folktale project.
//
// Licensed under MIT. See LICENCE for full licence information.
// See CONTRIBUTORS for the list of contributors to the project.
//
//----------------------------------------------------------------------

var define = Object.defineProperty;

/*~
 * stability: stable
 * authors:
 *   - Quildreen Motta
 *
 * complexity : O(n), n is the length of the array
 * type: |
 *   (Array (String or Symbol, 'a)) => Object 'a
 */
var fromPairs = function fromPairs(pairs) {
  return pairs.reduce(function (r, _ref) {
    var _ref2 = _slicedToArray(_ref, 2),
        k = _ref2[0],
        v = _ref2[1];

    return define(r, k, { value: v,
      writable: true,
      enumerable: true,
      configurable: true
    });
  }, {});
};

// --[ Exports ]-------------------------------------------------------
module.exports = fromPairs;


text: module.exports = new EventSource('/api/builds/stream')


text:
package com.mbui.sdk.feature.pullrefresh.builders;

import android.view.View;

import com.mbui.sdk.feature.pullrefresh.judge.ViewBorderJudge;

/**
 * Created by chenwei on 15/1/14.
 * 需要实现下拉上拉的View需要实现这个接口,由RefreshController统一实现刷新的过程
 */
public interface HeaderFooterBuilder extends ViewBorderJudge {
    public void addHeaderView(View view);

    public void addFooterView(View view);

    public boolean removeHeaderView(View view);

    public boolean removeFooterView(View view);

    public int getHeaderViewsCount();

    public int getFooterViewsCount();

    public View getFirstHeader();

    public View getLastFooter();
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>Non-parser-inserted style elements should still work</title>
<link rel="author" title="Domenic Denicola" href="mailto:d@domenic.me">
<link rel="help" href="https://html.spec.whatwg.org/multipage/semantics.html#update-a-style-block">
<link rel="help" href="https://drafts.csswg.org/cssom/#the-linkstyle-interface">

Test