text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#ifndef EIGEN_VISITOR_H
#define EIGEN_VISITOR_H

template<typename Visitor, typename Derived, int UnrollCount>
struct ei_visitor_impl
{
  enum {
    col = (UnrollCount-1) / Derived::RowsAtCompileTime,
    row = (UnrollCount-1) % Derived::RowsAtCompileTime
  };

  inline static void run(const Derived &mat, Visitor& visitor)
  {
    ei_visitor_impl<Visitor, Derived, UnrollCount-1>::run(mat, visitor);
    visitor(mat.coeff(row, col), row, col);
  }
};

template<typename Visitor, typename Derived>
struct ei_visitor_impl<Visitor, Derived, 1>
{
  inline static void run(const Derived &mat, Visitor& visitor)
  {
    return visitor.init(mat.coeff(0, 0), 0, 0);
  }
};

template<typename Visitor, typename Derived>
struct ei_visitor_impl<Visitor, Derived, Dynamic>
{
  typedef typename Derived::Index Index;
  inline static void run(const Derived& mat, Visitor& visitor)
  {
    visitor.init(mat.coeff(0,0), 0, 0);
    for(Index i = 1; i < mat.rows(); ++i)
      visitor(mat.coeff(i, 0), i, 0);
    for(Index j = 1; j < mat.cols(); ++j)
      for(Index i = 0; i < mat.rows(); ++i)
        visitor(mat.coeff(i, j), i, j);
  }
};

/** Applies the visitor \a visitor to the whole coefficients of the matrix or vector.
  *
  * The template parameter \a Visitor is the type of the visitor and provides the following interface:
  * \code
  * struct MyVisitor {
  *   // called for the first coefficient
  *   void init(const Scalar& value, Index i, Index j);
  *   // called for all other coefficients
  *   void operator() (const Scalar& value, Index i, Index j);
  * };
  * \endcode
  *
  * \note compared to one or two \em for \em loops, visitors offer automatic
  * unrolling for small fixed size matrix.
  *
  * \sa minCoeff(Index*,Index*), maxCoeff(Index*,Index*), DenseBase::redux()
  */
template<typename Derived>
template<typename Visitor>
void DenseBase<Derived>::visit(Visitor& visitor) const
{
  enum { unroll = SizeAtCompileTime != Dynamic
                   && CoeffReadCost != Dynamic
                   && (SizeAtCompileTime == 1 || ei_functor_traits<Visitor>::Cost != Dynamic)
                   && SizeAtCompileTime * CoeffReadCost + (SizeAtCompileTime-1) * ei_functor_traits<Visitor>::Cost
                      <= EIGEN_UNROLLING_LIMIT };
  return ei_visitor_impl<Visitor, Derived,
      unroll ? int(SizeAtCompileTime) : Dynamic
    >::run(derived(), visitor);
}

/** \internal
  * \brief Base class to implement min and max visitors
  */
template <typename Derived>
struct ei_coeff_visitor
{
  typedef typename Derived::Index Index;
  typedef typename Derived::Scalar Scalar;
  Index row, col;
  Scalar res;
  inline void init(const Scalar& value, Index i, Index j)
  {
    res = value;
    row = i;
    col = j;
  }
};

/** \internal
  * \brief Visitor computing the min coefficient with its value and coordinates
  *
  * \sa DenseBase::minCoeff(Index*, Index*)
  */
template <typename Derived>
struct ei_min_coeff_visitor : ei_coeff_visitor<Derived>
{
  typedef typename Derived::Index Index;
  typedef typename Derived::Scalar Scalar;
  void operator() (const Scalar& value, Index i, Index j)
  {
    if(value < this->res)
    {
      this->res = value;
      this->row = i;
      this->col = j;
    }
  }
};

template<typename Scalar>
struct ei_functor_traits<ei_min_coeff_visitor<Scalar> > {
  enum {
    Cost = NumTraits<Scalar>::AddCost
  };
};

/** \internal
  * \brief Visitor computing the max coefficient with its value and coordinates
  *
  * \sa DenseBase::maxCoeff(Index*, Index*)
  */
template <typename Derived>
struct ei_max_coeff_visitor : ei_coeff_visitor<Derived>
{
  typedef typename Derived::Index Index;
  typedef typename Derived::Scalar Scalar;
  void operator() (const Scalar& value, Index i, Index j)
  {
    if(value > this->res)
    {
      this->res = value;
      this->row = i;
      this->col = j;
    }
  }
};

template<typename Scalar>
struct ei_functor_traits<ei_max_coeff_visitor<Scalar> > {
  enum {
    Cost = NumTraits<Scalar>::AddCost
  };
};

/** \returns the minimum of all coefficients of *this
  * and puts in *row and *col its location.
  *
  * \sa DenseBase::minCoeff(Index*), DenseBase::maxCoeff(Index*,Index*), DenseBase::visitor(), DenseBase::minCoeff()
  */
template<typename Derived>
typename ei_traits<Derived>::Scalar
DenseBase<Derived>::minCoeff(Index* row, Index* col) const
{
  ei_min_coeff_visitor<Derived> minVisitor;
  this->visit(minVisitor);
  *row = minVisitor.row;
  if (col) *col = minVisitor.col;
  return minVisitor.res;
}

/** \returns the minimum of all coefficients of *this
  * and puts in *index its location.
  *
  * \sa DenseBase::minCoeff(Index*,Index*), DenseBase::maxCoeff(Index*,Index*), DenseBase::visitor(), DenseBase::minCoeff()
  */
template<typename Derived>
typename ei_traits<Derived>::Scalar
DenseBase<Derived>::minCoeff(Index* index) const
{
  EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
  ei_min_coeff_visitor<Derived> minVisitor;
  this->visit(minVisitor);
  *index = (RowsAtCompileTime==1) ? minVisitor.col : minVisitor.row;
  return minVisitor.res;
}

/** \returns the maximum of all coefficients of *this
  * and puts in *row and *col its location.
  *
  * \sa DenseBase::minCoeff(Index*,Index*), DenseBase::visitor(), DenseBase::maxCoeff()
  */
template<typename Derived>
typename ei_traits<Derived>::Scalar
DenseBase<Derived>::maxCoeff(Index* row, Index* col) const
{
  ei_max_coeff_visitor<Derived> maxVisitor;
  this->visit(maxVisitor);
  *row = maxVisitor.row;
  if (col) *col = maxVisitor.col;
  return maxVisitor.res;
}

/** \returns the maximum of all coefficients of *this
  * and puts in *index its location.
  *
  * \sa DenseBase::maxCoeff(Index*,Index*), DenseBase::minCoeff(Index*,Index*), DenseBase::visitor(), DenseBase::maxCoeff()
  */
template<typename Derived>
typename ei_traits<Derived>::Scalar
DenseBase<Derived>::maxCoeff(Index* index) const
{
  EIGEN_STATIC_ASSERT_VECTOR_ONLY(Derived)
  ei_max_coeff_visitor<Derived> maxVisitor;
  this->visit(maxVisitor);
  *index = (RowsAtCompileTime==1) ? maxVisitor.col : maxVisitor.row;
  return maxVisitor.res;
}

#endif // EIGEN_VISITOR_H


text:
namespace fs = boost::filesystem;

namespace RCF {

    // FileStream

    FileStream::FileStream() : mImplPtr( new FileStreamImpl() )
    {
    }

    FileStream::FileStream(FileStreamImplPtr implPtr) :
        mImplPtr(implPtr)
    {
    }

    FileStream::FileStream(const std::string & filePath) :
        mImplPtr(new FileStreamImpl(filePath) )
    {
    }

    FileStream::FileStream(const FileManifest & manifest) :
        mImplPtr(new FileStreamImpl(manifest) )
    {
    }

    std::string FileStream::getLocalPath() const
    {
        RCF_ASSERT(mImplPtr);
        FileManifest & manifest = mImplPtr->mManifest;
        fs::path localPath = manifest.mManifestBase;
        RCF_ASSERT(manifest.mFiles.size() > 0);
        localPath /= (*manifest.mFiles[0].mFilePath.begin());
        return nativeString(localPath);
    }

    FileManifest & FileStream::getManifest() const
    {
        RCF_ASSERT(mImplPtr);
        return mImplPtr->mManifest;
    }

    void FileStream::setDownloadToPath(const std::string & downloadToPath)
    {
        RCF_ASSERT(mImplPtr);
        mImplPtr->mDownloadToPath = downloadToPath;
    }

    std::string FileStream::getDownloadToPath() const
    {
        RCF_ASSERT(mImplPtr);
        return nativeString(mImplPtr->mDownloadToPath);
    }

    void FileStream::setTransferRateBps(boost::uint32_t transferRateBps)
    {
        RCF_ASSERT(mImplPtr);
        mImplPtr->mTransferRateBps = transferRateBps;
    }

    boost::uint32_t FileStream::getTransferRateBps()
    {
        RCF_ASSERT(mImplPtr);
        return mImplPtr->mTransferRateBps;
    }

#if RCF_FEATURE_SF==1

    void FileStream::serialize(SF::Archive & ar)
    {
        ar & *mImplPtr;
    }

    void FileStreamImpl::serializeImplSf(
        SF::Archive & ar,
        boost::uint32_t & transferId,
        Direction & dir)
    {
        ar & transferId & dir;
    }

    void FileStreamImpl::serialize(SF::Archive & ar)
    {
        bool isSaving = ar.isWrite();

        serializeGeneric(
            isSaving,
            boost::bind(
                &FileStreamImpl::serializeImplSf,
                this,
                boost::ref(ar),
                _1,
                _2) );
    }

#endif

    void FileStream::upload(RCF::ClientStub & clientStub)
    {
        boost::uint32_t chunkSize = 1024*1024;

        clientStub.uploadFiles(
            mImplPtr->mManifest,
            mImplPtr->mUploadId,
            chunkSize,
            mImplPtr->mTransferRateBps,
            mImplPtr->mSessionLocalId);

        mImplPtr->mSessionLocalId = 0;
    }

    fs::path makeTempDir(const fs::path & basePath, const std::string & prefix);

    void FileStream::download(RCF::ClientStub & clientStub)
    {
        boost::uint32_t chunkSize = 1024*1024;

        if (mImplPtr->mDownloadToPath.empty())
        {
            mImplPtr->mDownloadToPath = makeTempDir("RCF-Downloads", "");
        }

        clientStub.downloadFiles(
            nativeString(mImplPtr->mDownloadToPath),
            mImplPtr->mManifest,
            chunkSize,
            mImplPtr->mTransferRateBps,
            mImplPtr->mSessionLocalId);

        mImplPtr->mManifest.mManifestBase = mImplPtr->mDownloadToPath;
        mImplPtr->mSessionLocalId = 0;
    }

    // FileStreamImpl

