text:
namespace blink {

const PaintArtifact& PaintController::paintArtifact() const
{
    DCHECK(m_newDisplayItemList.isEmpty());
    DCHECK(m_newPaintChunks.isInInitialState());
    return m_currentPaintArtifact;
}

bool PaintController::useCachedDrawingIfPossible(const DisplayItemClient& client, DisplayItem::Type type)
{
    DCHECK(DisplayItem::isDrawingType(type));

    if (displayItemConstructionIsDisabled())
        return false;

    if (!clientCacheIsValid(client))
        return false;

#if DCHECK_IS_ON()
    if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled() && isCheckingUnderInvalidation()) {
        // We are checking under-invalidation of a subsequence enclosing this display item.
        // Let the client continue to actually paint the display item.
        return false;
    }
#endif

    size_t cachedItem = findCachedItem(DisplayItem::Id(client, type));
    if (cachedItem == kNotFound) {
        NOTREACHED();
        return false;
    }

    ++m_numCachedNewItems;
    ensureNewDisplayItemListInitialCapacity();
    if (!DCHECK_IS_ON() || !RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled())
        processNewItem(m_newDisplayItemList.appendByMoving(m_currentPaintArtifact.getDisplayItemList()[cachedItem]));

    m_nextItemToMatch = cachedItem + 1;
    // Items before m_nextItemToMatch have been copied so we don't need to index them.
    if (m_nextItemToMatch > m_nextItemToIndex)
        m_nextItemToIndex = m_nextItemToMatch;

#if DCHECK_IS_ON()
    if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) {
        if (!isCheckingUnderInvalidation()) {
            m_underInvalidationCheckingBegin = cachedItem;
            m_underInvalidationCheckingEnd = cachedItem + 1;
            m_underInvalidationMessagePrefix = "";
        }
        // Return false to let the painter actually paint, and we will check if the new painting
        // is the same as the cached.
        return false;
    }
#endif

    return true;
}

bool PaintController::useCachedSubsequenceIfPossible(const DisplayItemClient& client)
{
    if (displayItemConstructionIsDisabled() || subsequenceCachingIsDisabled())
        return false;

    if (!clientCacheIsValid(client))
        return false;

#if DCHECK_IS_ON()
    if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled() && isCheckingUnderInvalidation()) {
        // We are checking under-invalidation of an ancestor subsequence enclosing this one.
        // The ancestor subsequence is supposed to have already "copied", so we should let the
        // client continue to actually paint the descendant subsequences without "copying".
        return false;
    }
#endif

    size_t cachedItem = findCachedItem(DisplayItem::Id(client, DisplayItem::Subsequence));
    if (cachedItem == kNotFound) {
        NOTREACHED();
        return false;
    }

    // |cachedItem| will point to the first item after the subsequence or end of the current list.
    ensureNewDisplayItemListInitialCapacity();
    copyCachedSubsequence(cachedItem);

    m_nextItemToMatch = cachedItem;
    // Items before |cachedItem| have been copied so we don't need to index them.
    if (cachedItem > m_nextItemToIndex)
        m_nextItemToIndex = cachedItem;

#if DCHECK_IS_ON()
    if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) {
        // Return false to let the painter actually paint, and we will check if the new painting
        // is the same as the cached.
        return false;
    }
#endif

    return true;
}

bool PaintController::lastDisplayItemIsNoopBegin() const
{
    if (m_newDisplayItemList.isEmpty())
        return false;

    const auto& lastDisplayItem = m_newDisplayItemList.last();
    return lastDisplayItem.isBegin() && !lastDisplayItem.drawsContent();
}

void PaintController::removeLastDisplayItem()
{
    if (m_newDisplayItemList.isEmpty())
        return;

#if DCHECK_IS_ON()
    // Also remove the index pointing to the removed display item.
    DisplayItemIndicesByClientMap::iterator it = m_newDisplayItemIndicesByClient.find(&m_newDisplayItemList.last().client());
    if (it != m_newDisplayItemIndicesByClient.end()) {
        Vector<size_t>& indices = it->value;
        if (!indices.isEmpty() && indices.last() == (m_newDisplayItemList.size() - 1))
            indices.removeLast();
    }

    if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled() && isCheckingUnderInvalidation()) {
        if (m_skippedProbableUnderInvalidationCount) {
            --m_skippedProbableUnderInvalidationCount;
        } else {
            DCHECK(m_underInvalidationCheckingBegin);
            --m_underInvalidationCheckingBegin;
        }
    }
#endif
    m_newDisplayItemList.removeLast();

    if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
        m_newPaintChunks.decrementDisplayItemIndex();
}

const DisplayItem* PaintController::lastDisplayItem(unsigned offset)
{
    if (offset < m_newDisplayItemList.size())
        return &m_newDisplayItemList[m_newDisplayItemList.size() - offset - 1];
    return nullptr;
}

void PaintController::processNewItem(DisplayItem& displayItem)
{
    DCHECK(!m_constructionDisabled);

#if CHECK_DISPLAY_ITEM_CLIENT_ALIVENESS
    if (!isSkippingCache()) {
        if (displayItem.isCacheable()) {
            // Mark the client shouldKeepAlive under this PaintController.
            // The status will end after the new display items are committed.
            displayItem.client().beginShouldKeepAlive(this);

            if (!m_currentSubsequenceClients.isEmpty()) {
                // Mark the client shouldKeepAlive under the current subsequence.
                // The status will end when the subsequence owner is invalidated or deleted.
                displayItem.client().beginShouldKeepAlive(m_currentSubsequenceClients.last());
            }
        }

        if (displayItem.getType() == DisplayItem::Subsequence) {
            m_currentSubsequenceClients.append(&displayItem.client());
        } else if (displayItem.getType() == DisplayItem::EndSubsequence) {
            CHECK(m_currentSubsequenceClients.last() == &displayItem.client());
            m_currentSubsequenceClients.removeLast();
        }
    }
#endif

    if (isSkippingCache())
        displayItem.setSkippedCache();

#if DCHECK_IS_ON()
    // Verify noop begin/end pairs have been removed.
    if (m_newDisplayItemList.size() >= 2 && displayItem.isEnd()) {
        const auto& beginDisplayItem = m_newDisplayItemList[m_newDisplayItemList.size() - 2];
        if (beginDisplayItem.isBegin() && beginDisplayItem.getType() != DisplayItem::Subsequence && !beginDisplayItem.drawsContent())
            DCHECK(!displayItem.isEndAndPairedWith(beginDisplayItem.getType()));
    }

    size_t index = findMatchingItemFromIndex(displayItem.getId(), m_newDisplayItemIndicesByClient, m_newDisplayItemList);
    if (index != kNotFound) {
#ifndef NDEBUG
        showDebugData();
        WTFLogAlways("DisplayItem %s has duplicated id with previous %s (index=%d)\n",
            displayItem.asDebugString().utf8().data(), m_newDisplayItemList[index].asDebugString().utf8().data(), static_cast<int>(index));
#endif
        NOTREACHED();
    }
    addItemToIndexIfNeeded(displayItem, m_newDisplayItemList.size() - 1, m_newDisplayItemIndicesByClient);

    if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled())
        checkUnderInvalidation();
#endif // DCHECK_IS_ON()

    if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
        m_newPaintChunks.incrementDisplayItemIndex(displayItem);
}

void PaintController::updateCurrentPaintChunkProperties(const PaintChunk::Id* id, const PaintChunkProperties& newProperties)
{
    m_newPaintChunks.updateCurrentPaintChunkProperties(id, newProperties);
}

const PaintChunkProperties& PaintController::currentPaintChunkProperties() const
{
    return m_newPaintChunks.currentPaintChunkProperties();
}

void PaintController::invalidateAll()
{
    // Can only be called during layout/paintInvalidation, not during painting.
    DCHECK(m_newDisplayItemList.isEmpty());
    m_currentPaintArtifact.reset();
    m_currentCacheGeneration.invalidate();
}

bool PaintController::clientCacheIsValid(const DisplayItemClient& client) const
{
#if CHECK_DISPLAY_ITEM_CLIENT_ALIVENESS
    CHECK(client.isAlive());
#endif
    if (isSkippingCache())
        return false;
    return client.displayItemsAreCached(m_currentCacheGeneration);
}

size_t PaintController::findMatchingItemFromIndex(const DisplayItem::Id& id, const DisplayItemIndicesByClientMap& displayItemIndicesByClient, const DisplayItemList& list)
{
    DisplayItemIndicesByClientMap::const_iterator it = displayItemIndicesByClient.find(&id.client);
    if (it == displayItemIndicesByClient.end())
        return kNotFound;

    const Vector<size_t>& indices = it->value;
    for (size_t index : indices) {
        const DisplayItem& existingItem = list[index];
        DCHECK(!existingItem.hasValidClient() || existingItem.client() == id.client);
        if (id == existingItem.getId())
            return index;
    }

    return kNotFound;
}

void PaintController::addItemToIndexIfNeeded(const DisplayItem& displayItem, size_t index, DisplayItemIndicesByClientMap& displayItemIndicesByClient)
{
    if (!displayItem.isCacheable())
        return;

    DisplayItemIndicesByClientMap::iterator it = displayItemIndicesByClient.find(&displayItem.client());
    Vector<size_t>& indices = it == displayItemIndicesByClient.end() ?
        displayItemIndicesByClient.add(&displayItem.client(), Vector<size_t>()).storedValue->value : it->value;
    indices.append(index);
}

