text:
//=============================================================================================================

#include "realtimeevokedmodel.h"

#include <QDebug>
#include <QBrush>
#include <QThread>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace SCDISPLIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

RealTimeEvokedModel::RealTimeEvokedModel(QObject *parent)
: QAbstractTableModel(parent)
, m_matData(MatrixXd(0,0))
, m_matDataFreeze(MatrixXd(0,0))
, m_fSps(1024.0f)
, m_bIsFreezed(false)
, m_bProjActivated(false)
, m_bCompActivated(false)
, m_bIsInit(false)
, m_iMaxFilterLength(100)
{

}

//*************************************************************************************************************

RealTimeEvokedModel::~RealTimeEvokedModel()
{
    std::cout<<"RealTimeEvokedModel::~RealTimeEvokedModel"<<std::endl;
}

//*************************************************************************************************************
//virtual functions
int RealTimeEvokedModel::rowCount(const QModelIndex & /*parent*/) const
{
    if(!m_qMapIdxRowSelection.empty()) {
        return m_qMapIdxRowSelection.size();
    }

    return 0;
}

//*************************************************************************************************************

int RealTimeEvokedModel::columnCount(const QModelIndex & /*parent*/) const
{
    return 3;
}

//*************************************************************************************************************

QVariant RealTimeEvokedModel::data(const QModelIndex &index, int role) const
{
    if(role != Qt::DisplayRole && role != Qt::BackgroundRole && role != RealTimeEvokedModelRoles::GetAverageData) {
        return QVariant();
    }

    if(index.isValid()) {
        qint32 row = m_qMapIdxRowSelection[index.row()];

        //******** first column (chname) ********
        if(index.column() == 0 && role == Qt::DisplayRole) {
            return QVariant(m_pRTE->info()->ch_names[row]);
        }

        //******** second column (butterfly data plot) ********
        //TODO: Bring this into a better structure see colum three
        if(index.column()==1) {
            QVariant v;

            switch(role) {
                case Qt::DisplayRole: {
                    //pack all adjacent (after reload) RowVectorPairs into a QList
                    RowVectorXd rowVec;

                    if(m_bIsFreezed) {
                        // data freeze
                        if(m_filterData.isEmpty()) {
                            rowVec = m_matDataFreeze.row(row);
                        } else {
                            rowVec = m_matDataFilteredFreeze.row(row);
                        }
                    } else {
                        // data stream
                        if(m_filterData.isEmpty()) {
                            rowVec = m_matData.row(row);
                        } else {
                            rowVec = m_matDataFiltered.row(row);
                        }
                    }

                    v.setValue(rowVec);

                    return v;
                    break;
                }
                case Qt::BackgroundRole: {
//                    if(m_fiffInfo.bads.contains(m_chInfolist[row].ch_name)) {
//                        QBrush brush;
//                        brush.setStyle(Qt::SolidPattern);
//    //                    qDebug() << m_chInfolist[row].ch_name << "is marked as bad, index:" << row;
//                        brush.setColor(Qt::red);
//                        return QVariant(brush);
//                    }
//                    else
                        return QVariant();

                    break;
                }
            } // end role switch
        } // end column check

        //******** third column (2D layout data plot, this third column is needed because the te data needs to be in another strucutre for the 2D layout to work) ********
        if(index.column()==2) {
            QVariant v;
            RowVectorPair averagedData;

            switch(role) {
                case RealTimeEvokedModelRoles::GetAverageData: {
                    if(m_bIsFreezed){
                        // data freeze
                        if(m_filterData.isEmpty()) {
                            averagedData.first = m_matDataFreeze.data();
                            averagedData.second = m_matDataFreeze.cols();
                        } else {
                            averagedData.first = m_matDataFilteredFreeze.data();
                            averagedData.second = m_matDataFilteredFreeze.cols();
                        }

                        v.setValue(averagedData);
                    }
                    else {
                        // data
                        if(m_filterData.isEmpty()) {
                            averagedData.first = m_matData.data();
                            averagedData.second = m_matData.cols();
                        } else {
                            averagedData.first = m_matDataFiltered.data();
                            averagedData.second = m_matDataFiltered.cols();
                        }

                        v.setValue(averagedData);
                    }
                }
            }

            return v;
        }//end column check

    } // end index.valid() check

    return QVariant();
}

//*************************************************************************************************************

QVariant RealTimeEvokedModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if(role != Qt::DisplayRole && role != Qt::TextAlignmentRole) {
        return QVariant();
    }

    if(orientation == Qt::Horizontal) {
        switch(section) {
        case 0: //chname column
            return QVariant();
        case 1: //data plot column
            switch(role) {
            case Qt::DisplayRole:
                return QVariant("data plot");
            case Qt::TextAlignmentRole:
                return QVariant(Qt::AlignLeft);
            }
            return QVariant("data plot");
        }
    }
    else if(orientation == Qt::Vertical) {
        QModelIndex chname = createIndex(section,0);
        switch(role) {
        case Qt::DisplayRole:
            return QVariant(data(chname).toString());
        }
    }

    return QVariant();
}

//*************************************************************************************************************

void RealTimeEvokedModel::setRTE(QSharedPointer<RealTimeEvoked> &pRTE)
{
    beginResetModel();
    m_pRTE = pRTE;

    //Generate bad channel index list
    RowVectorXi sel;// = RowVectorXi(0,0);
    QStringList emptyExclude;

    if(m_pRTE->info()->bads.size() > 0) {
        sel = FiffInfoBase::pick_channels(m_pRTE->info()->ch_names, m_pRTE->info()->bads, emptyExclude);
    }

    m_vecBadIdcs = sel;

    m_fSps = m_pRTE->info()->sfreq;

    //Create the initial SSP projector
    updateProjection();

    //Init list of channels which are to filtered
    createFilterChannelList(m_pRTE->info()->ch_names);

    endResetModel();

    resetSelection();
}

//*************************************************************************************************************

void RealTimeEvokedModel::updateData()
{
    if(m_matData.cols() != m_pRTE->getValue()->data.cols()) {
        //init data matrix
        m_matData.conservativeResize(m_pRTE->info()->chs.size(), m_pRTE->getValue()->data.cols());
        m_matData.setZero();
        m_matDataFreeze.conservativeResize(m_pRTE->info()->chs.size(), m_pRTE->getValue()->data.cols());
        m_matDataFreeze.setZero();
        m_matDataFiltered.conservativeResize(m_pRTE->info()->chs.size(), m_pRTE->getValue()->data.cols());
        m_matDataFiltered.setZero();
        m_matDataFilteredFreeze.conservativeResize(m_pRTE->info()->chs.size(), m_pRTE->getValue()->data.cols());
        m_matDataFilteredFreeze.setZero();
    }

    bool doProj = m_bProjActivated && m_matData.cols() > 0 && m_matData.rows() == m_matProj.cols() ? true : false;

    bool doComp = m_bCompActivated && m_matData.cols() > 0 && m_matData.rows() == m_matComp.cols() ? true : false;

    if(doComp) {
        if(doProj) {
            //Comp + Proj
            m_matData = m_matSparseProjCompMult * m_pRTE->getValue()->data;
        } else {
            //Comp
            m_matData = m_matSparseCompMult * m_pRTE->getValue()->data;
        }
    } else {
        if(doProj) {
            //Proj
            m_matData = m_matSparseProjMult * m_pRTE->getValue()->data;
        } else {
            //None - Raw
            m_matData = m_pRTE->getValue()->data;
        }
    }

    m_pairBaseline = m_pRTE->getValue()->baseline;

    if(!m_filterData.isEmpty()) {
        filterChannelsConcurrently();
    }

    m_bIsInit = true;

    //Update data content
    QModelIndex topLeft = this->index(0,1);
    QModelIndex bottomRight = this->index(m_pRTE->info()->nchan-1,1);
    QVector<int> roles; roles << Qt::DisplayRole;
    emit dataChanged(topLeft, bottomRight, roles);
}

//*************************************************************************************************************

QColor RealTimeEvokedModel::getColor(qint32 row) const
{
    if(row < m_qMapIdxRowSelection.size()) {
        qint32 chRow = m_qMapIdxRowSelection[row];
        return m_pRTE->chColor()[chRow];
    }

    return QColor();
}

//*************************************************************************************************************

fiff_int_t RealTimeEvokedModel::getKind(qint32 row) const
{
    if(row < m_qMapIdxRowSelection.size()) {
        qint32 chRow = m_qMapIdxRowSelection[row];
        return m_pRTE->info()->chs[chRow].kind;
    }

    return 0;
}

//*************************************************************************************************************

fiff_int_t RealTimeEvokedModel::getUnit(qint32 row) const
{
    if(row < m_qMapIdxRowSelection.size()) {
        qint32 chRow = m_qMapIdxRowSelection[row];
        return m_pRTE->info()->chs[chRow].unit;
    }

    return FIFF_UNIT_NONE;
}

//*************************************************************************************************************

fiff_int_t RealTimeEvokedModel::getCoil(qint32 row) const
{
    if(row < m_qMapIdxRowSelection.size()) {
        qint32 chRow = m_qMapIdxRowSelection[row];
        return m_pRTE->info()->chs[chRow].coil_type;
    }

    return FIFFV_COIL_NONE;
}

//*************************************************************************************************************

void RealTimeEvokedModel::selectRows(const QList<qint32> &selection)
{
    beginResetModel();

    m_qMapIdxRowSelection.clear();

    qint32 count = 0;
    for(qint32 i = 0; i < selection.size(); ++i) {
        if(selection[i] < m_pRTE->info()->nchan) {
            m_qMapIdxRowSelection.insert(count,selection[i]);
            ++count;
        }
    }

    emit newSelection(selection);

    endResetModel();
}

//*************************************************************************************************************

void RealTimeEvokedModel::resetSelection()
{
    beginResetModel();

    m_qMapIdxRowSelection.clear();

    for(qint32 i = 0; i < m_pRTE->info()->nchan; ++i) {
        m_qMapIdxRowSelection.insert(i,i);
    }

    endResetModel();
}

//*************************************************************************************************************

void RealTimeEvokedModel::setScaling(const QMap< qint32,float >& p_qMapChScaling)
{
    beginResetModel();
    m_qMapChScaling = p_qMapChScaling;
    endResetModel();
}

//*************************************************************************************************************

