text:
#include <algorithm>
#include <controller/ExampleOperationalCredentialsIssuer.h>
#include <credentials/CHIPCert.h>
#include <lib/core/CHIPTLV.h>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <lib/support/PersistentStorageMacros.h>
#include <lib/support/SafeInt.h>
#include <lib/support/ScopedBuffer.h>
#include <lib/support/TestGroupData.h>

namespace chip {
namespace Controller {

constexpr const char kOperationalCredentialsIssuerKeypairStorage[]             = "ExampleOpCredsCAKey";
constexpr const char kOperationalCredentialsIntermediateIssuerKeypairStorage[] = "ExampleOpCredsICAKey";
constexpr const char kOperationalCredentialsRootCertificateStorage[]           = "ExampleCARootCert";
constexpr const char kOperationalCredentialsIntermediateCertificateStorage[]   = "ExampleCAIntermediateCert";

using namespace Credentials;
using namespace Crypto;
using namespace TLV;

namespace {

enum CertType : uint8_t
{
    kRcac = 0,
    kIcac = 1,
    kNoc  = 2
};

CHIP_ERROR IssueX509Cert(uint32_t now, uint32_t validity, ChipDN issuerDn, ChipDN desiredDn, CertType certType, bool maximizeSize,
                         const Crypto::P256PublicKey & subjectPublicKey, Crypto::P256Keypair & issuerKeypair,
                         MutableByteSpan & outX509Cert)
{
    constexpr size_t kDERCertFutureExtEncodingOverhead = 12;
    constexpr size_t kTLVCertFutureExtEncodingOverhead = kDERCertFutureExtEncodingOverhead + 5;
    constexpr size_t kMaxCertPaddingLength             = 200;
    constexpr size_t kTLVDesiredSize                   = kMaxCHIPCertLength;
    constexpr uint8_t sOID_Extension_SubjectAltName[]  = { 0x55, 0x1d, 0x11 };

    Platform::ScopedMemoryBuffer<uint8_t> derBuf;
    ReturnErrorCodeIf(!derBuf.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY);
    MutableByteSpan derSpan{ derBuf.Get(), kMaxDERCertLength };

    int64_t serialNumber = 1;

    switch (certType)
    {
    case CertType::kRcac: {
        X509CertRequestParams rcacRequest = { serialNumber, now, now + validity, desiredDn, desiredDn };
        ReturnErrorOnFailure(NewRootX509Cert(rcacRequest, issuerKeypair, derSpan));
        break;
    }
    case CertType::kIcac: {
        X509CertRequestParams icacRequest = { serialNumber, now, now + validity, desiredDn, issuerDn };
        ReturnErrorOnFailure(NewICAX509Cert(icacRequest, subjectPublicKey, issuerKeypair, derSpan));
        break;
    }
    case CertType::kNoc: {
        X509CertRequestParams nocRequest = { serialNumber, now, now + validity, desiredDn, issuerDn };
        ReturnErrorOnFailure(NewNodeOperationalX509Cert(nocRequest, subjectPublicKey, issuerKeypair, derSpan));
        break;
    }
    default:
        return CHIP_ERROR_INVALID_ARGUMENT;
    }

    if (maximizeSize)
    {
        Platform::ScopedMemoryBuffer<uint8_t> paddedTlvBuf;
        ReturnErrorCodeIf(!paddedTlvBuf.Alloc(kMaxCHIPCertLength + kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY);
        MutableByteSpan paddedTlvSpan{ paddedTlvBuf.Get(), kMaxCHIPCertLength + kMaxCertPaddingLength };
        ReturnErrorOnFailure(ConvertX509CertToChipCert(derSpan, paddedTlvSpan));

        Platform::ScopedMemoryBuffer<uint8_t> paddedDerBuf;
        ReturnErrorCodeIf(!paddedDerBuf.Alloc(kMaxDERCertLength + kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY);
        MutableByteSpan paddedDerSpan{ paddedDerBuf.Get(), kMaxDERCertLength + kMaxCertPaddingLength };

        Platform::ScopedMemoryBuffer<char> fillerBuf;
        ReturnErrorCodeIf(!fillerBuf.Alloc(kMaxCertPaddingLength), CHIP_ERROR_NO_MEMORY);
        memset(fillerBuf.Get(), 'A', kMaxCertPaddingLength);

        int derPaddingLen = static_cast<int>(kMaxDERCertLength - kDERCertFutureExtEncodingOverhead - derSpan.size());
        int tlvPaddingLen = static_cast<int>(kTLVDesiredSize - kTLVCertFutureExtEncodingOverhead - paddedTlvSpan.size());
        size_t paddingLen = 0;
        if (derPaddingLen >= 1 && tlvPaddingLen >= 1)
        {
            paddingLen = std::min(static_cast<size_t>(std::min(derPaddingLen, tlvPaddingLen)), kMaxCertPaddingLength);
        }

        for (; paddingLen > 0; paddingLen--)
        {
            paddedDerSpan = MutableByteSpan{ paddedDerBuf.Get(), kMaxDERCertLength + kMaxCertPaddingLength };
            paddedTlvSpan = MutableByteSpan{ paddedTlvBuf.Get(), kMaxCHIPCertLength + kMaxCertPaddingLength };

            Optional<FutureExtension> futureExt;
            FutureExtension ext = { ByteSpan(sOID_Extension_SubjectAltName),
                                    ByteSpan(reinterpret_cast<uint8_t *>(fillerBuf.Get()), paddingLen) };
            futureExt.SetValue(ext);

            switch (certType)
            {
            case CertType::kRcac: {
                X509CertRequestParams rcacRequest = { serialNumber, now, now + validity, desiredDn, desiredDn, futureExt };
                ReturnErrorOnFailure(NewRootX509Cert(rcacRequest, issuerKeypair, paddedDerSpan));
                break;
            }
            case CertType::kIcac: {
                X509CertRequestParams icacRequest = { serialNumber, now, now + validity, desiredDn, issuerDn, futureExt };
                ReturnErrorOnFailure(NewICAX509Cert(icacRequest, subjectPublicKey, issuerKeypair, paddedDerSpan));
                break;
            }
            case CertType::kNoc: {
                X509CertRequestParams nocRequest = { serialNumber, now, now + validity, desiredDn, issuerDn, futureExt };
                ReturnErrorOnFailure(NewNodeOperationalX509Cert(nocRequest, subjectPublicKey, issuerKeypair, paddedDerSpan));
                break;
            }
            default:
                return CHIP_ERROR_INVALID_ARGUMENT;
            }

            ReturnErrorOnFailure(ConvertX509CertToChipCert(paddedDerSpan, paddedTlvSpan));

            if (paddedDerSpan.size() <= kMaxDERCertLength && paddedTlvSpan.size() <= kMaxCHIPCertLength)
            {
                ChipLogProgress(Controller, "Generated maximized certificate with %u DER bytes, %u TLV bytes",
                                static_cast<unsigned>(paddedDerSpan.size()), static_cast<unsigned>(paddedTlvSpan.size()));
                return CopySpanToMutableSpan(paddedDerSpan, outX509Cert);
            }
        }
    }

    return CopySpanToMutableSpan(derSpan, outX509Cert);
}

} // namespace

CHIP_ERROR ExampleOperationalCredentialsIssuer::Initialize(PersistentStorageDelegate & storage)
{
    using namespace ASN1;
    ASN1UniversalTime effectiveTime;
    CHIP_ERROR err;

    // Initializing the default start validity to start of 2021. The default validity duration is 10 years.
    CHIP_ZERO_AT(effectiveTime);
    effectiveTime.Year  = 2021;
    effectiveTime.Month = 1;
    effectiveTime.Day   = 1;
    ReturnErrorOnFailure(ASN1ToChipEpochTime(effectiveTime, mNow));

    Crypto::P256SerializedKeypair serializedKey;
    {
        // Scope for keySize, because we use it as an in/out param.
        uint16_t keySize = static_cast<uint16_t>(serializedKey.Capacity());

        PERSISTENT_KEY_OP(mIndex, kOperationalCredentialsIssuerKeypairStorage, key,
                          err = storage.SyncGetKeyValue(key, serializedKey.Bytes(), keySize));
        serializedKey.SetLength(keySize);
    }

    if (err != CHIP_NO_ERROR)
    {
        ChipLogProgress(Controller, "Couldn't get %s from storage: %s", kOperationalCredentialsIssuerKeypairStorage, ErrorStr(err));
        // Storage doesn't have an existing keypair. Let's create one and add it to the storage.
        ReturnErrorOnFailure(mIssuer.Initialize());
        ReturnErrorOnFailure(mIssuer.Serialize(serializedKey));

        PERSISTENT_KEY_OP(mIndex, kOperationalCredentialsIssuerKeypairStorage, key,
                          ReturnErrorOnFailure(
                              storage.SyncSetKeyValue(key, serializedKey.Bytes(), static_cast<uint16_t>(serializedKey.Length()))));
    }
    else
    {
        // Use the keypair from the storage
        ReturnErrorOnFailure(mIssuer.Deserialize(serializedKey));
    }

    {
        // Scope for keySize, because we use it as an in/out param.
        uint16_t keySize = static_cast<uint16_t>(serializedKey.Capacity());

        PERSISTENT_KEY_OP(mIndex, kOperationalCredentialsIntermediateIssuerKeypairStorage, key,
                          err = storage.SyncGetKeyValue(key, serializedKey.Bytes(), keySize));
        serializedKey.SetLength(keySize);
    }

    if (err != CHIP_NO_ERROR)
    {
        ChipLogProgress(Controller, "Couldn't get %s from storage: %s", kOperationalCredentialsIntermediateIssuerKeypairStorage,
                        ErrorStr(err));
        // Storage doesn't have an existing keypair. Let's create one and add it to the storage.
        ReturnErrorOnFailure(mIntermediateIssuer.Initialize());
        ReturnErrorOnFailure(mIntermediateIssuer.Serialize(serializedKey));

        PERSISTENT_KEY_OP(mIndex, kOperationalCredentialsIntermediateIssuerKeypairStorage, key,
                          ReturnErrorOnFailure(
                              storage.SyncSetKeyValue(key, serializedKey.Bytes(), static_cast<uint16_t>(serializedKey.Length()))));
    }
    else
    {
        // Use the keypair from the storage
        ReturnErrorOnFailure(mIntermediateIssuer.Deserialize(serializedKey));
    }

    mStorage     = &storage;
    mInitialized = true;
    return CHIP_NO_ERROR;
}

CHIP_ERROR ExampleOperationalCredentialsIssuer::GenerateNOCChainAfterValidation(NodeId nodeId, FabricId fabricId,
                                                                                const CATValues & cats,
                                                                                const Crypto::P256PublicKey & pubkey,
                                                                                MutableByteSpan & rcac, MutableByteSpan & icac,
                                                                                MutableByteSpan & noc)
{
    ChipDN rcac_dn;
    CHIP_ERROR err      = CHIP_NO_ERROR;
    uint16_t rcacBufLen = static_cast<uint16_t>(std::min(rcac.size(), static_cast<size_t>(UINT16_MAX)));
    PERSISTENT_KEY_OP(mIndex, kOperationalCredentialsRootCertificateStorage, key,
                      err = mStorage->SyncGetKeyValue(key, rcac.data(), rcacBufLen));
    // Always regenerate RCAC on maximally sized certs. The keys remain the same, so everything is fine.
    if (mUseMaximallySizedCerts)
    {
        err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND;
    }

    if (err == CHIP_NO_ERROR)
    {
        uint64_t rcacId;
        // Found root certificate in the storage.
        rcac.reduce_size(rcacBufLen);
        ReturnErrorOnFailure(ExtractSubjectDNFromX509Cert(rcac, rcac_dn));
        ReturnErrorOnFailure(rcac_dn.GetCertChipId(rcacId));
        VerifyOrReturnError(rcacId == mIssuerId, CHIP_ERROR_INTERNAL);
    }
    // If root certificate not found in the storage, generate new root certificate.
    else
    {
        ReturnErrorOnFailure(rcac_dn.AddAttribute_MatterRCACId(mIssuerId));

        ChipLogProgress(Controller, "Generating RCAC");
        ReturnErrorOnFailure(IssueX509Cert(mNow, mValidity, rcac_dn, rcac_dn, CertType::kRcac, mUseMaximallySizedCerts,
                                           mIssuer.Pubkey(), mIssuer, rcac));
        VerifyOrReturnError(CanCastTo<uint16_t>(rcac.size()), CHIP_ERROR_INTERNAL);

        // Re-extract DN based on final generated cert
        rcac_dn = ChipDN{};
        ReturnErrorOnFailure(ExtractSubjectDNFromX509Cert(rcac, rcac_dn));

        PERSISTENT_KEY_OP(mIndex, kOperationalCredentialsRootCertificateStorage, key,
                          ReturnErrorOnFailure(mStorage->SyncSetKeyValue(key, rcac.data(), static_cast<uint16_t>(rcac.size()))));
    }

    ChipDN icac_dn;
    uint16_t icacBufLen = static_cast<uint16_t>(std::min(icac.size(), static_cast<size_t>(UINT16_MAX)));
    PERSISTENT_KEY_OP(mIndex, kOperationalCredentialsIntermediateCertificateStorage, key,
                      err = mStorage->SyncGetKeyValue(key, icac.data(), icacBufLen));
    // Always regenerate ICAC on maximally sized certs. The keys remain the same, so everything is fine.
    if (mUseMaximallySizedCerts)
    {
        err = CHIP_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND;
    }
    if (err == CHIP_NO_ERROR)
    {
        uint64_t icacId;
        // Found intermediate certificate in the storage.
        icac.reduce_size(icacBufLen);
        ReturnErrorOnFailure(ExtractSubjectDNFromX509Cert(icac, icac_dn));
        ReturnErrorOnFailure(icac_dn.GetCertChipId(icacId));
        VerifyOrReturnError(icacId == mIntermediateIssuerId, CHIP_ERROR_INTERNAL);
    }
    // If intermediate certificate not found in the storage, generate new intermediate certificate.
    else
    {
        ReturnErrorOnFailure(icac_dn.AddAttribute_MatterICACId(mIntermediateIssuerId));

        ChipLogProgress(Controller, "Generating ICAC");
        ReturnErrorOnFailure(IssueX509Cert(mNow, mValidity, rcac_dn, icac_dn, CertType::kIcac, mUseMaximallySizedCerts,
                                           mIntermediateIssuer.Pubkey(), mIssuer, icac));
        VerifyOrReturnError(CanCastTo<uint16_t>(icac.size()), CHIP_ERROR_INTERNAL);

        // Re-extract DN based on final generated cert
        icac_dn = ChipDN{};
        ReturnErrorOnFailure(ExtractSubjectDNFromX509Cert(icac, icac_dn));

        PERSISTENT_KEY_OP(mIndex, kOperationalCredentialsIntermediateCertificateStorage, key,
                          ReturnErrorOnFailure(mStorage->SyncSetKeyValue(key, icac.data(), static_cast<uint16_t>(icac.size()))));
    }

    ChipDN noc_dn;
    ReturnErrorOnFailure(noc_dn.AddAttribute_MatterFabricId(fabricId));
    ReturnErrorOnFailure(noc_dn.AddAttribute_MatterNodeId(nodeId));
    ReturnErrorOnFailure(noc_dn.AddCATs(cats));

    ChipLogProgress(Controller, "Generating NOC");
    return IssueX509Cert(mNow, mValidity, icac_dn, noc_dn, CertType::kNoc, mUseMaximallySizedCerts, pubkey, mIntermediateIssuer,
                         noc);
}

CHIP_ERROR ExampleOperationalCredentialsIssuer::GenerateNOCChain(const ByteSpan & csrElements, const ByteSpan & csrNonce,
                                                                 const ByteSpan & attestationSignature,
                                                                 const ByteSpan & attestationChallenge, const ByteSpan & DAC,
                                                                 const ByteSpan & PAI,
                                                                 Callback::Callback<OnNOCChainGeneration> * onCompletion)
{
    VerifyOrReturnError(mInitialized, CHIP_ERROR_WELL_UNINITIALIZED);
    // At this point, Credential issuer may wish to validate the CSR information
    (void) attestationChallenge;
    (void) csrNonce;

    NodeId assignedId;
    if (mNodeIdRequested)
    {
        assignedId       = mNextRequestedNodeId;
        mNodeIdRequested = false;
    }
    else
    {
        assignedId = mNextAvailableNodeId++;
    }

    ChipLogProgress(Controller, "Verifying Certificate Signing Request");
    TLVReader reader;
    reader.Init(csrElements);

    if (reader.GetType() == kTLVType_NotSpecified)
    {
        ReturnErrorOnFailure(reader.Next());
    }

    VerifyOrReturnError(reader.GetType() == kTLVType_Structure, CHIP_ERROR_WRONG_TLV_TYPE);
    VerifyOrReturnError(reader.GetTag() == AnonymousTag(), CHIP_ERROR_UNEXPECTED_TLV_ELEMENT);

    TLVType containerType;
    ReturnErrorOnFailure(reader.EnterContainer(containerType));
    ReturnErrorOnFailure(reader.Next(kTLVType_ByteString, TLV::ContextTag(1)));

    ByteSpan csr(reader.GetReadPoint(), reader.GetLength());
    reader.ExitContainer(containerType);

    P256PublicKey pubkey;
    ReturnErrorOnFailure(VerifyCertificateSigningRequest(csr.data(), csr.size(), pubkey));

    chip::Platform::ScopedMemoryBuffer<uint8_t> noc;
    ReturnErrorCodeIf(!noc.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY);
    MutableByteSpan nocSpan(noc.Get(), kMaxDERCertLength);

    chip::Platform::ScopedMemoryBuffer<uint8_t> icac;
    ReturnErrorCodeIf(!icac.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY);
    MutableByteSpan icacSpan(icac.Get(), kMaxDERCertLength);

    chip::Platform::ScopedMemoryBuffer<uint8_t> rcac;
    ReturnErrorCodeIf(!rcac.Alloc(kMaxDERCertLength), CHIP_ERROR_NO_MEMORY);
    MutableByteSpan rcacSpan(rcac.Get(), kMaxDERCertLength);

    ReturnErrorOnFailure(
        GenerateNOCChainAfterValidation(assignedId, mNextFabricId, chip::kUndefinedCATs, pubkey, rcacSpan, icacSpan, nocSpan));

    // TODO(#13825): Should always generate some IPK. Using a temporary fixed value until APIs are plumbed in to set it end-to-end
    // TODO: Force callers to set IPK if used before GenerateNOCChain will succeed.
    ByteSpan defaultIpkSpan = chip::GroupTesting::DefaultIpkValue::GetDefaultIpk();

    // The below static assert validates a key assumption in types used (needed for public API conformance)
    static_assert(CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES == kAES_CCM128_Key_Length, "IPK span sizing must match");

    // Prepare IPK to be sent back. A more fully-fledged operational credentials delegate
    // would obtain a suitable key per fabric.
    uint8_t ipkValue[CHIP_CRYPTO_SYMMETRIC_KEY_LENGTH_BYTES];
    Crypto::AesCcm128KeySpan ipkSpan(ipkValue);

    ReturnErrorCodeIf(defaultIpkSpan.size() != sizeof(ipkValue), CHIP_ERROR_INTERNAL);
    memcpy(&ipkValue[0], defaultIpkSpan.data(), defaultIpkSpan.size());

    // Callback onto commissioner.
    ChipLogProgress(Controller, "Providing certificate chain to the commissioner");
    onCompletion->mCall(onCompletion->mContext, CHIP_NO_ERROR, nocSpan, icacSpan, rcacSpan, MakeOptional(ipkSpan),
                        Optional<NodeId>());
    return CHIP_NO_ERROR;
}

CHIP_ERROR ExampleOperationalCredentialsIssuer::GetRandomOperationalNodeId(NodeId * aNodeId)
{
    for (int i = 0; i < 10; ++i)
    {
        CHIP_ERROR err = DRBG_get_bytes(reinterpret_cast<uint8_t *>(aNodeId), sizeof(*aNodeId));
        if (err != CHIP_NO_ERROR)
        {
            return err;
        }

        if (IsOperationalNodeId(*aNodeId))
        {
            return CHIP_NO_ERROR;
        }
    }

    // Terrible, universe-ending luck (chances are 1 in 2^280 or so here, if our
    // DRBG is good).
    return CHIP_ERROR_INTERNAL;
}

} // namespace Controller
} // namespace chip


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;

namespace Symblr.Symbols
{
    /// <summary>
    /// Represents a collection of <see cref="SourceInformation"/>.
    /// </summary>
    public class SourceInformationCollection : Collection<SourceInformation>
    {
        private static readonly SourceInformationCollection _empty = new SourceInformationCollection(new SourceInformation[0]);