    FileStreamImpl::FileStreamImpl() :
        mTransferRateBps(0),
        mSessionLocalId(0),
        mDirection(Unspecified)
    {
    }

    FileStreamImpl::FileStreamImpl(const std::string & filePath) :
        mManifest(filePath),
        mTransferRateBps(0),
        mSessionLocalId(0),
        mDirection(Unspecified)
    {
    }

    FileStreamImpl::FileStreamImpl(const FileManifest & manifest) :
        mManifest(manifest),
        mTransferRateBps(0),
        mSessionLocalId(0),
        mDirection(Unspecified)
    {
    }

    FileStreamImpl::~FileStreamImpl()
    {
    }

    void FileStreamImpl::serializeGeneric(
        bool isWriting,
        boost::function2<void, boost::uint32_t &, Direction &> serializeImpl)
    {
        // Determine if we are client side or server side.
        // TODO: what if both of these are non-zero?
        RCF::ClientStub * pClientStub = RCF::getTlsClientStubPtr();
        RCF::RcfSession * pSession = RCF::getTlsRcfSessionPtr();

        // Client side.
        // Append a ref to ourselves the the current ClientStub.
        // After serializing regular parameters, we'll regain control.
        if (pClientStub)
        {
            if (isWriting)
            {
                if (mDirection == Upload)
                {
                    mSessionLocalId = pClientStub->addUploadStream(
                        FileUpload(shared_from_this()));
                }
                else if (mDirection == Download)
                {
                    mSessionLocalId = pClientStub->addDownloadStream(
                        FileDownload(shared_from_this()));
                }

                serializeImpl(mSessionLocalId, mDirection);
            }
            else
            {
                // Shouldn't really be in here.
                boost::uint32_t sessionLocalId = 0;
                Direction dir = Unspecified;
                serializeImpl(sessionLocalId, dir);
            }
        }
        else if (pSession)
        {
            if (isWriting)
            {
                // Shouldn't really be in here.
                boost::uint32_t sessionLocalId = 0;
                Direction dir = Unspecified;
                serializeImpl(sessionLocalId, dir);
            }
            else
            {
                serializeImpl(mSessionLocalId, mDirection);

                if (mDirection == Upload && mSessionLocalId)
                {
                    RcfSession::SessionUploads::iterator iter =
                        pSession->mSessionUploads.find(mSessionLocalId);

                    if (iter != pSession->mSessionUploads.end())
                    {
                        FileUploadInfoPtr uploadPtr = iter->second;
                        mManifest = uploadPtr->mManifest;
                        mManifest.mManifestBase = uploadPtr->mUploadPath;

                        pSession->mSessionUploads.erase(iter);
                    }
                    else
                    {
                        // Couldn't find the upload.
                    }
                }
                else if (mDirection == Download && mSessionLocalId)
                {
                    pSession->addDownloadStream(
                        mSessionLocalId,
                        FileDownload(shared_from_this()));
                }
            }
        }
    }

    // FileUpload

    FileUpload::FileUpload()
    {
        mImplPtr->mDirection = FileStreamImpl::Upload;
    }

    FileUpload::FileUpload(const std::string & filePath) : FileStream(filePath)
    {
        mImplPtr->mDirection = FileStreamImpl::Upload;
    }

    FileUpload::FileUpload(const FileManifest & manifest) : FileStream(manifest)
    {
        mImplPtr->mDirection = FileStreamImpl::Upload;
    }

    FileUpload::FileUpload(FileStreamImplPtr implPtr) : FileStream(implPtr)
    {
        mImplPtr->mDirection = FileStreamImpl::Upload;
    }

    // FileDownload

    FileDownload::FileDownload()
    {
        mImplPtr->mDirection = FileStreamImpl::Download;
    }

    FileDownload::FileDownload(const std::string & filePath) : FileStream(filePath)
    {
        mImplPtr->mDirection = FileStreamImpl::Download;
    }

    FileDownload::FileDownload(const FileManifest & manifest) : FileStream(manifest)
    {
        mImplPtr->mDirection = FileStreamImpl::Download;
    }

    FileDownload::FileDownload(FileStreamImplPtr implPtr) : FileStream(implPtr)
    {
        mImplPtr->mDirection = FileStreamImpl::Download;
    }

    // ClientStub

    boost::uint32_t ClientStub::addUploadStream(FileUpload fileStream)
    {
        mUploadStreams.push_back(fileStream);
        return static_cast<boost::uint32_t>(mUploadStreams.size());
    }

    void ClientStub::processUploadStreams()
    {
        ThreadLocalCached< std::vector<FileUpload> > tlcFileStreams;
        std::vector<FileUpload> & fileStreams = tlcFileStreams.get();
        RCF_ASSERT(fileStreams.empty());
        fileStreams.swap(mUploadStreams);
        for (std::size_t i=0; i<fileStreams.size(); ++i)
        {
            fileStreams[i].upload(*this);
        }
    }

    boost::uint32_t ClientStub::addDownloadStream(FileDownload fileStream)
    {
        mDownloadStreams.push_back(fileStream);
        return static_cast<boost::uint32_t>(mDownloadStreams.size());
    }

    void ClientStub::setFileProgressCallback(FileProgressCb fileProgressCb)
    {
        mFileProgressCb = fileProgressCb;
    }

    void ClientStub::setTransferWindowS(boost::uint32_t transferWindowS)
    {
        mTransferWindowS = transferWindowS;
    }

    boost::uint32_t ClientStub::getTransferWindowS()
    {
        return mTransferWindowS;
    }

    // TODO: resuming of failed transfers, in either direction.

    boost::uint32_t calculateEffectiveBps(
        boost::uint32_t serverBps,
        boost::uint32_t clientBps)
    {
        boost::uint32_t effectiveBps = 0;
        if (serverBps == 0)
        {
            effectiveBps = clientBps;
        }
        else if (clientBps == 0)
        {
            effectiveBps = serverBps;
        }
        else
        {
            effectiveBps = (std::min)(serverBps, clientBps);
        }
        return effectiveBps;
    }

    void ClientStub::uploadFiles(
        const std::string & whichFile,
        std::string & uploadId,
        boost::uint32_t chunkSize,
        boost::uint32_t transferRateBps,
        boost::uint32_t sessionLocalId)
    {
        RCF::FileManifest manifest(whichFile);
        uploadFiles(manifest, uploadId, chunkSize, transferRateBps, sessionLocalId);
    }