size_t PaintController::findCachedItem(const DisplayItem::Id& id)
{
    DCHECK(clientCacheIsValid(id.client));

    // Try to find the item sequentially first. This is fast if the current list and the new list are in
    // the same order around the new item. If found, we don't need to update and lookup the index.
    for (size_t i = m_nextItemToMatch; i < m_currentPaintArtifact.getDisplayItemList().size(); ++i) {
        // We encounter an item that has already been copied which indicates we can't do sequential matching.
        const DisplayItem& item = m_currentPaintArtifact.getDisplayItemList()[i];
        if (!item.hasValidClient())
            break;
        if (id == item.getId()) {
#if DCHECK_IS_ON()
            ++m_numSequentialMatches;
#endif
            return i;
        }
        // We encounter a different cacheable item which also indicates we can't do sequential matching.
        if (item.isCacheable())
            break;
    }

    size_t foundIndex = findMatchingItemFromIndex(id, m_outOfOrderItemIndices, m_currentPaintArtifact.getDisplayItemList());
    if (foundIndex != kNotFound) {
#if DCHECK_IS_ON()
        ++m_numOutOfOrderMatches;
#endif
        return foundIndex;
    }

    return findOutOfOrderCachedItemForward(id);
}

// Find forward for the item and index all skipped indexable items.
size_t PaintController::findOutOfOrderCachedItemForward(const DisplayItem::Id& id)
{
    for (size_t i = m_nextItemToIndex; i < m_currentPaintArtifact.getDisplayItemList().size(); ++i) {
        const DisplayItem& item = m_currentPaintArtifact.getDisplayItemList()[i];
        DCHECK(item.hasValidClient());
        if (id == item.getId()) {
#if DCHECK_IS_ON()
            ++m_numSequentialMatches;
#endif
            return i;
        }
        if (item.isCacheable()) {
#if DCHECK_IS_ON()
            ++m_numIndexedItems;
#endif
            addItemToIndexIfNeeded(item, i, m_outOfOrderItemIndices);
        }
    }

#ifndef NDEBUG
    showDebugData();
    LOG(ERROR) << id.client.debugName() << ":" << DisplayItem::typeAsDebugString(id.type);
#endif
    NOTREACHED() << "Can't find cached display item";
    // We did not find the cached display item. This should be impossible, but may occur if there is a bug
    // in the system, such as under-invalidation, incorrect cache checking or duplicate display ids.
    // In this case, the caller should fall back to repaint the display item.
    return kNotFound;
}

// Copies a cached subsequence from current list to the new list. On return,
// |cachedItemIndex| points to the item after the EndSubsequence item of the subsequence.
// When paintUnderInvaldiationCheckingEnabled() we'll not actually copy the subsequence,
// but mark the begin and end of the subsequence for under-invalidation checking.
void PaintController::copyCachedSubsequence(size_t& cachedItemIndex)
{
    DisplayItem* cachedItem = &m_currentPaintArtifact.getDisplayItemList()[cachedItemIndex];
#if DCHECK_IS_ON()
    DCHECK(cachedItem->getType() == DisplayItem::Subsequence);
    if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) {
        DCHECK(!isCheckingUnderInvalidation());
        m_underInvalidationCheckingBegin = cachedItemIndex;
        m_underInvalidationMessagePrefix = "(In cached subsequence of " + cachedItem->client().debugName() + ")";
    }
#endif

    DisplayItem::Id endSubsequenceId(cachedItem->client(), DisplayItem::EndSubsequence);
    Vector<PaintChunk>::const_iterator cachedChunk;
    if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
        cachedChunk = m_currentPaintArtifact.findChunkByDisplayItemIndex(cachedItemIndex);
        updateCurrentPaintChunkProperties(cachedChunk->id ? &*cachedChunk->id : nullptr, cachedChunk->properties);
    } else {
        // This is to avoid compilation error about uninitialized variable on Windows.
        cachedChunk = m_currentPaintArtifact.paintChunks().begin();
    }

    while (true) {
        DCHECK(cachedItem->hasValidClient());
#if CHECK_DISPLAY_ITEM_CLIENT_ALIVENESS
        CHECK(cachedItem->client().isAlive());
#endif
        ++m_numCachedNewItems;
        bool metEndSubsequence = cachedItem->getId() == endSubsequenceId;
        if (!DCHECK_IS_ON() || !RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) {
            if (RuntimeEnabledFeatures::slimmingPaintV2Enabled() && cachedItemIndex == cachedChunk->endIndex) {
                ++cachedChunk;
                updateCurrentPaintChunkProperties(cachedChunk->id ? &*cachedChunk->id : nullptr, cachedChunk->properties);
            }
            processNewItem(m_newDisplayItemList.appendByMoving(*cachedItem));
            if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
                DCHECK((!m_newPaintChunks.lastChunk().id && !cachedChunk->id) || m_newPaintChunks.lastChunk().matches(*cachedChunk));
        }

        ++cachedItemIndex;
        if (metEndSubsequence)
            break;

        // We should always be able to find the EndSubsequence display item.
        DCHECK(cachedItemIndex < m_currentPaintArtifact.getDisplayItemList().size());
        cachedItem = &m_currentPaintArtifact.getDisplayItemList()[cachedItemIndex];
    }

#if DCHECK_IS_ON()
    if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) {
        m_underInvalidationCheckingEnd = cachedItemIndex;
        DCHECK(isCheckingUnderInvalidation());
    }
#endif
}

static IntRect visualRectForDisplayItem(const DisplayItem& displayItem, const LayoutSize& offsetFromLayoutObject)
{
    LayoutRect visualRect = displayItem.client().visualRect();
    visualRect.move(-offsetFromLayoutObject);
    return enclosingIntRect(visualRect);
}

void PaintController::resetCurrentListIndices()
{
    m_nextItemToMatch = 0;
    m_nextItemToIndex = 0;
#if DCHECK_IS_ON()
    m_underInvalidationCheckingBegin = 0;
    m_underInvalidationCheckingEnd = 0;
    m_skippedProbableUnderInvalidationCount = 0;
#endif
}

void PaintController::commitNewDisplayItems(const LayoutSize& offsetFromLayoutObject)
{
    TRACE_EVENT2("blink,benchmark", "PaintController::commitNewDisplayItems",
        "current_display_list_size", (int)m_currentPaintArtifact.getDisplayItemList().size(),
        "num_non_cached_new_items", (int)m_newDisplayItemList.size() - m_numCachedNewItems);
    m_numCachedNewItems = 0;

    // These data structures are used during painting only.
    DCHECK(!isSkippingCache());
#if DCHECK_IS_ON()
    m_newDisplayItemIndicesByClient.clear();
#endif

    SkPictureGpuAnalyzer gpuAnalyzer;

    m_currentCacheGeneration = DisplayItemClient::CacheGenerationOrInvalidationReason::next();
    Vector<const DisplayItemClient*> skippedCacheClients;
    for (const auto& item : m_newDisplayItemList) {
        // No reason to continue the analysis once we have a veto.
        if (gpuAnalyzer.suitableForGpuRasterization())
            item.analyzeForGpuRasterization(gpuAnalyzer);

        // TODO(wkorman): Only compute and append visual rect for drawings.
        m_newDisplayItemList.appendVisualRect(visualRectForDisplayItem(item, offsetFromLayoutObject));

        if (item.isCacheable()) {
            item.client().setDisplayItemsCached(m_currentCacheGeneration);
        } else {
            if (item.client().isJustCreated())
                item.client().clearIsJustCreated();
            if (item.skippedCache())
                skippedCacheClients.append(&item.client());
        }
    }

    for (auto* client : skippedCacheClients)
        client->setDisplayItemsUncached();

    // The new list will not be appended to again so we can release unused memory.
    m_newDisplayItemList.shrinkToFit();
    m_currentPaintArtifact = PaintArtifact(std::move(m_newDisplayItemList), m_newPaintChunks.releasePaintChunks(), gpuAnalyzer.suitableForGpuRasterization());
    resetCurrentListIndices();
    m_outOfOrderItemIndices.clear();

    if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
        for (const auto& chunk : m_currentPaintArtifact.paintChunks()) {
            if (chunk.id && chunk.id->client.isJustCreated())
                chunk.id->client.clearIsJustCreated();
        }
    }

    // We'll allocate the initial buffer when we start the next paint.
    m_newDisplayItemList = DisplayItemList(0);

#if CHECK_DISPLAY_ITEM_CLIENT_ALIVENESS
    CHECK(m_currentSubsequenceClients.isEmpty());
    DisplayItemClient::endShouldKeepAliveAllClients(this);
#endif

#if DCHECK_IS_ON()
    m_numSequentialMatches = 0;
    m_numOutOfOrderMatches = 0;
    m_numIndexedItems = 0;
#endif
}