        /// <summary>
        /// Gets an empty <see cref="SourceInformationCollection"/>.
        /// </summary>
        public static SourceInformationCollection Empty
        {
            get { return _empty; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SourceInformationCollection" /> class.
        /// </summary>
        public SourceInformationCollection()
            : base()
        {

        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SourceInformationCollection"/> class.
        /// </summary>
        /// <param name="underlyingCollection">The underlying collection.</param>
        public SourceInformationCollection(IList<SourceInformation> underlyingCollection)
            : base(underlyingCollection)
        {

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
title: It's All About the Pentiums
layout: post
---

A couple of months ago I wrote about [searching for the ultimate dev laptop]({% post_url 2015-12-03-search-for-ultimate-dev-laptop %}). Today there are some updates, but I'm going to focus on the processors. In this case, I'm looking at the top-of-the-line model each:

            Model
            Family
            Number
            Speed/Cores

            Apple MacBook Pro 13" (early-2015)
            "Broadwell-U" (5th gen)	5557U	2 x 3.1GHz

            Apple MacBook Pro 15" (mid-2015)
            "Haswell-H" (4th gen)	4980HQ	4 x 2.8GHz

            Dell Latitude E5470
            "Skylake-H" (6th gen)	6820HQ	4 x 2.7GHz

            Dell XPS 13
            "Skylake-U" (6th gen)	6560U	2 x 2.7GHz

            Lenovo T460s
            "Skylake-U" (6th gen)	6600U	2 x 2.6GHz

Some notes:

* Apple has *still not released or announced* updated MacBook Pros. Hence, they are a generation behind.
* Dell has updated their Latitudes to latest processors. But the 6820HQ is technically the *older* Skylake-H.
* I'm now also comparing the Dell XPS 13. It's even smaller than the Latitude. It has Thunderbolt instead of HDMI. It's also touch, and perhaps a bit under-powered. But not severely. The biggest difference is that you can upgrade the HD and some other components.
* Lenovo has also updated their T series. The Skylake-U is the "low power" processor.

So I'm still torn. I'm definitely going to wait and see what Apple does this summer.


text: welcome to my hometown


text:
<?php
namespace Nemundo\App\Dataset\Data\Dataset;
class DatasetBulk extends \Nemundo\Model\Data\AbstractModelDataBulk {
/**
* @var DatasetModel
*/
protected $model;

/**
* @var string
*/
public $dataset;

/**
* @var string
*/
public $url;

/**
* @var string
*/
public $description;

/**
* @var string
*/
public $licence;

/**
* @var string
*/
public $organisationId;

/**
* @var string
*/
public $categoryId;

/**
* @var string
*/
public $phpClass;

/**
* @var string
*/
public $licenceUrl;

/**
* @var string
*/
public $documentationUrl;

public function __construct() {
parent::__construct();
$this->model = new DatasetModel();
}
public function save() {
$this->typeValueList->setModelValue($this->model->dataset, $this->dataset);
$this->typeValueList->setModelValue($this->model->url, $this->url);
$this->typeValueList->setModelValue($this->model->description, $this->description);
$this->typeValueList->setModelValue($this->model->licence, $this->licence);
$this->typeValueList->setModelValue($this->model->organisationId, $this->organisationId);
$this->typeValueList->setModelValue($this->model->categoryId, $this->categoryId);
$this->typeValueList->setModelValue($this->model->phpClass, $this->phpClass);
$this->typeValueList->setModelValue($this->model->licenceUrl, $this->licenceUrl);
$this->typeValueList->setModelValue($this->model->documentationUrl, $this->documentationUrl);
$id = parent::save();
return $id;
}
}


text:
package de.johni0702.sponge.noteblockapi.song;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.spongepowered.api.data.type.NotePitch;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;

public class TestNoteBlock {

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void testConstructor() {
        NotePitch notePitch = mock(NotePitch.class);
        NoteBlock layer = new NoteBlock(Instrument.STICKS, notePitch);
        assertEquals(Instrument.STICKS, layer.getInstrument());
        assertEquals(notePitch, layer.getPitch());
    }

    @Test
    public void testConstructorNoInstrument() {
        exception.expect(NullPointerException.class);
        new NoteBlock(null, mock(NotePitch.class));
    }

    @Test
    public void testConstructorNoPitch() {
        exception.expect(NullPointerException.class);
        new NoteBlock(Instrument.STICKS, null);
    }

}


text:
<?php

namespace OV\CMSBundle\Service\Domain;

use OV\CMSBundle\Service\Application\ConfigurationService;

class ConfigurationServiceTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var ConfigurationService
     */
    private $configurationService;

    public function setUp()
    {
        $this->configurationService = new ConfigurationService();
    }

    public function testInitialization()
    {
        $this->assertInstanceOf(
            'OV\CMSBundle\Service\Application\ConfigurationService',
            $this->configurationService
        );
    }
}


text:
import Ember from 'ember';
import SecurityGroupERouteMixin from 'ember-flexberry-security/mixins/security-group-e-route';
import { module, test } from 'qunit';

module('Unit | Mixin | security group e route');

// Replace this with your real tests.
test('it works', function(assert) {
  let SecurityGroupERouteObject = Ember.Object.extend(SecurityGroupERouteMixin);
  let subject = SecurityGroupERouteObject.create();
  assert.ok(subject);
});


text:
require 'call_me_ruby'
require 'shanty/config'
require 'shanty/config_mixin'
require 'shanty/plugin_dsl'
require 'shanty/project'

module Shanty
  # Some basic functionality for every plugin.
  class Plugin
    include CallMeRuby
    extend ConfigMixin
    extend PluginDsl

    attr_reader :project, :env

    def initialize(project, env)
      @project = project
      @env = env
    end

    # External getters
    def self.project_providers
      @project_providers ||= []
    end

    def self.project_globs
      @project_globs ||= []
    end

    def self.tags
      @tags ||= [name]
    end

    def self.name
      to_s.split('::').last.downcase.gsub('plugin', '').to_sym
    end

    def self.info
      {
        name: name,
        description: @description,
        tags: tags,
        subscribes: class_callbacks.keys,
        config: config
      }
    end

    # Outside builders

    def self.projects(env)
      Set.new.tap do |projects|
        projects.merge(project_providers.flat_map { |provider| send(provider, env) })
        env.file_tree.glob(*project_globs).each do |path|
          projects << find_or_create_project(File.dirname(path), env)
        end

        projects.each { |project| project.add_plugin(self) }
      end
    end

    # Inner class methods
    def self.find_or_create_project(path, env)
      path = File.absolute_path(path)
      (env.projects[path] ||= Project.new(path, env))
    end

    def artifacts
      []
    end

    def config
      @config ||= Config.new(project.config[self.class.name], env.config[self.class.name], self.class.config)
    end
  end
end


text:
**WARNING: This is highly experimental! No guaranties whatsoever!**

This Atomic Reactor plugin was born from the need of inspecting
the workflow object accessible by [plugins](https://github.com/projectatomic/atomic-reactor/blob/master/docs/plugins.md).

We also wanted to try functions provided by these plugins.

## Usage

`exit_inspect_plugins.py` and `inspectors.py` should end up in the
`plugins` directory of the `atomic-reactor` installation in your buildroot.

For example one could add these lines to the Dockerfile of the buildroot:

```
ADD https://raw.githubusercontent.com/csomh/atomic-reactor-inspect-plugins/master/exit_inspect_plugins.py /usr/lib/python2.7/site-packages/atomic_reactor/plugins/exit_inspect_plugins.py
ADD https://raw.githubusercontent.com/csomh/atomic-reactor-inspect-plugins/master/inspectors.py /usr/lib/python2.7/site-packages/atomic_reactor/plugins/inspectors.py
```

Additional functions to inspect the [workflow object](https://github.com/projectatomic/atomic-reactor/blob/master/docs/plugin_development.md) can be added to `inspectors.py`.

All functions will be attached to the plugin instance and will have access
to `workflow`, `log` and `target` through `self`.

Additionally all calls to the inspector functions will receive as a parameter
the plugin module they inspect. If there is no plugin module name requested,
the module parameter can be `None`.

To enable the exit plugin for a build [osbs-client](https://github.com/projectatomic/osbs-client/) can be [configured](https://github.com/projectatomic/osbs-client/blob/master/docs/configuration_file.md#build-json-templates) to ask for this plugin to be run.

Example configuration placed in `prod_inner.json`s exit plugin section:

```json
{
    "name": "inspect_plugins",
    "required": false,
    "args": {
        "plugins": [
            {
                "name": "pre_reactor_config",
                "inspect_funk": [
                    "get_config"
                ]
            }
        ]
    }
}
```

This will cause the plugin to import `pre_reactor_config` plugin and pass it
to each inspector function specified in `inspector_funk`.

The `plugins` argument is a list, so one can specify multiple plugins to
inspect.


text:
package cloudprovider

import (
	"k8s.io/kubernetes/pkg/cloudprovider"
	"kubeup.com/archon/pkg/cluster"
)

type PublicIPInterface interface {
	EnsurePublicIP(clusterName string, instance *cluster.Instance) (status *cluster.InstanceStatus, err error)
	EnsurePublicIPDeleted(clusterName string, instance *cluster.Instance) error
}

type PrivateIPInterface interface {
	EnsurePrivateIP(clusterName string, instance *cluster.Instance) (status *cluster.InstanceStatus, err error)
	EnsurePrivateIPDeleted(clusterName string, instance *cluster.Instance) error
}

type ArchonInterface interface {
	EnsureNetwork(clusterName string, network *cluster.Network) (status *cluster.NetworkStatus, err error)
	EnsureNetworkDeleted(clusterName string, network *cluster.Network) error
	//AddNetworkAnnotation(clusterName string, instance *cluster.Instance, network *cluster.Network) error

	ListInstances(clusterName string, network *cluster.Network, selector map[string]string) (names []string, instances []*cluster.InstanceStatus, err error)
	GetInstance(clusterName string, instance *cluster.Instance) (status *cluster.InstanceStatus, err error)
	EnsureInstance(clusterName string, instance *cluster.Instance) (status *cluster.InstanceStatus, err error)
	EnsureInstanceDeleted(clusterName string, instance *cluster.Instance) error

	PublicIP() (PublicIPInterface, bool)
	PrivateIP() (PrivateIPInterface, bool)
}

type Interface interface {
	cloudprovider.Interface
	Archon() (ArchonInterface, bool)
}


text:
title: SpaR-Spatial Analysis using R
layout: post
tags: Activities
---

This project deals with the use of R in Spatial Analysis. With the members of [**GSDHL**](http://www.gshdl.uni-kiel.de/de/)
we discuss and work with subjects like Rasters, Interpolation or Point processes and simulations.
If you want to find out more about this project you are able to find detailed information [**here**](https://crc1266-a2.github.io/spaR/).


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespavisit;

import com.yahoo.document.FixedBucketSpaces;
import com.yahoo.document.fieldset.DocIdOnly;
import com.yahoo.document.fieldset.DocumentOnly;
import com.yahoo.document.select.parser.ParseException;
import com.yahoo.documentapi.ProgressToken;
import com.yahoo.documentapi.VisitorControlHandler;
import com.yahoo.documentapi.VisitorParameters;
import com.yahoo.documentapi.VisitorSession;
import com.yahoo.documentapi.messagebus.MessageBusDocumentAccess;
import com.yahoo.documentapi.messagebus.MessageBusParams;
import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol;
import com.yahoo.log.LogSetup;
import com.yahoo.messagebus.StaticThrottlePolicy;
import com.yahoo.vespaclient.ClusterDef;
import com.yahoo.vespaclient.ClusterList;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Client using visiting, used by the vespa-visit command line tool.
 *
 * @author Einar M R Rosenvinge
 */
public class VdsVisit {

    private VdsVisitParameters params;
    private MessageBusParams mbparams = new MessageBusParams();
    private VisitorSession session;

    private final VisitorSessionAccessorFactory sessionAccessorFactory;
    private VisitorSessionAccessor sessionAccessor;
    private ShutdownHookRegistrar shutdownHookRegistrar;

    public interface ShutdownHookRegistrar {

        void registerShutdownHook(Thread thread);

    }

    public interface VisitorSessionAccessor {

        VisitorSession createVisitorSession(VisitorParameters params) throws ParseException;
        void shutdown();

    }

    public interface VisitorSessionAccessorFactory {

        VisitorSessionAccessor createVisitorSessionAccessor();

    }

    private static class MessageBusVisitorSessionAccessor implements VisitorSessionAccessor {

        private MessageBusDocumentAccess access;

        private MessageBusVisitorSessionAccessor(MessageBusParams mbparams) {
            access = new MessageBusDocumentAccess(mbparams);
        }
        @Override
        public VisitorSession createVisitorSession(VisitorParameters params) throws ParseException {
            return access.createVisitorSession(params);
        }

        @Override
        public void shutdown() {
            access.shutdown();
        }

    }

    private static class MessageBusVisitorSessionAccessorFactory implements VisitorSessionAccessorFactory {

        MessageBusParams mbparams;

        private MessageBusVisitorSessionAccessorFactory(MessageBusParams mbparams) {
            this.mbparams = mbparams;
        }

        @Override
        public VisitorSessionAccessor createVisitorSessionAccessor() {
            return new MessageBusVisitorSessionAccessor(mbparams);
        }

    }

    private static class JvmRuntimeShutdownHookRegistrar implements ShutdownHookRegistrar {

        @Override
        public void registerShutdownHook(Thread thread) {
            Runtime.getRuntime().addShutdownHook(thread);
        }

    }

    public VdsVisit() {
        this.sessionAccessorFactory = new MessageBusVisitorSessionAccessorFactory(mbparams);
        this.shutdownHookRegistrar = new JvmRuntimeShutdownHookRegistrar();
    }

    public VdsVisit(VisitorSessionAccessorFactory sessionAccessorFactory, ShutdownHookRegistrar shutdownHookRegistrar) {
        this.sessionAccessorFactory = sessionAccessorFactory;
        this.shutdownHookRegistrar = shutdownHookRegistrar;
    }

    public static void main(String args[]) {
        LogSetup.initVespaLogging("vespa-visit");
        VdsVisit vdsVisit = new VdsVisit();

        Options options = createOptions();

        try {
            ArgumentParser parser = new ArgumentParser(options);
            vdsVisit.params = parser.parse(args);
            if (vdsVisit.params == null) {
                vdsVisit.printSyntax(options);
                System.exit(0);
            }
            ClusterList clusterList = new ClusterList("client");
            vdsVisit.params.getVisitorParameters().setRoute(
                    resolveClusterRoute(clusterList, vdsVisit.params.getCluster()));
        } catch (org.apache.commons.cli.ParseException e) {
            System.err.println("Failed to parse arguments. Try --help for syntax. " + e.getMessage());
            System.exit(1);
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }

        if (vdsVisit.params.isVerbose()) {
            verbosePrintParameters(vdsVisit.params, System.err);
        }

        try {
            vdsVisit.run();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    private void printSyntax(Options options) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("vespa-visit <options>", "Visit documents from Vespa", options , "");
    }

    @SuppressWarnings("AccessStaticViaInstance")
    protected static Options createOptions() {
        Options options = new Options();
        options.addOption("h", "help", false, "Show this syntax page.");

        options.addOption(Option.builder("d")
                .longOpt("datahandler")
                .hasArg(true)
                .argName("target")
                .desc("Send results to the given target.")
                .build());

        options.addOption(Option.builder("s")
                .longOpt("selection")
                .hasArg(true)
                .argName("selection")
                .desc("What documents to visit.")
                .build());

        options.addOption(Option.builder("f")
                .longOpt("from")
                .hasArg(true)
                .argName("timestamp")
                .desc("Only visit from the given timestamp (microseconds).")
                .type(Number.class)
                .build());

        options.addOption(Option.builder("t")
                .longOpt("to")
                .hasArg(true)
                .argName("timestamp")
                .desc("Only visit up to the given timestamp (microseconds).")
                .type(Number.class).build());

        options.addOption(Option.builder("l")
                .longOpt("fieldset")
                .hasArg(true)
                .argName("fieldset")
                .desc("Retrieve the specified fields only (see https://docs.vespa.ai/en/documents.html#fieldsets). Default is [document].")
                .build());

        options.addOption(Option.builder()
                .longOpt("visitinconsistentbuckets")
                .hasArg(false)
                .desc("Don't wait for inconsistent buckets to become consistent.")
                .build());

        options.addOption(Option.builder("m")
                .longOpt("maxpending")
                .hasArg(true)
                .argName("num")
                .desc("Maximum pending messages to data handlers per storage visitor.")
                .type(Number.class)
                .build());

        options.addOption(Option.builder()
                .longOpt("maxpendingsuperbuckets")
                .hasArg(true)
                .argName("num")
                .desc("Maximum pending visitor messages from the vespa-visit client. If set, dynamic throttling of visitors will be disabled!")
                .type(Number.class)
                .build());

        options.addOption(Option.builder("b")
                .longOpt("maxbuckets")
                .hasArg(true)
                .argName("num")
                .desc("Maximum buckets per visitor.")
                .type(Number.class)
                .build());

        options.addOption("i", "printids", false, "Display only document identifiers.");

        options.addOption(Option.builder("p")
                .longOpt("progress")
                .hasArg(true)
                .argName("file")
                .desc("Use given file to track progress.")
                .build());

        options.addOption(Option.builder("o")
                .longOpt("timeout")
                .hasArg(true)
                .argName("milliseconds")
                .desc("Time out visitor after given time.")
                .type(Number.class)
                .build());

        options.addOption(Option.builder("u")
                .longOpt("buckettimeout")
                .hasArg(true)
                .argName("milliseconds")
                .desc("Fail visitor if visiting a single bucket takes longer than this (default same as timeout)")
                .type(Number.class)
                .build());

        options.addOption(Option.builder()
                .longOpt("visitlibrary")
                .hasArg(true)
                .argName("string")
                .desc("Use the given visitor library.")
                .build());

        options.addOption(Option.builder()
                .longOpt("libraryparam")
                .numberOfArgs(2)
                .argName("key> <val")
                .desc("Give the following parameter to the visitor.")
                .build());

        options.addOption("r", "visitremoves", false, "Include information about removed documents.");

        options.addOption(Option.builder("c")
                .longOpt("cluster")
                .hasArg(true)
                .argName("cluster")
                .desc("Visit the given cluster.")
                .build());

        options.addOption("v", "verbose", false, "Indent XML, show progress and info on STDERR.");

        options.addOption(Option.builder()
                .longOpt("statistics")
                .hasArg(true)
                .argName("args")
                .desc("Use CountVisitor for document statistics. Use comma-separated arguments.")
                .build());

        options.addOption(Option.builder()
                .longOpt("abortonclusterdown")
                .hasArg(false)
                .desc("Abort if cluster is down.")
                .build());

        options.addOption(Option.builder()
                .longOpt("maxtotalhits")
                .hasArg(true)
                .argName("num")
                .desc("Abort visiting when we have received this many total documents. This is only an approximate number, all pending work will be completed and those documents will also be returned.")
                .type(Number.class)
                .build());

        options.addOption(Option.builder()
                .longOpt("processtime")
                .hasArg(true)
                .argName("num")
                .desc("Sleep this amount of millisecs before processing message. (Debug option for pretending to be slow client)")
                .type(Number.class)
                .build());
        options.addOption(Option.builder()
                .longOpt("priority")
                .hasArg(true)
                .argName("name")
                .desc("Priority used for each visitor. Defaults to NORMAL_3. " +
                        "Use with care to avoid starving lower prioritized traffic in the cluster")
                .build());

        options.addOption(Option.builder()
                .longOpt("tracelevel")
                .hasArg(true)
                .argName("level")
                .desc("Tracelevel ([0-9]) to use for debugging purposes")
                .type(Number.class)
                .build());

        options.addOption(Option.builder()
                .longOpt("skipbucketsonfatalerrors")
                .hasArg(false)
                .desc("Skip visiting super buckets with fatal error codes.")
                .build());

        options.addOption(Option.builder()
                .longOpt("jsonoutput")
                .desc("Output documents as JSON (default format)")
                .hasArg(false)
                .build());

        options.addOption(Option.builder("x")
              .longOpt("xmloutput")
              .desc("Output documents as XML")
              .hasArg(false)
              .build());

        options.addOption(Option.builder()
                .longOpt("bucketspace")
                .hasArg(true)
                .argName("space")
                .desc(String.format("Bucket space to visit ('%s' or '%s'). If not specified, '%s' is used.",
                        FixedBucketSpaces.defaultSpace(), FixedBucketSpaces.globalSpace(), FixedBucketSpaces.defaultSpace()))
                .build());

        return options;
    }

    public static class VdsVisitParameters {

        private VisitorParameters visitorParameters;
        /** If not specified in options, will get form cluster list */
        private String cluster = null;
        private boolean verbose = false;
        private boolean printIdsOnly = false;
        private String statisticsParts = null;
        private boolean abortOnClusterDown = false;
        private int processTime = 0;
        private int fullTimeout = 7 * 24 * 60 * 60 * 1000;
        private boolean jsonOutput = false;

        public VisitorParameters getVisitorParameters() {
            return visitorParameters;
        }

        public void setVisitorParameters(VisitorParameters visitorParameters) {
            this.visitorParameters = visitorParameters;
        }

        public String getCluster() {
            return cluster;
        }

        public void setCluster(String cluster) {
            this.cluster = cluster;
        }

        public boolean isVerbose() {
            return verbose;
        }

        public void setVerbose(boolean verbose) {
            this.verbose = verbose;
        }

        public boolean isPrintIdsOnly() {
            return printIdsOnly;
        }

        public void setPrintIdsOnly(boolean printIdsOnly) {
            this.printIdsOnly = printIdsOnly;
        }

        public String getStatisticsParts() {
            return statisticsParts;
        }

        public void setStatisticsParts(String statisticsParts) {
            this.statisticsParts = statisticsParts;
        }

        public boolean getAbortOnClusterDown() {
            return abortOnClusterDown;
        }

        public void setAbortOnClusterDown(boolean abortOnClusterDown) {
            this.abortOnClusterDown = abortOnClusterDown;
        }

        public int getFullTimeout() {
            return fullTimeout;
        }

        public void setFullTimeout(int fullTimeout) {
            this.fullTimeout = fullTimeout;
        }

        public int getProcessTime() {
            return processTime;
        }

        public void setProcessTime(int processTime) {
            this.processTime = processTime;
        }

        public void setJsonOutput(boolean jsonOutput) {
            this.jsonOutput = jsonOutput;
        }
    }

    protected static class ArgumentParser {
        private Options options;

        public ArgumentParser(Options options) {
            this.options = options;
        }

        public VdsVisitParameters parse(String args[]) throws org.apache.commons.cli.ParseException {
            VdsVisitParameters allParams = new VdsVisitParameters();
            VisitorParameters params = new VisitorParameters("");
            CommandLineParser parser = new DefaultParser();
            CommandLine line = parser.parse(options, args);

            if (line.hasOption("h")) {
                return null;
            }
            if (line.hasOption("d")) {
                params.setRemoteDataHandler(line.getOptionValue("d"));
            }
            if (line.hasOption("s")) {
                params.setDocumentSelection(line.getOptionValue("s"));
            }
            if (line.hasOption("bucketspace")) {
                params.setBucketSpace(line.getOptionValue("bucketspace"));
            }
            if (line.hasOption("f")) {
                params.setFromTimestamp(((Number) line.getParsedOptionValue("f")).longValue());
            }
            if (line.hasOption("t")) {
                params.setToTimestamp(((Number) line.getParsedOptionValue("t")).longValue());
            }
            if (line.hasOption("e")) {
                throw new IllegalArgumentException("Headers only option has been removed.");
            }
            if (line.hasOption("l")) {
                params.fieldSet(line.getOptionValue("l"));
            } else {
                params.fieldSet(DocumentOnly.NAME);
            }
            if (line.hasOption("visitinconsistentbuckets")) {
                params.visitInconsistentBuckets(true);
            }
            if (line.hasOption("m")) {
                params.setMaxPending(((Number) line.getParsedOptionValue("m")).intValue());
            }
            if (line.hasOption("b")) {
                params.setMaxBucketsPerVisitor(((Number) line.getParsedOptionValue("b")).intValue());
            }
            if (line.hasOption("i")) {
                allParams.setPrintIdsOnly(true);
                params.fieldSet(DocIdOnly.NAME);
            }
            if (line.hasOption("p")) {
                params.setResumeFileName(line.getOptionValue("p"));
            }
            if (line.hasOption("o")) {
                allParams.setFullTimeout(((Number) line.getParsedOptionValue("o")).intValue());
                params.setTimeoutMs(allParams.getFullTimeout());
            }
            if (line.hasOption("u")) {
                params.setTimeoutMs(((Number) line.getParsedOptionValue("u")).intValue());
            }
            if (line.hasOption("visitlibrary")) {
                params.setVisitorLibrary(line.getOptionValue("visitlibrary"));
            }
            if (line.hasOption("libraryparam")) {
                String key = line.getOptionValues("libraryparam")[0];
                String value = line.getOptionValues("libraryparam")[1];
                params.setLibraryParameter(key, value);
            }
            if (line.hasOption("r")) {
                params.visitRemoves(true);
            }
            if (line.hasOption("c")) {
                allParams.setCluster(line.getOptionValue("c"));
            }

            if (line.hasOption("v")) {
                allParams.setVerbose(true);
            }

            if (line.hasOption("statistics")) {
                allParams.setStatisticsParts(line.getOptionValue("statistics"));
                params.fieldSet(DocIdOnly.NAME);
                params.setVisitorLibrary("CountVisitor");
            }

            if (line.hasOption("abortonclusterdown")) {
                allParams.setAbortOnClusterDown(true);
            }
            if (line.hasOption("processtime")) {
                allParams.setProcessTime(((Number) line.getParsedOptionValue("processtime")).intValue());
            }
            if (line.hasOption("maxtotalhits")) {
                params.setMaxTotalHits(((Number)line.getParsedOptionValue("maxtotalhits")).intValue());
            }
            if (line.hasOption("tracelevel")) {
                params.setTraceLevel(((Number)line.getParsedOptionValue("tracelevel")).intValue());
            }
            if (line.hasOption("priority")) {
                try {
                    DocumentProtocol.Priority priority = DocumentProtocol.getPriorityByName(
                            line.getOptionValue("priority"));
                    params.setPriority(priority);
                } catch (IllegalArgumentException e) {
                    throw new IllegalArgumentException("Unknown priority name");
                }
            } else {
                // Let bulk visitor jobs have a low priority by default to avoid stalling concurrent
                // (real time) write and read operations.
                params.setPriority(DocumentProtocol.Priority.LOW_1);
            }
            if (line.hasOption("skipbucketsonfatalerrors")) {
                params.skipBucketsOnFatalErrors(true);
            }
            if (line.hasOption("maxpendingsuperbuckets")) {
                StaticThrottlePolicy throttlePolicy = new StaticThrottlePolicy();
                throttlePolicy.setMaxPendingCount(((Number)line.getParsedOptionValue("maxpendingsuperbuckets")).intValue());
                params.setThrottlePolicy(throttlePolicy);
            }

            boolean jsonOutput = line.hasOption("jsonoutput");
            boolean xmlOutput = line.hasOption("xmloutput");
            if (jsonOutput && xmlOutput) {
                throw new IllegalArgumentException("Cannot combine both xml and json output");
            }
            allParams.setJsonOutput(!xmlOutput);

            allParams.setVisitorParameters(params);
            return allParams;
        }
    }

    // For unit testing only
    protected void setVdsVisitParameters(VdsVisitParameters vdsVisitParameters) {
        this.params = vdsVisitParameters;
    }

    protected static String resolveClusterRoute(ClusterList clusters, String wantedCluster) {
        if (clusters.getStorageClusters().size() == 0) {
            throw new IllegalArgumentException("Your Vespa cluster does not have any content clusters " +
                                               "declared. Visiting feature is not available.");
        }

        ClusterDef found = null;

        String names = clusters.getStorageClusters()
                               .stream().map(c -> "'" + c.getName() + "'")
                               .collect(Collectors.joining(", "));
        if (wantedCluster != null) {
            for (ClusterDef c : clusters.getStorageClusters()) {
                if (c.getName().equals(wantedCluster)) {
                    found = c;
                }
            }
            if (found == null) {
                throw new IllegalArgumentException("Your vespa cluster contains the content clusters " +
                                                   names + ", not '" + wantedCluster +
                                                   "'. Please select a valid vespa cluster.");
            }
        } else if (clusters.getStorageClusters().size() == 1) {
            found = clusters.getStorageClusters().get(0);
        } else {
            throw new IllegalArgumentException("Your vespa cluster contains the content clusters " +
                                               names + ". Please use the -c option to select one of them as a target for visiting.");
        }

        return found.getRoute();
    }

    protected static void verbosePrintParameters(VdsVisitParameters vdsParams, PrintStream out) {
        VisitorParameters params = vdsParams.getVisitorParameters();
        if (params.getTimeoutMs() != -1) {
            out.println("Time out visitor after " + params.getTimeoutMs() + " ms.");
        }
        if (params.getDocumentSelection() == null || params.getDocumentSelection().equals("")) {
            out.println("Visiting all documents");
        } else {
            out.println("Visiting documents matching: " + params.getDocumentSelection());
        }
        out.println(String.format("Visiting bucket space: %s", params.getBucketSpace()));
        if (params.getFromTimestamp() != 0 && params.getToTimestamp() != 0) {
            out.println("Visiting in the inclusive timestamp range "
                               + params.getFromTimestamp() + " - " + params.getToTimestamp() + ".");
        } else if (params.getFromTimestamp() != 0) {
            out.println("Visiting from and including timestamp " + params.getFromTimestamp() + ".");
        } else if (params.getToTimestamp() != 0) {
            out.println("Visiting to and including timestamp " + params.getToTimestamp() + ".");
        }
        out.println("Visiting field set " + params.fieldSet() + ".");
        if (params.visitInconsistentBuckets()) {
            out.println("Visiting inconsistent buckets.");
        }
        if (params.visitRemoves()) {
            out.println("Including remove entries.");
        }
        if (params.getResumeFileName() != null && !"".equals(params.getResumeFileName())) {
            out.println("Tracking progress in file: " + params.getResumeFileName());
        }
        if (vdsParams.isPrintIdsOnly()) {
            out.println("Only showing document identifiers.");
        }
        out.println("Let visitor have maximum " + params.getMaxPending() + " replies pending on data handlers per storage node visitor.");
        out.println("Visit maximum " + params.getMaxBucketsPerVisitor() + " buckets per visitor.");
        if (params.getRemoteDataHandler() != null) {
            out.println("Sending data to data handler at: " + params.getRemoteDataHandler());
        }
        if (params.getRoute() != null) {
            out.println("Visiting cluster '" + params.getRoute() + "'.");
        }
        if (params.getVisitorLibrary() != null) {
            out.println("Using visitor library '" + params.getVisitorLibrary() + "'.");
        }
        if (params.getLibraryParameters().size() > 0) {
            out.println("Adding the following library specific parameters:");
            for (Map.Entry<String, byte[]> entry : params.getLibraryParameters().entrySet()) {
                out.println("  " + entry.getKey() + " = " +
                            new String(entry.getValue(), StandardCharsets.UTF_8));
            }
        }
        if (params.getPriority() != DocumentProtocol.Priority.NORMAL_3) {
            out.println("Visitor priority " + params.getPriority().name());
        }
        if (params.skipBucketsOnFatalErrors()) {
            out.println("Skip visiting super buckets with fatal errors.");
        }
    }

    private void onDocumentSelectionException(Exception e) {
        System.err.println("Illegal document selection string '" +
                params.getVisitorParameters().getDocumentSelection() + "'.\n");
        System.exit(1);
    }

    private void onIllegalArgumentException(Exception e) {
        System.err.println("Illegal arguments : \n");
        System.err.println(e.getMessage());
        System.exit(1);
    }

    public void run() {
        System.exit(doRun());
    }

    protected int doRun() {
        VisitorParameters visitorParameters = params.getVisitorParameters();
        // If progress file already exists, create resume token from it
        if (visitorParameters.getResumeFileName() != null &&
            !"".equals(visitorParameters.getResumeFileName()))
        {
            try {
                File file = new File(visitorParameters.getResumeFileName());
                FileInputStream fos = new FileInputStream(file);

                StringBuilder builder = new StringBuilder();
                byte[] b = new byte[100000];
                int length;

                while ((length = fos.read(b)) > 0) {
                    builder.append(new String(b, 0, length));
                }
                fos.close();
                visitorParameters.setResumeToken(new ProgressToken(builder.toString()));

                if (params.isVerbose()) {
                    System.err.format("Resuming visitor already %.1f %% finished.\n",
                            visitorParameters.getResumeToken().percentFinished());
                }
            } catch (FileNotFoundException e) {
                // Ignore; file has not been created yet but will be shortly.
            } catch (IOException e) {
                System.err.println("Could not open progress file: " + visitorParameters.getResumeFileName());
                e.printStackTrace(System.err);
                return 1;
            }
        }

        initShutdownHook();
        sessionAccessor = sessionAccessorFactory.createVisitorSessionAccessor();

        VdsVisitHandler handler;

        handler = new StdOutVisitorHandler(
                params.isPrintIdsOnly(),
                params.isVerbose(),
                params.isVerbose(),
                params.isVerbose(),
                params.getStatisticsParts() != null,
                params.getAbortOnClusterDown(),
                params.getProcessTime(),
                params.jsonOutput);

        if (visitorParameters.getResumeFileName() != null) {
            handler.setProgressFileName(visitorParameters.getResumeFileName());
        }

        visitorParameters.setControlHandler(handler.getControlHandler());
        if (visitorParameters.getRemoteDataHandler() == null) {
            visitorParameters.setLocalDataHandler(handler.getDataHandler());
        }

        if (params.getStatisticsParts() != null) {
            String[] parts = params.getStatisticsParts().split(",");
            for (String s : parts) {
                visitorParameters.setLibraryParameter(s, "true");
            }
        }

        try {
            session = sessionAccessor.createVisitorSession(visitorParameters);
            while (true) {
                try {
                    if (session.waitUntilDone(params.getFullTimeout())) break;
                } catch (InterruptedException e) {}
            }

            if (visitorParameters.getTraceLevel() > 0) {
                System.out.println(session.getTrace().toString());
            }
        } catch (ParseException e) {
            onDocumentSelectionException(e);
        } catch (IllegalArgumentException e) {
            onIllegalArgumentException(e);
        } catch (Exception e) {
            System.err.println("Document selection string was: " + visitorParameters.getDocumentSelection());
            System.err.println("Caught unexpected exception: ");
            e.printStackTrace(System.err);
            return 1;
        }
        if (visitorParameters.getControlHandler().getResult().code
                == VisitorControlHandler.CompletionCode.SUCCESS)
        {
            return 0;
        } else {
            return 1;
        }
    }

    private void initShutdownHook() {
        shutdownHookRegistrar.registerShutdownHook(new CleanUpThread());
    }

    class CleanUpThread extends Thread {
        public void run() {
            try {
                if (session != null) {
                    session.destroy();
                }
            } catch (IllegalStateException ise) {
                //ignore this
            }
            try {
                if (sessionAccessor != null) {
                    sessionAccessor.shutdown();
                }
            } catch (IllegalStateException ise) {
                //ignore this too
            }
        }
    }
}


text:
<?php
namespace Dp\Adaptor;

abstract class DinnerAdaptorAbstract
{
	protected $type;
	protected $budget;

	public function setType($type)
	{
		$this->type	= $type;
	}

	public function getType()
	{
		return $this->type;
	}

	public function setBudget($budget)
	{
		$this->budget	= $budget;
	}

	public function getBudget()
	{
		return $this->budget;
	}
}


text:
/**
 */
package eu.scasefp7.eclipse.storyboards.util;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.util.Switch;

import eu.scasefp7.eclipse.storyboards.*;

/**
 *
 * The Switch for the model's inheritance hierarchy.
 * It supports the call {@link #doSwitch(EObject) doSwitch(object)} to invoke the caseXXX method for each
 * class of the model,
 * starting with the actual class of the object
 * and proceeding up the inheritance hierarchy
 * until a non-null result is returned,
 * which is the result of the switch.
 *
 * @see eu.scasefp7.eclipse.storyboards.StoryboardsPackage
 * @generated
 */
public class StoryboardsSwitch<T> extends Switch<T> {
	/**
	 * The cached model package
	 *
	 *
	 * @generated
	 */
	protected static StoryboardsPackage modelPackage;

	/**
	 * Creates an instance of the switch.
	 *
	 *
	 * @generated
	 */
	public StoryboardsSwitch() {
		if (modelPackage == null) {
			modelPackage = StoryboardsPackage.eINSTANCE;
		}
	}

	/**
	 * Checks whether this is a switch for the given package.
	 *
	 *
	 * @param ePackage the package in question.
	 * @return whether this is a switch for the given package.
	 * @generated
	 */
	@Override
	protected boolean isSwitchFor(EPackage ePackage) {
		return ePackage == modelPackage;
	}

	/**
	 * Calls caseXXX for each class of the model until one returns a non null result; it yields that result.
	 *
	 *
	 * @return the first non-null result returned by a caseXXX call.
	 * @generated
	 */
	@Override
	protected T doSwitch(int classifierID, EObject theEObject) {
		switch (classifierID) {
			case StoryboardsPackage.PROPERTY: {
				Property property = (Property)theEObject;
				T result = caseProperty(property);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.STORYBOARD_DIAGRAM: {
				StoryboardDiagram storyboardDiagram = (StoryboardDiagram)theEObject;
				T result = caseStoryboardDiagram(storyboardDiagram);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.ACTION: {
				Action action = (Action)theEObject;
				T result = caseAction(action);
				if (result == null) result = caseActionNode(action);
				if (result == null) result = caseNode(action);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.NODE: {
				Node node = (Node)theEObject;
				T result = caseNode(node);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.CONDITION: {
				Condition condition = (Condition)theEObject;
				T result = caseCondition(condition);
				if (result == null) result = caseNode(condition);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.START_NODE: {
				StartNode startNode = (StartNode)theEObject;
				T result = caseStartNode(startNode);
				if (result == null) result = caseNode(startNode);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.END_NODE: {
				EndNode endNode = (EndNode)theEObject;
				T result = caseEndNode(endNode);
				if (result == null) result = caseNode(endNode);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.CONDITION_PATH: {
				ConditionPath conditionPath = (ConditionPath)theEObject;
				T result = caseConditionPath(conditionPath);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.STORYBOARD: {
				Storyboard storyboard = (Storyboard)theEObject;
				T result = caseStoryboard(storyboard);
				if (result == null) result = caseActionNode(storyboard);
				if (result == null) result = caseNode(storyboard);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			case StoryboardsPackage.ACTION_NODE: {
				ActionNode actionNode = (ActionNode)theEObject;
				T result = caseActionNode(actionNode);
				if (result == null) result = caseNode(actionNode);
				if (result == null) result = defaultCase(theEObject);
				return result;
			}
			default: return defaultCase(theEObject);
		}
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Property'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Property'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseProperty(Property object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Storyboard Diagram'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Storyboard Diagram'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseStoryboardDiagram(StoryboardDiagram object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Action'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Action'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseAction(Action object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Node'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Node'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseNode(Node object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Condition'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Condition'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseCondition(Condition object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Start Node'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Start Node'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseStartNode(StartNode object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'End Node'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'End Node'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseEndNode(EndNode object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Condition Path'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Condition Path'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseConditionPath(ConditionPath object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Storyboard'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Storyboard'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseStoryboard(Storyboard object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'Action Node'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'Action Node'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject)
	 * @generated
	 */
	public T caseActionNode(ActionNode object) {
		return null;
	}

	/**
	 * Returns the result of interpreting the object as an instance of 'EObject'.
	 *
	 * This implementation returns null;
	 * returning a non-null result will terminate the switch, but this is the last case anyway.
	 *
	 * @param object the target of the switch.
	 * @return the result of interpreting the object as an instance of 'EObject'.
	 * @see #doSwitch(org.eclipse.emf.ecore.EObject)
	 * @generated
	 */
	@Override
	public T defaultCase(EObject object) {
		return null;
	}

} // StoryboardsSwitch