void RealTimeEvokedModel::updateProjection()
{
    //
    //  Update the SSP projector
    //
    if(m_pRTE->info()->chs.size()>0) {
        m_bProjActivated = false;
        for(qint32 i = 0; i < m_pRTE->info()->projs.size(); ++i) {
            if(m_pRTE->info()->projs[i].active) {
                m_bProjActivated = true;
            }
        }

        m_pRTE->info()->make_projector(m_matProj);
        qDebug() << "updateProjection :: New projection calculated :: m_bProjActivated is "<<m_bProjActivated;

        //set columns of matrix to zero depending on bad channels indexes
        RowVectorXi sel;// = RowVectorXi(0,0);
        QStringList emptyExclude;

        if(m_pRTE->info()->bads.size() > 0) {
            sel = FiffInfoBase::pick_channels(m_pRTE->info()->ch_names, m_pRTE->info()->bads, emptyExclude);
        }

        m_vecBadIdcs = sel;

        for(qint32 j = 0; j < m_vecBadIdcs.cols(); ++j) {
            m_matProj.col(m_vecBadIdcs[j]).setZero();
        }

//        std::cout << "Bads\n" << m_vecBadIdcs << std::endl;
//        std::cout << "Proj\n";
//        std::cout << m_matProj.block(0,0,10,10) << std::endl;

        qint32 nchan = m_pRTE->info()->nchan;
        qint32 i, k;

        typedef Eigen::Triplet<double> T;
        std::vector<T> tripletList;
        tripletList.reserve(nchan);

        //
        // Make proj sparse
        //
        tripletList.clear();
        tripletList.reserve(m_matProj.rows()*m_matProj.cols());
        for(i = 0; i < m_matProj.rows(); ++i) {
            for(k = 0; k < m_matProj.cols(); ++k) {
                if(m_matProj(i,k) != 0) {
                    tripletList.push_back(T(i, k, m_matProj(i,k)));
                }
            }
        }

        m_matSparseProjMult = SparseMatrix<double>(m_matProj.rows(),m_matProj.cols());
        if(tripletList.size() > 0) {
            m_matSparseProjMult.setFromTriplets(tripletList.begin(), tripletList.end());
        }

        //Create full multiplication matrix
        m_matSparseProjCompMult = m_matSparseProjMult * m_matSparseCompMult;
    }
}

//*************************************************************************************************************

void RealTimeEvokedModel::updateCompensator(int to)
{
    //
    //  Update the compensator
    //
    if(m_pRTE->info())
    {
        if(to == 0) {
            m_bCompActivated = false;
        } else {
            m_bCompActivated = true;
        }

//        qDebug()<<"to"<<to;
//        qDebug()<<"from"<<from;
//        qDebug()<<"m_bCompActivated"<<m_bCompActivated;

        FiffCtfComp newComp;
        m_pRTE->info()->make_compensator(0, to, newComp);//Do this always from 0 since we always read new raw data, we never actually perform a multiplication on already existing data

        //We do not need to call this->m_pFiffInfo->set_current_comp(to);
        //Because we will set the compensators to the coil in the same FiffInfo which is already used to write to file.
        //Note that the data is written in raw form not in compensated form.
        m_matComp = newComp.data->data;

        //
        // Make proj sparse
        //
        qint32 nchan = m_pRTE->info()->nchan;
        qint32 i, k;

        typedef Eigen::Triplet<double> T;
        std::vector<T> tripletList;
        tripletList.reserve(nchan);

        tripletList.clear();
        tripletList.reserve(m_matComp.rows()*m_matComp.cols());
        for(i = 0; i < m_matComp.rows(); ++i) {
            for(k = 0; k < m_matComp.cols(); ++k) {
                if(m_matComp(i,k) != 0) {
                    tripletList.push_back(T(i, k, m_matComp(i,k)));
                }
            }
        }

        m_matSparseCompMult = SparseMatrix<double>(m_matComp.rows(),m_matComp.cols());
        if(tripletList.size() > 0) {
            m_matSparseCompMult.setFromTriplets(tripletList.begin(), tripletList.end());
        }

        //Create full multiplication matrix
        m_matSparseProjCompMult = m_matSparseProjMult * m_matSparseCompMult;
    }
}

//*************************************************************************************************************

void RealTimeEvokedModel::toggleFreeze()
{
    m_bIsFreezed = !m_bIsFreezed;

    if(m_bIsFreezed) {
        m_matDataFilteredFreeze = m_matDataFiltered;
        m_matDataFreeze = m_matData;
    }

    //Update data content
    QModelIndex topLeft = this->index(0,1);
    QModelIndex bottomRight = this->index(this->rowCount(),1);
    QVector<int> roles; roles << Qt::DisplayRole;
    emit dataChanged(topLeft, bottomRight, roles);
}

//*************************************************************************************************************

void RealTimeEvokedModel::filterChanged(QList<FilterData> filterData)
{
    m_filterData = filterData;

    m_iMaxFilterLength = 1;
    for(int i=0; i<filterData.size(); i++) {
        if(m_iMaxFilterLength<filterData.at(i).m_iFilterOrder) {
            m_iMaxFilterLength = filterData.at(i).m_iFilterOrder;
        }
    }

    //Filter all visible data channels at once
    //filterChannelsConcurrently();
}

//*************************************************************************************************************

void RealTimeEvokedModel::setFilterChannelType(QString channelType)
{
    m_sFilterChannelType = channelType;
    m_filterChannelList = m_visibleChannelList;

    //This version is for when all channels of a type are to be filtered (not only the visible ones).
    //Create channel filter list independent from channelNames
    m_filterChannelList.clear();

    for(int i = 0; i<m_pRTE->info()->chs.size(); i++) {
        if((m_pRTE->info()->chs.at(i).kind == FIFFV_MEG_CH || m_pRTE->info()->chs.at(i).kind == FIFFV_EEG_CH ||
            m_pRTE->info()->chs.at(i).kind == FIFFV_EOG_CH || m_pRTE->info()->chs.at(i).kind == FIFFV_ECG_CH ||
            m_pRTE->info()->chs.at(i).kind == FIFFV_EMG_CH) && !m_pRTE->info()->bads.contains(m_pRTE->info()->chs.at(i).ch_name)) {
            if(m_sFilterChannelType == "All") {
                m_filterChannelList << m_pRTE->info()->chs.at(i).ch_name;
            } else if(m_pRTE->info()->chs.at(i).ch_name.contains(m_sFilterChannelType)) {
                m_filterChannelList << m_pRTE->info()->chs.at(i).ch_name;
            }
        }
    }

//    if(channelType != "All") {
//        QMutableListIterator<QString> i(m_filterChannelList);
//        while(i.hasNext()) {
//            QString val = i.next();
//            if(!val.contains(channelType, Qt::CaseInsensitive)) {
//                i.remove();
//            }
//        }
//    }

//    m_bDrawFilterFront = false;

    //Filter all visible data channels at once
    //filterChannelsConcurrently();
}

//*************************************************************************************************************

void RealTimeEvokedModel::createFilterChannelList(QStringList channelNames)
{
    m_filterChannelList.clear();
    m_visibleChannelList = channelNames;

    //    //Create channel fiter list based on channelNames
    //    for(int i = 0; i<m_pFiffInfo->chs.size(); i++) {
    //        if((m_pFiffInfo->chs.at(i).kind == FIFFV_MEG_CH || m_pFiffInfo->chs.at(i).kind == FIFFV_EEG_CH ||
    //            m_pFiffInfo->chs.at(i).kind == FIFFV_EOG_CH || m_pFiffInfo->chs.at(i).kind == FIFFV_ECG_CH ||
    //            m_pFiffInfo->chs.at(i).kind == FIFFV_EMG_CH) && !m_pFiffInfo->bads.contains(m_pFiffInfo->chs.at(i).ch_name)) {
    //            if(m_sFilterChannelType == "All" && channelNames.contains(m_pFiffInfo->chs.at(i).ch_name))
    //                m_filterChannelList << m_pFiffInfo->chs.at(i).ch_name;
    //            else if(m_pFiffInfo->chs.at(i).ch_name.contains(m_sFilterChannelType) && channelNames.contains(m_pFiffInfo->chs.at(i).ch_name))
    //                m_filterChannelList << m_pFiffInfo->chs.at(i).ch_name;
    //        }
    //    }

    //Create channel filter list independent from channelNames
    for(int i = 0; i<m_pRTE->info()->chs.size(); i++) {
        if((m_pRTE->info()->chs.at(i).kind == FIFFV_MEG_CH || m_pRTE->info()->chs.at(i).kind == FIFFV_EEG_CH ||
            m_pRTE->info()->chs.at(i).kind == FIFFV_EOG_CH || m_pRTE->info()->chs.at(i).kind == FIFFV_ECG_CH ||
            m_pRTE->info()->chs.at(i).kind == FIFFV_EMG_CH) && !m_pRTE->info()->bads.contains(m_pRTE->info()->chs.at(i).ch_name)) {
            if(m_sFilterChannelType == "All") {
                m_filterChannelList << m_pRTE->info()->chs.at(i).ch_name;
            } else if(m_pRTE->info()->chs.at(i).ch_name.contains(m_sFilterChannelType)) {
                m_filterChannelList << m_pRTE->info()->chs.at(i).ch_name;
            }
        }
    }

//    for(int i = 0; i<m_filterChannelList.size(); i++)
//        std::cout<<m_filterChannelList.at(i).toStdString()<<std::endl;

    //Filter all visible data channels at once
    //filterChannelsConcurrently();
}

//*************************************************************************************************************

void doFilterPerChannelRTE(QPair<QList<FilterData>,QPair<int,RowVectorXd> > &channelDataTime)
{
    for(int i=0; i<channelDataTime.first.size(); i++) {
        //channelDataTime.second.second = channelDataTime.first.at(i).applyConvFilter(channelDataTime.second.second, true, FilterData::ZeroPad);
        channelDataTime.second.second = channelDataTime.first.at(i).applyFFTFilter(channelDataTime.second.second, true, FilterData::ZeroPad); //FFT Convolution for rt is not suitable. FFT make the signal filtering non causal.
    }
}

//*************************************************************************************************************