size_t PaintController::approximateUnsharedMemoryUsage() const
{
    size_t memoryUsage = sizeof(*this);

    // Memory outside this class due to m_currentPaintArtifact.
    memoryUsage += m_currentPaintArtifact.approximateUnsharedMemoryUsage() - sizeof(m_currentPaintArtifact);

    // TODO(jbroman): If display items begin to have significant external memory
    // usage that's not shared with the embedder, we should account for it here.
    //
    // External objects, shared with the embedder, such as SkPicture, should be
    // excluded to avoid double counting. It is the embedder's responsibility to
    // count such objects.
    //
    // At time of writing, the only known case of unshared external memory was
    // the rounded clips vector in ClipDisplayItem, which is not expected to
    // contribute significantly to memory usage.

    // Memory outside this class due to m_newDisplayItemList.
    DCHECK(m_newDisplayItemList.isEmpty());
    memoryUsage += m_newDisplayItemList.memoryUsageInBytes();

    return memoryUsage;
}

void PaintController::appendDebugDrawingAfterCommit(const DisplayItemClient& displayItemClient, PassRefPtr<SkPicture> picture, const LayoutSize& offsetFromLayoutObject)
{
    DCHECK(m_newDisplayItemList.isEmpty());
    DrawingDisplayItem& displayItem = m_currentPaintArtifact.getDisplayItemList().allocateAndConstruct<DrawingDisplayItem>(displayItemClient, DisplayItem::DebugDrawing, picture);
    displayItem.setSkippedCache();
    // TODO(wkorman): Only compute and append visual rect for drawings.
    m_currentPaintArtifact.getDisplayItemList().appendVisualRect(visualRectForDisplayItem(displayItem, offsetFromLayoutObject));
}

#if DCHECK_IS_ON()

void PaintController::showUnderInvalidationError(const char* reason, const DisplayItem& newItem, const DisplayItem* oldItem) const
{
    LOG(ERROR) << m_underInvalidationMessagePrefix << " " << reason;
#ifndef NDEBUG
    LOG(ERROR) << "New display item: " << newItem.asDebugString();
    LOG(ERROR) << "Old display item: " << (oldItem ? oldItem->asDebugString() : "None");
#else
    LOG(ERROR) << "Run debug build to get more details.";
#endif
    LOG(ERROR) << "See http://crbug.com/619103.";

#ifndef NDEBUG
    const SkPicture* newPicture = newItem.isDrawing() ? static_cast<const DrawingDisplayItem&>(newItem).picture() : nullptr;
    const SkPicture* oldPicture = oldItem && oldItem->isDrawing() ? static_cast<const DrawingDisplayItem*>(oldItem)->picture() : nullptr;
    LOG(INFO) << "new picture:\n" << (newPicture ? pictureAsDebugString(newPicture) : "None");
    LOG(INFO) << "old picture:\n" << (oldPicture ? pictureAsDebugString(oldPicture) : "None");

    showDebugData();
#endif // NDEBUG
}

void PaintController::checkUnderInvalidation()
{
    DCHECK(RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled());

    if (!isCheckingUnderInvalidation())
        return;

    const DisplayItem& newItem = m_newDisplayItemList.last();
    size_t oldItemIndex = m_underInvalidationCheckingBegin + m_skippedProbableUnderInvalidationCount;
    const DisplayItem* oldItem = oldItemIndex < m_currentPaintArtifact.getDisplayItemList().size() ? &m_currentPaintArtifact.getDisplayItemList()[oldItemIndex] : nullptr;

    bool oldAndNewEqual = oldItem && newItem.equals(*oldItem);
    if (!oldAndNewEqual) {
        if (newItem.isBegin()) {
            // Temporarily skip mismatching begin display item which may be removed when we remove a no-op pair.
            ++m_skippedProbableUnderInvalidationCount;
            return;
        }
        if (newItem.isDrawing() && m_skippedProbableUnderInvalidationCount == 1) {
            DCHECK_GE(m_newDisplayItemList.size(), 2u);
            if (m_newDisplayItemList[m_newDisplayItemList.size() - 2].getType() == DisplayItem::BeginCompositing) {
                // This might be a drawing item between a pair of begin/end compositing display items that will be folded
                // into a single drawing display item.
                ++m_skippedProbableUnderInvalidationCount;
                return;
            }
        }
    }

    if (m_skippedProbableUnderInvalidationCount || !oldAndNewEqual) {
        // If we ever skipped reporting any under-invalidations, report the earliest one.
        showUnderInvalidationError("under-invalidation: display item changed",
            m_newDisplayItemList[m_newDisplayItemList.size() - m_skippedProbableUnderInvalidationCount - 1],
            &m_currentPaintArtifact.getDisplayItemList()[m_underInvalidationCheckingBegin]);
        NOTREACHED();
    }

    ++m_underInvalidationCheckingBegin;
}

#endif // DCHECK_IS_ON()

String PaintController::displayItemListAsDebugString(const DisplayItemList& list) const
{
    StringBuilder stringBuilder;
    size_t i = 0;
    for (auto it = list.begin(); it != list.end(); ++it, ++i) {
        const DisplayItem& displayItem = *it;
        if (i)
            stringBuilder.append(",\n");
        stringBuilder.append(String::format("{index: %d, ", (int)i));
#ifndef NDEBUG
        displayItem.dumpPropertiesAsDebugString(stringBuilder);
#else
        stringBuilder.append(String::format("clientDebugName: %s", displayItem.client().debugName().ascii().data()));
#endif
        if (displayItem.hasValidClient()) {
            stringBuilder.append(", cacheIsValid: ");
            stringBuilder.append(clientCacheIsValid(displayItem.client()) ? "true" : "false");
        }
        if (list.hasVisualRect(i)) {
            IntRect visualRect = list.visualRect(i);
            stringBuilder.append(String::format(", visualRect: [%d,%d %dx%d]",
                visualRect.x(), visualRect.y(),
                visualRect.width(), visualRect.height()));
        }
        stringBuilder.append('}');
    }
    return stringBuilder.toString();
}

void PaintController::showDebugData() const
{
    WTFLogAlways("current display item list: [%s]\n", displayItemListAsDebugString(m_currentPaintArtifact.getDisplayItemList()).utf8().data());
    WTFLogAlways("new display item list: [%s]\n", displayItemListAsDebugString(m_newDisplayItemList).utf8().data());
}

} // namespace blink


text:
package test;

import com.smallchill.api.common.exception.*;
import com.smallchill.web.model.UserApproval;
import com.smallchill.web.service.UserApprovalService;
import com.smallchill.web.service.impl.BothUserHasApprovalException;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 用户审核
 * Created by yesong on 2016/10/31 0031.
 */
public class UserApprovalTest extends BaseJunit4Test{

    @Autowired
    private UserApprovalService userApprovalService;

    /**
     * 结识申请
     */
    @Test
    public void testUseroneway() {
        UserApproval ua = new UserApproval();
        ua.setFromUserId(20);
        ua.setToUserId(21);
        ua.setType(3);
        ua.setValidateInfo("申请加为好友");
        try {
            userApprovalService.toUserOneWay(ua,"21");
        } catch (UserHasApprovalException e) {
            e.printStackTrace();
        } catch (UsernotFriendException e) {
            e.printStackTrace();
        } catch (BothUserHasApprovalException e) {
            e.printStackTrace();
        } catch (UserHasFriendException e) {
            e.printStackTrace();
        } catch (UserInOthersBlankException e) {
            e.printStackTrace();
        } catch (UserInMyBlankException e) {
            e.printStackTrace();
        }
    }