    void ClientStub::uploadFiles(
        const FileManifest & manifest,
        std::string & uploadId,
        boost::uint32_t chunkSize,
        boost::uint32_t transferRateBps,
        boost::uint32_t sessionLocalId)
    {
        RCF_LOG_3()(manifest.mFiles.size())(chunkSize)(sessionLocalId)
            << "ClientStub::uploadFiles() - entry.";

        ClientStub & clientStub = *this;

        if (! clientStub.isConnected())
        {
            clientStub.connect();
        }

        RcfClient<I_FileTransferService> ftsClient(clientStub);
        ftsClient.getClientStub().setTransport( clientStub.releaseTransport() );
        ftsClient.getClientStub().setTargetToken( Token());

        RestoreClientTransportGuard guard(clientStub, ftsClient.getClientStub());
        RCF_UNUSED_VARIABLE(guard);

        // 1) Send manifest to server, and an optimistic first chunk.
        // 2) Server replies, with index, pos and CRC of next chunk to transfer.
        // --> CRC only passed if pos != chunk length
        // 3) Client goes into a loop, sending chunks until all files are transferred.

        namespace fs = boost::filesystem;

        fs::path manifestBase = manifest.mManifestBase;

        FileChunk startPos;
        boost::uint32_t maxMessageLength    = 0;
        boost::uint32_t clientBps           = transferRateBps;
        boost::uint32_t serverBps           = 0;
        boost::uint32_t effectiveBps        = 0;

        RCF_LOG_3()(manifest.mFiles.size())(chunkSize)(sessionLocalId)
            << "ClientStub::uploadFiles() - calling BeginUpload().";

        ftsClient.BeginUpload(
            manifest,
            std::vector<FileChunk>(),
            startPos,
            maxMessageLength,
            uploadId,
            serverBps,
            sessionLocalId);

        RCF_LOG_3()(startPos.mFileIndex)(startPos.mOffset)(maxMessageLength)(uploadId)(serverBps)
            << "ClientStub::uploadFiles() - BeginUpload() returned.";

        boost::uint64_t totalByteSize = manifest.getTotalByteSize();

        boost::uint64_t totalBytesUploadedSoFar = 0;
        for (std::size_t i=0; i<startPos.mFileIndex; ++i)
        {
            totalBytesUploadedSoFar += manifest.mFiles[i].mFileSize;
        }
        totalBytesUploadedSoFar += startPos.mOffset;

        // Progress callback.
        FileTransferProgress progressInfo;
        progressInfo.mBytesTotalToTransfer = totalByteSize;
        progressInfo.mBytesTransferredSoFar = totalBytesUploadedSoFar;
        progressInfo.mServerLimitBps = serverBps;
        if (mFileProgressCb)
        {
            mFileProgressCb(progressInfo);
        }

        boost::uint32_t firstFile = startPos.mFileIndex;
        boost::uint64_t firstPos = startPos.mOffset;

        // Limit the chunk size to 80 % of max message length.
        if (maxMessageLength == 0)
        {
            chunkSize = 1024*1024;
        }
        else
        {
            chunkSize = RCF_MIN(chunkSize, maxMessageLength*8/10);
        }

        effectiveBps = calculateEffectiveBps(serverBps, clientBps);

        Timer windowTimer;
        boost::uint32_t windowBytesTotal    = mTransferWindowS*effectiveBps;
        boost::uint32_t windowBytesSoFar    = 0;

        std::vector<FileChunk> chunks;

        // Async file reading.
        FileIoRequestPtr readOp( new FileIoRequest() );
        ByteBuffer bufferRead(chunkSize);
        ByteBuffer bufferSend(chunkSize);

        std::size_t bufferReadPos = 0;

        std::size_t currentFile = firstFile;

        // Skip zero-size entries.
        while (     currentFile < manifest.mFiles.size()
            &&  manifest.mFiles[currentFile].mFileSize == 0)
        {
            ++currentFile;
        }

        while (currentFile != manifest.mFiles.size())
        {
            const FileInfo & info = manifest.mFiles[currentFile];
            fs::path filePath = manifestBase / info.mFilePath;

            // Upload chunks to the server until we're done.

            RCF_LOG_3()(filePath)
                << "ClientStub::uploadFiles() - opening file.";

            IfstreamPtr fin( new std::ifstream(
                filePath.string().c_str(),
                std::ios::binary));

            RCF_VERIFY(*fin, Exception(_RcfError_FileOpen(nativeString(filePath))));

            boost::uint64_t filePos = 0;
            if (currentFile == firstFile)
            {
                filePos = firstPos;

                RCF_LOG_3()(filePos)
                    << "ClientStub::uploadFiles() - seeking in file.";

                fin->seekg( static_cast<std::streamoff>(filePos) );
            }

            readOp->complete();

            const boost::uint64_t FileSize = fs::file_size(filePath);
            while (filePos < FileSize)
            {
                std::size_t bytesRead = 0;

                bool shouldSend = false;
                bool shouldReadAhead = true;

                // Wait for current read to complete.
                if (readOp->isInitiated())
                {
                    readOp->complete();

                    bytesRead = static_cast<std::size_t>(
                        readOp->getBytesTransferred());

                    RCF_LOG_3()(bytesRead)
                        << "ClientStub::uploadFiles() - completing read from file.";

                    RCF_VERIFY(
                        bytesRead > 0,
                        Exception(_RcfError_FileRead(nativeString(filePath), filePos)));

                    FileChunk chunk;
                    chunk.mFileIndex = (boost::uint32_t) currentFile;
                    chunk.mOffset = filePos;
                    chunk.mData = ByteBuffer(bufferRead, bufferReadPos, bytesRead);

                    RCF_LOG_3()(chunk.mFileIndex)(chunk.mOffset)(chunk.mData.getLength())
                        << "ClientStub::uploadFiles() - adding chunk.";

                    chunks.push_back( chunk );

                    bufferReadPos += bytesRead;
                    filePos += bytesRead;
                    windowBytesSoFar += (boost::uint32_t) bytesRead;

                    if (bufferReadPos == bufferRead.getLength())
                    {
                        shouldSend = true;
                    }

                    if (effectiveBps && windowBytesSoFar >= windowBytesTotal)
                    {
                        shouldSend = true;
                    }

                    if (filePos == FileSize)
                    {
                        ++currentFile;

                        // Skip zero-size entries.
                        while (     currentFile < manifest.mFiles.size()
                                &&  manifest.mFiles[currentFile].mFileSize == 0)
                        {
                            ++currentFile;
                        }

                        // Have we done all the files?
                        if (currentFile == manifest.mFiles.size())
                        {
                            shouldSend = true;
                        }

                        // No read ahead if we are transitioning from one file to another.
                        shouldReadAhead = false;
                    }

                    if (shouldSend)
                    {
                        bufferSend.swap(bufferRead);
                        bufferReadPos = 0;
                    }
                }

                // Read ahead.
                if (shouldReadAhead)
                {
                    RCF_LOG_3()(bufferRead.getLength())(bufferReadPos)
                        << "ClientStub::uploadFiles() - initiating read from file.";

                    RCF_ASSERT_LT(bufferReadPos, bufferRead.getLength());

                    std::size_t bytesToRead =
                        static_cast<std::size_t>(bufferRead.getLength() - bufferReadPos);

                    // Trim to throttle settings.
                    if (effectiveBps)
                    {
                        if (windowBytesSoFar < windowBytesTotal)
                        {
                            boost::uint32_t windowBytesRemaining =
                                windowBytesTotal - windowBytesSoFar;

                            bytesToRead = RCF_MIN(
                                static_cast<boost::uint32_t>(bytesToRead),
                                windowBytesRemaining);
                        }
                        else
                        {
                            bytesToRead = 0;
                        }

                        RCF_LOG_3()(bytesToRead)(windowBytesSoFar)(windowBytesTotal)
                            << "ClientStub::uploadFiles() - trimming chunk size to throttle setting.";
                    }

                    if (bytesToRead)
                    {
                        readOp->initiateRead(fin, ByteBuffer(bufferRead, bufferReadPos, bytesToRead));
                    }
                }

                // Upload accumulated file chunks.
                if (shouldSend)
                {
                    RCF_LOG_3()(chunks.size())
                        << "ClientStub::uploadFiles() - calling UploadChunks().";

                    ftsClient.UploadChunks(chunks, serverBps);

                    effectiveBps = calculateEffectiveBps(serverBps, clientBps);

                    RCF_LOG_3()(serverBps)
                        << "ClientStub::uploadFiles() - UploadChunks() returned.";

                    std::size_t bytesSent = 0;
                    for (std::size_t i=0; i<chunks.size(); ++i)
                    {
                        bytesSent += chunks[i].mData.getLength();
                    }
                    totalBytesUploadedSoFar += bytesSent;

                    chunks.clear();

                    // Progress callback.
                    progressInfo.mBytesTotalToTransfer = totalByteSize;
                    progressInfo.mBytesTransferredSoFar = totalBytesUploadedSoFar;
                    progressInfo.mServerLimitBps = serverBps;
                    if (mFileProgressCb)
                    {
                        mFileProgressCb(progressInfo);
                    }

                    if (effectiveBps)
                    {
                        // Recalculate window size based on possibly updated bps setting.
                        windowBytesTotal = mTransferWindowS * effectiveBps;
                        if (windowBytesSoFar >= windowBytesTotal)
                        {
                            RCF_LOG_3()(windowBytesSoFar)(windowBytesTotal)
                                << "ClientStub::uploadFiles() - window capacity reached.";

                            // Exceeded window capacity. Wait for window to expire.
                            boost::uint32_t windowMsSoFar = windowTimer.getDurationMs();
                            if (windowMsSoFar < mTransferWindowS*1000)
                            {
                                boost::uint32_t waitMs = mTransferWindowS*1000 - windowMsSoFar;

                                RCF_LOG_3()(waitMs)
                                    << "ClientStub::uploadFiles() - waiting for next window.";

                                sleepMs(waitMs);
                                while (!windowTimer.elapsed(mTransferWindowS*1000))
                                {
                                    sleepMs(100);
                                }
                            }
                        }

                        // If window has expired, open a new one.
                        if (windowTimer.elapsed(mTransferWindowS*1000))
                        {
                            windowTimer.restart();

                            // Carry over balance from previous window.
                            if (windowBytesSoFar > windowBytesTotal)
                            {
                                windowBytesSoFar = windowBytesSoFar - windowBytesTotal;
                            }
                            else
                            {
                                windowBytesSoFar = 0;
                            }

                            RCF_LOG_3()(mTransferWindowS)(windowBytesSoFar)
                                << "ClientStub::uploadFiles() - new transfer window.";
                        }
                    }
                }
            }
        }
        RCF_LOG_3()(totalByteSize)(totalBytesUploadedSoFar)
            << "ClientStub::uploadFiles() - exit.";
    }

    void trimManifest(
        const FileManifest & manifest,
        boost::uint64_t & bytesAlreadyTransferred,
        FileChunk & startPos)
    {
        fs::path manifestBase = manifest.mManifestBase;
        RCF_ASSERT(!manifestBase.empty());

        bytesAlreadyTransferred = 0;
        startPos = FileChunk();

        std::size_t whichFile=0;
        boost::uint64_t offset = 0;

        for (whichFile=0; whichFile<manifest.mFiles.size(); ++whichFile)
        {
            const FileInfo & fileInfo = manifest.mFiles[whichFile];
            fs::path p = manifestBase / fileInfo.mFilePath;

            if (!fs::exists(p))
            {
                break;
            }

            if (fs::is_directory(p) && fileInfo.mIsDirectory)
            {
                continue;
            }

            if (fs::is_directory(p) && !fileInfo.mIsDirectory)
            {
                break;
            }

            RCF_ASSERT(fs::exists(p) && !fs::is_directory(p));

            boost::uint64_t fileSize = fs::file_size(p);

            if (fileSize < fileInfo.mFileSize)
            {
                bytesAlreadyTransferred += fileSize;
                offset = fileSize;
                break;
            }

            if (fileSize > fileInfo.mFileSize)
            {
                break;
            }

            RCF_ASSERT_EQ(fileSize , fileInfo.mFileSize);

            bytesAlreadyTransferred += fileSize;
        }

        if (whichFile <= manifest.mFiles.size())
        {
            startPos.mFileIndex = (boost::uint32_t) whichFile;
            startPos.mOffset = offset;
        }
    }

    void processZeroSizeEntries(
        FileManifest & manifest,
        const fs::path & manifestBase,
        boost::uint32_t & currentFile)
    {
        while (     currentFile < manifest.mFiles.size()
                &&  manifest.mFiles[currentFile].mFileSize == 0)
        {
            FileInfo & info = manifest.mFiles[currentFile];

            fs::path targetPath = manifestBase / info.mFilePath;
            if (info.mRenameFile.size() > 0)
            {
                targetPath = targetPath.branch_path() / info.mRenameFile;
            }

            if (info.mIsDirectory)
            {
                fs::create_directories(targetPath);
            }
            else
            {
                fs::path targetDir = (targetPath / "..").normalize();
                fs::create_directories(targetDir);

                std::ofstream fout(
                    nativeString(targetPath).c_str(),
                    std::ios::binary | std::ios::trunc );

                fout.close();

                std::time_t writeTime = info.mLastWriteTime;
                fs::last_write_time(targetPath, writeTime);
            }

            ++currentFile;
        }
    }