void RealTimeEvokedModel::filterChannelsConcurrently()
{
    //std::cout<<"START RealTimeEvokedModel::filterChannelsConcurrently()"<<std::endl;

    if(m_filterData.isEmpty()) {
        return;
    }

    //Generate QList structure which can be handled by the QConcurrent framework
    QList<QPair<QList<FilterData>,QPair<int,RowVectorXd> > > timeData;
    QList<int> notFilterChannelIndex;

    //Also append mirrored data in front and back to get rid of edge effects
    for(qint32 i=0; i<m_matData.rows(); ++i) {
        if(m_filterChannelList.contains(m_pRTE->info()->chs.at(i).ch_name)) {
            RowVectorXd datTemp(m_matData.row(i).cols() + 2 * m_iMaxFilterLength);
            datTemp << m_matData.row(i).head(m_iMaxFilterLength).reverse(), m_matData.row(i), m_matData.row(i).tail(m_iMaxFilterLength).reverse();
            timeData.append(QPair<QList<FilterData>,QPair<int,RowVectorXd> >(m_filterData,QPair<int,RowVectorXd>(i,datTemp)));
        } else {
            notFilterChannelIndex.append(i);
        }
    }

    //Do the concurrent filtering
    if(!timeData.isEmpty()) {
        QFuture<void> future = QtConcurrent::map(timeData,
                                             doFilterPerChannelRTE);

        future.waitForFinished();

        for(int r = 0; r<timeData.size(); r++) {
            m_matDataFiltered.row(timeData.at(r).second.first) = timeData.at(r).second.second.segment(m_iMaxFilterLength+m_iMaxFilterLength/2, m_matData.cols());
        }
    }

    //Fill filtered data with raw data if the channel was not filtered
    for(int i = 0; i<notFilterChannelIndex.size(); i++) {
        m_matDataFiltered.row(notFilterChannelIndex.at(i)) = m_matData.row(notFilterChannelIndex.at(i));
    }

    //std::cout<<"END RealTimeEvokedModel::filterChannelsConcurrently()"<<std::endl;
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.healthcare.v1.model;

/**
 * Pseudonymization method that generates surrogates via cryptographic hashing. Uses SHA-256.
 * Outputs a base64-encoded representation of the hashed output (for example,
 * `L7k0BHmF1ha5U3NfGykjro4xWi1MPVQPjhMAZbSV9mM=`).
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Healthcare API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class CryptoHashConfig extends com.google.api.client.json.GenericJson {

  /**
   * An AES 128/192/256 bit key. Causes the hash to be computed based on this key. A default key is
   * generated for each Deidentify operation and is used when neither `crypto_key` nor `kms_wrapped`
   * is specified. Must not be set if `kms_wrapped` is set.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String cryptoKey;

  /**
   * KMS wrapped key. Must not be set if `crypto_key` is set.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private KmsWrappedCryptoKey kmsWrapped;

  /**
   * An AES 128/192/256 bit key. Causes the hash to be computed based on this key. A default key is
   * generated for each Deidentify operation and is used when neither `crypto_key` nor `kms_wrapped`
   * is specified. Must not be set if `kms_wrapped` is set.
   * @see #decodeCryptoKey()
   * @return value or {@code null} for none
   */
  public java.lang.String getCryptoKey() {
    return cryptoKey;
  }

  /**
   * An AES 128/192/256 bit key. Causes the hash to be computed based on this key. A default key is
   * generated for each Deidentify operation and is used when neither `crypto_key` nor `kms_wrapped`
   * is specified. Must not be set if `kms_wrapped` is set.
   * @see #getCryptoKey()
   * @return Base64 decoded value or {@code null} for none
   *
   * @since 1.14
   */
  public byte[] decodeCryptoKey() {
    return com.google.api.client.util.Base64.decodeBase64(cryptoKey);
  }

  /**
   * An AES 128/192/256 bit key. Causes the hash to be computed based on this key. A default key is
   * generated for each Deidentify operation and is used when neither `crypto_key` nor `kms_wrapped`
   * is specified. Must not be set if `kms_wrapped` is set.
   * @see #encodeCryptoKey()
   * @param cryptoKey cryptoKey or {@code null} for none
   */
  public CryptoHashConfig setCryptoKey(java.lang.String cryptoKey) {
    this.cryptoKey = cryptoKey;
    return this;
  }

  /**
   * An AES 128/192/256 bit key. Causes the hash to be computed based on this key. A default key is
   * generated for each Deidentify operation and is used when neither `crypto_key` nor `kms_wrapped`
   * is specified. Must not be set if `kms_wrapped` is set.
   * @see #setCryptoKey()
   *
   *

   * The value is encoded Base64 or {@code null} for none.
   *

   *
   * @since 1.14
   */
  public CryptoHashConfig encodeCryptoKey(byte[] cryptoKey) {
    this.cryptoKey = com.google.api.client.util.Base64.encodeBase64URLSafeString(cryptoKey);
    return this;
  }

  /**
   * KMS wrapped key. Must not be set if `crypto_key` is set.
   * @return value or {@code null} for none
   */
  public KmsWrappedCryptoKey getKmsWrapped() {
    return kmsWrapped;
  }

  /**
   * KMS wrapped key. Must not be set if `crypto_key` is set.
   * @param kmsWrapped kmsWrapped or {@code null} for none
   */
  public CryptoHashConfig setKmsWrapped(KmsWrappedCryptoKey kmsWrapped) {
    this.kmsWrapped = kmsWrapped;
    return this;
  }

  @Override
  public CryptoHashConfig set(String fieldName, Object value) {
    return (CryptoHashConfig) super.set(fieldName, value);
  }

  @Override
  public CryptoHashConfig clone() {
    return (CryptoHashConfig) super.clone();
  }

}

redpajama_set_name: RedPajamaGithub


text:
package LinkFuture.Demo.Mongo.Repositories;

import LinkFuture.Demo.Mongo.Entities.UserInfo;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

import java.util.List;

/**
 * Created by Cyokin
 * on 5/8/2015.
 */

public interface UserRepository extends MongoRepository<UserInfo, String> {
     UserInfo findByAccount(String account);
     @Query("{account:{ $regex:?0}}")
     public List<UserInfo> searchByAccountLike(String like);
}


text:
This README discusses how to run and test the AWS SDK for Kotlin code examples for AWS Glue.

AWS Glue is a serverless data integration service that makes it easy to discover, prepare, and combine data for analytics, machine learning, and application development.

## ⚠ Important
* The SDK for Kotlin examples perform AWS operations for the account and AWS Region for which you've specified credentials. Running these examples might incur charges on your account. For details about the charges you can expect for a given service and API operation, see the [AWS Pricing page](https://aws.amazon.com/pricing/).
* Running the tests might result in charges to your AWS account.
*  We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege).
* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services).

## Code examples

### Single action

The following examples use the **GlueClient** object:

- [Creating an AWS Glue crawler](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/CreateCrawler.kt) (CreateCrawler command)
- [Deleting an AWS Glue crawler](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/DeleteCrawler.kt) (DeleteCrawler command)
- [Getting a specific AWS Glue crawler](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/GetCrawler.kt) (GetCrawler command)
- [Getting AWS Glue crawlers](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/GetCrawlers.kt) (GetCrawlers command)
- [Getting a database](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/GetDatabases.kt) (GetDatabase command)
- [Getting a job run request](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/GetJobRun.kt) (GetJobRun command)
- [Getting all AWS Glue jobs](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/GetJobs.kt) (GetJobs command)
- [Getting all AWS Glue workflows](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/ListWorkflows.kt) (ListWorkflows command)
- [Searching AWS Glue tables based on properties](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/SearchTables.kt) (SearchTables command)
- [Starting an AWS Glue crawler](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/StartCrawler.kt) (StartCrawler command)
- [Stopping an AWS Glue crawler](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/StopCrawler.kt) (StopCrawler command)

### Scenario

- [Performing various AWS Glue operations](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/kotlin/services/glue/src/main/kotlin/com/kotlin/glue/GlueScenario.kt) (Multiple commands)

## Running the AWS Glue Kotlin files

Some of these examples perform *destructive* operations on AWS resources, such as deleting a crawler by running the **DeleteCrawler** example. **Be very careful** when running an operation that deletes or modifies AWS resources in your account. We recommend creating separate test-only resources when experimenting with these examples.

To run these examples, set up your development environment to use Gradle. For more information,
see [Get started with the SDK for Kotlin](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/get-started.html).

 ## Testing the AWS Glue Kotlin files