    /**
     * 审核申请
     */
    @Test
    public void testUserApproval() {
        // 同意
        UserApproval ua = new UserApproval();
        ua.setFromUserId(6);
        ua.setToUserId(5);
        ua.setStatus(1);
//        userApprovalService.userApprovalAgree(ua);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\PostOrder\Types;

/**
 *
 * @property string $id
 * @property string $severity
 */
class EligibilityResponseError extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'id' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'id'
        ],
        'severity' => [
            'type' => 'string',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'severity'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
This repository contains some modules and scripts for CMake that I use in my projects. It can be a git submodule in a cmake folder for your projects.

*In your project root :*
```Shell
git submodule add https://github.com/ragotpaul/cmake-modules.git cmake/modules
```

*In your `CMakeLists.txt` :*
```CMake
set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules")
include(<module_name>)
```

## GitSubmodules

This module allow to add properly your third party dependencies in your project. If they're in a folder `lib` as a git submodule for example, you just need to set a new CMake variable `GIT_SUBMODULES` who list these folders and call `add_submodules(${GIT_SUBMODULES})`

*In your `CMakeLists.txt` :*
```CMake
include(GitSubmodules)
set(GIT_SUBMODULES
        lib/submodule1
        lib/submodule2)
add_submodules("${GIT_SUBMODULES}")
```

## OverrideOptions

This module allow to override options in a subdirectory for example.

*In your `CMakeLists.txt` :*
```CMake
include(OverrideOptions)
set_option(MYLIB_BUILD_TESTS OFF)
add_subdirectory(mylib)
```


text: ENV_CONTACT_POSITION_NAME = ENV['CONTACT_POSITION_NAME'] || 'Administrador Institucional de Datos'


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Pysäkkiaikataulut</string>
    <string name="action_settings">Asetukset</string>
    <string name="departure_list_update_no_connection_failure">Päivitys epäonnistui: Ei verkkoyhteyttä</string>
    <string name="departure_list_update_server_error">Päivitys epäonnistui: Palvelinvirhe</string>
    <string name="departure_list_update_timeout">Päivitys epäonnistui: Aikakatkaisu</string>
    <string name="departure_list_update_unexpected_failure">Päivitys epäonnistui: Odottamaton virhe</string>
    <string name="departure_now">Nyt</string>
    <string name="loading_default">Ladataan…</string>
    <string name="loading_departures">Ladataan lähtöjä…</string>
    <string name="loading_citybike_status">Ladataan tietoja…</string>
    <string name="nca_details">Pysäkkiaikataulujen katseleminen vaatii verkkoyhteyden. Ota verkkoyhteys käyttöön
        laitteen asetuksista.
    </string>
    <string name="nca_title">Ei verkkoyhteyttä</string>
    <string name="pref_cat_departures">Lähtöluettelo</string>
    <string name="pref_cat_general">Yleinen</string>
    <string name="pref_cat_stoplist">Pysäkkiluettelo</string>
    <string name="pref_key_departures_num_results">num_departures</string>
    <string name="pref_key_stoplist_num_results">stoplist_num_results</string>
    <string name="pref_key_use_location">use_location</string>
    <string name="pref_key_show_citybikes">show_citybikes</string>
    <string name="pref_num_departures_summary">Lähtölistassa näytettävien lähtöjen lukumäärä.</string>
    <string name="pref_num_departures_title">Lähtöjen lukumäärä</string>
    <string name="pref_stoplist_num_results_summary">Pysäkkihaussa näytettävien pysäkkien lukumäärä.</string>
    <string name="pref_stoplist_num_results_title">Hakutulosten määrä</string>
    <string name="pref_use_location_summary">Laajenna sovelluksen toiminnallisuutta laitteen sijaintitiedolla.</string>
    <string name="pref_use_location_title">Käytä sijaintitietoja</string>
    <string name="retry">Yritä uudelleen</string>
    <string name="stop_list_item_icon_desc">Pysäkin tyyppi</string>
    <string name="stop_location_espoo">Espoo</string>
    <string name="stop_location_helsinki">Helsinki</string>
    <string name="stop_location_hyvinkaa">Hyvinkää</string>
    <string name="stop_location_jarvenpaa">Järvenpää</string>
    <string name="stop_location_kauniainen">Järvenpää</string>
    <string name="stop_location_kerava">Kerava</string>
    <string name="stop_location_knummi">Kirkkonummi</string>
    <string name="stop_location_lahti">Lahti</string>
    <string name="stop_location_mantsala">Mäntsälä</string>
    <string name="stop_location_nurmijarvi">Nurmijärvi</string>
    <string name="stop_location_pornainen">Pornainen</string>
    <string name="stop_location_porvoo">Porvoo</string>
    <string name="stop_location_riihimaki">Riihimäki</string>
    <string name="stop_location_sipoo">Sipoo</string>
    <string name="stop_location_tuusula">Tuusula</string>
    <string name="stop_location_unknown">Tuntematon</string>
    <string name="stop_location_vantaa">Vantaa</string>
    <string name="stop_name_with_platform">%1$s, laituri %2$s</string>
    <string name="stop_name_with_track">%1$s, raide %2$s</string>
    <string name="stoplist_search_description">Suodata pysäkkilistaa nimen perusteella.</string>
    <string name="stoplist_search_title">Etsi pysäkkejä</string>
    <string name="stoplist_empty_favorites_description">Aloita etsimällä usein käyttämiäsi pysäkkejä ja lisää ne
        suosikkeihin.
    </string>
    <string name="stoplist_empty_favorites_title">Suosikkipysäkit</string>
    <string name="stoplist_search_empty_description">Haku ei vastaa yhtään pysäkkiä.</string>
    <string name="stoplist_search_empty_title">Pysäkkejä ei löytynyt</string>
    <string name="stoplist_search_hint">Etsi pysäkkejä…</string>
    <string name="unexpected_error_message">Jotain odottamatonta tapahtui ja viimeisin toimenpide epäonnistui. Jos
        näet tämän virheen useita kertoja, jotain on pahasti vialla.
    </string>
    <string name="unexpected_error_title">Oho, jotain meni pieleen</string>
    <string name="action_update">Päivitä pysäkkitiedot</string>
    <string name="db_update_loading_message">Pysäkkitietoja päivitetään…</string>
    <string name="settings">Asetukset</string>
    <string name="stopdb_last_update">stopdb_last_update_timestamp</string>
    <string name="departures_empty_title">Ei lähtöjä</string>
    <string name="departures_empty_desc">Pysäkillä ei ole liikennettä lähitulevaisuudessa.</string>

    <string name="bottom_favorites">Suosikit</string>
    <string name="bottom_nearby">Lähellä</string>
    <string name="acquiring_location">Haetaan sijaintia…</string>
    <string name="location_disabled">Sijainti pois käytöstä</string>
    <string name="location_disabled_dialog_stop_using_it">Älä käytä sijaintia</string>
    <string name="location_disabled_dialog_title">Sijainti ei käytössä</string>
    <string name="location_disabled_dialog_message">Jos haluat etsiä pysäkkejä sijaintisi perusteella, ota
        sijaintipalvelut käyttöön laitteen asetuksista.
    </string>
    <string name="station_generic">Terminaali</string>
    <string name="station_subway">Metroasema</string>
    <string name="station_train">Juna-asema</string>
    <string name="platform_code_default">Laituri %s</string>
    <string name="platform_code_train">Raide %s</string>
    <string name="pref_key_show_arrivals_to_terminus">show_arrivals_to_terminus</string>
    <string name="pref_show_arrivals_to_terminus_title">Näytä pääteasemalle saapuvat kulkuneuvot</string>
    <string name="pref_show_arrivals_to_terminus_summary">Näytä päätepysäkilleen matkustajia jättävät linjat
        pysäkkikohtaisessa lähtölistauksessa.
    </string>
    <string name="citybike_station">Kaupunkipyöräasema</string>
    <string name="citybike_station_availability">%1$d/%2$d</string>
    <string name="citybike_status_active">Käytössä</string>
    <string name="citybike_status_inactive">Ei käytössä</string>
    <string name="pref_show_citybikes_title">Näytä kaupunkipyöräasemat</string>
    <string name="pref_show_citybikes_summary">Näytä kaupunkipyöräasemat pysäkkilistassa.</string>

    <string name="action_edit_filters">Muokkaa linjasuodattimia</string>
    <string name="action_save">Tallenna</string>
    <string name="departure_route_description">Reitti</string>
    <string name="action_toggle_filters">Suodata / Näytä kaikki</string>

</resources>


text:
package org.apache.ignite.internal.processors.cache.distributed;

import java.util.concurrent.CountDownLatch;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.configuration.Factory;
import javax.cache.integration.CacheLoaderException;
import javax.cache.integration.CacheWriterException;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.store.CacheStoreAdapter;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;

import static org.apache.ignite.cache.CacheAtomicityMode.ATOMIC;
import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;
import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC;

/**
 *
 */
public class CacheAsyncOperationsTest extends GridCommonAbstractTest {
    /** */
    private static volatile CountDownLatch latch;

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        if (igniteInstanceName.equals(getTestIgniteInstanceName(1)))
            cfg.setClientMode(true);

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        startGrids(2);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testAsyncOperationsTx() throws Exception {
        asyncOperations(TRANSACTIONAL);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testAsyncOperationsMvccTx() throws Exception {
        asyncOperations(TRANSACTIONAL_SNAPSHOT);
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testAsyncOperationsAtomic() throws Exception {
        asyncOperations(ATOMIC);
    }

    /** {@inheritDoc} */
    @Override protected void afterTest() throws Exception {
        super.afterTest();

        CountDownLatch latch0 = latch;

        if (latch0 != null)
            latch0.countDown();

        latch = null;
    }

    /**
     * @param atomicityMode Atomicity mode.
     * @throws Exception If failed.
     */
    public void asyncOperations(CacheAtomicityMode atomicityMode) throws Exception {
        try (IgniteCache<Integer, Integer> cache = ignite(1).getOrCreateCache(cacheConfiguration(atomicityMode))) {
            async1(cache);

            async2(cache);
        }
    }

    /**
     * @param cache Cache.
     */
    private void async1(IgniteCache<Integer, Integer> cache) {
        cache.put(1, 1);

        latch = new CountDownLatch(1);

        IgniteFuture<?> fut1 = cache.putAsync(0, 0);

        IgniteFuture<?> fut2 = cache.getAndPutAsync(1, 2);

        IgniteFuture<?> fut3 = cache.getAndPutAsync(1, 3);

        assertFalse(fut1.isDone());
        assertFalse(fut2.isDone());
        assertFalse(fut3.isDone());

        latch.countDown();

        try {
            fut1.get();

            fail();
        }
        catch (CacheException e) {
            log.info("Expected error: " + e);
        }

        assertEquals(1, fut2.get());
        assertEquals(2, fut3.get());

        assertNull(cache.get(0));
        assertEquals((Integer)3, cache.get(1));
    }
    /**
     *
     * @param cache Cache.
     */
    private void async2(IgniteCache<Integer, Integer> cache) {
        cache.put(1, 1);

        latch = new CountDownLatch(1);

        IgniteFuture<?> fut1 = cache.putAsync(0, 0);

        IgniteFuture<?> fut2 = cache.putAsync(0, 0);

        IgniteFuture<?> fut3 = cache.getAndPutAsync(1, 2);

        IgniteFuture<?> fut4 = cache.putAsync(0, 0);

        assertFalse(fut1.isDone());
        assertFalse(fut2.isDone());
        assertFalse(fut3.isDone());
        assertFalse(fut4.isDone());

        latch.countDown();

        try {
            fut1.get();

            fail();
        }
        catch (CacheException e) {
            log.info("Expected error: " + e);
        }

        try {
            fut2.get();

            fail();
        }
        catch (CacheException e) {
            log.info("Expected error: " + e);
        }

        assertEquals(1, fut3.get());

        try {
            fut4.get();

            fail();
        }
        catch (CacheException e) {
            log.info("Expected error: " + e);
        }

        assertNull(cache.get(0));
        assertEquals((Integer)2, cache.get(1));
    }

    /**
     * @param atomicityMode Atomicity mode.
     * @return Cache configuration.
     */
    private CacheConfiguration<Integer, Integer> cacheConfiguration(CacheAtomicityMode atomicityMode) {
        CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME);

        ccfg.setCacheMode(PARTITIONED);
        ccfg.setAtomicityMode(atomicityMode);
        ccfg.setWriteSynchronizationMode(FULL_SYNC);
        ccfg.setWriteThrough(true);
        ccfg.setCacheStoreFactory(new StoreFactory());

        return ccfg;
    }

    /**
     *
     */
    private static class StoreFactory implements Factory<TestStore> {
        /** {@inheritDoc} */
        @Override public TestStore create() {
            return new TestStore();
        }
    }

    /**
     *
     */
    private static class TestStore extends CacheStoreAdapter<Integer, Integer> {
        /** {@inheritDoc} */
        @Override public Integer load(Integer key) throws CacheLoaderException {
            return null;
        }

        /** {@inheritDoc} */
        @Override public void write(Cache.Entry<? extends Integer, ? extends Integer> entry) {
            CountDownLatch latch0 = latch;

            if (latch0 != null)
                U.awaitQuiet(latch0);

            Integer key = entry.getKey();

            if (key.equals(0)) {
                System.out.println(Thread.currentThread().getName() + ": fail operation for key: " + key);

                throw new CacheWriterException("Test error.");
            }
        }

        /** {@inheritDoc} */
        @Override public void delete(Object key) {
            // No-op.
        }
    }
}


text:
<?php

    /**
     * Class for manage the recipes
     *
     * @property INT $idrecipes
     * @property String $name
     * @property String $imageurl
     * @property String $description
     * @property INT $average
     * @property INT $totalvotes
     *
     */

    class Recipe {

        private $idrecipes;
        private $name;
        private $imageurl;
        private $description;
        private $average;
        private $totalvotes;

        function __construct($idrecipes, $name, $imageurl, $description, $average, $totalvotes) {
            $this->idrecipes = $idrecipes;
            $this->name = $name;
            $this->imageurl = $imageurl;
            $this->description = $description;
            $this->average = $average;
            $this->totalvotes = $totalvotes;
        }

        public function show() {
            echo '
'.$this->name.'
';
            echo '
'.$this->description.'
';
            echo '
'.$this->average.'
';
            echo '
'.$this->totalvotes.'
';
            echo 'imageurl.'" />';
        }

        function getIdrecipes() {
            return $this->idrecipes;
        }

        function getName() {
            return $this->name;
        }

        function getImageurl() {
            return $this->imageurl;
        }

        function getDescription() {
            return $this->description;
        }

        function getAverage() {
            return $this->average;
        }

        function getTotalvotes() {
            return $this->totalvotes;
        }

        function setIdrecipes($idrecipes) {
            $this->idrecipes = $idrecipes;
        }

        function setName($name) {
            $this->name = $name;
        }

        function setImageurl($imageurl) {
            $this->imageurl = $imageurl;
        }

        function setDescription($description) {
            $this->description = $description;
        }

        function setAverage($average) {
            $this->average = $average;
        }

        function setTotalvotes($totalvotes) {
            $this->totalvotes = $totalvotes;
        }

    }

?>


text:
const baseurl = 'https://en.wikipedia.org/w/api.php?';
const randurl = 'https://en.wikipedia.org/wiki/Special:Random';
const noResultsMessage = 'No results for this search. Re-enter your search or click the "Random" button to get a random article.';

feather.replace();

$('#random').click(() => {
  window.open(randurl, '_blank');
});

$('#search-button').click(() => {
  search($('#search-field').val());
});

$('#search-field').keypress((e) => {
  if (e.which == 13) {
    e.preventDefault();
    search($('#search-field').val());
  }
});

$.fn.extend({
    animateCss: function (animationName) {
        var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        this.addClass('animated ' + animationName).one(animationEnd, function() {
            $(this).removeClass('animated ' + animationName);
        });
        return this;
    }
});

function search(term) {
  const filtered_term = encodeURI(term);
  // console.log(filtered_term);
  const endpoint = `format=json&action=query&generator=search&gsrnamespace=0&gsrsearch=${filtered_term}&gsrlimit=10&pilimit=max&prop=extracts&exintro&explaintext&exsentences=1&exlimit=max`;
  let html = '';
  $.ajax({
    url: baseurl + endpoint,
    dataType: 'jsonp',
    type: 'get',
    success: res => {
      if (res.hasOwnProperty('error')) {
        html += '
';
        html += '
';
        html += '
';
        html += `<p class="lead description">${noResultsMessage}</p>`;
        html += '

';
      } else {
        const pages = $.map(res.query.pages, (el) => {
        return el;
        });
        pages.forEach(page => {
          html += '
';
          html += '
';
          html += '
';
          html += `<a href="https://en.wikipedia.org/?curid=${page.pageid}" target="_blank">`;
          html += '
';
          html += `<h5>${page.title}</h5>`;
          html += `<p class="lead description">${page.extract}</p>`;
          html += '

';
        });
      }
      $('#results').html(html);
      $('#results').animateCss('fadeIn');
    }
  });
}


text:
function TrackerController($scope)
{
	$scope.head  = {text:null, position:[0,0,0], rotation:[0,0,0]};
	$scope.wand  = {text:null, position:[0,0,0], rotation:[0,0,0]};
	$scope.wand2 = {text:null, position:[0,0,0], rotation:[0,0,0]};
	//$scope.pointer = {label:" ", ip:" ", position: [0,0], zoom:0, buttons:[0,0,0]};
	$scope.ptrs = {};
	$scope.numptrs = 0;

	console.log("Href ", window.location.href);

	//var url = 'http://' + window.location.hostname + ':8080';
	//var url = window.location.href;
        var url = window.location.origin;
	var socket = io.connect( url );
	console.log("Connected to server: ", url);
	window.socket = socket;

	socket.on('head', function (data) {
		// force angular update
		$scope.$apply(function() {
			$scope.head.text  = data.text;
			$scope.head.rotation  = data.rot;
			$scope.head.position  = data.pos;
		});
  	});
	socket.on('wand', function (data) {
		// force angular update
		$scope.$apply(function() {
			$scope.wand.text  = data.text;
			$scope.wand.rotation  = data.rot;
			$scope.wand.position  = data.pos;
		});
  	});
	socket.on('wand2', function (data) {
		// force angular update
		$scope.$apply(function() {
			$scope.wand2.text = data.text;
			$scope.wand2.rotation  = data.rot;
			$scope.wand2.position  = data.pos;
		});
  	});

	// Process 'Pointer' data type (sagePointer)
	socket.on('pointer', function (data) {
		// force angular data
		$scope.$apply(function() {
			if (data.id in $scope.ptrs) {
				// pass
			} else {
				$scope.numptrs = $scope.numptrs + 1;
			}
			$scope.ptrs[ data.id ] = data;

			// $scope.pointer.label    = data.label;
			// $scope.pointer.ip       = data.ip;
			// $scope.pointer.position = data.position;
			// $scope.pointer.zoom     = data.zoom;
			// $scope.pointer.buttons  = data.mouse;

			// {label:ptrinfo[0], ip:ptrinfo[1], mouse:[], color:colorpt, zoom:0, position:[0,0]};

		});
  	});

}

window.onbeforeunload = function (event) {
  var message = 'Sure you want to leave?';
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
}


text:
class COpFileWavOut : public COp
{
public:
	COpFileWavOut();
	virtual ~COpFileWavOut();
public:
	virtual void Proc();
	virtual void Update();
#ifdef OP_USE_ROUTINES
	virtual void Routine( unsigned int uiIndex );
#endif // OP_USE_ROUTINES

	OP_GENERIC_COPY_CTOR_DEC( COpFileWavOut )
	OP_GENERIC_METHODS_DEC( COpFileWavOut )

protected:
	bool NewFile();
protected:
	unsigned m_uiIsOpen;
	CFileStreamWav m_oFileOut;
#ifdef OP_USE_RUNTIME_INFO
	CTime m_oTime;
#endif // OP_USE_RUNTIME_INFO
};

#endif // OP_INC_OP_FILE_WAV_OUT
#endif // _OP_FILE_WAV_OUT_H_


text:
define([],
function() {
  /** generate DOM events as if the mouse was clicked
   *
   * .selection:D3Selection     - mouse events will target the first element in the selection
   * .?position:[Number,Number] - location of the click: (pixel offset from selection's upper left)
   */
  return function(selection, position) {
    var node = selection.node(),
        jqSelection = jQuery(node),
        offset = jqSelection.offset();
    if (!position) position = [1, 1];
    var docPosition = [
      offset.left + position[0],
      offset.top + position[1]
    ];
    jqSelection.simulate("mousedown", {clientX: docPosition[0], clientY: docPosition[1]});
    jqSelection.simulate("mouseup", {clientX: docPosition[0], clientY: docPosition[1]});
    jqSelection.simulate("click", {clientX: docPosition[0], clientY: docPosition[1]});
  }
});


text:
#include "Coordinate.hh"
#include "Vector.hh"

#include <cstddef>

using namespace std;

Coordinate::Coordinate(double x, double y, double z) : position(x, y, z), index(0)
{
}

const Vector<double> &Coordinate::Position() const
{
   return position;
}


text:
package lcom;

import java.io.Serializable;
import java.util.List;

import org.onebusaway.geospatial.model.CoordinatePoint;
import org.onebusaway.transit_data.model.StopBean;
import org.onebusaway.transit_data.model.schedule.FrequencyBean;
import org.onebusaway.transit_data.model.service_alerts.ServiceAlertBean;

public final class TripStatusBean implements Serializable {

  private static final long serialVersionUID = 2L;

  /****
   * These are fields that we can supply from schedule data
   ****/

  private TripBean activeTrip;

  private int blockTripSequence = -1;

  private long serviceDate;

  private FrequencyBean frequency;

  private double scheduledDistanceAlongTrip = Double.NaN;

  private double totalDistanceAlongTrip = Double.NaN;

  /****
   * These are fields that we can supply from schedule data, but also update
   * from real-time data when available
   ****/

  private String phase;

  private String status;

  private double distanceAlongTrip = Double.NaN;

  private CoordinatePoint location;

  private double orientation = Double.NaN;

  private StopBean closestStop;

  private int closestStopTimeOffset;

  private StopBean nextStop;

  private int nextStopTimeOffset;

  private double nextStopDistanceFromVehicle;

  /****
   * These are fields that we can supply only from real-time data
   ****/

  private boolean predicted = false;

  private long lastUpdateTime;

  private long lastLocationUpdateTime;

  private double lastKnownDistanceAlongTrip = Double.NaN;

  private CoordinatePoint lastKnownLocation;

  private double lastKnownOrientation = Double.NaN;

  private double scheduleDeviation;

  private String vehicleId;

  private List<ServiceAlertBean> situations;

  public TripBean getActiveTrip() {
    return activeTrip;
  }

  public void setActiveTrip(TripBean activeTrip) {
    this.activeTrip = activeTrip;
  }

  public int getBlockTripSequence() {
    return blockTripSequence;
  }

  public void setBlockTripSequence(int blockTripSequence) {
    this.blockTripSequence = blockTripSequence;
  }

  public long getServiceDate() {
    return serviceDate;
  }

  public void setServiceDate(long serviceDate) {
    this.serviceDate = serviceDate;
  }

  public FrequencyBean getFrequency() {
    return frequency;
  }

  public void setFrequency(FrequencyBean frequency) {
    this.frequency = frequency;
  }

  /**
   * The vehicle's scheduled distance along the trip.
   *
   * @return distance, in meters
   */
  public double getScheduledDistanceAlongTrip() {
    return scheduledDistanceAlongTrip;
  }

  public void setScheduledDistanceAlongTrip(double scheduledDistanceAlongTrip) {
    this.scheduledDistanceAlongTrip = scheduledDistanceAlongTrip;
  }

  public double getTotalDistanceAlongTrip() {
    return totalDistanceAlongTrip;
  }

  public void setTotalDistanceAlongTrip(double totalDistanceAlongTrip) {
    this.totalDistanceAlongTrip = totalDistanceAlongTrip;
  }

  public String getPhase() {
    return phase;
  }

  public void setPhase(String phase) {
    this.phase = phase;
  }

  public String getStatus() {
    return status;
  }

  public void setStatus(String status) {
    this.status = status;
  }

  /**
   * @return true if {@link #getDistanceAlongTrip()} has been set
   */
  public boolean isDistanceAlongTripSet() {
    return !Double.isNaN(distanceAlongTrip);
  }

  /**
   * See description in {@link #getDistanceAlongTrip()}.
   *
   * @param distanceAlongTrip
   */
  public void setDistanceAlongTrip(double distanceAlongTrip) {
    this.distanceAlongTrip = distanceAlongTrip;
  }

  /**
   * The vehicle's distance along the trip.
   *
   * @return distance, in meters
   */
  public double getDistanceAlongTrip() {
    return distanceAlongTrip;
  }

  public CoordinatePoint getLocation() {
    return location;
  }

  public void setLocation(CoordinatePoint location) {
    this.location = location;
  }

  public boolean isOrientationSet() {
    return !Double.isNaN(orientation);
  }

  /**
   * In degrees, 0º is East, 90º is North, 180º is West, and 270º is South
   */
  public double getOrientation() {
    return orientation;
  }

  public void setOrientation(double orientation) {
    this.orientation = orientation;
  }

  public StopBean getClosestStop() {
    return closestStop;
  }

  public void setClosestStop(StopBean closestStop) {
    this.closestStop = closestStop;
  }

  /**
   * The time offset, in seconds, from the closest stop to the current position
   * of the transit vehicle among the stop times of the current trip. If the
   * number is positive, the stop is coming up. If negative, the stop has
   * already been passed.
   *
   * @return time, in seconds
   */
  public int getClosestStopTimeOffset() {
    return closestStopTimeOffset;
  }

  /**
   * See description in {@link #getClosestStopTimeOffset()}.
   *
   * @param closestStopTimeOffset the time offset from the closest stop, in
   *          seconds
   */
  public void setClosestStopTimeOffset(int closestStopTimeOffset) {
    this.closestStopTimeOffset = closestStopTimeOffset;
  }

  public StopBean getNextStop() {
    return nextStop;
  }

  public void setNextStop(StopBean nextStop) {
    this.nextStop = nextStop;
  }

  /**
   * The time offset, in seconds, from the next stop to the current position of
   * the transit vehicle according to the schedule.
   *
   * @return time, in seconds
   */
  public int getNextStopTimeOffset() {
    return nextStopTimeOffset;
  }

  public void setNextStopTimeOffset(int nextStopTimeOffset) {
    this.nextStopTimeOffset = nextStopTimeOffset;
  }

  public double getNextStopDistanceFromVehicle() {
    return nextStopDistanceFromVehicle;
  }

  public void setNextStopDistanceFromVehicle(double d) {
    this.nextStopDistanceFromVehicle = d;
  }

  /**
   * @return true if there is an real-time data for this trip, whether
   *         prediction or location
   */
  public boolean isPredicted() {
    return predicted;
  }

  public void setPredicted(boolean predicted) {
    this.predicted = predicted;
  }

  public void setLastUpdateTime(long time) {
    this.lastUpdateTime = time;
  }

  /**
   * @return the time we last heard from the bus (Unix-time)
   */
  public long getLastUpdateTime() {
    return lastUpdateTime;
  }

  /**
   * @return the time we last received a location update from the bus
   *         (Unix-time)
   */
  public long getLastLocationUpdateTime() {
    return lastLocationUpdateTime;
  }

  public void setLastLocationUpdateTime(long lastLocationUpdateTime) {
    this.lastLocationUpdateTime = lastLocationUpdateTime;
  }

  public boolean isLastKnownDistanceAlongTripSet() {
    return !Double.isNaN(lastKnownDistanceAlongTrip);
  }

  public double getLastKnownDistanceAlongTrip() {
    return lastKnownDistanceAlongTrip;
  }

  public void setLastKnownDistanceAlongTrip(double lastKnownDistanceAlongTrip) {
    this.lastKnownDistanceAlongTrip = lastKnownDistanceAlongTrip;
  }

  public CoordinatePoint getLastKnownLocation() {
    return lastKnownLocation;
  }

  public void setLastKnownLocation(CoordinatePoint lastKnownLocation) {
    this.lastKnownLocation = lastKnownLocation;
  }

  public boolean isLastKnownOrientationSet() {
    return !Double.isNaN(lastKnownOrientation);
  }

  public double getLastKnownOrientation() {
    return lastKnownOrientation;
  }

  public void setLastKnownOrientation(double lastKnownOrientation) {
    this.lastKnownOrientation = lastKnownOrientation;
  }

  public boolean isScheduleDeviationSet() {
    return !Double.isNaN(scheduleDeviation);
  }

  public double getScheduleDeviation() {
    return scheduleDeviation;
  }

  public void setScheduleDeviation(double scheduleDeviation) {
    this.scheduleDeviation = scheduleDeviation;
  }

  public String getVehicleId() {
    return vehicleId;
  }

  public void setVehicleId(String vehicleId) {
    this.vehicleId = vehicleId;
  }

  public List<ServiceAlertBean> getSituations() {
    return situations;
  }

  public void setSituations(List<ServiceAlertBean> situations) {
    this.situations = situations;
  }
}


text:
<?php
// ************************** Globals **************************
// Define variables for PHP and the CMS
require_once('_hidden/php_script/define.php');

// ************************** Locals **************************
// Either setup the website for the first time or load the database/site settings
initial_setup();

// Ensure the database is configured for the correct environment
db_prepare();

// Connect to memcache
if (extension_loaded('memcache') && constant_test('SETTING_MEMCACHE','enable'))
{
	// Connect to memcache
	$memcache = new Memcache;

	if (!@$memcache->connect(MEMCACHE_SERVER, MEMCACHE_PORT)) unset($memcache);
}

// Get the secure DB functions
eval(simpleDB("SELECT method FROM php_methods WHERE name='cms_database' LIMIT 1",true));

// Load and evaluate the 3 CMS preloads
$qry = "SELECT method,name,post FROM php_methods WHERE name=? OR name=? OR name=? ORDER BY name LIMIT 3";
$params = array('cms_preload_error','cms_preload_define','cms_preload_session');
$result = query($qry, $params);
foreach($result as $row) { eval($row['method']); }

// ************************** Pager **************************
// Uncomment this to recache each page load
//$_SESSION['recache']=true;

// If the indexinc.php doesn't exist or an admin called a recache
if (!file_exists(CMS_FILE_INCLUDE) || isset($_SESSION['recache']))
{
	// Unset recache so it is only called once
	if (isset($_SESSION['recache'])) unset($_SESSION['recache']);

	$result_define = query("SELECT name, current_value FROM site_setting", array());
	foreach ($result_define as $row)
	{
		define($row['name'],$row['current_value'],true);
	}

	$result_define = query("SELECT name, color FROM site_color", array());
	foreach ($result_define as $row)
	{
		define($row['name'],$row['color']);
	}

	cache_file(CMS_FILE_INCLUDE, catch_output(method_retrieve('cms_backbone')));
	cache_file('js'.DIR_SEP.'javascript.js', method_retrieve("script_javascript"));
	cache_file('js'.DIR_SEP.'jquery.js', method_retrieve("script_jquery"));

	$writing = '';
	$writing .= method_retrieve('style_default');
	$writing .= NEWLINE;
	$writing .= '$output = <<< OUTPUT';
	$writing .= NEWLINE;
	$writing .= NEWLINE;
	$writing .= method_retrieve('style_html');
	$writing .= NEWLINE;
	$writing .= NEWLINE;
	$writing .= 'OUTPUT;';
	$writing .= NEWLINE;
	$writing .= 'echo $output;';
	$writing .= NEWLINE;
	$writing .= NEWLINE;

	cache_file('style'.DIR_SEP.'style.css', catch_output($writing));
}
include CMS_FILE_INCLUDE;

// Page load time output (won't load on Style.css stuff)
if (function_exists('br') && function_exists('isGroupMember'))
{
	if (isGroupMember(1) && constant_test('SETTING_PHP_VARIABLES','show'))
	{
		echo '
';
		echo PtimerStop();
		echo catch_output(method_retrieve('cms_verbose'));
		echo '
';
	}
}

// ************************** Clean **************************
// Keep the tmp folder clean of error logs
//if (file_exists(CMS_ERROR_PHP)) unlink(CMS_ERROR_PHP);
//if (file_exists(ini_get('error_log'))) unlink(ini_get('error_log'));

?>


text:
package uploaders

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/bitrise-io/go-utils/log"
	"github.com/bitrise-io/go-utils/retry"
	"github.com/bitrise-io/go-utils/urlutil"
)

// ArtifactURLs ...
type ArtifactURLs struct {
	PublicInstallPageURL string
	PermanentDownloadURL string
}

func createArtifact(buildURL, token, artifactPth, artifactType string) (string, string, error) {
	log.Printf("creating artifact")

	// create form data
	artifactName := filepath.Base(artifactPth)
	fileSize, err := fileSizeInBytes(artifactPth)
	if err != nil {
		return "", "", fmt.Errorf("failed to get file size, error: %s", err)
	}

	megaBytes := fileSize / 1024.0 / 1024.0
	roundedMegaBytes := int(roundPlus(megaBytes, 2))

	if roundedMegaBytes < 1 {
		log.Printf("  file size: %dB", int(fileSize))
	} else {
		log.Printf("  file size: %dMB", roundedMegaBytes)
	}

	data := url.Values{
		"api_token":       {token},
		"title":           {artifactName},
		"filename":        {artifactName},
		"artifact_type":   {artifactType},
		"file_size_bytes": {fmt.Sprintf("%d", int(fileSize))},
	}
	// ---

	// perform request
	uri, err := urlutil.Join(buildURL, "artifacts.json")
	if err != nil {
		return "", "", fmt.Errorf("failed to generate create artifact url, error: %s", err)
	}

	var response *http.Response

	// process response
	type createArtifactResponse struct {
		ErrorMessage string `json:"error_msg"`
		UploadURL    string `json:"upload_url"`
		ID           int    `json:"id"`
	}

	var artifactResponse createArtifactResponse

	if err := retry.Times(3).Wait(5 * time.Second).Try(func(attempt uint) error {
		if attempt > 0 {
			log.Warnf("%d attempt failed", attempt)
		}
		response, err = http.PostForm(uri, data)
		if err != nil {
			return fmt.Errorf("failed to perform create artifact request, error: %s", err)
		}

		defer func() {
			if err := response.Body.Close(); err != nil {
				log.Errorf("Failed to close reponse body, error: %s", err)
			}
		}()

		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return fmt.Errorf("failed to read create artifact response, error: %s", err)
		}
		if response.StatusCode != http.StatusOK {
			return fmt.Errorf("failed to create artifact on bitrise, status code: %d, response: %s", response.StatusCode, string(body))
		}

		if err := json.Unmarshal(body, &artifactResponse); err != nil {
			return fmt.Errorf("failed to unmarshal response (%s), error: %s", string(body), err)
		}

		if artifactResponse.ErrorMessage != "" {
			return fmt.Errorf("failed to create artifact on bitrise, error message: %s", artifactResponse.ErrorMessage)
		}
		if artifactResponse.UploadURL == "" {
			return fmt.Errorf("failed to create artifact on bitrise, error: no upload url received")
		}
		if artifactResponse.ID == 0 {
			return fmt.Errorf("failed to create artifact on bitrise, error: no artifact id received")
		}

		return nil
	}); err != nil {
		return "", "", err
	}

	return artifactResponse.UploadURL, fmt.Sprintf("%d", artifactResponse.ID), nil
}

func uploadArtifact(uploadURL, artifactPth, contentType string) error {
	log.Printf("uploading artifact")

	netClient := &http.Client{
		Timeout: 10 * time.Minute,
	}

	return retry.Times(3).Wait(5).Try(func(attempt uint) error {
		file, err := os.Open(artifactPth)
		if err != nil {
			return fmt.Errorf("failed to open artifact, error: %s", err)
		}
		defer func() {
			if err := file.Close(); err != nil {
				log.Warnf("failed to close file, error: %s", err)
			}
		}()

		// Set Content Length manually (https://stackoverflow.com/a/39764726), as it is part of signature in signed URL
		fileInfo, err := file.Stat()
		if err != nil {
			return fmt.Errorf("failed to get file info for %s, error: %s", artifactPth, err)
		}

		// Initializes request body to nil to send a Content-Length of 0: https://github.com/golang/go/issues/20257#issuecomment-299509391
		var reqBody io.Reader
		if fileInfo.Size() > 0 {
			reqBody = ioutil.NopCloser(file)
		}

		request, err := http.NewRequest(http.MethodPut, uploadURL, reqBody)
		if err != nil {
			return fmt.Errorf("failed to create request, error: %s", err)
		}

		if contentType != "" {
			request.Header.Add("Content-Type", contentType)
		}

		request.ContentLength = fileInfo.Size()

		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
		defer cancel()
		request = request.WithContext(ctx)

		resp, err := netClient.Do(request)
		if err != nil {
			return fmt.Errorf("failed to upload artifact, error: %s", err)
		}

		defer func() {
			if err := resp.Body.Close(); err != nil {
				log.Errorf("Failed to close response body, error: %s", err)
			}
		}()

		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return fmt.Errorf("failed to read response body, error: %s", err)
		}

		if resp.StatusCode != http.StatusOK {
			return fmt.Errorf("non success status code: %d, headers: %s, body: %s", resp.StatusCode, resp.Header, body)
		}

		return nil
	})
}