    void ClientStub::downloadFiles(
        const std::string & downloadLocation,
        FileManifest & totalManifest,
        boost::uint32_t chunkSize,
        boost::uint32_t transferRateBps,
        boost::uint32_t sessionLocalId)
    {
        RCF_LOG_3()(downloadLocation)(chunkSize)(transferRateBps)(sessionLocalId)
            << "ClientStub::downloadFiles() - entry.";

        ClientStub & clientStub = *this;

        if (! clientStub.isConnected())
        {
            clientStub.connect();
        }

        RCF::RcfClient<RCF::I_FileTransferService> ftsClient(clientStub);
        ftsClient.getClientStub().setTransport( clientStub.releaseTransport() );
        ftsClient.getClientStub().setTargetToken( Token());

        // Disable incoming max message length, as we can't say how big the
        // the manifest is going to be.
        ftsClient.getClientStub().getTransport().setMaxMessageLength(0);

        RestoreClientTransportGuard guard(clientStub, ftsClient.getClientStub());
        RCF_UNUSED_VARIABLE(guard);

        // Download chunks from the server until we're done.

        // TODO: optional first chunks.
        FileManifest manifest;
        FileTransferRequest request;
        std::vector<FileChunk> chunks;
        boost::uint32_t serverMaxMessageLength = 0;
        boost::uint32_t serverBps = 0;

        RCF_LOG_3()(downloadLocation)(chunkSize)(transferRateBps)(sessionLocalId)
            << "ClientStub::downloadFiles() - calling BeginDownload().";

        ftsClient.BeginDownload(
            manifest,
            request,
            chunks,
            serverMaxMessageLength,
            serverBps,
            sessionLocalId);

        boost::uint32_t clientMaxMessageLength = static_cast<boost::uint32_t>(
            getTransport().getMaxMessageLength());

        RCF_LOG_3()(manifest.mFiles.size())(serverMaxMessageLength)(clientMaxMessageLength)(serverBps)
            << "ClientStub::downloadFiles() - BeginDownload() returned.";

        chunkSize = RCF_MIN(chunkSize, serverMaxMessageLength*8/10);
        chunkSize = RCF_MIN(chunkSize, clientMaxMessageLength*8/10);

        fs::path manifestBase = downloadLocation;

        boost::uint32_t currentFile = 0;
        boost::uint64_t currentPos = 0;

        // See if we have any fragments already downloaded.
        bool resume = false;
        manifest.mManifestBase = downloadLocation;
        boost::uint64_t bytesAlreadyTransferred = 0;
        FileChunk startPos;
        trimManifest(manifest, bytesAlreadyTransferred, startPos);
        if (bytesAlreadyTransferred)
        {
            RCF_LOG_3()(startPos.mFileIndex)(startPos.mOffset)
                << "ClientStub::downloadFiles() - calling TrimDownload().";

            ftsClient.TrimDownload(startPos);

            RCF_LOG_3()(startPos.mFileIndex)(startPos.mOffset)
                << "ClientStub::downloadFiles() - TrimDownload() returned.";

            currentFile = startPos.mFileIndex;
            currentPos = startPos.mOffset;
            resume = true;
        }

        OfstreamPtr fout( new std::ofstream() );
        FileIoRequestPtr writeOp( new FileIoRequest() );

        boost::uint32_t adviseWaitMs = 0;

        // Calculate total byte count of the manifest.
        boost::uint64_t totalByteSize = manifest.getTotalByteSize();

        // Did we get any chunks on the BeginDownload() call?
        boost::uint64_t totalBytesReadSoFar = bytesAlreadyTransferred;
        RCF_ASSERT(chunks.empty());
        for (std::size_t i=0; i<chunks.size(); ++i)
        {
            totalBytesReadSoFar += chunks[i].mData.getLength();
        }

        // Progress callback.
        FileTransferProgress progressInfo;
        progressInfo.mBytesTotalToTransfer = totalByteSize;
        progressInfo.mBytesTransferredSoFar = totalBytesReadSoFar;
        progressInfo.mServerLimitBps = serverBps;
        if (mFileProgressCb)
        {
            mFileProgressCb(progressInfo);
        }

        const boost::uint32_t TransferWindowS = 5;
        RCF::Timer transferWindowTimer;
        boost::uint32_t transferWindowBytes = 0;
        bool localWait = false;

        processZeroSizeEntries(manifest, manifestBase, currentFile);

        while (currentFile != manifest.mFiles.size())
        {
            RCF_ASSERT(chunks.empty() || (currentFile == 0 && currentPos == 0));

            // Round trip to the server for more chunks.
            if (chunks.empty())
            {
                FileTransferRequest request;
                request.mFile = currentFile;
                request.mPos = currentPos;
                request.mChunkSize = chunkSize;

                // Respect server throttle settings.
                if (adviseWaitMs)
                {
                    RCF_LOG_3()(adviseWaitMs)
                        << "ClientStub::downloadFiles() - waiting on server throttle.";

                    // This needs to be a sub-second accurate sleep, or the timing tests will
                    // be thrown.
                    sleepMs(adviseWaitMs);
                    adviseWaitMs = 0;
                }

                // Respect local throttle setting.
                if (localWait)
                {
                    boost::uint32_t startTimeMs = transferWindowTimer.getStartTimeMs();
                    boost::uint32_t nowMs = getCurrentTimeMs();
                    if (nowMs < startTimeMs + 1000*TransferWindowS)
                    {
                        boost::uint32_t waitMs = startTimeMs + 1000*TransferWindowS - nowMs;

                        RCF_LOG_3()(waitMs)(mTransferWindowS)
                            << "ClientStub::downloadFiles() - waiting on client throttle.";

                        // Existing behavior - if we're going to wait, wait at least a second.
                        waitMs = RCF_MAX(boost::uint32_t(1000), waitMs);
                        RCF::sleepMs(waitMs);
                        localWait = false;
                    }
                }

                // Trim chunk size according to transfer rate.
                if (transferRateBps)
                {
                    if (transferWindowTimer.elapsed(TransferWindowS*1000))
                    {
                        transferWindowTimer.restart();
                        transferWindowBytes = 0;
                    }

                    boost::uint32_t bytesTotal = transferRateBps * TransferWindowS;
                    boost::uint32_t bytesRemaining =  bytesTotal - transferWindowBytes;

                    if (bytesRemaining < request.mChunkSize)
                    {
                        localWait = true;
                    }

                    RCF_LOG_3()(request.mChunkSize)(bytesRemaining)
                        << "ClientStub::downloadFiles() - trimming request chunk size to client throttle.";

                    request.mChunkSize = RCF_MIN(request.mChunkSize, bytesRemaining);
                }

                RCF_LOG_3()(request.mFile)(request.mPos)(request.mChunkSize)(startPos.mOffset)
                    << "ClientStub::downloadFiles() - calling DownloadChunks().";

                ftsClient.DownloadChunks(request, chunks, adviseWaitMs, serverBps);

                RCF_LOG_3()(chunks.size())(adviseWaitMs)(serverBps)
                    << "ClientStub::downloadFiles() - DownloadChunks() returned.";

                // Update byte totals.
                for (std::size_t i=0; i<chunks.size(); ++i)
                {
                    totalBytesReadSoFar += chunks[i].mData.getLength();
                    transferWindowBytes += (boost::uint32_t) chunks[i].mData.getLength();
                }

                // Progress callback.
                progressInfo.mBytesTotalToTransfer = totalByteSize;
                progressInfo.mBytesTransferredSoFar = totalBytesReadSoFar;
                progressInfo.mServerLimitBps = serverBps;
                if (mFileProgressCb)
                {
                    mFileProgressCb(progressInfo);
                }
            }

            // Write to disk.
            for (std::size_t i=0; i<chunks.size(); ++i)
            {
                const FileChunk & chunk = chunks[i];

                if (chunk.mFileIndex != currentFile || chunk.mOffset != currentPos)
                {
                    // TODO: error
                    RCF_ASSERT(0);
                }

                FileInfo & info = manifest.mFiles[currentFile];

                fs::path filePath = manifestBase / info.mFilePath;
                if (info.mRenameFile.size() > 0)
                {
                    filePath = filePath.branch_path() / info.mRenameFile;
                }

                if (currentPos == 0 || resume)
                {
                    RCF_ASSERT(writeOp->isCompleted());

                    if (currentPos == 0)
                    {
                        // Create new file.
                        RCF_LOG_3()(filePath)
                            << "ClientStub::downloadFiles() - opening file (truncating).";

                        fs::create_directories(filePath.branch_path());
                        fout->clear();
                        fout->open( filePath.string().c_str(), std::ios::out | std::ios::binary | std::ios::trunc);
                        RCF_VERIFY(fout->good(), Exception(_RcfError_FileOpen(nativeString(filePath))));
                    }
                    else
                    {
                        // Create new file.
                        RCF_LOG_3()(filePath)
                            << "ClientStub::downloadFiles() - opening file (appending).";

                        // Append to existing file.
                        fout->clear();
                        fout->open( filePath.string().c_str(), std::ios::out | std::ios::binary | std::ios::app | std::ios::ate);
                        RCF_VERIFY(fout->good(), Exception(_RcfError_FileOpen(nativeString(filePath))));
                        resume = false;

                        // TODO: verify file position against currentPos.
                        // ...
                    }
                }

                // Wait for previous write to complete.
                if (writeOp->isInitiated())
                {
                    writeOp->complete();
                    boost::uint64_t bytesWritten = writeOp->getBytesTransferred();

                    RCF_LOG_3()(bytesWritten)
                        << "ClientStub::downloadFiles() - file write completed.";

                    if (bytesWritten == 0)
                    {
                        fout->close();

                        std::time_t writeTime = info.mLastWriteTime;
                        fs::last_write_time(filePath, writeTime);

                        Exception e(_RcfError_FileWrite(nativeString(filePath), currentPos));
                        RCF_THROW(e);
                    }
                }

                if (currentPos + chunk.mData.getLength() > manifest.mFiles[chunk.mFileIndex].mFileSize)
                {
                    // TODO: error
                    RCF_ASSERT(0);
                }

                // Check stream state.
                if (!fout->good())
                {
                    Exception e(_RcfError_FileWrite(nativeString(filePath), currentPos));
                    RCF_THROW(e);
                }

                RCF_ASSERT_EQ(currentPos , (boost::uint64_t) fout->tellp());

                RCF_LOG_3()(chunk.mData.getLength())
                    << "ClientStub::downloadFiles() - file write initiated.";

                writeOp->initateWrite(fout, chunk.mData);

                currentPos += chunk.mData.getLength();

                if (currentPos == manifest.mFiles[currentFile].mFileSize)
                {
                    writeOp->complete();
                    boost::uint64_t bytesWritten = writeOp->getBytesTransferred();

                    RCF_LOG_3()(bytesWritten)
                        << "ClientStub::downloadFiles() - file write completed.";

                    RCF_LOG_3()(currentFile)
                        << "ClientStub::downloadFiles() - closing file.";

                    if (bytesWritten == 0)
                    {
                        fout->close();

                        std::time_t writeTime = info.mLastWriteTime;
                        fs::last_write_time(filePath, writeTime);

                        Exception e(_RcfError_FileWrite(nativeString(filePath), currentPos));
                        RCF_THROW(e);
                    }

                    fout->close();

                    std::time_t writeTime = info.mLastWriteTime;
                    fs::last_write_time(filePath, writeTime);

                    currentPos = 0;
                    ++currentFile;

                    processZeroSizeEntries(manifest, manifestBase, currentFile);

                    if (currentFile < manifest.mFiles.size())
                    {
                        currentPos = manifest.mFiles[currentFile].mFileStartPos;
                    }
                }
            }

            chunks.clear();
        }

        totalManifest = manifest;

        RCF_LOG_3()(totalManifest.mFiles.size())
            << "ClientStub::downloadFiles() - exit.";

    }
} // namespace RCF

redpajama_set_name: RedPajamaGithub


text:
"""
This module creates an SBMLDiagram for the given SBML model using graphviz.
"""

from __future__ import print_function, division, absolute_import
import roadrunner
import warnings
import tempfile
try:
    import libsbml
except ImportError:
    import tesbml as libsbml
from six import string_types

try:
    from IPython.display import Image, display
except ImportError:
    pass
import os