You can test the Kotlin code examples for AWS Glue by running a test file named **GlueTest**. This file uses JUnit 5 to run the JUnit tests and is located in the **src/test/kotlin** folder. For more information, see [https://junit.org/junit5/](https://junit.org/junit5/).

You can run the JUnit tests from an IDE, such as IntelliJ, or from the command line. As each test runs, you can view messages that inform you if the various tests succeed or fail. For example, the following message informs you that Test 3 passed.

	Test 3 passed

**WARNING**: _Running these JUnit tests manipulates real Amazon resources and might incur charges on your account._

 ### Properties file
Before running the AWS Glue JUnit tests, you must define values in the **config.properties** file located in the **resources** folder. This file contains values that are required to run the JUnit tests. For example, you define a crawler name used in the tests. If you do not define all values, the JUnit tests fail.

Define these values to successfully run the JUnit tests:

- **IAM** - The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that has AWS Glue and Amazon Simple Storage Service (Amazon S3) permissions.
- **s3Path** - The Amazon S3 target that contains data (for example, CSV data).
- **cron** - A cron expression used to specify the schedule (for example, cron(15 12 * * ? *).
- **crawlerName** - The crawler name used in various tests.
- **existingCrawlerName** - An existing crawler name that is deleted.
- **databaseName** - The name of the database used in the **CreateCrawler** test.
- **existingDatabaseName** - The name of an existing database.
- **tableName** - The name of a database table used in the **GetTable** test.
- **text** - A string used for a text search and used in the **SearchTables** test.
- **jobNameSc** - A Job name used for the Scenario test.
- **s3PathSc** - The Amazon S3 target that contains data used for the Scenario test.
- **dbNameSc** - The name of the database used for the Scenario test.
- **crawlerNameSc** - The crawler name used for the Scenario test.
- **scriptLocationSc** - The Amazon S3 path to a script that runs a job used for the Scenario test.
- **locationUri** - The location of the database used for the Scenario test.

**Note:** To set up the CSV data and other requirements needed for the unit tests, follow [Tutorial: Adding an AWS Glue crawler](https://docs.aws.amazon.com/glue/latest/ug/tutorial-add-crawler.html).

### Command line
To run the JUnit tests from the command line, you can use the following command.

		mvn test

You will see output from the JUnit tests, as shown here.

	[INFO] -------------------------------------------------------
	[INFO]  T E S T S
	[INFO] -------------------------------------------------------
	[INFO] Running GlueTest
	Test 1 passed
	Test 2 passed
	...
	Done!
	[INFO] Results:
	[INFO]
	[INFO] Tests run: 11, Failures: 0, Errors: 0, Skipped: 0
	[INFO]
	INFO] --------------------------------------------
	[INFO] BUILD SUCCESS
	[INFO]--------------------------------------------
	[INFO] Total time:  12.003 s
	[INFO] Finished at: 2020-02-10T14:25:08-05:00
	[INFO] --------------------------------------------

### Unsuccessful tests

If you do not define the correct values in the properties file, your JUnit tests are not successful. You will see an error message such as the following. You need to double-check the values that you set in the properties file and run the tests again.

	[INFO]
	[INFO] --------------------------------------
	[INFO] BUILD FAILURE
	[INFO] --------------------------------------
	[INFO] Total time:  19.038 s
	[INFO] Finished at: 2020-02-10T14:41:51-05:00
	[INFO] ---------------------------------------
	[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.1:test (default-test) on project GlueServiceTest:  There are test failures.
	[ERROR];

## Additional resources
* [Developer Guide - AWS SDK for Kotlin](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/get-started.html).
* [AWS Glue Developer Guide](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html).
* [AWS Glue Studio User Guide](https://docs.aws.amazon.com/glue/latest/ug/notebooks-chapter.html).
* [Interface GlueClient](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/glue/GlueClient.html).

Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0


text:
% Psychtoolbox:PsychFiles.
%
% help Psychtoolbox % For an overview, triple-click me & hit enter.
%
%   BreakLines              - Break string into lines and terminators.
%   CheckDirs               - Check if specified directories exist and (optionally) creates them if necessary.
%   DirList                 - Recursively lists all directories (optionally also all files) in the specified directory.
%   FileFromFolder          - Returns all files in specified folder.
%   FindFolder              - Find a folder on MATLAB path.
%   FolderFromFolder        - Returns all directories in specified folder.
%   HDRRead                 - Generic reader for HDR image files. Dispatches into dedicated readers for different file formats.
%   LiteralUnderscore       - Insert escape ("\") before each underscore char in string.
%   LogVar                  - Traverses a MATLAB variable and creates a string to represent it. When this string is evaluated with EVAL, the original variable is obtained.
%   PsychReadImageGStreamer - Reads an image file (or URL) by (ab)using GStreamer's ability to read image files like pseudo-movies.
%   PsychSaveAsEps          - Save matrix as an EPS file.
%   QuoteString             - Wraps a string in quotes.
%   ReadStructsFromText     - Read struct array from a tab delimited text file.
%   ReplaceLineTerminators  - Strip and Replace line terminators.
%   Var2Str                 - Wrapper for Var2Str that saves a variable to a text file.
%   WriteStructsToText      - Write a struct array to a tab delimited text file.

% Copyright (c) 1996-2003 by Denis Pelli & David Brainard


text:
package com.leetcode.aaront;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author tonyhui
 * @since 17/2/28
 */
public class IntersectionOfTwoArraysII {
    public static void main(String[] args) {
        IntersectionOfTwoArraysII i = new IntersectionOfTwoArraysII();
        System.out.println(Arrays.toString(i.intersect(new int[]{1, 2, 2, 1}, new int[]{2, 2})));
        System.out.println(Arrays.toString(i.intersect(new int[]{1, 2}, new int[]{1, 1})));
    }

    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        List<Integer> result = new ArrayList<>();
        for (int i = 0, len = nums2.length; i < len; i++) {
            int index = binarySearch(nums1, nums2[i]);
            if (index != -1) {
                result.add(nums2[i]);
                nums1 = delete(nums1, index);
            }
        }
        return result.stream().mapToInt(r -> r).toArray();
    }

    public int binarySearch(int[] arraySorted, int num) {
        int low = 0;
        int high = arraySorted.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arraySorted[mid] == num) return mid;
            if (arraySorted[mid] > num) high = mid - 1;
            else low = mid + 1;
        }
        return -1;
    }

    public int[] delete(int[] array, int index) {
        for (int i = index, len = array.length; i < len - 1; i++) {
            array[i] = array[i + 1];
        }
        return Arrays.copyOfRange(array, 0, array.length - 1);
    }

}


text:
package com.vikingbrain.dmt.view.util;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import com.vikingbrain.dmt.R;
import com.vikingbrain.dmt.pojo.TypeServiceStatus;

/** @author Steven Osborn - http://steven.bitsetters.com */
public class IconifiedServiceListAdapter extends BaseAdapter implements Filterable {

     /** Remember our context so we can use it when constructing views. */
     private Context mContext;

     private static String lastFilter;

     class IconifiedFilter extends Filter {
 		@Override
		protected FilterResults performFiltering(CharSequence arg0) {

			lastFilter = (arg0 != null) ? arg0.toString() : null;

			Filter.FilterResults results = new Filter.FilterResults();

			// No results yet?
			if (mOriginalItems == null) {
				results.count = 0;
				results.values = null;
				return results;
			}

			int count = mOriginalItems.size();

			if (arg0 == null || arg0.length() == 0) {
				results.count = count;
				results.values = mOriginalItems;
				return results;
			}

			List<IconifiedService> filteredItems = new ArrayList<IconifiedService>(count);

			int outCount = 0;
			CharSequence lowerCs = arg0.toString().toLowerCase();

			for (int x=0; x<count; x++) {
				IconifiedService text = mOriginalItems.get(x);

				if (text.getName().toLowerCase().contains(lowerCs)) {
					// This one matches.
					filteredItems.add(text);
					outCount++;
				}
			}

			results.count = outCount;
			results.values = filteredItems;
			return results;
		}

		@Override
		protected void publishResults(CharSequence arg0, FilterResults arg1) {
			mItems = (List<IconifiedService>) arg1.values;
			notifyDataSetChanged();
		}

		List<IconifiedService> synchronousFilter(CharSequence filter) {
			FilterResults results = performFiltering(filter);
			return (List<IconifiedService>) (results.values);
		}
     }

     private IconifiedFilter mFilter = new IconifiedFilter();

     private List<IconifiedService> mItems = new ArrayList<IconifiedService>();
     private List<IconifiedService> mOriginalItems = new ArrayList<IconifiedService>();

     public IconifiedServiceListAdapter(Context context) {
          mContext = context;
     }

     public void addItem(IconifiedService it) { mItems.add(it); }

     public void setListItems(List<IconifiedService> lit, boolean filter) {
    	 mOriginalItems = lit;

    	 if (filter) {
    		 mItems = mFilter.synchronousFilter(lastFilter);
    	 } else {
    		 mItems = lit;
    	 }
     }

     /** @return The number of items in the */
     public int getCount() { return mItems.size(); }

     public Object getItem(int position) { return mItems.get(position); }

public Object getItems() { return mItems; }

     public boolean areAllItemsSelectable() { return false; }
/*
     public boolean isSelectable(int position) {
          try{
               return mItems.get(position).isSelectable();
          }catch (IndexOutOfBoundsException aioobe){
               return super.isSelectable(position);
          }
     }
     */

     /** Use the array index as a unique id. */
     public long getItemId(int position) {
          return position;
     }

     /** @param convertView The old view to overwrite, if one is passed
      * @returns a IconifiedTextView that holds wraps around an IconifiedText */
     public View getView(int position, View convertView, ViewGroup parent) {
    	 IconifiedServiceView btv;
         if (convertView == null) {
        	 	btv = new IconifiedServiceView(mContext);
         } else { // Reuse/Overwrite the View passed
              // We are assuming(!) that it is castable!
              btv = (IconifiedServiceView) convertView;
         }

         IconifiedService current = mItems.get(position);

         //name
         btv.setText(current.getName());

         //status Adapt the enum status to the show in the view
         int infoColor = mContext.getResources().getColor(R.color.black);
         TypeServiceStatus status = current.getStatus();
         if (TypeServiceStatus.RUNNING.equals(status)){
        	 btv.setInfo(mContext.getString(R.string.running));
        	 btv.setButtonChangeStatusText(mContext.getString(R.string.stop));
        	 btv.setButtonChangeStatusVisibility(View.VISIBLE);
        	 btv.setButtonRefreshStatusVisibility(View.VISIBLE);
        	 infoColor = mContext.getResources().getColor(R.color.lightGreen);

         } else if (TypeServiceStatus.STOPPED.equals(status)){
        	 btv.setInfo(mContext.getString(R.string.stopped));
        	 btv.setButtonChangeStatusText(mContext.getString(R.string.start));
        	 btv.setButtonChangeStatusVisibility(View.VISIBLE);
        	 btv.setButtonRefreshStatusVisibility(View.VISIBLE);
        	 infoColor = mContext.getResources().getColor(R.color.lightRed);

         } else if (TypeServiceStatus.LOADING.equals(status)){
        	 btv.setInfo(mContext.getString(R.string.title_loading));
        	 btv.setButtonChangeStatusVisibility(View.GONE);
        	 btv.setButtonRefreshStatusVisibility(View.GONE);
        	 infoColor = mContext.getResources().getColor(R.color.lightBlue);

         } else if (TypeServiceStatus.SENDING_COMMAND.equals(status)){
        	 btv.setInfo(mContext.getString(R.string.service_sending_command));
        	 btv.setButtonChangeStatusVisibility(View.GONE);
        	 btv.setButtonRefreshStatusVisibility(View.VISIBLE);
        	 infoColor = mContext.getResources().getColor(R.color.lightBlue);

         } else if (TypeServiceStatus.UNKNOWN.equals(status)){
        	 btv.setInfo(mContext.getString(R.string.unknown));
        	 btv.setButtonChangeStatusVisibility(View.GONE);
        	 btv.setButtonRefreshStatusVisibility(View.VISIBLE);
        	 infoColor = mContext.getResources().getColor(R.color.lightRed);
         }

         //Text button refresh
         btv.setButtonRefreshStatusText(mContext.getString(R.string.refresh));

         //Set the tag so later I can manage the onclick from a method in the activity
         btv.getButtonChangeStatus().setTag(current);
         btv.getButtonRefreshStatus().setTag(current);

       	 int color = mContext.getResources().getColor(R.color.black);
     	 btv.setTextColor(color);

     	 //Color for info
 	     btv.setInfoColor(infoColor);

 	     //isSelected is still usable

         return btv;
     }

	public Filter getFilter() {
		return mFilter;
	}

}


text:
'use strict';

var bin = require('./');
var BinBuild = require('bin-build');
var log = require('imagemin-log');
var path = require('path');

/**
 * Install binary and check whether it works.
 * If the test fails, try to build it.
 */

var args = [
	'-copy', 'none',
	'-optimize',
	'-outfile', path.join(__dirname, '../test/fixtures/test-optimized.jpg'),
	path.join(__dirname, '../test/fixtures/test.jpg')
];

bin.run(args, function (err) {
	if (err) {
		log.warn('jpegtran pre-build test failed');
		log.info('compiling from source');

		var cfg = [
			'./configure --disable-shared',
			'--prefix="' + bin.dest() + '" --bindir="' + bin.dest() + '"'
		].join(' ');

		if (process.platform === 'darwin' && process.arch === 'x64') {
			cfg = 'CFLAGS="-m32" LDFLAGS="-m32" ' + cfg;
		}

		var builder = new BinBuild()
			.src('http://downloads.sourceforge.net/project/libjpeg-turbo/' + bin.v + '/libjpeg-turbo-' + bin.v + '.tar.gz')
			.cmd(cfg)
			.cmd('make install');

		return builder.run(function (err) {
			if (err) {
				log.error(err.stack);
				return;
			}

			log.success('jpegtran built successfully');
		});
	}

	log.success('jpegtran pre-build test passed successfully');
});


text:
require "spec_helper"

describe GraphQL::Schema::Object do
  describe "class attributes" do
    let(:object_class) { Jazz::Ensemble }

    it "tells type data" do
      assert_equal "Ensemble", object_class.graphql_name
      assert_equal "A group of musicians playing together", object_class.description
      assert_equal 6, object_class.fields.size
      assert_equal 3, object_class.interfaces.size
      # Compatibility methods are delegated to the underlying BaseType
      assert object_class.respond_to?(:connection_type)
    end

    describe "path" do
      it "is the type name" do
        assert_equal "Ensemble", object_class.path
      end
    end

    it "inherits fields and interfaces" do
      new_object_class = Class.new(object_class) do
        field :newField, String, null: true
        field :name, String, description: "The new description", null: true
      end

      # one more than the parent class
      assert_equal 7, new_object_class.fields.size
      # inherited interfaces are present
      assert_equal 3, new_object_class.interfaces.size
      # The new field is present
      assert new_object_class.fields.key?("newField")
      # The overridden field is present:
      name_field = new_object_class.fields["name"]
      assert_equal "The new description", name_field.description
    end

    it "inherits name and description" do
      # Manually assign a name since `.name` isn't populated for dynamic classes
      new_subclass_1 = Class.new(object_class) do
        graphql_name "NewSubclass"
      end
      new_subclass_2 = Class.new(new_subclass_1)
      assert_equal "NewSubclass", new_subclass_1.graphql_name
      assert_equal "NewSubclass", new_subclass_2.graphql_name
      assert_equal object_class.description, new_subclass_2.description
    end

    it "should take Ruby name (without Type suffix) as default graphql name" do
      TestingClassType = Class.new(GraphQL::Schema::Object)
      assert_equal "TestingClass", TestingClassType.graphql_name
    end

    it "raise on anonymous class without declared graphql name" do
      anonymous_class = Class.new(GraphQL::Schema::Object)
      assert_raises NotImplementedError do
        anonymous_class.graphql_name
      end
    end

    class OverrideNameObject < GraphQL::Schema::Object
      class << self
        def default_graphql_name
          "Override"
        end
      end
    end

    it "can override the default graphql_name" do
      override_name_object = OverrideNameObject

      assert_equal "Override", override_name_object.graphql_name
    end
  end

  describe "implementing interfaces" do
    it "raises an error when trying to implement a non-interface module" do
      object_type = Class.new(GraphQL::Schema::Object)

      module NotAnInterface
      end

      err = assert_raises do
        object_type.implements(NotAnInterface)
      end

      message = "NotAnInterface cannot be implemented since it's not a GraphQL Interface. Use `include` for plain Ruby modules."
      assert_equal message, err.message
    end

    it "does not inherit singleton methods from base interface when implementing another interface" do
      object_type = Class.new(GraphQL::Schema::Object)
      methods = object_type.singleton_methods
      method_defs = Hash[methods.zip(methods.map{|method| object_type.method(method.to_sym)})]

      module InterfaceType
        include GraphQL::Schema::Interface
      end

      object_type.implements(InterfaceType)
      new_method_defs = Hash[methods.zip(methods.map{|method| object_type.method(method.to_sym)})]
      assert_equal method_defs, new_method_defs
    end
  end

  describe "using GraphQL::Function" do
    new_test_func_payload = Class.new(GraphQL::Schema::Object) do
      graphql_name "TestFuncPayload"
      field :name, String, null: false
    end

    it "returns data on a field" do
      new_func_class = Class.new(GraphQL::Function) do
        argument :name, GraphQL::STRING_TYPE
        type new_test_func_payload

        def call(o, a, c)
          { name: a[:name] }
        end
      end

      new_object_class = Class.new(GraphQL::Schema::Object) do
        graphql_name "GraphQL"
        field :test, function: new_func_class.new
      end

      schema = Class.new(GraphQL::Schema) do
        query(new_object_class)
      end

      query_str = <<-GRAPHQL
      {
        test(name: "graphql") {
          name
        }
      }
      GRAPHQL
      res = schema.execute(query_str)
      assert_equal "graphql", res["data"]["test"]["name"]
    end

    it "returns data on a connection" do
      new_func_class = Class.new(GraphQL::Function) do
        argument :name, GraphQL::STRING_TYPE
        type new_test_func_payload.connection_type

        def call(o, a, c)
          [{ name: a[:name] }]
        end
      end

      new_object_class = Class.new(GraphQL::Schema::Object) do
        graphql_name "GraphQL"
        field :test_conn, function: new_func_class.new
      end

      schema = Class.new(GraphQL::Schema) do
        query(new_object_class)
      end

      query_str = <<-GRAPHQL
      {
        testConn(name: "graphql") {
          edges {
            node {
              name
            }
          }
        }
      }
      GRAPHQL
      res = schema.execute(query_str)
      assert_equal "graphql", res["data"]["testConn"]["edges"][0]["node"]["name"]
    end
  end

  describe "wrapping a Hash" do
    it "automatically looks up symbol and string keys" do
      query_str = <<-GRAPHQL
      {
        hashyEnsemble {
          musicians { name }
          formedAt
        }
      }
      GRAPHQL
      res = Jazz::Schema.execute(query_str)
      ensemble = res["data"]["hashyEnsemble"]
      assert_equal ["Jerry Garcia"], ensemble["musicians"].map { |m| m["name"] }
      assert_equal "May 5, 1965", ensemble["formedAt"]
    end

    it "works with strings and symbols" do
      query_str = <<-GRAPHQL
      {
        hashByString { falsey }
        hashBySym { falsey }
      }
      GRAPHQL
      res = Jazz::Schema.execute(query_str)
      assert_equal false, res["data"]["hashByString"]["falsey"]
      assert_equal false, res["data"]["hashBySym"]["falsey"]
    end
  end

  describe "wrapping `nil`" do
    it "doesn't wrap nil in lists" do
      query_str = <<-GRAPHQL
      {
        namedEntities {
          name
        }
      }
      GRAPHQL

      res = Jazz::Schema.execute(query_str)
      expected_items = [{"name" => "Bela Fleck and the Flecktones"}, nil]
      assert_equal expected_items, res["data"]["namedEntities"]
    end
  end

  describe ".to_graphql" do
    let(:obj_type) { Jazz::Ensemble.to_graphql }
    it "returns a matching GraphQL::ObjectType" do
      assert_equal "Ensemble", obj_type.name
      assert_equal "A group of musicians playing together", obj_type.description
      assert_equal 6, obj_type.all_fields.size

      name_field = obj_type.all_fields[2]
      assert_equal "name", name_field.name
      assert_equal GraphQL::STRING_TYPE.to_non_null_type, name_field.type
      assert_equal nil, name_field.description
    end

    it "has a custom implementation" do
      assert_equal obj_type.metadata[:config], :configged
    end

    it "uses the custom field class" do
      query_str = <<-GRAPHQL
      {
        ensembles { upcaseName }
      }
      GRAPHQL

      res = Jazz::Schema.execute(query_str)
      assert_equal ["BELA FLECK AND THE FLECKTONES", "ROBERT GLASPER EXPERIMENT"], res["data"]["ensembles"].map { |e| e["upcaseName"] }
    end
  end

  describe "in queries" do
    after {
      Jazz::Models.reset
    }

    it "returns data" do
      query_str = <<-GRAPHQL
      {
        ensembles { name }
        instruments { name }
      }
      GRAPHQL
      res = Jazz::Schema.execute(query_str)
      expected_ensembles = [
        {"name" => "Bela Fleck and the Flecktones"},
        {"name" => "ROBERT GLASPER Experiment"},
      ]
      assert_equal expected_ensembles, res["data"]["ensembles"]
      assert_equal({"name" => "Banjo"}, res["data"]["instruments"].first)
    end

    it "does mutations" do
      mutation_str = <<-GRAPHQL
      mutation AddEnsemble($name: String!) {
        addEnsemble(input: { name: $name }) {
          id
        }
      }
      GRAPHQL

      query_str = <<-GRAPHQL
      query($id: ID!) {
        find(id: $id) {
          ... on Ensemble {
            name
          }
        }
      }
      GRAPHQL

      res = Jazz::Schema.execute(mutation_str, variables: { name: "Miles Davis Quartet" })
      new_id = res["data"]["addEnsemble"]["id"]

      res2 = Jazz::Schema.execute(query_str, variables: { id: new_id })
      assert_equal "Miles Davis Quartet", res2["data"]["find"]["name"]
    end

    it "initializes root wrappers once" do
      query_str = " { oid1: objectId oid2: objectId }"
      res = Jazz::Schema.execute(query_str)
      assert_equal res["data"]["oid1"], res["data"]["oid2"]
    end

    it "skips fields properly" do
      query_str = "{ find(id: \"MagicalSkipId\") { __typename } }"
      res = Jazz::Schema.execute(query_str)
      # TBH I think `{}` is probably righter than `nil`, I guess we'll see.
      skip_value = TESTING_INTERPRETER ? {} : nil
      assert_equal({"data" => skip_value }, res.to_h)
    end
  end

  describe "when fields conflict with built-ins" do
    it "warns when no override" do
      expected_warning = "X's `field :method` conflicts with a built-in method, use `resolver_method:` to pick a different resolver method for this field (for example, `resolver_method: :resolve_method` and `def resolve_method`)\n"
      assert_output "", expected_warning do
        Class.new(GraphQL::Schema::Object) do
          graphql_name "X"
          field :method, String, null: true
        end
      end
    end

    it "doesn't warn with an override" do
      assert_output "", "" do
        Class.new(GraphQL::Schema::Object) do
          graphql_name "X"
          field :method, String, null: true, resolver_method: :resolve_method
        end
      end
    end
  end
end


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

<title>Uses of Class net.jini.lookup.LookupCacheImpl.CacheTaskWrapper (River-Internet vtrunk API Documentation (internals))</title>
<meta name="date" content="2016-03-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.jini.lookup.LookupCacheImpl.CacheTaskWrapper

Packages that use LookupCacheImpl.CacheTaskWrapper

Package
Description

net.jini.lookup

Standard utility classes for managing the join state of a service
and the service discovery duties of a client or service.

Uses of LookupCacheImpl.CacheTaskWrapper in net.jini.lookup

Fields in net.jini.lookup with type parameters of type LookupCacheImpl.CacheTaskWrapper

Modifier and Type
Field and Description

private java.util.concurrent.ConcurrentLinkedQueue<LookupCacheImpl.CacheTaskWrapper>
LookupCacheImpl.CacheTaskDependencyManager.pending

Methods in net.jini.lookup that return LookupCacheImpl.CacheTaskWrapper

Modifier and Type
Method and Description

(package private) LookupCacheImpl.CacheTaskWrapper
LookupCacheImpl.CacheTaskDependencyManager.submit(Runnable t)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright 2007-2013, multiple authors.
Licensed under the Apache License, Version 2.0, see the NOTICE file for attributions.


text:
import numpy as np
from scipy.sparse import csr_matrix
from openfermion.third_party.representability._dualbasis import \
    DualBasisElement, DualBasis

class TMap(object):

    def __init__(self, tensors):
        """
        provide a map of tensor name to tensors

        :param tensors: list of tensors
        :return: TMap object
        """
        self.tensors = tensors
        self._map = dict(map(lambda x: (x.name, x), self.tensors))

    def __getitem__(self, i):
        return self._map[i]

    def __iter__(self):
        for tt in self.tensors:
            yield tt

class MultiTensor(object):

    def __init__(self, tensors, dual_basis=DualBasis()):
        """
        A collection of tensor objects with maps from name to tensor

        Args:
            tensors: a dictionary or tuple of tensors and their associated call
                     name.
            DualBasisElement dual_basis: the set of linear operators restricting
                                         the feasible elements of the linear
                                         space generated by vectorizing the
                                         tensors.
        """
        if not isinstance(tensors, list):
            raise TypeError("MultiTensor accepts a list")

        # this preserves the order the user passes with the tensors
        self.tensors = TMap(tensors)

        # since all the tensors are indexed from zero...I need to know their
        # numbering offset when combined with everything.
        self.off_set_map = self.make_offset_dict(self.tensors)

        # An iterable object that provides access to the dual basis elements
        self.dual_basis = dual_basis
        self.vec_dim = sum([vec.size for vec in self.tensors])

    @staticmethod
    def make_offset_dict(tensors):
        if not isinstance(tensors, TMap):
            raise TypeError("Tensors must be a TMap")

        tally = 0
        offsets = {}
        # this is why ordered dicts are great.  Remembering orderings
        for tensor_value in tensors:
            offsets[tensor_value.name] = tally
            tally += tensor_value.size

        return offsets

    def vectorize_tensors(self):
        """
        vectorize the tensors

        :returns: a vectorized form of the tensors
        """
        vec = np.empty((0, 1))
        for tensor in self.tensors:
            vec = np.vstack((vec, tensor.vectorize()))
        return vec

    def add_dual_elements(self, dual_element):
        """
        Add  a dual element to the dual basis
        """
        if not isinstance(dual_element, DualBasisElement):
            raise TypeError(
                "dual_element variable needs to be a DualBasisElement type")

        # we should extend TMap to add
        self.dual_basis.elements.extend(dual_element)

    def synthesize_dual_basis(self):
        """
        from the list of maps create a m x n sparse matrix for Ax=b

        where x is the vectorized form of all the tensors.  This would be
        the very last step usually.

        :returns: sparse matrix
        """
        # go throught the dual basis list and synthesize each element
        dual_row_indices = []
        dual_col_indices = []
        dual_data_values = []

        # this forms the b-vector of ax + b = c
        bias_data_values = []
        # this forms the c-vector of ax + b = c
        inner_prod_data_values = []
        for index, dual_element in enumerate(self.dual_basis):
            dcol, dval = self.synthesize_element(dual_element)
            dual_row_indices.extend([index] * len(dcol))
            dual_col_indices.extend(dcol)
            dual_data_values.extend(dval)
            inner_prod_data_values.append(float(dual_element.dual_scalar))
            bias_data_values.append(dual_element.constant_bias)
        sparse_dual_operator = csr_matrix(
            (dual_data_values, (dual_row_indices, dual_col_indices)),
            [index + 1, self.vec_dim])

        sparse_bias_vector = csr_matrix(
            (bias_data_values, (range(index + 1), [0] * (index + 1))),
            [index + 1, 1])

        sparse_innerp_vector = csr_matrix(
            (inner_prod_data_values, (range(index + 1), [0] * (index + 1))),
            [index + 1, 1])

        return sparse_dual_operator, sparse_bias_vector, sparse_innerp_vector

    def synthesize_element(self, element):
        """
        Generate the row index and column index for an element

        :param DualBasisElement element: element of the dual basis to vectorize
        """
        col_idx = []
        data_vals = []
        for tlabel, velement, coeff in element:
            col_idx.append(self.off_set_map[tlabel] +
                           self.tensors[tlabel].index_vectorized(*velement))
            data_vals.append(coeff)

        return col_idx, data_vals


text:
<?xml version='1.0' encoding='UTF-8'?>
<CreateInstanceResponse>
	<InstanceId>i-28n7dkvov</InstanceId>
	<RequestId>DA38B11A-9D6D-420B-942F-95D68606C4FC</RequestId>
</CreateInstanceResponse>


text:
<?php

	require_once(__CA_MODELS_DIR__.'/ca_objects.php');

	$va_facets 				= $this->getVar('available_facets');
	$va_facets_with_content	= $this->getVar('facets_with_content');
	$va_facet_info 			= $this->getVar('facet_info');
	$va_criteria 			= is_array($this->getVar('criteria')) ? $this->getVar('criteria') : array();
	$va_results 			= $this->getVar('result');

	$vs_browse_target		= $this->getVar('target');

	$t_object = new ca_objects();
	$va_random_items = $t_object->getRandomItems(10, array('checkAccess' => $this->getVar('access_values'), 'hasRepresentations' => 1));
	$va_labels = array();
	$va_media = array();
	if(is_array($va_random_items) && sizeof($va_random_items)){
		$va_labels = $t_object->getPreferredDisplayLabelsForIDs(array_keys($va_random_items));
		$va_media = $t_object->getPrimaryMediaForIDs(array_keys($va_random_items), array('medium'), array('checkAccess' => $this->getVar('access_values')));
	}
	JavascriptLoadManager::register('cycle');

	if (!$this->request->isAjax()) {
		if ($this->getVar('browse_selector')) {
	?>

<?php print _t('Browse for').' '.$this->getVar('browse_selector'); ?>

	<?php
		}
?>

<?php
	}
?>

<?php
			if (sizeof($va_criteria)) {
				print "
";

				$vn_x = 0;
				print "
";
				foreach($va_criteria as $vs_facet_name => $va_row_ids) {
					$vn_x++;
					$vn_row_c = 0;
					foreach($va_row_ids as $vn_row_id => $vs_label) {
						print "{$vs_label}".caNavLink($this->request, 'x', 'close', '', 'Browse', 'removeCriteria', array('facet' => $vs_facet_name, 'id' => $vn_row_id))."\n";
						$vn_row_c++;
					}

				}
				print caNavLink($this->request, _t('Clear all'), 'startOver', '', 'Browse', 'clearCriteria', array());
				print "
\n";

				if (sizeof($va_facets)) {
?>

<?php print _t('Refine by'); ?>:
<?php
						$vn_i = 1;
						$va_available_facets = $this->getVar('available_facets');
						foreach($va_available_facets as $vs_facet_code => $va_facet_info) {
							print "".$va_facet_info['label_plural']."";
							if($vn_i < sizeof($va_available_facets)){
								print ", ";
							}
							$vn_i++;
						}
?>

<?php
				}
				print "
";

			} else {
				if (sizeof($va_facets)) {
					if ($vs_browse_target == "ca_occurrences") {
						$va_target = "productions";
					} elseif ($vs_browse_target == "ca_objects") {
						$va_target = "objects";
					} else {
						$va_target = "people";
					}
					print "
";
					$va_available_facets = $this->getVar('available_facets');
					foreach($va_available_facets as $vs_facet_code => $va_facet_info) {
						print "
Filter {$va_target} by ".$va_facet_info['label_plural']."request->getThemeUrlPath()."/graphics/arrow_right_gray.gif' width='6' height='7' border='0'>
\n";
						print "

";
					}
					print "
";
				}
			}

?>

<?php
	if (sizeof($va_criteria) > 0) {
		# --- show results
		print $this->render('Results/paging_controls_html.php');

		print $this->render('Search/search_controls_html.php');
		if($this->getVar('current_view') != 'map' && $this->request->isLoggedIn() && !$this->request->config->get('disable_my_collections')){
			print $this->render('Search/search_tools_html.php');
		}
?>

<?php
		print "
";
		$vs_view = $this->getVar('current_view');
		if(in_array($vs_view, array_keys($this->getVar('result_views')))){
			print $this->render('Results/'.$vs_browse_target.'_results_'.$vs_view.'_html.php');
		}
		print "
";
	}
	if (!$this->request->isAjax()) {
?>

<?php
	}
?>


text:
package com.osa.se.service;

import com.osa.se.dao.PaymentRepository;
import com.osa.se.model.Payment;
import org.springframework.stereotype.Service;

/**
 * Created by tarinidash on 2/28/17.
 */
@Service
public class PaymentService {

    private PaymentRepository paymentRepository;

    public PaymentService(PaymentRepository paymentRepository) {
        this.paymentRepository = paymentRepository;
    }

    public Payment save(Payment payment) {
        return paymentRepository.save(payment);
    }

    public Payment findOne(String paymentId) {
        return paymentRepository.findOne(paymentId);
    }

    public Iterable<Payment> findAll() {
        return paymentRepository.findAll();
    }

    public boolean exists(String paymentId) {
        return paymentRepository.exists(paymentId);
    }

    public long count() {
        return paymentRepository.count();
    }

    public void delete(String paymentId) {
        paymentRepository.delete(paymentId);
    }

    public void delete(Payment payment) {
        paymentRepository.delete(payment);
    }

    public void deleteAll() {
        paymentRepository.deleteAll();
    }

}


text:
FROM debian:jessie
MAINTAINER Lukas Martinelli <me@lukasmartinelli.ch>

# install dependencies for building facebook libraries
RUN apt-get update
RUN apt-get install -y \
    python \
    ruby-full make cmake pkg-config \
    openjdk-7-jre \
    git \
    wget unzip \
    nodejs npm

RUN gem install bugspots

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

RUN wget https://github.com/pmd/pmd/releases/download/pmd_releases%2F5.3.3/pmd-bin-5.3.3.zip && \
    unzip pmd-bin-5.3.3.zip && \
    rm pmd-bin-5.3.3.zip
ENV PMD_BINARY /usr/src/app/pmd-bin-5.3.3/bin/run.sh

COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app

EXPOSE 3000
CMD ["nodejs", "server.js"]


text:
export class Social {
  public name: string;
  public url: string;
}


text:
namespace Xilium.CefGlue
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    using Xilium.CefGlue.Interop;

    /// <summary>
    /// Class used for managing cookies. The methods of this class may be called on
    /// any thread unless otherwise indicated.
    /// </summary>
    public sealed unsafe partial class CefCookieManager
    {
        /// <summary>
        /// Returns the global cookie manager. By default data will be stored at
        /// CefSettings.cache_path if specified or in memory otherwise.
        /// </summary>
        public static CefCookieManager Global
        {
            get
            {
                return CefCookieManager.FromNative(
                    cef_cookie_manager_t.get_global_manager()
                    );
            }
        }

        /// <summary>
        /// Creates a new cookie manager. If |path| is empty data will be stored in
        /// memory only. Otherwise, data will be stored at the specified |path|. To
        /// persist session cookies (cookies without an expiry date or validity
        /// interval) set |persist_session_cookies| to true. Session cookies are
        /// generally intended to be transient and most Web browsers do not persist
        /// them. Returns NULL if creation fails.
        /// </summary>
        public static CefCookieManager Create(string path, bool persistSessionCookies)
        {
            fixed (char* path_str = path)
            {
                var n_path = new cef_string_t(path_str, path != null ? path.Length : 0);

                return CefCookieManager.FromNativeOrNull(
                    cef_cookie_manager_t.create_manager(&n_path, persistSessionCookies ? 1 : 0)
                    );
            }
        }

        /// <summary>
        /// Set the schemes supported by this manager. By default only "http" and
        /// "https" schemes are supported. Must be called before any cookies are
        /// accessed.
        /// </summary>
        public void SetSupportedSchemes(string[] schemes)
        {
            var n_schemes = cef_string_list.From(schemes);
            cef_cookie_manager_t.set_supported_schemes(_self, n_schemes);
            libcef.string_list_free(n_schemes);
        }

        /// <summary>
        /// Visit all cookies. The returned cookies are ordered by longest path, then
        /// by earliest creation date. Returns false if cookies cannot be accessed.
        /// </summary>
        public bool VisitAllCookies(CefCookieVisitor visitor)
        {
            if (visitor == null) throw new ArgumentNullException("visitor");

            return cef_cookie_manager_t.visit_all_cookies(_self, visitor.ToNative()) != 0;
        }

        /// <summary>
        /// Visit a subset of cookies. The results are filtered by the given url
        /// scheme, host, domain and path. If |includeHttpOnly| is true HTTP-only
        /// cookies will also be included in the results. The returned cookies are
        /// ordered by longest path, then by earliest creation date. Returns false if
        /// cookies cannot be accessed.
        /// </summary>
        public bool VisitUrlCookies(string url, bool includeHttpOnly, CefCookieVisitor visitor)
        {
            if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
            if (visitor == null) throw new ArgumentNullException("visitor");

            fixed (char* url_str = url)
            {
                var n_url = new cef_string_t(url_str, url.Length);

                return cef_cookie_manager_t.visit_url_cookies(_self, &n_url, includeHttpOnly ? 1 : 0, visitor.ToNative()) != 0;
            }
        }

        /// <summary>
        /// Sets a cookie given a valid URL and explicit user-provided cookie
        /// attributes. This function expects each attribute to be well-formed. It will
        /// check for disallowed characters (e.g. the ';' character is disallowed
        /// within the cookie value attribute) and will return false without setting
        /// the cookie if such characters are found. This method must be called on the
        /// IO thread.
        /// </summary>
        public bool SetCookie(string url, CefCookie cookie)
        {
            if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url");
            if (cookie == null) throw new ArgumentNullException("cookie");

            int n_result;
            var n_cookie = cookie.ToNative();
            fixed (char* url_str = url)
            {
                var n_url = new cef_string_t(url_str, url.Length);
                n_result = cef_cookie_manager_t.set_cookie(_self, &n_url, n_cookie);
            }
            CefCookie.Free(n_cookie);
            return n_result != 0;
        }

        /// <summary>
        /// Delete all cookies that match the specified parameters. If both |url| and
        /// values |cookie_name| are specified all host and domain cookies matching
        /// both will be deleted. If only |url| is specified all host cookies (but not
        /// domain cookies) irrespective of path will be deleted. If |url| is empty all
        /// cookies for all hosts and domains will be deleted. Returns false if a non-
        /// empty invalid URL is specified or if cookies cannot be accessed. This
        /// method must be called on the IO thread.
        /// </summary>
        public bool DeleteCookies(string url, string cookieName)
        {
            fixed (char* url_str = url)
            fixed (char* cookieName_str = cookieName)
            {
                var n_url = new cef_string_t(url_str, url != null ? url.Length : 0);
                var n_cookieName = new cef_string_t(cookieName_str, cookieName != null ? cookieName.Length : 0);

                return cef_cookie_manager_t.delete_cookies(_self, &n_url, &n_cookieName) != 0;
            }
        }

        /// <summary>
        /// Sets the directory path that will be used for storing cookie data. If
        /// |path| is empty data will be stored in memory only. Otherwise, data will be
        /// stored at the specified |path|. To persist session cookies (cookies without
        /// an expiry date or validity interval) set |persist_session_cookies| to true.
        /// Session cookies are generally intended to be transient and most Web browsers
        /// do not persist them. Returns false if cookies cannot be accessed.
        /// </summary>
        public bool SetStoragePath(string path, bool persistSessionCookies)
        {
            fixed (char* path_str = path)
            {
                var n_path = new cef_string_t(path_str, path != null ? path.Length : 0);

                return cef_cookie_manager_t.set_storage_path(_self, &n_path, persistSessionCookies ? 1 : 0) != 0;
            }
        }

        /// <summary>
        /// Flush the backing store (if any) to disk and execute the specified
        /// |callback| on the IO thread when done. Returns false if cookies cannot be
        /// accessed.
        /// </summary>
        public bool FlushStore(CefCompletionCallback callback)
        {
            var n_handler = callback != null ? callback.ToNative() : null;

            return cef_cookie_manager_t.flush_store(_self, n_handler) != 0;
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

<title>Exemple d'un formulaire</title>
<meta content="width=device-width,initial-scale=1" name="viewport">

<meta name="description" content="La Boîte à outils de l'expérience Web (BOEW) rassemble différents composants réutilisables et prêts-à-utiliser pour la conception et la mise à jour de sites Web innovateurs qui sont à la fois accessibles, conviviaux et interopérables. Tous ces composants réutilisables sont des logiciels libres mis à la disposition des ministères et des collectivités Web externes.">

<link href="./lib/GCWeb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="./lib/GCWeb/css/theme.min.css">

<link rel="stylesheet" href="./lib/wet-boew/css/noscript.min.css" />

Passer au contenu principal

Passer à « À propos de ce site »

Sélection de la langue

English

<object type="image/svg+xml" tabindex="-1" data="./lib/GCWeb/assets/sig-blk-fr.svg"></object> Gouvernement du Canada

Recherche et menus

Recherche et menus

Recherche

<form action="#" method="post" name="cse-search-box" role="search" class="form-inline">

Recherchez le site Web
<input id="wb-srch-q" list="wb-srch-q-ac" class="wb-srch-q form-control" name="q" type="search" value="" size="27" maxlength="150" placeholder="Rechercher dans Canada.ca">
<datalist id="wb-srch-q-ac">

</datalist>

<button type="submit" id="wb-srch-sub" class="btn btn-primary btn-small" name="wb-srch-sub">Recherche</button>

</form>

Menu des sujets

Emplois

Immigration

Voyage

Entreprises

Prestations

Santé

Impôts

Autres services

Vous êtes ici :

Accueil

Page de contenu

Exemple d'un formulaire d'application 2

Ce formulaire n'est pas connecté à un serveur - les données ne sont pas enregistrées.

		<form action="./exform3-fr.html" method="get" id="validation-example" novalidate>

				Numéro de téléphone en journée

Modifier certains chiffres pour protéger votre identité.

				<input class="form-control" id="tel1" name="tel1" type="tel" data-rule-phoneus="true" aria-describedby="tel1-desc">

				Si vous pouviez voyager n'importe où pour vos vacances d'été, quel serait le pays que vous aimeriez le plus visiter?(obligatoire)
				<select class="form-control" id="country1" name="country1" required="required">
					<option value="">Sélectionnez une destination</option>
					<option value="acores">Açores</option>
					<option value="afghanistan">Afghanistan</option>
					<option value="afrique-du-sud">Afrique du Sud</option>
					<option value="albanie">Albanie</option>
					<option value="algerie">Algérie</option>
					<option value="allemagne">Allemagne</option>
					<option value="andorre">Andorre</option>
					<option value="angola">Angola</option>
					<option value="anguilla">Anguilla</option>
					<option value="antarctique">Antarctique</option>
					<option value="antigua-et-barbuda">Antigua-et-Barbuda</option>
					<option value="arabie-saoudite">Arabie saoudite</option>
					<option value="argentine">Argentine</option>
					<option value="armenie">Arménie</option>
					<option value="aruba">Aruba</option>
					<option value="australie">Australie</option>
					<option value="autriche">Autriche</option>
					<option value="azerbaidjan">Azerbaïdjan</option>
					<option value="bahamas">Bahamas</option>
					<option value="bahrein">Bahreïn</option>
					<option value="bangladesh">Bangladesh</option>
					<option value="barbade">Barbade</option>
					<option value="belarus">Bélarus</option>
					<option value="belgique">Belgique</option>
					<option value="belize">Belize</option>
					<option value="benin">Bénin</option>
					<option value="bermudes">Bermudes</option>
					<option value="bhoutan">Bhoutan</option>
					<option value="birmanie-myanmar">Birmanie (Myanmar)</option>
					<option value="bolivie">Bolivie</option>
					<option value="bonaire">Bonaire</option>
					<option value="bosnie-herzegovine">Bosnie-Herzégovine</option>
					<option value="botswana">Botswana</option>
					<option value="bresil">Brésil</option>
					<option value="brunei-darussalam">Brunéi Darussalam</option>
					<option value="bulgarie">Bulgarie</option>
					<option value="burkina-faso">Burkina Faso</option>
					<option value="burundi">Burundi</option>
					<option value="cabo-verde">Cabo Verde</option>
					<option value="cambodge">Cambodge</option>
					<option value="cameroun">Cameroun</option>
					<option value="chili">Chili</option>
					<option value="chine">Chine</option>
					<option value="chypre">Chypre</option>
					<option value="colombie">Colombie</option>
					<option value="comores">Comores</option>
					<option value="coree-nord-rpdc">Corée, Nord (RPDC)</option>
					<option value="coree-sud">Corée, Sud</option>
					<option value="costa-rica">Costa Rica</option>
					<option value="cote-d-ivoire">Côte d'Ivoire</option>
					<option value="croatie">Croatie</option>
					<option value="cuba">Cuba</option>
					<option value="curacao">Curaçao</option>
					<option value="danemark">Danemark</option>
					<option value="djibouti">Djibouti</option>
					<option value="dominique">Dominique</option>
					<option value="egypte">Égypte</option>
					<option value="emirats-arabes-unis">Émirats arabes unis</option>
					<option value="equateur">Équateur</option>
					<option value="erythree">Érythrée</option>
					<option value="espagne">Espagne</option>
					<option value="estonie">Estonie</option>
					<option value="etats-unis">États-Unis</option>
					<option value="ethiopie">Éthiopie</option>
					<option value="fidji">Fidji</option>
					<option value="finlande">Finlande</option>
					<option value="france">France</option>
					<option value="gabon">Gabon</option>
					<option value="gambie">Gambie</option>
					<option value="georgie">Géorgie</option>
					<option value="ghana">Ghana</option>
					<option value="gibraltar">Gibraltar</option>
					<option value="grece">Grèce</option>
					<option value="grenade">Grenade</option>
					<option value="groenland">Groenland</option>
					<option value="guadeloupe">Guadeloupe</option>
					<option value="guam">Guam</option>
					<option value="guatemala">Guatemala</option>
					<option value="guinee">Guinée</option>
					<option value="guinee-bissau">Guinée-Bissau</option>
					<option value="guinee-equatoriale">Guinée équatoriale</option>
					<option value="guyana">Guyana</option>
					<option value="guyane-francaise">Guyane française</option>
					<option value="haiti">Haïti</option>
					<option value="honduras">Honduras</option>
					<option value="hong-kong">Hong Kong</option>
					<option value="hongrie">Hongrie</option>
					<option value="maurice-ile">Île Maurice</option>
					<option value="caimans-iles">Îles Caïmans</option>
					<option value="iles-canaries">Îles Canaries</option>
					<option value="iles-cook">Îles Cook</option>
					<option value="iles-malouines">Îles Malouines</option>
					<option value="mariannes-du-nord-iles">Îles Mariannes du Nord</option>
					<option value="marshall-iles">Îles Marshall</option>
					<option value="salomon-iles">Îles Salomon</option>
					<option value="turques-et-caiques-iles">Îles Turques et Caïques</option>
					<option value="iles-vierges-americaines">Îles Vierges américaines</option>
					<option value="iles-vierges-britanniques">Îles Vierges britanniques </option>
					<option value="inde">Inde</option>
					<option value="indonesie">Indonésie</option>
					<option value="iran">Iran</option>
					<option value="iraq">Iraq</option>
					<option value="irlande">Irlande</option>
					<option value="islande">Islande</option>
					<option value="israel-la-cisjordanie-et-la-bande-de-gaza">Israël, la Cisjordanie et la bande de Gaza</option>
					<option value="italie">Italie</option>
					<option value="jamaique">Jamaïque</option>
					<option value="japon">Japon</option>
					<option value="jordanie">Jordanie</option>
					<option value="kazakhstan">Kazakhstan</option>
					<option value="kenya">Kenya</option>
					<option value="kiribati">Kiribati</option>
					<option value="kosovo">Kosovo</option>
					<option value="koweit">Koweït</option>
					<option value="laos">Laos</option>
					<option value="lesotho">Lesotho</option>
					<option value="lettonie">Lettonie</option>
					<option value="liban">Liban</option>
					<option value="liberia">Libéria</option>
					<option value="libye">Libye</option>
					<option value="liechtenstein">Liechtenstein</option>
					<option value="lituanie">Lituanie</option>
					<option value="luxembourg">Luxembourg</option>
					<option value="macao">Macao</option>
					<option value="macedoine">Macédoine</option>
					<option value="madagascar">Madagascar</option>
					<option value="malaisie">Malaisie</option>
					<option value="malawi">Malawi</option>
					<option value="maldives">Maldives</option>
					<option value="mali">Mali</option>
					<option value="malte">Malte</option>
					<option value="maroc">Maroc</option>
					<option value="martinique">Martinique</option>
					<option value="mauritanie">Mauritanie</option>
					<option value="mayotte">Mayotte</option>
					<option value="mexique">Mexique</option>
					<option value="micronesie-efm">Micronésie (EFM)</option>
					<option value="moldova">Moldova</option>
					<option value="monaco">Monaco</option>
					<option value="mongolie">Mongolie</option>
					<option value="montenegro">Monténégro</option>
					<option value="montserrat">Montserrat</option>
					<option value="mozambique">Mozambique</option>
					<option value="namibie">Namibie</option>
					<option value="nauru">Nauru</option>
					<option value="nepal">Népal</option>
					<option value="nicaragua">Nicaragua</option>
					<option value="niger">Niger</option>
					<option value="nigeria">Nigéria</option>
					<option value="niue">Niue</option>
					<option value="norvege">Norvège</option>
					<option value="nouvelle-caledonie">Nouvelle-Calédonie</option>
					<option value="nouvelle-zelande">Nouvelle-Zélande</option>
					<option value="oman">Oman</option>
					<option value="ouganda">Ouganda</option>
					<option value="ouzbekistan">Ouzbékistan</option>
					<option value="pakistan">Pakistan</option>
					<option value="palaos">Palaos</option>
					<option value="panama">Panama</option>
					<option value="papouasie-nouvelle-guinee">Papouasie-Nouvelle-Guinée</option>
					<option value="paraguay">Paraguay</option>
					<option value="pays-bas">Pays-Bas</option>
					<option value="perou">Pérou</option>
					<option value="philippines">Philippines</option>
					<option value="pologne">Pologne</option>
					<option value="polynesie-francaise">Polynésie française</option>
					<option value="puerto-rico">Porto Rico</option>
					<option value="portugal">Portugal</option>
					<option value="qatar">Qatar</option>
					<option value="republique-centrafricaine">République centrafricaine</option>
					<option value="congo-kinshasa">République démocratique du Congo (Kinshasa)</option>
					<option value="republique-dominicaine">République dominicaine</option>
					<option value="congo-brazzaville">République du Congo (Brazzaville)</option>
					<option value="republique-kirghize">République kirghize</option>
					<option value="republique-tcheque">République tchèque</option>
					<option value="roumanie">Roumanie</option>
					<option value="royaume-uni">Royaume-Uni</option>
					<option value="russie">Russie</option>
					<option value="rwanda">Rwanda</option>
					<option value="saint-barthelemy">Saint-Barthélemy</option>
					<option value="saint-kitts-et-nevis">Saint-Kitts-et-Nevis</option>
					<option value="saint-marin">Saint-Marin</option>
					<option value="saint-martin">Saint-Martin</option>
					<option value="saint-pierre-et-miquelon">Saint-Pierre-et-Miquelon</option>
					<option value="saint-vincent-et-grenadines">Saint-Vincent-et-Grenadines</option>
					<option value="sainte-lucie">Sainte-Lucie</option>
					<option value="salvador">Salvador</option>
					<option value="samoa">Samoa</option>
					<option value="samoa-americaines">Samoa américaines</option>
					<option value="sao-tome-et-principe">São Tomé-et-Principe</option>
					<option value="senegal">Sénégal</option>
					<option value="serbie">Serbie</option>
					<option value="seychelles">Seychelles</option>
					<option value="sierra-leone">Sierra Leone</option>
					<option value="singapour">Singapour</option>
					<option value="sint-maarten">Sint Maarten</option>
					<option value="slovaquie">Slovaquie</option>
					<option value="slovenie">Slovénie</option>
					<option value="somalie">Somalie</option>
					<option value="soudan">Soudan</option>
					<option value="sudan-du-sud">Soudan du Sud</option>
					<option value="sri-lanka">Sri Lanka</option>
					<option value="suede">Suède</option>
					<option value="suisse">Suisse</option>
					<option value="suriname">Suriname</option>
					<option value="swaziland">Swaziland</option>
					<option value="syrie">Syrie</option>
					<option value="tadjikistan">Tadjikistan</option>
					<option value="taiwan">Taïwan</option>
					<option value="tanzanie">Tanzanie</option>
					<option value="tchad">Tchad</option>
					<option value="thailande">Thaïlande</option>
					<option value="timor-leste-timor-oriental">Timor-Leste (Timor oriental)</option>
					<option value="togo">Togo</option>
					<option value="tokelau">Tokelau</option>
					<option value="tonga">Tonga</option>
					<option value="trinite-et-tobago">Trinité-et-Tobago</option>
					<option value="tunisie">Tunisie</option>
					<option value="turkmenistan">Turkménistan</option>
					<option value="turquie">Turquie</option>
					<option value="tuvalu">Tuvalu</option>
					<option value="ukraine">Ukraine</option>
					<option value="uruguay">Uruguay</option>
					<option value="vanuatu">Vanuatu</option>
					<option value="venezuela">Venezuela</option>
					<option value="vietnam">Vietnam</option>
					<option value="yemen">Yémen</option>
					<option value="zambie">Zambie</option>
					<option value="zimbabwe">Zimbabwe</option>
				</select>

		<input type="button" onclick="submitForm('./index-fr.html')" value="Précédent" class="cancel btn btn-default" >
		<input type="submit" value="Suivant" class="btn btn-primary" >
		</form>

Date de modification :

<time property="dateModified">2015-01-28</time>

Activités et initiatives du gouvernement du Canada

Accédez aux activités et initiatives du gouvernement du Canada

À propos de ce site

Coordonnées

Lien 1

Lien 2

Lien 3

Nouvelles

Salle de presse

Communiqués de presse

Avis aux médias

Discours

Déclarations

Gouvernement

Comment le gouvernement fonctionne

Ministères et organismes

Premier ministre

Ministres

Fonction publique et force militaire

Politiques, règlements et lois

Bibliothèques

Publications

Statistiques et données

À propos de Canada.ca

Transparence

Établissement de rapports à l'échelle du gouvernement

Gouvernement ouvert

Divulgation proactive

Avis

Confidentialité

Rétroaction

Médias sociaux

Centre mobile

Haut de la page

<object type="image/svg+xml" tabindex="-1" role="img" data="./lib/GCWeb/assets/wmms-blk.svg" aria-label="Symbole du gouvernement du Canada"></object>


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Macro BOOST_VMD_EMPTY</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="index.html" title="Chapter 1. The Variadic Macro Data Library 1.9">
<link rel="up" href="header/boost/vmd/empty_hpp.html" title="Header <boost/vmd/empty.hpp>">
<link rel="prev" href="header/boost/vmd/empty_hpp.html" title="Header <boost/vmd/empty.hpp>">
<link rel="next" href="header/boost/vmd/enum_hpp.html" title="Header <boost/vmd/enum.hpp>">

Home
Libraries
People
FAQ
More

Macro BOOST_VMD_EMPTY

BOOST_VMD_EMPTY — Outputs emptiness.

Synopsis

// In header: <boost/vmd/empty.hpp>

BOOST_VMD_EMPTY(...)

Description

... = any variadic parameters. The parameters are ignored.

This macro is used to output emptiness ( nothing ) no matter what is passed to it.

If you use this macro to return a result, as in 'result BOOST_VMD_EMPTY' subsequently invoked, you should surround the result with BOOST_VMD_IDENTITY_RESULT to smooth over a VC++ problem.

Copyright © 2010-2017 Tropic Software
      East Inc


text:
struct PP_Rect;

namespace ppapi {

struct URLResponseInfoData;
struct ViewData;

namespace proxy {

class PPP_Instance_Proxy : public InterfaceProxy {
 public:
  explicit PPP_Instance_Proxy(Dispatcher* dispatcher);
  virtual ~PPP_Instance_Proxy();

  static const PPP_Instance* GetInstanceInterface();

  PPP_Instance_Combined* ppp_instance_target() const {
    return combined_interface_.get();
  }

  // InterfaceProxy implementation.
  virtual bool OnMessageReceived(const IPC::Message& msg);

 private:
  // Message handlers.
  void OnPluginMsgDidCreate(PP_Instance instance,
                            const std::vector<std::string>& argn,
                            const std::vector<std::string>& argv,
                            PP_Bool* result);
  void OnPluginMsgDidDestroy(PP_Instance instance);
  void OnPluginMsgDidChangeView(PP_Instance instance,
                                const ViewData& new_data,
                                PP_Bool flash_fullscreen);
  void OnPluginMsgDidChangeFocus(PP_Instance instance, PP_Bool has_focus);
  void OnPluginMsgHandleDocumentLoad(PP_Instance instance,
                                     int pending_loader_host_id,
                                     const URLResponseInfoData& data);

  scoped_ptr<PPP_Instance_Combined> combined_interface_;
};

}  // namespace proxy
}  // namespace ppapi

#endif  // PPAPI_PROXY_PPP_INSTANCE_PROXY_H_


text:
package io.crate.metadata.cluster;

import io.crate.metadata.PartitionName;
import io.crate.metadata.RelationName;
import io.crate.metadata.Schemas;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.IndexTemplateMetadata;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Settings;
import org.junit.Test;

import java.io.IOException;
import java.util.Collections;

import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_CREATION_DATE;
import static org.elasticsearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.common.settings.AbstractScopedSettings.ARCHIVED_SETTINGS_PREFIX;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;

public class AlterTableClusterStateExecutorTest {

    @Test
    public void testPrivateSettingsAreRemovedOnUpdateTemplate() throws IOException {
        IndexScopedSettings indexScopedSettings = new IndexScopedSettings(Settings.EMPTY, Collections.emptySet());

        RelationName relationName = new RelationName(Schemas.DOC_SCHEMA_NAME, "t1");
        String templateName = PartitionName.templateName(relationName.schema(), relationName.name());

        Settings settings = Settings.builder()
            .put(SETTING_CREATION_DATE, false)      // private, must be filtered out
            .put(SETTING_NUMBER_OF_SHARDS, 4)
            .build();
        IndexTemplateMetadata indexTemplateMetadata = IndexTemplateMetadata.builder(templateName)
            .patterns(Collections.singletonList("*"))
            .settings(settings)
            .build();

        ClusterState initialState = ClusterState.builder(ClusterState.EMPTY_STATE)
            .metadata(Metadata.builder().put(indexTemplateMetadata))
            .build();

        ClusterState result =
            AlterTableClusterStateExecutor.updateTemplate(initialState,
                                                          relationName,
                                                          settings,
                                                          Collections.emptyMap(),
                                                          (x, y) -> { },
                                                          indexScopedSettings);

        IndexTemplateMetadata template = result.getMetadata().getTemplates().get(templateName);
        assertThat(template.settings().keySet(), contains(SETTING_NUMBER_OF_SHARDS));
    }

    @Test
    public void testMarkArchivedSettings() {
        Settings.Builder builder = Settings.builder()
            .put(SETTING_NUMBER_OF_SHARDS, 4);
        Settings preparedSettings = AlterTableClusterStateExecutor.markArchivedSettings(builder.build());
        assertThat(preparedSettings.keySet(), containsInAnyOrder(SETTING_NUMBER_OF_SHARDS, ARCHIVED_SETTINGS_PREFIX + "*"));
    }

}


text:
{% load fb_versions %}

            {% include "partials/site-nav.html" %}

                {% if sponsors_cta %}

                    Become a sponsor

                {% else %}
                {% if title %}

{{ title }}

                {% else %}

Technology oriented conference for developers & designers

October 3rd & 4th, 2015

Hypo Expo XXI Slavonska avenija 6 Zagreb, Croatia

                {% endif %}
                {% endif %}

        {% if keynote and keynotes %}

                Buy tickets!
                Become a sponsor

                {% for talk in keynotes %}

                            {% if forloop.counter == 1 %}Saturday{% else %}Sunday{% endif %} Keynote

{{ talk.application.applicant.user.get_full_name }}

{{ talk.title }}

                {% endfor %}

        {% endif %}