func finishArtifact(buildURL, token, artifactID, artifactInfo, notifyUserGroups, notifyEmails, isEnablePublicPage string) (ArtifactURLs, error) {
	log.Printf("finishing artifact")

	// create form data
	data := url.Values{"api_token": {token}}
	if artifactInfo != "" {
		data["artifact_info"] = []string{artifactInfo}
	}
	if notifyUserGroups != "" {
		data["notify_user_groups"] = []string{notifyUserGroups}
	}
	if notifyEmails != "" {
		data["notify_emails"] = []string{notifyEmails}
	}
	if isEnablePublicPage == "true" {
		data["is_enable_public_page"] = []string{"yes"}
	}
	// ---

	// perform request
	uri, err := urlutil.Join(buildURL, "artifacts", artifactID, "finish_upload.json")
	if err != nil {
		return ArtifactURLs{}, fmt.Errorf("failed to generate finish artifact url, error: %s", err)
	}

	var response *http.Response

	type finishArtifactResponse struct {
		PublicInstallPageURL string   `json:"public_install_page_url"`
		PermanentDownloadURL string   `json:"permanent_download_url"`
		InvalidEmails        []string `json:"invalid_emails"`
	}

	var artifactResponse finishArtifactResponse
	if err := retry.Times(3).Wait(5 * time.Second).Try(func(attempt uint) error {
		if attempt > 0 {
			log.Warnf("%d attempt failed", attempt)
		}
		response, err = http.PostForm(uri, data)
		if err != nil {
			return fmt.Errorf("failed to perform finish artifact request, error: %s", err)
		}
		defer func() {
			if err := response.Body.Close(); err != nil {
				log.Errorf("Failed to close reponse body, error: %s", err)
			}
		}()

		// process response
		body, err := ioutil.ReadAll(response.Body)
		if err != nil {
			return fmt.Errorf("failed to read finish artifact response, error: %s", err)
		}
		if response.StatusCode != http.StatusOK {
			return fmt.Errorf("failed to create artifact on bitrise, status code: %d, response: %s", response.StatusCode, string(body))
		}

		if err := json.Unmarshal(body, &artifactResponse); err != nil {
			return fmt.Errorf("failed to unmarshal response (%s), error: %s", string(body), err)
		}

		return nil
	}); err != nil {
		return ArtifactURLs{}, err
	}

	if len(artifactResponse.InvalidEmails) > 0 {
		log.Warnf("Invalid e-mail addresses: %s", strings.Join(artifactResponse.InvalidEmails, ", "))
	}

	if isEnablePublicPage == "true" {
		if artifactResponse.PublicInstallPageURL == "" {
			return ArtifactURLs{}, fmt.Errorf("public install page was enabled, but no public install page generated")
		}

		return ArtifactURLs{
			PublicInstallPageURL: artifactResponse.PublicInstallPageURL,
			PermanentDownloadURL: artifactResponse.PermanentDownloadURL,
		}, nil
	}

	return ArtifactURLs{
		PermanentDownloadURL: artifactResponse.PermanentDownloadURL,
	}, nil
}