class SBMLDiagram(object):
    """ Create network diagram from a sbml model. """

    def __init__(self, sbml,
                 species={},
                 reactions={},
                 reactants={},
                 products={},
                 modifiers={}):
        """
        :param sbml: SBML string, libsbml.SBMLDocument object, or libsbml.Model object
        :param species:
        :type species:
        :param reactions:
        :type reactions:
        :param reactants:
        :type reactants:
        :param products:
        :type products:
        :param modifiers:
        :type modifiers:
        """
        # load model
        if isinstance(sbml, string_types):
            self.doc = libsbml.readSBMLFromString(sbml)
            self.model = self.doc.getModel()
        elif isinstance(sbml, libsbml.SBMLDocument):
            self.doc = sbml
            self.model = self.doc.getModel()
        elif isinstance(sbml, libsbml.Model):
            self.model = sbml
        else:
            raise Exception('SBML Input is not valid')
        # create graph
        self.g = SBMLDiagram._createGraph(self.model,
                                          species=species,
                                          reactions=reactions,
                                          reactants=reactants,
                                          products=products,
                                          modifiers=modifiers)

    @staticmethod
    def _createGraph(model, species={}, reactions={}, reactants={}, products={}, modifiers={}):
        """ Creates the acyclic graph from the given model.

        :param model:
        :type model:
        :param species:
        :type species:
        :param reactions:
        :type reactions:
        :param reactants:
        :type reactants:
        :param products:
        :type products:
        :param modifiers:
        :type modifiers:
        :return:
        :rtype:
        """

        try:
            import pygraphviz as pgv
        except ImportError as e:
            pgv = None
            roadrunner.Logger.log(roadrunner.Logger.LOG_WARNING, str(e))
            warnings.warn("'pygraphviz' could not be imported, cannot draw network diagrams", ImportWarning, stacklevel=2)

        g = pgv.AGraph(strict=False, directed=True)

        # set some default node attributes
        g.node_attr['style'] = 'filled'
        g.node_attr['shape'] = 'circle'
        g.node_attr['fixedsize'] = 'true'
        g.node_attr['fillcolor'] = '#FFFFFF'
        g.node_attr['fontcolor'] = '#000000'
        # g.node_attr['height'] = '40'
        # g.node_attr['width'] = '40'

        # species nodes
        for s in (model.getSpecies(k) for k in range(model.getNumSpecies())):
            if s.getName():
                label = s.getName()
            else:
                label = s.getId()
            g.add_node(s.getId(), label=label, width=0.15*len(label), **species)
            n = g.get_node(s.getId())

            # boundary species
            if s.isSetBoundaryCondition() and s.getBoundaryCondition() == True:
                n.attr['fillcolor'] = '#717FF0'

        for r in (model.getReaction(k) for k in range(model.getNumReactions())):
            # reaction nodes
            if r.getName():
                label = r.getName()
            else:
                label = r.getId()
            g.add_node(r.getId(), label=label, width=0.15*len(label), **reactions)
            n = g.get_node(r.getId())
            n.attr['fillcolor'] = '#D1D1D1'
            n.attr['shape'] = 'square'
            # n.attr['height'] = int(int(g.node_attr['height'])/2.0)
            # n.attr['width'] = int(int(g.node_attr['width'])/2.0)

            # edges
            for s in (r.getReactant(k) for k in range(r.getNumReactants())):
                g.add_edge(s.getSpecies(), r.getId(), **reactants)
            for s in (r.getProduct(k) for k in range(r.getNumProducts())):
                g.add_edge(r.getId(), s.getSpecies(), **products)
            for s in (r.getModifier(k) for k in range(r.getNumModifiers())):
                g.add_edge(s.getSpecies(), r.getId(), **modifiers)
        return g

    def draw(self, layout='neato', **kwargs):
        """ Draw the graph.
        Optional layout=['neato'|'dot'|'twopi'|'circo'|'fdp'|'nop']
        will use specified graphviz layout method.

        :param layout: pygraphviz layout algorithm (default: 'neato')
        :type layout: str
        """
        f, filePath = tempfile.mkstemp(suffix='.png')
        self.g.layout(prog=layout)
        self.g.draw(filePath)

        i = Image(filename=filePath)
        display(i)
        os.close(f)
        os.remove(filePath)


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Coming Soon</title>
    <meta name="description" content="Website Under Construction">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="assets/css/bootstrap.css" rel="stylesheet">

    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/responsive.css">
    <link rel="stylesheet" href="assets/css/TimeCircles.css">

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

    <link href='http://fonts.googleapis.com/css?family=Lato:400,700|Lobster|Roboto+Slab:400,700' rel='stylesheet' type='text/css'>

    <link rel="shortcut icon" href="../img/logo_32.ico">

Coming Soon


text:
import {Injectable, Provider} from 'angular2/core'
import {window} from 'angular2/src/facade/browser';
import {unimplemented} from 'angular2/src/facade/exceptions';

function _window(): Window {
  return window
}

export abstract class WINDOW {
  get nativeWindow(): Window {
      return unimplemented();
  }
}

class WindowRef_ extends WINDOW {
    constructor() {
        super();
    }
    get nativeWindow(): Window {
        return _window();
    }
}

export const WINDOW_PROVIDERS = [
    new Provider(WINDOW, {useClass: WindowRef_}),
];


text:
feature 'Manage internships', :devise do
#   As a manager
#   I want to be able to add, find, edit and delete internships
#   So I have all the time the overview

  scenario 'create internship' do
    skip
    sign_in_as_manager

    create_internship institution_name: 'Einrichtung1'
  end

  scenario 'edit internship' do
    skip
    sign_in_as_manager
    given_internship institution_name: 'Einrichtung1'

    click_on 'Praktika'
    click_row_with 'Einrichtung1'
    click_on 'Bearbeiten'
    fill_in :Beginn, with: ''
    click_on 'Speichern'
    expect(page).to have_content('Praktikum konnte nicht gespeichert werden')
    fill_in :Beginn, with: '1.1.2016'
    click_on 'Speichern'
    expect(page).to have_content('Praktikum gespeichert')
    expect(page).to have_content('Einrichtung1')
  end

  scenario 'delete internship' do
    skip
    sign_in_as_manager
    given_internship institution_name: 'Einrichtung1'

    click_on 'Praktika'
    click_row_with 'Einrichtung1'
    click_on 'Löschen'
    expect(page).to have_content('Praktikum gelöscht')
  end
end


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Microsoft.Azure.SqlDatabase.ElasticScale.ShardManagement
{
    /// <summary>
    /// Arguments used to create a <see cref="PointMapping{TKey}"/>.
    /// </summary>
    /// <typeparam name="TKey">Type of the key (point).</typeparam>
    public sealed class PointMappingCreationInfo<TKey>
    {
        /// <summary>
        /// Arguments used to create a point mapping.
        /// </summary>
        /// <param name="point">Point value being mapped.</param>
        /// <param name="shard">Shard used as the mapping target.</param>
        /// <param name="status">Status of the mapping.</param>
        public PointMappingCreationInfo(TKey point, Shard shard, MappingStatus status)
        {
            ExceptionUtils.DisallowNullArgument(shard, "shard");
            this.Value = point;
            this.Shard = shard;
            this.Status = status;

            this.Key = new ShardKey(ShardKey.ShardKeyTypeFromType(typeof(TKey)), point);
        }

        /// <summary>
        /// Gets the point value being mapped.
        /// </summary>
        public TKey Value
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the Shard of the mapping.
        /// </summary>
        public Shard Shard
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the Status of the mapping.
        /// </summary>
        public MappingStatus Status
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the key value associated with the <see cref="PointMapping{TKey}"/>.
        /// </summary>
        internal ShardKey Key
        {
            get;
            private set;
        }
    }

    /// <summary>
    /// Represents a mapping between the singleton key value of a shardlet (a point) and a <see cref="Shard"/>.
    /// </summary>
    /// <typeparam name="TKey">Type of the key (point).</typeparam>
    public sealed class PointMapping<TKey> : IShardProvider<TKey>, ICloneable<PointMapping<TKey>>, IMappingInfoProvider
    {
        /// <summary>
        /// Shard object associated with the mapping.
        /// </summary>
        private Shard _shard;

        /// <summary>
        /// Constructs a point mapping given mapping creation arguments.
        /// </summary>
        /// <param name="manager">Owning ShardMapManager.</param>
        /// <param name="creationInfo">Mapping creation information.</param>
        internal PointMapping(ShardMapManager manager, PointMappingCreationInfo<TKey> creationInfo)
        {
            Debug.Assert(manager != null);
            Debug.Assert(creationInfo != null);
            Debug.Assert(creationInfo.Shard != null);

            this.Manager = manager;

            _shard = creationInfo.Shard;

            this.StoreMapping = new DefaultStoreMapping(
                Guid.NewGuid(),
                creationInfo.Shard,
                creationInfo.Key.RawValue,
                null,
                (int)creationInfo.Status);

            this.Key = creationInfo.Key;
            this.Value = creationInfo.Value;
        }

        /// <summary>
        /// Internal constructor used for deserialization from store representation of
        /// the mapping object.
        /// </summary>
        /// <param name="manager">Owning ShardMapManager.</param>
        /// <param name="shardMap">Owning shard map.</param>
        /// <param name="mapping">Storage representation of the mapping.</param>
        internal PointMapping(
            ShardMapManager manager,
            ShardMap shardMap,
            IStoreMapping mapping)
        {
            Debug.Assert(manager != null);
            this.Manager = manager;

            Debug.Assert(mapping != null);
            Debug.Assert(mapping.ShardMapId != default(Guid));
            Debug.Assert(mapping.StoreShard.ShardMapId != default(Guid));
            this.StoreMapping = mapping;

            _shard = new Shard(this.Manager, shardMap, mapping.StoreShard);

            this.Key = ShardKey.FromRawValue(ShardKey.ShardKeyTypeFromType(typeof(TKey)), mapping.MinValue);
            this.Value = (TKey)this.Key.Value;
        }

        /// <summary>
        /// Gets Status of the mapping.
        /// </summary>
        public MappingStatus Status
        {
            get
            {
                return ((MappingStatus)this.StoreMapping.Status & MappingStatus.Online);
            }
        }

        /// <summary>
        /// Gets Shard that contains the key value.
        /// </summary>
        public Shard Shard
        {
            get
            {
                return _shard;
            }
        }

        /// <summary>
        /// Gets key value.
        /// </summary>
        public TKey Value
        {
            get;
            private set;
        }

        /// <summary>
        /// Holder of the key value's binary representation.
        /// </summary>
        internal ShardKey Key
        {
            get;
            private set;
        }

        /// <summary>
        /// Identity of the mapping.
        /// </summary>
        internal Guid Id
        {
            get
            {
                return this.StoreMapping.Id;
            }
        }

        /// <summary>
        /// Identify of the ShardMap this shard belongs to.
        /// </summary>
        internal Guid ShardMapId
        {
            get
            {
                return this.StoreMapping.ShardMapId;
            }
        }

        /// <summary>
        /// Reference to the ShardMapManager.
        /// </summary>
        internal ShardMapManager Manager
        {
            get;
            set;
        }

        /// <summary>
        /// Storage representation of the mapping.
        /// </summary>
        internal IStoreMapping StoreMapping
        {
            get;
            private set;
        }

        /// <summary>
        /// The Tracer
        /// </summary>
        private static ILogger Tracer
        {
            get
            {
                return TraceHelper.Tracer;
            }
        }

        /// <summary>
        /// Converts the object to its string representation.
        /// </summary>
        /// <returns>String representation of the object.</returns>
        public override string ToString()
        {
            return StringUtils.FormatInvariant("P[{0}:{1}]", this.Id, this.Key);
        }

        /// <summary>
        /// Determines whether the specified object is equal to the current object.
        /// </summary>
        /// <param name="obj">The object to compare with the current object.</param>
        /// <returns>True if the specified object is equal to the current object; otherwise, false.</returns>
        public override bool Equals(object obj)
        {
            PointMapping<TKey> other = obj as PointMapping<TKey>;

            if (other == null)
            {
                return false;
            }

            if (this.Id.Equals(other.Id))
            {
                Debug.Assert(this.Key == other.Key);
                return true;
            }

            return false;
        }

        /// <summary>
        /// Calculates the hash code for this instance.
        /// </summary>
        /// <returns>Hash code for the object.</returns>
        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }

        #region IShardProvider<TKey>

        /// <summary>
        /// Shard that contains the key value.
        /// </summary>
        Shard IShardProvider.ShardInfo
        {
            get
            {
                return this.Shard;
            }
        }

        /// <summary>
        /// Performs validation that the local representation is as up-to-date
        /// as the representation on the backing data store.
        /// </summary>
        /// <param name="shardMap">Shard map to which the shard provider belongs.</param>
        /// <param name="conn">Connection used for validation.</param>
        void IShardProvider.Validate(IStoreShardMap shardMap, SqlConnection conn)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            Tracer.TraceInfo(TraceSourceConstants.ComponentNames.PointMapping,
                "Validate", "Start; Connection: {0};", conn.ConnectionString);

            ValidationUtils.ValidateMapping(
                conn,
                this.Manager,
                shardMap,
                this.StoreMapping);

            stopwatch.Stop();

            Tracer.TraceInfo(TraceSourceConstants.ComponentNames.PointMapping,
                "Validate", "Complete; Connection: {0}; Duration: {1}",
                conn.ConnectionString, stopwatch.Elapsed);
        }

        /// <summary>
        /// Asynchronously performs validation that the local representation is as
        /// up-to-date as the representation on the backing data store.
        /// </summary>
        /// <param name="shardMap">Shard map to which the shard provider belongs.</param>
        /// <param name="conn">Connection used for validation.</param>
        /// <returns>A task to await validation completion</returns>
        async Task IShardProvider.ValidateAsync(IStoreShardMap shardMap, SqlConnection conn)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            Tracer.TraceInfo(TraceSourceConstants.ComponentNames.PointMapping,
                "ValidateAsync", "Start; Connection: {0};", conn.ConnectionString);

            await ValidationUtils.ValidateMappingAsync(
                conn,
                this.Manager,
                shardMap,
                this.StoreMapping).ConfigureAwait(false);

            stopwatch.Stop();

            Tracer.TraceInfo(TraceSourceConstants.ComponentNames.PointMapping,
                "ValidateAsync", "Complete; Connection: {0}; Duration: {1}",
                conn.ConnectionString, stopwatch.Elapsed);
        }

        /// <summary>
        /// The key value.
        /// </summary>
        TKey IShardProvider<TKey>.Value
        {
            get
            {
                return this.Value;
            }
        }

        #endregion IShardProvider<TKey>

        #region ICloneable<PointMapping<TKey>>

        /// <summary>
        /// Clones the instance.
        /// </summary>
        /// <returns>Clone of the instance.</returns>
        public PointMapping<TKey> Clone()
        {
            return new PointMapping<TKey>(this.Manager, this.Shard.ShardMap, this.StoreMapping);
        }

        #endregion ICloneable<PointMapping<TKey>>

        #region IMappingInfoProvider

        /// <summary>
        /// ShardMapManager for the object.
        /// </summary>
        ShardMapManager IMappingInfoProvider.Manager
        {
            get
            {
                return this.Manager;
            }
        }

        /// <summary>
        /// Shard map associated with the mapping.
        /// </summary>
        Guid IMappingInfoProvider.ShardMapId
        {
            get
            {
                return this.ShardMapId;
            }
        }

        /// <summary>
        /// Storage representation of the mapping.
        /// </summary>
        IStoreMapping IMappingInfoProvider.StoreMapping
        {
            get
            {
                return this.StoreMapping;
            }
        }

        /// <summary>
        /// Type of the mapping.
        /// </summary>
        MappingKind IMappingInfoProvider.Kind
        {
            get
            {
                return MappingKind.PointMapping;
            }
        }

        /// <summary>
        /// Mapping type, useful for diagnostics.
        /// </summary>
        string IMappingInfoProvider.TypeName
        {
            get
            {
                return "PointMapping";
            }
        }

        #endregion IMappingInfoProvider
    }
}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Options;

namespace Roslyn.Hosting.Diagnostics
{
    /// <summary>
    /// provide a way to access internal logging framework
    /// </summary>
    public static class DiagnosticOnly_Logger
    {
        /// <summary>
        /// get roslyn event source name
        /// </summary>
        public static string GetRoslynEventSourceName()
        {
            return EventSource.GetName(typeof(RoslynEventSource));
        }

        /// <summary>
        /// get roslyn event source guid
        /// </summary>
        public static Guid GetRoslynEventSourceGuid()
        {
            return EventSource.GetGuid(typeof(RoslynEventSource));
        }

        /// <summary>
        /// reset logger to default one
        /// </summary>
        public static void ResetLogger()
        {
            Logger.SetLogger(null);
        }

        /// <summary>
        /// let one such as ETA to set logger for the service layer
        /// </summary>
        internal static void SetLogger(IGlobalOptionService optionsService, string loggerName)
        {
            if (loggerName == null)
            {
                ResetLogger();
            }

            Logger.SetLogger(GetLogger(optionsService, loggerName));
        }

        /// <summary>
        /// get string representation of functionId
        /// </summary>
        public static string GetFunctionId(int functionId)
        {
            return ((FunctionId)functionId).ToString();
        }

        /// <summary>
        /// use Roslyn Logger from outside
        /// </summary>
        public static IDisposable LogBlock(string functionId)
        {
            return Logger.LogBlock(GetFunctionId(functionId), CancellationToken.None);
        }

        /// <summary>
        /// use Roslyn Logger from outside
        /// </summary>
        public static IDisposable LogBlock(string functionId, string message)
        {
            return Logger.LogBlock(GetFunctionId(functionId), message, CancellationToken.None);
        }

        /// <summary>
        /// get given functionId's int value
        /// </summary>
        public static int GetFunctionIdValue(string functionId)
        {
            // this will throw if given functionid doesn't exist
            return (int)GetFunctionId(functionId);
        }

        private static FunctionId GetFunctionId(string functionId)
        {
            return (FunctionId)Enum.Parse(typeof(FunctionId), functionId);
        }

        private static ILogger GetLogger(IGlobalOptionService optionsService, string loggerName)
        {
            switch (loggerName)
            {
                case "EtwLogger":
                    return new EtwLogger(optionsService);
                case "TraceLogger":
                    return new TraceLogger(Logger.GetLoggingChecker(optionsService));
                default:
                    return EmptyLogger.Instance;
            }
        }
    }
}


text:
const vscode = require('vscode');
const BlindJS = require('./lib/blind');

const getCompleteDocumentRange = document => {
	const firstLine = document.lineAt(0);
	const lastLine = document.lineAt(document.lineCount - 1);
	return new vscode.Range(firstLine.range.start, lastLine.range.end);
};

let disposableType;
function activate(context) {
	console.log('activate');

	const disposableOpenWithBlindJs = vscode.commands.registerCommand('extension.openWithBlindJs', function ({ fsPath }) {
		const setting = vscode.Uri.file(fsPath);

		disposableType = vscode.commands.registerCommand('type', () => {
			const typed = BlindJS.type();
			const { _line, _character } = vscode.window.activeTextEditor.selection.anchor;

			vscode.window.activeTextEditor.edit(activeEditor => {
				let newPosition;
				let newSelection;

				activeEditor.replace(getCompleteDocumentRange(activeEditor._document), typed);

				newPosition = new vscode.Position(_line + 1, _character + 1);
				newSelection = new vscode.Selection(newPosition, newPosition);

				vscode.window.activeTextEditor.selection = newSelection;
			});
		});

		vscode.workspace.openTextDocument(setting).then((a) => {
			vscode.window.showTextDocument(a).then(e => {
				e.edit(edit => {
					const { _document } = edit;
					const input = _document.getText();

					BlindJS.start({
						input
					});

					edit.delete(getCompleteDocumentRange(_document));
				});
			});
		}, (error) => {
			console.error({ error });
		});
	});

	const disposableTerminateBlindJs = vscode.commands.registerCommand('extension.terminateBlindJs', function () {
		console.log('terminateBlindJs');

		disposableType.dispose()
	});

	context.subscriptions.push(disposableType);
	context.subscriptions.push(disposableTerminateBlindJs);
	context.subscriptions.push(disposableOpenWithBlindJs);
}
exports.activate = activate;

function deactivate() { }

module.exports = {
	activate,
	deactivate
}


text:
<?php

namespace Zend\Markup;

use Zend\Loader\PluginBroker;

/**
 * Broker for markup parser instances
 *
 * @category   Zend
 * @package    Zend_Markup
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class ParserBroker extends PluginBroker
{
    /**
     * @var string Default plugin loading strategy
     */
    protected $defaultClassLoader = 'Zend\Markup\ParserLoader';

    /**
     * Determine if we have a valid parser
     *
     * @param  mixed $plugin
     * @return true
     * @throws Exception
     */
    protected function validatePlugin($plugin)
    {
        if (!$plugin instanceof Parser) {
            throw new Exception('Markup parsers must implement Zend\Markup\Parser');
        }
        return true;
    }
}


text:
package com.xhaleera.whiteshark.exceptions;

/**
 * Exception thrown when the stream format identifier cannot be found.
 *
 * @author Christophe SAUVEUR (christophe@xhaleera.com)
 * @since 1.0
 * @version 1.0
 */
public class WhiteSharkMissingFormatIdentifierException extends WhiteSharkException {

	/** Serialization version UID */
	static final long serialVersionUID = 1;

	/**
	 * Constructor with custom message
	 * @param arg0 Custom message
	 */
	public WhiteSharkMissingFormatIdentifierException(String arg0) {
		super(arg0);
	}

}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file was generated by:
//   ./tools/json_schema_compiler/compiler.py.
// NOTE: The format of types has changed. 'FooType' is now
//   'chrome.quickUnlockPrivate.FooType'.
// Please run the closure compiler before committing changes.
// See https://chromium.googlesource.com/chromium/src/+/master/docs/closure_compilation.md