text:
<!doctype html>

<html lang="en">
  <head>
    <title>uvalib-skip-nav test</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1, user-scalable=yes">
    <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
    <script src="../../web-component-tester/browser.js"></script>

    <link rel="import" href="../uvalib-skip-nav.html">
  </head>
  <body>

    <test-fixture id="basic">
      <template>
        <uvalib-skip-nav></uvalib-skip-nav>
      </template>
    </test-fixture>

    <script>
      suite('uvalib-skip-nav', function() {

        test('instantiating the element works', function() {
          var element = fixture('basic');
          assert.equal(element.is, 'uvalib-skip-nav');
        });

        a11ySuite('basic');

      });
    </script>
  </body>
</html>


text:
[![Gem Version](https://badge.fury.io/rb/motion-encodable.png)](http://badge.fury.io/rb/motion-encodable)
[![Build Status](https://travis-ci.org/satococoa/motion-encodable.png?branch=master)](https://travis-ci.org/satococoa/motion-encodable)
[![Dependency Status](https://gemnasium.com/satococoa/motion-encodable.png)](https://gemnasium.com/satococoa/motion-encodable)
[![Code Climate](https://codeclimate.com/github/satococoa/motion-encodable.png)](https://codeclimate.com/github/satococoa/motion-encodable)

Implement NSCoding protocol methods with ease for RubyMotion.

## Installation

Add this line to your application's Gemfile:

    gem 'motion-encodable'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install motion-encodable

## Usage

```
class Entry
  include Motion::Encodable
  properties :title, :body
end
```

Now, you can serialize and deserialize your object using NSCoding protocol.

```
entry = Entry.new
entry.title = 'foo'
entry.body = 'bar'

# save to NSUserDefaults
user_defaults = NSUserDefaults.standardUserDefaults
user_defaults[:entry] = entry.to_data

loaded_entry = Entry.load(user_defaults[:entry])
loaded_entry.instance_variable_get('@title') # => "foo"
loaded_entry.instance_variable_get('@body') # => "bar"

# save to file
dir_path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0]
file_path = dir_path + '/entry.dat'
entry.save_to_file(file_path)

loaded_entry = Entry.load(NSData.dataWithContentsOfFile(file_path))
loaded_entry.instance_variable_get('@title') # => "foo"
loaded_entry.instance_variable_get('@body') # => "bar"
```

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
<!DOCTYPE html>
<html>
<body>
<script src="../resources/runner.js"></script>
<script>
for (var i = 0; i < 1000; i++) {
    var div = document.createElement("div");
    div.id = "foo" + i;
    div.className = "bar" + i;
    document.body.appendChild(div);
}

var h1 = document.createElement("h1");
h1.id = "id";
h1.className = "class";
document.body.lastChild.appendChild(h1);

PerfTestRunner.measureRunsPerSecond({
    description: "This benchmark tests querySelectorAll() for an element that appears near the tail of the document, and is a child of an element with a given id",
    run: function() {
        for (var i = 0; i < 100; i++) {
            var res = document.querySelectorAll("#foo999 > h1");
        }
    }});
</script>
</body>
</html>


text:
(function() {

   var inputEx = YAHOO.inputEx;

/**
 * @class Create a uneditable field where you can stick the html you want
 * Added Options:
 *

 *
visu: inputEx visu type

 *

 * @extends inputEx.Field
 * @constructor
 * @param {Object} options inputEx.Field options object
 */
inputEx.UneditableField = function(options) {
	inputEx.UneditableField.superclass.constructor.call(this,options);
};
YAHOO.lang.extend(inputEx.UneditableField, inputEx.Field,
/**
 * @scope inputEx.UneditableField.prototype
 */
{

   /**
    * Set the default values of the options
    * @param {Object} options Options object (inputEx inputParams) as passed to the constructor
    */
	setOptions: function(options) {
      inputEx.UneditableField.superclass.setOptions.call(this,options);
      this.options.visu = options.visu;
   },

   /**
    * Store the value and update the visu
    * @param {Any} val The value that will be sent to the visu
    * @param {boolean} [sendUpdatedEvt] (optional) Wether this setValue should fire the updatedEvt or not (default is true, pass false to NOT send the event)
    */
   setValue: function(val, sendUpdatedEvt) {
      this.value = val;

      inputEx.renderVisu(this.options.visu, val, this.fieldContainer);

	   inputEx.UneditableField.superclass.setValue.call(this, val, sendUpdatedEvt);
   },

   /**
    * Return the stored value
    * @return {Any} The previously stored value
    */
   getValue: function() {
      return this.value;
   }

});

/**
 * Register this class as "url" type
 */
inputEx.registerType("uneditable", inputEx.UneditableField);

})();


text: Create project


text:
using namespace std;
using namespace qpid::messaging;
using namespace qpid::types;

unsigned long currentTimeMillis() {
	struct timeval curTime;
	gettimeofday(&curTime, NULL);
	return (curTime.tv_usec + curTime.tv_sec * 1000000ul)/1000;
}

inline Variant utf8(const char* s) {
	Variant utf8Value(s);
	utf8Value.setEncoding("utf8");
	return utf8Value;
}

int main(int argc, char** argv) {
    string broker = "localhost:5672";
    string address = "amq.match";
    string connectionOptions = "{reconnect: true}";

    Connection connection(broker, connectionOptions);
    try {
        connection.open();
        Session session = connection.createSession();
        Sender sender = session.createSender(address);

		int NUMBER_OF_ITERATIONS = 1000000;
		unsigned long startTime = currentTimeMillis();

		for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {
			char* buffer = new char[50000];
			Message message(buffer, 50000);
if ((i % 3) == 0) message.setProperty("item-owner", utf8("jdadams"));
else message.setProperty("item-owner", utf8("fadams"));

message.setProperty("data-service", utf8("amqp-delivery"));

        	sender.send(message);

			delete buffer;

			cout << "Sent message #" << i << endl;
			if ((i % 100) == 99) {
				session.sync();
			}
		}

		session.sync();
		unsigned long finishTime = currentTimeMillis();

		cout << "Elapsed time = " << (finishTime - startTime) << ", messages/second = " << NUMBER_OF_ITERATIONS*1000.0f/(finishTime - startTime) << endl;

        connection.close();
        return 0;
    } catch(const exception& error) {
        cerr << "ItemProducer Exception: " << error.what() << endl;
        connection.close();
        return 1;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:interpolator="@android:anim/decelerate_interpolator"
    android:shareInterpolator="true">
    <alpha
        android:duration="300"
        android:fromAlpha="1.0"
        android:toAlpha="0.1"/>
    <translate
        android:duration="300"
        android:fromXDelta="0%p"
        android:fromYDelta="0%p"
        android:toXDelta="-100%p"
        android:toYDelta="0%p"/>
</set>