/** @fileoverview Externs generated from namespace: quickUnlockPrivate */

/**
 * @const
 */
chrome.quickUnlockPrivate = {};

/**
 * @enum {string}
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#type-QuickUnlockMode
 */
chrome.quickUnlockPrivate.QuickUnlockMode = {
  PIN: 'PIN',
};

/**
 * @enum {string}
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#type-CredentialProblem
 */
chrome.quickUnlockPrivate.CredentialProblem = {
  TOO_SHORT: 'TOO_SHORT',
  TOO_LONG: 'TOO_LONG',
  TOO_WEAK: 'TOO_WEAK',
  CONTAINS_NONDIGIT: 'CONTAINS_NONDIGIT',
};

/**
 * @typedef {{
 *   errors: !Array<!chrome.quickUnlockPrivate.CredentialProblem>,
 *   warnings: !Array<!chrome.quickUnlockPrivate.CredentialProblem>
 * }}
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#type-CredentialCheck
 */
chrome.quickUnlockPrivate.CredentialCheck;

/**
 * @typedef {{
 *   minLength: number,
 *   maxLength: number
 * }}
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#type-CredentialRequirements
 */
chrome.quickUnlockPrivate.CredentialRequirements;

/**
 * Returns the set of quick unlock modes that are available for the user to use.
 * Some quick unlock modes may be disabled by policy.
 * @param {function(!Array<!chrome.quickUnlockPrivate.QuickUnlockMode>):void}
 *     onComplete
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#method-getAvailableModes
 */
chrome.quickUnlockPrivate.getAvailableModes = function(onComplete) {};

/**
 * Returns the quick unlock modes that are currently enabled and usable on the
 * lock screen.
 * @param {function(!Array<!chrome.quickUnlockPrivate.QuickUnlockMode>):void}
 *     onComplete
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#method-getActiveModes
 */
chrome.quickUnlockPrivate.getActiveModes = function(onComplete) {};

/**
 * Checks if the given credential can be used for the given unlock mode.
 * Enterprise policy can change credential requirements.
 * @param {!chrome.quickUnlockPrivate.QuickUnlockMode} mode The quick unlock
 *     mode that is used.
 * @param {string} credential The given credential.
 * @param {function(!chrome.quickUnlockPrivate.CredentialCheck):void} onComplete
 *     Called with a list of warnings and errors the given     |credential| has
 *     (or an empty list if there are none).
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#method-checkCredential
 */
chrome.quickUnlockPrivate.checkCredential = function(mode, credential, onComplete) {};

/**
 * Gets the credential requirements for the given unlock mode.
 * @param {!chrome.quickUnlockPrivate.QuickUnlockMode} mode The quick unlock
 *     mode that is used.
 * @param {function(!chrome.quickUnlockPrivate.CredentialRequirements):void}
 *     onComplete Called with the credential requirements of the given
 *     |mode|.
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#method-getCredentialRequirements
 */
chrome.quickUnlockPrivate.getCredentialRequirements = function(mode, onComplete) {};

/**
 * Update the set of quick unlock modes that are currently active/enabled.
 * @param {string} accountPassword The password associated with the account
 *     (e.g. the GAIA password). This is required to change the quick unlock
 *     credentials.
 * @param {!Array<!chrome.quickUnlockPrivate.QuickUnlockMode>} modes The quick
 *     unlock modes that should be active.
 * @param {!Array<string>} credentials The associated credential for each mode.
 *     To keep the credential the same for the associated mode, pass an empty
 *     string.
 * @param {function(boolean):void} onComplete Called with true if the quick
 *     unlock state was updated, false otherwise. The update is treated as a
 *     single atomic operation.
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#method-setModes
 */
chrome.quickUnlockPrivate.setModes = function(accountPassword, modes, credentials, onComplete) {};

/**
 * Called after the active set of quick unlock modes has changed.
 * @type {!ChromeEvent}
 * @see https://developer.chrome.com/extensions/quickUnlockPrivate#event-onActiveModesChanged
 */
chrome.quickUnlockPrivate.onActiveModesChanged;


text:
/**
 * clock_domain_descriptor_imp.cpp
 *
 * CLOCK DOMAIN descriptor implementation
 */

#include <vector>
#include "avdecc_error.h"
#include "enumeration.h"
#include "log_imp.h"
#include "adp.h"
#include "end_station_imp.h"
#include "system_tx_queue.h"
#include "aecp_controller_state_machine.h"
#include "clock_domain_descriptor_imp.h"

namespace avdecc_lib
{
    clock_domain_descriptor_imp::clock_domain_descriptor_imp(end_station_imp *end_station_obj, const uint8_t *frame, ssize_t pos, size_t frame_len) : descriptor_base_imp(end_station_obj)
    {
        ssize_t ret = jdksavdecc_descriptor_clock_domain_read(&clock_domain_desc, frame, pos, frame_len);

        if (ret < 0)
        {
            throw avdecc_read_descriptor_error("clock_domain_desc_read error");
        }

        store_clock_sources(frame, pos);
        memset(&aem_cmd_set_clk_src_resp, 0, sizeof(struct jdksavdecc_aem_command_set_clock_source_response));
        memset(&aem_cmd_get_clk_src_resp, 0, sizeof(struct jdksavdecc_aem_command_get_clock_source_response));
    }

    clock_domain_descriptor_imp::~clock_domain_descriptor_imp() {}

    uint16_t STDCALL clock_domain_descriptor_imp::descriptor_type() const
    {
        assert(clock_domain_desc.descriptor_type == JDKSAVDECC_DESCRIPTOR_CLOCK_DOMAIN);
        return clock_domain_desc.descriptor_type;
    }

    uint16_t STDCALL clock_domain_descriptor_imp::descriptor_index() const
    {
        return clock_domain_desc.descriptor_index;
    }

    uint8_t * STDCALL clock_domain_descriptor_imp::object_name()
    {
        return clock_domain_desc.object_name.value;
    }

    uint16_t STDCALL clock_domain_descriptor_imp::localized_description()
    {
        return clock_domain_desc.localized_description;
    }

    uint16_t STDCALL clock_domain_descriptor_imp::clock_source_index()
    {
        return clock_domain_desc.clock_source_index;
    }

    uint16_t clock_domain_descriptor_imp::clock_sources_offset()
    {
        assert(clock_domain_desc.clock_sources_offset == 76);
        return clock_domain_desc.clock_sources_offset;
    }

    uint16_t STDCALL clock_domain_descriptor_imp::clock_sources_count()
    {
        assert(clock_domain_desc.clock_sources_count <= 249);
        return clock_domain_desc.clock_sources_count;
    }

    void clock_domain_descriptor_imp::store_clock_sources(const uint8_t *frame, size_t pos)
    {
        uint16_t offset = 0;

        for(uint32_t i = 0; i < clock_sources_count(); i++)
        {
            clk_src_vec.push_back(jdksavdecc_uint16_get(frame, clock_sources_offset() + pos + offset));
            offset += 0x2;
        }
    }

    uint16_t STDCALL clock_domain_descriptor_imp::get_clock_source_by_index(size_t clk_src_index)
    {
        return clk_src_vec.at(clk_src_index);
    }

    uint16_t STDCALL clock_domain_descriptor_imp::set_clock_source_clock_source_index()
    {
        return aem_cmd_set_clk_src_resp.clock_source_index;
    }

    void clock_domain_descriptor_imp::update_clock_source_index(uint16_t clock_source_index)
    {
        clock_domain_desc.clock_source_index = clock_source_index;
    }

    uint16_t STDCALL clock_domain_descriptor_imp::get_clock_source_clock_source_index()
    {
        return aem_cmd_get_clk_src_resp.clock_source_index;
    }

    int STDCALL clock_domain_descriptor_imp::send_set_clock_source_cmd(void *notification_id, uint16_t new_clk_src_index)
    {
        struct jdksavdecc_frame cmd_frame;
        struct jdksavdecc_aem_command_set_clock_source aem_cmd_set_clk_src;
        ssize_t aem_cmd_set_clk_src_returned;
        memset(&aem_cmd_set_clk_src,0,sizeof(aem_cmd_set_clk_src));

        /***************************************** AECP Common Data ******************************************/
        aem_cmd_set_clk_src.aem_header.aecpdu_header.controller_entity_id = base_end_station_imp_ref->get_adp()->get_controller_entity_id();
        // Fill aem_cmd_set_clk_src.sequence_id in AEM Controller State Machine
        aem_cmd_set_clk_src.aem_header.command_type = JDKSAVDECC_AEM_COMMAND_SET_CLOCK_SOURCE;

        /***************** AECP Message Specific Data ****************/
        aem_cmd_set_clk_src.descriptor_type = descriptor_type();
        aem_cmd_set_clk_src.descriptor_index = descriptor_index();
        aem_cmd_set_clk_src.clock_source_index = new_clk_src_index;

        /*************************** Fill frame payload with AECP data and send the frame ***********************/
        aecp_controller_state_machine_ref->ether_frame_init(base_end_station_imp_ref->mac(), &cmd_frame,
						ETHER_HDR_SIZE + JDKSAVDECC_AEM_COMMAND_SET_CLOCK_SOURCE_COMMAND_LEN);
        aem_cmd_set_clk_src_returned = jdksavdecc_aem_command_set_clock_source_write(&aem_cmd_set_clk_src,
                                                                                cmd_frame.payload,
                                                                                ETHER_HDR_SIZE,
                                                                                sizeof(cmd_frame.payload));

        if(aem_cmd_set_clk_src_returned < 0)
        {
            log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "aem_cmd_set_clk_src_write error\n");
            assert(aem_cmd_set_clk_src_returned >= 0);
            return -1;
        }

        aecp_controller_state_machine_ref->common_hdr_init(JDKSAVDECC_AECP_MESSAGE_TYPE_AEM_COMMAND,
                                                            &cmd_frame,
                                                            base_end_station_imp_ref->entity_id(),
                                                            JDKSAVDECC_AEM_COMMAND_SET_CLOCK_SOURCE_COMMAND_LEN -
                                                            JDKSAVDECC_COMMON_CONTROL_HEADER_LEN);
        system_queue_tx(notification_id, CMD_WITH_NOTIFICATION, cmd_frame.payload, cmd_frame.length);

        return 0;

    }

    int clock_domain_descriptor_imp::proc_set_clock_source_resp(void *&notification_id, const uint8_t *frame, size_t frame_len, int &status)
    {
        struct jdksavdecc_frame cmd_frame;
        ssize_t aem_cmd_set_clk_src_resp_returned;
        uint32_t msg_type;
        bool u_field;

        memcpy(cmd_frame.payload, frame, frame_len);

        aem_cmd_set_clk_src_resp_returned = jdksavdecc_aem_command_set_clock_source_response_read(&aem_cmd_set_clk_src_resp,
                                                                                frame,
                                                                                ETHER_HDR_SIZE,
                                                                                frame_len);

        if(aem_cmd_set_clk_src_resp_returned < 0)
        {
            log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "aem_cmd_set_clk_src_resp_read error\n");
            assert(aem_cmd_set_clk_src_resp_returned >= 0);
            return -1;
        }

        msg_type = aem_cmd_set_clk_src_resp.aem_header.aecpdu_header.header.message_type;
        status = aem_cmd_set_clk_src_resp.aem_header.aecpdu_header.header.status;
        u_field = aem_cmd_set_clk_src_resp.aem_header.command_type >> 15 & 0x01; // u_field = the msb of the uint16_t command_type

        aecp_controller_state_machine_ref->update_inflight_for_rcvd_resp(notification_id, msg_type, u_field, &cmd_frame);

        if(status == AEM_STATUS_SUCCESS)
        {
            update_clock_source_index(aem_cmd_set_clk_src_resp.clock_source_index);
        }

        return 0;
    }

    int STDCALL clock_domain_descriptor_imp::send_get_clock_source_cmd(void *notification_id)
    {
        struct jdksavdecc_frame cmd_frame;
        struct jdksavdecc_aem_command_get_clock_source aem_cmd_get_clk_src;
        ssize_t aem_cmd_get_clk_src_returned;

        memset(&aem_cmd_get_clk_src,0,sizeof(aem_cmd_get_clk_src));

        /***************************************** AECP Common Data ******************************************/
        aem_cmd_get_clk_src.aem_header.aecpdu_header.controller_entity_id = base_end_station_imp_ref->get_adp()->get_controller_entity_id();
        // Fill aem_cmd_get_clk_src.sequence_id in AEM Controller State Machine
        aem_cmd_get_clk_src.aem_header.command_type = JDKSAVDECC_AEM_COMMAND_GET_CLOCK_SOURCE;

        /****************** AECP Message Specific Data ***************/
        aem_cmd_get_clk_src.descriptor_type = descriptor_type();
        aem_cmd_get_clk_src.descriptor_index = descriptor_index();

        /***************************** Fill frame payload with AECP data and send the frame ***********************/
        aecp_controller_state_machine_ref->ether_frame_init(base_end_station_imp_ref->mac(), &cmd_frame,
										ETHER_HDR_SIZE + JDKSAVDECC_AEM_COMMAND_GET_CLOCK_SOURCE_COMMAND_LEN);
        aem_cmd_get_clk_src_returned = jdksavdecc_aem_command_get_clock_source_write(&aem_cmd_get_clk_src,
                                                                                cmd_frame.payload,
                                                                                ETHER_HDR_SIZE,
                                                                                sizeof(cmd_frame.payload));

        if(aem_cmd_get_clk_src_returned < 0)
        {
            log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "aem_cmd_get_clk_src_write error\n");
            assert(aem_cmd_get_clk_src_returned >= 0);
            return -1;
        }

        aecp_controller_state_machine_ref->common_hdr_init(JDKSAVDECC_AECP_MESSAGE_TYPE_AEM_COMMAND,
                                                            &cmd_frame,
                                                            base_end_station_imp_ref->entity_id(),
                                                            JDKSAVDECC_AEM_COMMAND_GET_CLOCK_SOURCE_COMMAND_LEN -
                                                            JDKSAVDECC_COMMON_CONTROL_HEADER_LEN);
        system_queue_tx(notification_id, CMD_WITH_NOTIFICATION, cmd_frame.payload, cmd_frame.length);

        return 0;
    }

    int clock_domain_descriptor_imp::proc_get_clock_source_resp(void *&notification_id, const uint8_t *frame, size_t frame_len, int &status)
    {
        struct jdksavdecc_frame cmd_frame;
        ssize_t aem_cmd_get_clk_src_resp_returned;
        uint32_t msg_type;
        bool u_field;

        memcpy(cmd_frame.payload, frame, frame_len);

        aem_cmd_get_clk_src_resp_returned = jdksavdecc_aem_command_get_clock_source_response_read(&aem_cmd_get_clk_src_resp,
                                                                                frame,
                                                                                ETHER_HDR_SIZE,
                                                                                frame_len);

        if(aem_cmd_get_clk_src_resp_returned < 0)
        {
            log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "aem_cmd_get_clk_src_resp_read error\n");
            assert(aem_cmd_get_clk_src_resp_returned >= 0);
            return -1;
        }

        msg_type = aem_cmd_get_clk_src_resp.aem_header.aecpdu_header.header.message_type;
        status = aem_cmd_get_clk_src_resp.aem_header.aecpdu_header.header.status;
        u_field = aem_cmd_get_clk_src_resp.aem_header.command_type >> 15 & 0x01; // u_field = the msb of the uint16_t command_type

        aecp_controller_state_machine_ref->update_inflight_for_rcvd_resp(notification_id, msg_type, u_field, &cmd_frame);

        return 0;
    }
}


text:
// *****************************************************************************
//
//  © Component Factory Pty Ltd 2017. All rights reserved.
//	The software and associated documentation supplied hereunder are the
//  proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
//  Mornington, Vic 3931, Australia and are supplied subject to licence terms.
//
//  Version 4.6.0.0 	www.ComponentFactory.com
// *****************************************************************************

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;

namespace ComponentFactory.Krypton.Ribbon
{
	/// <summary>
	/// View element that draws nothing and takes up all given space.
	/// </summary>
    internal class ViewLayoutRibbonTabsSpare : ViewLeaf
    {
        #region Identity
        /// <summary>
        /// Initialize a new instance of the ViewLayoutRibbonTabsSpare class.
        /// </summary>
        public ViewLayoutRibbonTabsSpare()
        {
        }

		/// <summary>
		/// Obtains the String representation of this instance.
		/// </summary>
		/// <returns>User readable name of the instance.</returns>
		public override string ToString()
		{
			// Return the class name and instance identifier
            return "ViewLayoutRibbonTabsSpare:" + Id;
		}
        #endregion

        #region Layout
        /// <summary>
        /// Discover the preferred size of the element.
        /// </summary>
        /// <param name="context">Layout context.</param>
        public override Size GetPreferredSize(ViewLayoutContext context)
        {
            // Preferred size is calculated by parent for us
            return Size.Empty;
        }

        /// <summary>
		/// Perform a layout of the elements.
		/// </summary>
		/// <param name="context">Layout context.</param>
		public override void Layout(ViewLayoutContext context)
		{
			Debug.Assert(context != null);

            // Validate incoming reference
            if (context == null) throw new ArgumentNullException("context");

            // We take on all the available display area
			ClientRectangle = context.DisplayRectangle;
        }
		#endregion
	}
}


text:
                <button type="button" class="close" data-dismiss="modal">×</button>

Add New Customer

                <form id="addcustomerForm" action="/">

                            *Company Name:
                            <input type="text" class="form-control input-sm" name="customer_company_name" aria-describedby="sizing-addon2">

                            Account No:
                            <input type="text" class="form-control input-sm" name="customer_no" aria-describedby="sizing-addon2">

                            VAT No:
                            <input type="text" class="form-control numeric input-sm" name="customer_vat_number" aria-describedby="sizing-addon2">

                            Insured Amount (R):
                            <input type="text" class="form-control numeric input-sm" name="customer_insured_amount" aria-describedby="sizing-addon2">

                            Credit Amount (R):
                            <input type="text" class="form-control numeric input-sm" name="customer_credit" aria-describedby="sizing-addon2">

                            Tel No:
                            <input type="text" class="form-control numeric input-sm" name="customer_contact_number" aria-describedby="sizing-addon2">

                            Fax No:
                            <input type="text" class="form-control numeric input-sm" name="customer_fax_number" aria-describedby="sizing-addon2">

                        <input type="submit" value="Add Customer" class="btn btn-primary input-sm" />

                </form>

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

<?php echo $page_data['heading'] ?> <?php echo $page_data['sub-heading'] ?>

                Filter
                <select id="filter" name="filter" class="form-control default">
                    <option value="active">Active</option>
                    <option value="inactive" >Inactive</option>
                    <option value="all">All</option>
                </select>

                    <?php if (isset($edit_permission) && ($edit_permission)) : ?>
                         Add Customer
                    <?php endif; ?>

                            Customer ID
                            Account No
                            Company Name
                            Contact No
                            Province
                            Status

                        <?php foreach ($customers as $c) { ?>
                            <tr class='hidable <?php if (isset($view_permission) && ($view_permission)) { ?>clickable-row<?php } ?>' data-href="/list_data/customer_edit/<?php echo $c->customer_id; ?>" style="cursor: pointer;">

                                    <a href="/list_data/customer_edit/<?php echo $c->customer_id; ?>"><?php echo $c->customer_id; ?>
                                <?php echo $c->customer_no; ?>
                                <?php echo $c->customer_company_name; ?>
                                <?php echo $c->customer_contact_number; ?>
                                <?php echo $c->del_address_province; ?>
                                <a href="#" class="<?php if (isset($edit_permission) && ($edit_permission)): ?>editable<?php endif; ?>" id="customer_is_deleted" data-type="select" data-pk="<?= $c->customer_id ?>" data-placement="bottom" data-name="customer_is_deleted" data-url="/list_data/customer_quickstatuschange" data-value="<?php echo $c->customer_is_deleted ? "1" : "0"; ?>" data-source="{'0': 'Active', '1': 'Inactive'}"><?php echo $c->customer_is_deleted ? "Inactive" : "Active"; ?>

                        <?php } ?>


text:
require "#{ Rails.root }/lib/nypl/nypl_repo.rb"

if File.exist?(File.join(Rails.root, "/config/nypl_repo.yml"))
  config_file = YAML.load_file("#{ Rails.root }/config/nypl_repo.yml")
  REPO_CONFIG = config_file[ENV['RAILS_ENV']].symbolize_keys
else
  REPO_CONFIG = {}
end


text:
//
// Copyright (c) XSharp B.V.  All Rights Reserved.
// Licensed under the Apache License, Version 2.0.
// See License.txt in the project root for license information.
//
using Microsoft.VisualStudio.Shell.TableManager;

namespace XSharp.Project
{
    internal interface IListSinkManager
    {
        /// <summary>
        /// This is called if a new project is added after there is already a sink connected. Informs the sink
        /// of the new source of errors
        /// </summary>
        void AddListFactory(ITableEntriesSnapshotFactory factory);

        /// <summary>
        /// If a project is removed from the solution (unloaded, closed, etc) informs the sink
        /// that the source is no longer available.
        /// </summary>
        void RemoveListFactory(ITableEntriesSnapshotFactory factory);

        /// <summary>
        /// Called when a snapshot changes to have its errors updated by the subscriber. Pass null to have
        /// all the factories updated.
        /// </summary>
        void UpdateSink(ITableEntriesSnapshotFactory factory);
    }
}