text:
package org.jtwig.model.expression.operation.calculators.binary;

import org.jtwig.context.RenderContext;
import org.jtwig.model.expression.Expression;
import org.jtwig.model.position.Position;
import org.jtwig.util.JtwigValue;
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class GreaterOperationCalculatorTest {
    private final Position position = mock(Position.class);
    private final RenderContext context = mock(RenderContext.class);
    private final Expression leftOperand = mock(Expression.class);
    private final Expression rightOperand = mock(Expression.class);

    private GreaterOperationCalculator underTest = new GreaterOperationCalculator();

    @Test
    public void calculateWhenLeftGreaterThanRight() throws Exception {
        when(leftOperand.calculate(context)).thenReturn(new JtwigValue("2.0"));
        when(rightOperand.calculate(context)).thenReturn(new JtwigValue("1.0"));

        JtwigValue result = underTest.calculate(context, position, leftOperand, rightOperand);

        assertThat(result.asBoolean(), is(true));
    }

    @Test
    public void calculateWhenLeftEqualToRight() throws Exception {
        when(leftOperand.calculate(context)).thenReturn(new JtwigValue("1.0"));
        when(rightOperand.calculate(context)).thenReturn(new JtwigValue("1.0"));

        JtwigValue result = underTest.calculate(context, position, leftOperand, rightOperand);

        assertThat(result.asBoolean(), is(false));
    }

    @Test
    public void calculateWhenLeftLessThanRight() throws Exception {
        when(leftOperand.calculate(context)).thenReturn(new JtwigValue("1.0"));
        when(rightOperand.calculate(context)).thenReturn(new JtwigValue("2.0"));

        JtwigValue result = underTest.calculate(context, position, leftOperand, rightOperand);

        assertThat(result.asBoolean(), is(false));
    }
}

redpajama_set_name: RedPajamaGithub


text:
var roomSize = 5;
var roofHeight = 2.3;
var headHeight = 1.5;

var WALL_COLOR = 0xffffff;
var LAMP_COLOR = 0xfcffd4;

var roomCube;

var defaultMaterial;
var objLoader;
var scene;

function main()
{
    // Setup three.js WebGL renderer. Note: Antialiasing is a big performance hit.
    // Only enable it if you actually need to.
    var renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setPixelRatio(window.devicePixelRatio);

    // Append the canvas element created by the renderer to document body element.
    document.body.appendChild(renderer.domElement);

    // Create a three.js scene.
    scene = new THREE.Scene();

    // Create a three.js camera.
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);

    // Apply VR headset positional data to camera.
    var controls = new THREE.VRControls(camera);

    // Apply VR stereo rendering to renderer.
    var effect = new THREE.VREffect(renderer);
    effect.setSize(window.innerWidth, window.innerHeight);

    defaultMaterial = new THREE.MeshPhongMaterial({
                            specular: 0x111111,
                            shininess: 5,
                        });

    objLoader = new THREE.OBJLoader( manager );
    // Add a repeating grid as a skybox.
    //var boxWidth = 5;
    //var loader = new THREE.TextureLoader();
    //loader.load('img/box.png', onTextureLoaded);

    //function onTextureLoaded(texture) {
    //    texture.wrapS = THREE.RepeatWrapping;
    //    texture.wrapT = THREE.RepeatWrapping;
    //    texture.repeat.set(boxWidth, boxWidth);

    //    var geometry = new THREE.BoxGeometry(boxWidth, boxWidth, boxWidth);
    //    var material = new THREE.MeshBasicMaterial({
    //        map: texture,
    //        color: 0x01BE00,
    //        side: THREE.BackSide
    //    });

    //    var skybox = new THREE.Mesh(geometry, material);
    //    scene.add(skybox);
    //}

    var lampGeometry = new THREE.SphereGeometry(1,32,32);
    var lampMaterial = new THREE.MeshPhongMaterial({
                color: LAMP_COLOR,
                emissive: LAMP_COLOR
            });
    var lamp = new THREE.Mesh(lampGeometry, lampMaterial);
    lamp.scale.set(0.2, 0.1, 0.2);
    lamp.position.y = roofHeight;
    scene.add(lamp);

    var lamp = new THREE.Mesh(
            );
    var light = new THREE.PointLight(LAMP_COLOR, 1, 6);
    light.position.y = roofHeight - 0.2;
    scene.add(light);

    var ambiLight = new THREE.AmbientLight(0x404040);
    scene.add(ambiLight);

    roomCube = new THREE.Mesh(
                new THREE.BoxGeometry(roomSize, roofHeight, roomSize),
                new THREE.MeshPhongMaterial({
                    color: WALL_COLOR,
                    specular: 0x111111,
                    shininess: 5,
                    side: THREE.BackSide
                }));
    roomCube.position.set(0,roofHeight / 2, 0);

    scene.add(roomCube);

    // Create a VR manager helper to enter and exit VR mode.
    var params = {
        hideButton: false, // Default: false.
        isUndistorted: false // Default: false.
    };
    var manager = new WebVRManager(renderer, effect, params);

    // Create 3D objects.
    var geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
    var material = new THREE.MeshNormalMaterial();
    var cube = new THREE.Mesh(geometry, material);

    // Position cube mesh
    cube.position.z = -1;
    cube.position.y = 0.25;

    // Add cube mesh to your three.js scene
    //scene.add(cube);

    //Setup viewpoints
    loadLookButtonMedia();
    var toggleMoveButton = addLookButton(new THREE.Vector3(0,0,0), function(){console.log("movement toggled")});

    //Creating the actual furniture
    for(var i = 0; i < furnitures.length; i++)
    {
        f = furnitures[i];

        var pos = new THREE.Vector3(f[1] / 100, 0, f[2]/ 100);
        pos.sub(new THREE.Vector3(2.5, 0, 2.5));
        loadFurnitureModel(f[0], pos, f[3] * Math.PI / 180);
    }

    camera.position.set(1, headHeight, 1);

    // Request animation frame loop function
    var lastRender = 0;
    function animate(timestamp) {
        var delta = Math.min(timestamp - lastRender, 500);
        lastRender = timestamp;

        var toggleMovePos = camera.position.clone();
        toggleMovePos.y += 0.3;
        //toggleMovePos.set(0,1,0);
        toggleMoveButton.setPosition(toggleMovePos);

        updateLookButtons(camera);

        // Apply rotation to cube mesh
        cube.rotation.y += delta * 0.0006;

        // Update VR headset position and apply to camera.
        controls.update();

        // Render the scene through the manager.
        manager.render(scene, camera, timestamp);

        requestAnimationFrame(animate);
    }

    // Kick off animation loop
    animate(performance ? performance.now() : Date.now());

    // Reset the position sensor when 'z' pressed.
    function onKey(event) {
      if (event.keyCode == 90) { // z
        controls.resetSensor();
      }
    }

    window.addEventListener('keydown', onKey, true);
}


text:
@interface FLDecoratedAsyncQueue : FLAsyncQueueDecorator {
@private
    NSMutableArray* _decorators;
    id<FLAsyncQueue> _asyncQueue;
}

// none of these are thread safe. so set up your chain before using using it.

@property (readwrite,strong, nonatomic) id<FLAsyncQueue> asyncQueue;

- (void) addDecorator:(FLAsyncQueueDecorator*) decorator;
- (void) pushDecorator:(FLAsyncQueueDecorator*) decorator;
- (void) removeDecorator:(FLAsyncQueueDecorator*) decorator;
@end


text:
class FlightStatusController < GreetingsController
  before_filter :require_token
  def overview
    @flights = Flight.list_upcoming_visible_flights.order(:flight_ref)
    @date_debut = Date.strptime(params[:date_debut], "%d/%m/%y") unless params[:date_debut].nil? or params[:date_debut] == ""
    @date_fin = Date.strptime(params[:date_fin], "%d/%m/%y") unless params[:date_fin].nil? or params[:date_fin] == ""
    if @date_debut.is_a?(Date)
        @flights = @flights.where("flight_date >= ?",@date_debut)
      end
      if @date_fin.is_a?(Date)
        @flights = @flights.where("flight_date <= ? ",@date_fin)
      end

  	# @seats_per_day = Flight.list_upcoming_visible_flights.group(:flight_date).sum(:seats)
  	# @pax_blocked_per_day = Flight.list_upcoming_visible_flights.group(:flight_date).sum(:pax_blocked)
  	# @paxa_per_day = Flight.list_upcoming_visible_flights.joins(:resas).group(:flight_date).sum(:paxa)
  	# @paxe_per_day = Flight.list_upcoming_visible_flights.joins(:resas).group(:flight_date).sum(:paxe)
  	@paxa_per_flight = @flights.joins(:resas).group(:flight_ref).sum(:paxa)
    @paxe_per_flight = @flights.joins(:resas).group(:flight_ref).sum(:paxe)
  	@seats_per_flight = @flights.group(:flight_ref).sum(:seats)
    @pax_blocked_per_flight = @flights.group(:flight_ref).sum(:pax_blocked)
  end

  def daily
    @jour = Date.strptime(params[:flight_date], "%d/%m/%y")
  	@flights = Flight.list_upcoming_visible_flights.where(flight_date: @jour).order(:flight_ref)
    @paxa_per_flight = @flights.joins(:resas).group(:flight_ref).sum(:paxa)
    @seats_per_flight = @flights.group(:flight_ref).sum(:seats)
    @paxe_per_flight = @flights.joins(:resas).group(:flight_ref).sum(:paxe)
    @pax_blocked_per_flight = @flights.group(:flight_ref).sum(:pax_blocked)
  end

end


text:
package org.apache.harmony.test.stress.jni.localrefs;

import org.apache.harmony.test.stress.jni.share.MTTest;
import org.apache.harmony.test.stress.jni.share.JNITestError;
import org.apache.harmony.test.share.stress.ReliabilityRunner;

/**
 * @author Vladimir Nenashev
 * @version $Revision: 1.8 $
 */

public class LocalRefsTest8 extends MTTest {

    private int objCount;

    private int invCount;

    private int numRefs;

    // temporary array to create object sequence
    private static Object[] objs = null;

    public LocalRefsTest8(int threadId) {
        super(threadId);
    }

    public LocalRefsTest8() {
        super(-1);
    }

    private static native void init();

    private native void nativeMethod(int cnt, int len);

    public void doTest() {
        objCount = Integer.getInteger(
                "org.apache.harmony.test.stress.jni."
                        + "localrefs.LocalRefsTest8.objCount", 10000000)
                .intValue();

        invCount = Integer.getInteger(
                "org.apache.harmony.test.stress.jni."
                        + "localrefs.LocalRefsTest8.invCount", 20).intValue();

        numRefs = objCount / invCount;

        synchronized (LocalRefsTest8.class) {
            if (objs == null) {
                objs = new Object[objCount];
                for (int i = 0; i < objCount; i++)
                    objs[i] = new Object();
            }
        }

        for (int i = 0; i < invCount; i++) {
            try {
                nativeMethod(numRefs, objCount);
            } catch (Throwable t) {
                if (!(t instanceof OutOfMemoryError)) {
                    testLog("Working thread",
                            "LocalRefsTest8: ERROR: Exception caught:");
                    testLog("Working thread", t);
                    ReliabilityRunner.debug("Test error");
                    ReliabilityRunner.mainTest
                            .addError(this, new JNITestError());
                }
            }
        }
    }

    private Object[] getObjectArray() {
        return objs;
    }

    static {
        init();
    }
}


text:
function FirstObj()
{
    this.firstVar = 3;
}
FirstObj.prototype.firstMethod = function()
{
    alert(this.firstVar);
}

function SecObj()
{
    this.secVar = 4;
}
SecObj.prototype.secMethod = function()
{
    alert(this.secVar);
}

function ChildObj()
{
    var objs = [FirstObj, SecObj];
    Parents.inherit(this, objs);
}
ChildObj.prototype.test = function()
{
    this.firstMethod();
    this.secMethod();
}

var childObj = new ChildObj();
childObj.test(); // alerts firstVar & secVar


text:
package com.cooltee.dao.entity;

import com.cooltee.dao.orm.BaseEntity;

import javax.persistence.*;

/**
 * TODO add distributions about this class
 * Created by alittleseven on 2017/2/19.
 */
@Entity
@Table(name = "veh_user_group_rela")
public class UserGroupRela extends BaseEntity{

    @Id
    @GeneratedValue
    @Column(name = "id")
    private Long id;

    @Column(name = "user_id")
    private Long user_id;

    @Column(name = "group_id")
    private Long group_id;

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public Long getId() {
        return id;
    }

    public void setUser_id(Long user_id) {
        this.user_id = user_id;
    }

    public Long getUser_id() {
        return user_id;
    }

    public void setGroup_id(Long group_id) {
        this.group_id = group_id;
    }

    public Long getGroup_id() {
        return group_id;
    }
}


text:
'use strict';

var gulp          = require('gulp'),
    runSequence   = require('run-sequence');

// Launch all tasks bear hug now!
gulp.task('build', function(callback) {
  runSequence('clean', ['script', 'fonts', 'img', 'img-svg', 'css']);
});


text:
package gw.internal.xml.xsd.typeprovider.schema;

import gw.internal.xml.xsd.typeprovider.XmlSchemaIndex;
import gw.lang.reflect.LocationInfo;

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

import javax.xml.namespace.QName;

public final class XmlSchemaComplexContentRestriction extends XmlSchemaContent<XmlSchemaComplexContentRestriction> {

  private XmlSchemaParticle<?> _particle;
  private final List<XmlSchemaAttributeOrAttributeGroup> _attributes;
  private final QName _baseTypeName;
  private final XmlSchemaAnyAttribute _anyAttribute;
  private boolean _resolvedGroups;
  private boolean _resolvedAttributeGroups;

  public XmlSchemaComplexContentRestriction( XmlSchemaIndex schemaIndex, LocationInfo locationInfo, XmlSchemaParticle<?> particle, List<XmlSchemaAttributeOrAttributeGroup> attributes, QName baseTypeName, XmlSchemaAnyAttribute anyAttribute ) {
    super( schemaIndex, locationInfo );
    _particle = particle;
    _attributes = attributes;
    _baseTypeName = baseTypeName;
    _anyAttribute = anyAttribute;
  }

  public XmlSchemaParticle getParticle() {
    if ( ! _resolvedGroups ) {
      _particle = _particle == null ? null : _particle.resolveGroups();
      _resolvedGroups = true;
    }
    return _particle;
  }

  public List<XmlSchemaAttributeOrAttributeGroup> getAttributes() {
    if ( ! _resolvedAttributeGroups ) {
      for ( int i = 0; i < _attributes.size(); i++ ) {
        _attributes.set( i, _attributes.get( i ).resolveAttributeGroups() );
      }
      _resolvedAttributeGroups = true;
    }
    return _attributes;
  }

  public QName getBaseTypeName() {
    return _baseTypeName;
  }

  public XmlSchemaAnyAttribute getAnyAttribute() {
    return _anyAttribute;
  }

  @Override
  public XmlSchemaComplexContentRestriction copy( XmlSchemaIndex schemaIndex ) {
    return new XmlSchemaComplexContentRestriction( schemaIndex, getLocationInfo(), _particle == null ? null : _particle.copy( schemaIndex ), copyList(schemaIndex, _attributes), _baseTypeName, _anyAttribute == null ? null : _anyAttribute.copy( schemaIndex ) );
  }
}


text:
<!DOCTYPE html>

 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title>MarkerWithLabel Example</title>

A basic example of markers with labels. Note that an information window appears whether you
click the marker portion or the label portion of the MarkerWithLabel. The two markers shown here
are both draggable so you can easily verify that markers and labels overlap as expected.


text:
namespace quic {

QuicChromiumClock* QuicChromiumClock::GetInstance() {
  static base::NoDestructor<QuicChromiumClock> instance;
  return instance.get();
}

QuicChromiumClock::QuicChromiumClock() = default;

QuicChromiumClock::~QuicChromiumClock() = default;

QuicTime QuicChromiumClock::ApproximateNow() const {
  // At the moment, Chrome does not have a distinct notion of ApproximateNow().
  // We should consider implementing this using MessageLoop::recent_time_.
  return Now();
}

QuicTime QuicChromiumClock::Now() const {
  int64_t ticks = (base::TimeTicks::Now() - base::TimeTicks()).InMicroseconds();
  DCHECK_GE(ticks, 0);
  return CreateTimeFromMicroseconds(ticks);
}

QuicWallTime QuicChromiumClock::WallNow() const {
  const base::TimeDelta time_since_unix_epoch =
      base::Time::Now() - base::Time::UnixEpoch();
  int64_t time_since_unix_epoch_micro = time_since_unix_epoch.InMicroseconds();
  DCHECK_GE(time_since_unix_epoch_micro, 0);
  return QuicWallTime::FromUNIXMicroseconds(time_since_unix_epoch_micro);
}

// static
base::TimeTicks QuicChromiumClock::QuicTimeToTimeTicks(QuicTime quic_time) {
  // QuicChromiumClock defines base::TimeTicks() as equal to
  // quic::QuicTime::Zero(). See QuicChromiumClock::Now() above.
  QuicTime::Delta offset_from_zero = quic_time - QuicTime::Zero();
  int64_t offset_from_zero_us = offset_from_zero.ToMicroseconds();
  return base::TimeTicks() + base::Microseconds(offset_from_zero_us);
}

}  // namespace quic


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

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "babymeg.h"
#include "FormFiles/babymegsetupwidget.h"
#include "FormFiles/babymegprojectdialog.h"
#include "FormFiles/babymegsquidcontroldgl.h"
#include "FormFiles/babymeghpidgl.h"
#include "babymegclient.h"
#include "babymeginfo.h"

#include <iostream>

#include <utils/ioutils.h>
#include <utils/detecttrigger.h>
#include <fiff/fiff_types.h>
#include <fiff/fiff_dir_tree.h>
#include <rtClient/rtcmdclient.h>
#include <scMeas/newrealtimemultisamplearray.h>

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtCore/QtPlugin>
#include <QtCore/QTextStream>
#include <QtCore/QFile>

#include <QList>
#include <QDebug>
#include <QDir>
#include <QDateTime>

//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================

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

using namespace BABYMEGPLUGIN;
using namespace UTILSLIB;
using namespace SCSHAREDLIB;
using namespace IOBUFFER;
using namespace SCMEASLIB;

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

BabyMEG::BabyMEG()
: m_iBlinkStatus(0)
, m_iBufferSize(-1)
, m_bWriteToFile(false)
, m_sCurrentParadigm("")
, m_bIsRunning(false)
, m_bUseRecordTimer(false)
, m_pRawMatrixBuffer(0)
, m_sFiffProjections(QCoreApplication::applicationDirPath() + "/mne_scan_plugins/resources/babymeg/header.fif")
, m_sFiffCompensators(QCoreApplication::applicationDirPath() + "/mne_scan_plugins/resources/babymeg/compensator.fif")
, m_sBadChannels(QCoreApplication::applicationDirPath() + "/mne_scan_plugins/resources/babymeg/both.bad")
, m_iRecordingMSeconds(5*60*1000)
, m_dSfreq(1024)
, m_iSplitCount(0)
{
    m_pActionSetupProject = new QAction(QIcon(":/images/database.png"), tr("Setup Project"),this);
//    m_pActionSetupProject->setShortcut(tr("F12"));
    m_pActionSetupProject->setStatusTip(tr("Setup Project"));
    connect(m_pActionSetupProject, &QAction::triggered,
            this, &BabyMEG::showProjectDialog);
    addPluginAction(m_pActionSetupProject);

    m_pActionRecordFile = new QAction(QIcon(":/images/record.png"), tr("Start Recording"),this);
    m_pActionRecordFile->setStatusTip(tr("Start Recording"));
    connect(m_pActionRecordFile, &QAction::triggered,
            this, &BabyMEG::toggleRecordingFile);
    addPluginAction(m_pActionRecordFile);
    //m_pActionRecordFile->setEnabled(false);

    m_pActionSqdCtrl = new QAction(QIcon(":/images/sqdctrl.png"), tr("Squid Control"),this);
//    m_pActionSetupProject->setShortcut(tr("F12"));
    m_pActionSqdCtrl->setStatusTip(tr("Squid Control"));
    connect(m_pActionSqdCtrl, &QAction::triggered,
            this, &BabyMEG::showSqdCtrlDialog);
    addPluginAction(m_pActionSqdCtrl);

    m_pActionUpdateFiffInfo = new QAction(QIcon(":/images/latestFiffInfo.png"), tr("Update Fiff Info"),this);
    m_pActionUpdateFiffInfo->setStatusTip(tr("Update Fiff Info"));
    connect(m_pActionUpdateFiffInfo, &QAction::triggered,
            this, &BabyMEG::UpdateFiffInfo);
    addPluginAction(m_pActionUpdateFiffInfo);

    m_pActionUpdateFiffInfoForHPI = new QAction(QIcon(":/images/latestFiffInfoHPI.png"), tr("Update HPI to Fiff Info"),this);
    m_pActionUpdateFiffInfoForHPI->setStatusTip(tr("Update HPI to Fiff Info"));
    connect(m_pActionUpdateFiffInfoForHPI, &QAction::triggered,
            this, &BabyMEG::SetFiffInfoForHPI);
    addPluginAction(m_pActionUpdateFiffInfoForHPI);

    //Init timers
    if(!m_pRecordTimer) {
        m_pRecordTimer = QSharedPointer<QTimer>(new QTimer(this));
        m_pRecordTimer->setSingleShot(true);
        connect(m_pRecordTimer.data(), &QTimer::timeout,
                this, &BabyMEG::toggleRecordingFile);
    }

    if(!m_pBlinkingRecordButtonTimer) {
        m_pBlinkingRecordButtonTimer = QSharedPointer<QTimer>(new QTimer(this));
        connect(m_pBlinkingRecordButtonTimer.data(), &QTimer::timeout,
                this, &BabyMEG::changeRecordingButton);
    }

    if(!m_pUpdateTimeInfoTimer) {
        m_pUpdateTimeInfoTimer = QSharedPointer<QTimer>(new QTimer(this));
        connect(m_pUpdateTimeInfoTimer.data(), &QTimer::timeout,
                this, &BabyMEG::onRecordingRemainingTimeChange);
    }

    //If the basic MNE Scan version is to be build hide the HPI and squid control actions in the toolbar
    #ifdef BUILD_BASIC_MNESCAN_VERSION
    m_pActionSqdCtrl->setVisible(false);
    m_pActionUpdateFiffInfoForHPI->setVisible(false);
    #endif
}

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

BabyMEG::~BabyMEG()
{
    if(this->isRunning())
        stop();

    if(m_pMyClient && m_pMyClient->isConnected())
            m_pMyClient->DisConnectBabyMEG();

}

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

QSharedPointer<IPlugin> BabyMEG::clone() const
{
    QSharedPointer<BabyMEG> pBabyMEGClone(new BabyMEG());
    return pBabyMEGClone;
}

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

QString BabyMEG::getFilePath(bool currentTime) const
{
    QString sFilePath = m_sBabyMEGDataPath + "/" + m_sCurrentProject + "/" + m_sCurrentSubject;

    QString sTimeStamp;

    if(currentTime)
        sTimeStamp = QDateTime::currentDateTime().toString("yyMMdd_hhmmss");
    else
        sTimeStamp = "<YYMMDD_HMS>";

    if(m_sCurrentParadigm.isEmpty())
        sFilePath.append("/"+ sTimeStamp + "_" + m_sCurrentSubject + "_raw.fif");
    else
        sFilePath.append("/"+ sTimeStamp + "_" + m_sCurrentSubject + "_" + m_sCurrentParadigm + "_raw.fif");

    return sFilePath;
}

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

QString BabyMEG::getDataPath() const
{
    return m_sBabyMEGDataPath;
}

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

void BabyMEG::init()
{
    //BabyMEGData Path
    m_sBabyMEGDataPath = QDir::homePath() + "/BabyMEGData";
    if(!QDir(m_sBabyMEGDataPath).exists())
        QDir().mkdir(m_sBabyMEGDataPath);
    //Test Project
    if(!QDir(m_sBabyMEGDataPath+"/TestProject").exists())
        QDir().mkdir(m_sBabyMEGDataPath+"/TestProject");
    QSettings settings;
    m_sCurrentProject = settings.value(QString("Plugin/%1/currentProject").arg(getName()), "TestProject").toString();
    //Test Subject
    if(!QDir(m_sBabyMEGDataPath+"/TestProject/TestSubject").exists())
        QDir().mkdir(m_sBabyMEGDataPath+"/TestProject/TestSubject");
    m_sCurrentSubject = settings.value(QString("Plugin/%1/currentSubject").arg(getName()), "TestSubject").toString();

    //BabyMEG Inits
    pInfo = QSharedPointer<BabyMEGInfo>(new BabyMEGInfo());
    connect(pInfo.data(), &BabyMEGInfo::fiffInfoAvailable,
            this, &BabyMEG::setFiffInfo);
    connect(pInfo.data(), &BabyMEGInfo::SendDataPackage,
            this, &BabyMEG::setFiffData);
    connect(pInfo.data(), &BabyMEGInfo::SendCMDPackage,
            this, &BabyMEG::setCMDData);
    connect(pInfo.data(), &BabyMEGInfo::GainInfoUpdate,
            this, &BabyMEG::setFiffGainInfo);

    m_pMyClient = QSharedPointer<BabyMEGClient>(new BabyMEGClient(6340,this));
    m_pMyClient->SetInfo(pInfo);
    m_pMyClient->start();
    m_pMyClientComm = QSharedPointer<BabyMEGClient>(new BabyMEGClient(6341,this));
    m_pMyClientComm->SetInfo(pInfo);
    m_pMyClientComm->start();

    m_pMyClientComm->SendCommandToBabyMEGShortConnection("INFO");

    m_pMyClient->ConnectToBabyMEG();

    //init channels when fiff info is available
    connect(this, &BabyMEG::fiffInfoAvailable, this, &BabyMEG::initConnector);

    //Init projection dialog
    m_pBabyMEGProjectDialog = QSharedPointer<BabyMEGProjectDialog>(new BabyMEGProjectDialog(this));
}

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

void BabyMEG::unload()
{

}

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

void BabyMEG::initConnector()
{
    if(m_pFiffInfo)
    {
        m_pRTMSABabyMEG = PluginOutputData<NewRealTimeMultiSampleArray>::create(this, "BabyMEG Output", "BabyMEG");
        m_pRTMSABabyMEG->data()->setName(this->getName());//Provide name to auto store widget settings

        m_pRTMSABabyMEG->data()->initFromFiffInfo(m_pFiffInfo);
        m_pRTMSABabyMEG->data()->setMultiArraySize(1);

        m_pRTMSABabyMEG->data()->setSamplingRate(m_pFiffInfo->sfreq);

        m_pRTMSABabyMEG->data()->setVisibility(true);

        m_outputConnectors.append(m_pRTMSABabyMEG);

        //Look for trigger channels and initialise detected trigger map
        m_lTriggerChannelIndices.append(m_pFiffInfo->ch_names.indexOf("TRG001"));
        m_lTriggerChannelIndices.append(m_pFiffInfo->ch_names.indexOf("TRG002"));
        m_lTriggerChannelIndices.append(m_pFiffInfo->ch_names.indexOf("TRG003"));
        m_lTriggerChannelIndices.append(m_pFiffInfo->ch_names.indexOf("TRG004"));
        m_lTriggerChannelIndices.append(m_pFiffInfo->ch_names.indexOf("TRG005"));
        m_lTriggerChannelIndices.append(m_pFiffInfo->ch_names.indexOf("TRG006"));
        m_lTriggerChannelIndices.append(m_pFiffInfo->ch_names.indexOf("TRG007"));
        m_lTriggerChannelIndices.append(m_pFiffInfo->ch_names.indexOf("TRG008"));
    }
}

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

void BabyMEG::clear()
{
    m_pFiffInfo.reset();
    m_iBufferSize = -1;
}

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

void BabyMEG::showProjectDialog()
{
    m_pBabyMEGProjectDialog->setWindowFlags(Qt::WindowStaysOnTopHint);

    connect(m_pBabyMEGProjectDialog.data(), &BabyMEGProjectDialog::timerChanged,
            this, &BabyMEG::setRecordingTimerChanged);

    connect(m_pBabyMEGProjectDialog.data(), &BabyMEGProjectDialog::recordingTimerStateChanged,
            this, &BabyMEG::setRecordingTimerStateChanged);

    m_pBabyMEGProjectDialog->show();
}

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

void BabyMEG::showSqdCtrlDialog()
{
    //BabyMEGSQUIDControlDgl SQUIDCtrlDlg(this);
    //SQUIDCtrlDlg.exec();
    // added by Limin for nonmodal dialog
    if (SQUIDCtrlDlg == NULL)
        SQUIDCtrlDlg = QSharedPointer<BabyMEGSQUIDControlDgl>(new BabyMEGSQUIDControlDgl(this));

    if (!SQUIDCtrlDlg->isVisible())
    {
        SQUIDCtrlDlg->show();
        SQUIDCtrlDlg->raise();
        SQUIDCtrlDlg->Init();
    }
}

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

void BabyMEG::UpdateFiffInfo()
{
    // read gain info and save them to the m_pFiffInfo.range
    m_pMyClientComm->SendCommandToBabyMEGShortConnection("INFG");

    //sleep(0.5);

    //m_pActionRecordFile->setEnabled(true);

}

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

void BabyMEG::SetFiffInfoForHPI()
{
    if(!m_pFiffInfo)
    {
        QMessageBox msgBox;
        msgBox.setText("FiffInfo missing!");
        msgBox.exec();
        return;
    }
    else
    {
        qDebug()<<" Start to load Polhemus File";
        if (HPIDlg == NULL)
            HPIDlg = QSharedPointer<BabyMEGHPIDgl>(new BabyMEGHPIDgl(this));

        if (!HPIDlg->isVisible())
        {
            HPIDlg->show();
            HPIDlg->raise();
        }
    }
}

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

void BabyMEG::RecvHPIFiffInfo(const FiffInfo& info)
{
    // show the HPI info
    qDebug()<<"saved HPI" << m_pFiffInfo->dig.at(0).r[0];
    qDebug()<<"HPI"<< info.dig.at(0).kind << info.dig.at(0).r[0];
}

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

void BabyMEG::splitRecordingFile()
{
    qDebug() << "Split recording file";
    ++m_iSplitCount;
    QString nextFileName = m_sRecordFile.remove("_raw.fif");
    nextFileName += QString("-%1_raw.fif").arg(m_iSplitCount);

    /*
    * Write the link to the next file
    */
    qint32 data;
    m_pOutfid->start_block(FIFFB_REF);
    data = FIFFV_ROLE_NEXT_FILE;
    m_pOutfid->write_int(FIFF_REF_ROLE,&data);
    m_pOutfid->write_string(FIFF_REF_FILE_NAME, nextFileName);
    m_pOutfid->write_id(FIFF_REF_FILE_ID);//ToDo meas_id
    data = m_iSplitCount - 1;
    m_pOutfid->write_int(FIFF_REF_FILE_NUM, &data);
    m_pOutfid->end_block(FIFFB_REF);

    //finish file
    m_pOutfid->finish_writing_raw();

    //start next file
    m_qFileOut.setFileName(nextFileName);
    m_pOutfid = FiffStream::start_writing_raw(m_qFileOut, *m_pFiffInfo, m_cals, defaultMatrixXi, false);
    fiff_int_t first = 0;
    m_pOutfid->write_int(FIFF_FIRST_SAMPLE, &first);
}

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

void BabyMEG::toggleRecordingFile()
{
    //Setup writing to file
    if(m_bWriteToFile)
    {
        mutex.lock();
        m_pOutfid->finish_writing_raw();
        mutex.unlock();

        m_bWriteToFile = false;
        m_iSplitCount = 0;

        //Stop record timer
        m_pRecordTimer->stop();
        m_pUpdateTimeInfoTimer->stop();
        m_pBlinkingRecordButtonTimer->stop();

        m_pActionRecordFile->setIcon(QIcon(":/images/record.png"));
    }
    else
    {
        m_iSplitCount = 0;

        if(!m_pFiffInfo)
        {
            QMessageBox msgBox;
            msgBox.setText("FiffInfo missing!");
            msgBox.exec();
            return;
        }

        //Initiate the stream for writing to the fif file
        m_sRecordFile = getFilePath(true);
        m_qFileOut.setFileName(m_sRecordFile);
        if(m_qFileOut.exists())
        {
            QMessageBox msgBox;
            msgBox.setText("The file you want to write already exists.");
            msgBox.setInformativeText("Do you want to overwrite this file?");
            msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
            int ret = msgBox.exec();
            if(ret == QMessageBox::No)
                return;
        }

        //Set all projectors to zero before writing to file because we always write the raw data
        for(int i = 0; i<m_pFiffInfo->projs.size(); i++)
            m_pFiffInfo->projs[i].active = false;

        mutex.lock();
        m_pOutfid = FiffStream::start_writing_raw(m_qFileOut, *m_pFiffInfo, m_cals, defaultMatrixXi, false);
        fiff_int_t first = 0;
        m_pOutfid->write_int(FIFF_FIRST_SAMPLE, &first);
        mutex.unlock();

        m_bWriteToFile = true;

        //Start timers for record button blinking, recording timer and updating the elapsed time in the proj widget
        m_pBlinkingRecordButtonTimer->start(500);
        m_recordingStartedTime.restart();
        m_pUpdateTimeInfoTimer->start(1000);

        if(m_bUseRecordTimer)
            m_pRecordTimer->start(m_iRecordingMSeconds);
    }
}

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

void BabyMEG::setFiffData(QByteArray DATA)
{
    //get the first byte -- the data format
    int dformat = DATA.left(1).toInt();

    DATA.remove(0,1);
    qint32 rows = m_pFiffInfo->nchan;
    qint32 cols = (DATA.size()/dformat)/rows;

    qDebug() << "[BabyMEG] Matrix " << rows << "x" << cols << " [Data bytes:" << dformat << "]";

    MatrixXf rawData(Map<MatrixXf>( (float*)DATA.data(),rows, cols ));

    for(qint32 i = 0; i < rows*cols; ++i)
        IOUtils::swap_floatp(rawData.data()+i);

    if(m_bIsRunning)
    {
        if(!m_pRawMatrixBuffer)
            m_pRawMatrixBuffer = CircularMatrixBuffer<float>::SPtr(new CircularMatrixBuffer<float>(40, rows, cols));

        m_pRawMatrixBuffer->push(&rawData);
    }
//    else
//    {
////        std::cout << "Data coming" << std::endl; //"first ten elements \n" << rawData.block(0,0,1,10) << std::endl;

//        emit DataToSquidCtrlGUI(rawData);
//    }

    emit DataToSquidCtrlGUI(rawData);
}

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

void BabyMEG::setFiffInfo(const FiffInfo& p_FiffInfo)
{
    m_pFiffInfo = QSharedPointer<FiffInfo>(new FiffInfo(p_FiffInfo));

    if(!readProjectors())
    {
        qDebug() << "Not able to read projectors";
    }

    if(!readCompensators())
    {
        qDebug() << "Not able to read compensators";
    }

    if(!readBadChannels())
    {
        qDebug() << "Not able to read bad channels";
    }

    m_iBufferSize = pInfo->dataLength;
    m_dSfreq = pInfo->sfreq;

    //
    //   Add the calibration factors
    //
    m_cals = RowVectorXd(m_pFiffInfo->nchan);
    m_cals.setZero();
    for (qint32 k = 0; k < m_pFiffInfo->nchan; ++k)
        m_cals[k] = m_pFiffInfo->chs[k].range*m_pFiffInfo->chs[k].cal;

    //
    //  Initialize the data and calibration vector
    //
    typedef Eigen::Triplet<double> T;
    std::vector<T> tripletList;
    tripletList.reserve(m_pFiffInfo->nchan);
    for(qint32 i = 0; i < m_pFiffInfo->nchan; ++i)
        tripletList.push_back(T(i, i, this->m_cals[i]));

    m_sparseMatCals = SparseMatrix<double>(m_pFiffInfo->nchan, m_pFiffInfo->nchan);
    m_sparseMatCals.setFromTriplets(tripletList.begin(), tripletList.end());

    emit fiffInfoAvailable();
}

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

void BabyMEG::setFiffGainInfo(QStringList GainInfo)
{
    if(!m_pFiffInfo)
    {
        QMessageBox msgBox;
        msgBox.setText("FiffInfo missing!");
        msgBox.exec();
        return;
    }
    else
    {
        //set up the gain info
        qDebug()<<"Set Gain Info";
        for(qint32 i = 0; i < m_pFiffInfo->nchan; i++) {
            m_pFiffInfo->chs[i].range = 1.0f/GainInfo.at(i).toFloat();//1; // set gain
            m_cals[i] = m_pFiffInfo->chs[i].range*m_pFiffInfo->chs[i].cal;
            //qDebug()<<i<<"="<<m_pFiffInfo->chs[i].ch_name<<","<<m_pFiffInfo->chs[i].range;
        }

        // Initialize the data and calibration vector
        typedef Eigen::Triplet<double> T;
        std::vector<T> tripletList;
        tripletList.reserve(m_pFiffInfo->nchan);
        for(qint32 i = 0; i < m_pFiffInfo->nchan; ++i)
            tripletList.push_back(T(i, i, this->m_cals[i]));

        m_sparseMatCals = SparseMatrix<double>(m_pFiffInfo->nchan, m_pFiffInfo->nchan);
        m_sparseMatCals.setFromTriplets(tripletList.begin(), tripletList.end());
    }

}

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

void BabyMEG::setCMDData(QByteArray DATA)
{
    qDebug()<<"------"<<DATA;
//    m_commandManager["FLL"].reply(DATA);
    emit SendCMDDataToSQUIDControl(DATA);
    qDebug()<<"Data has been received.";
}

//*************************************************************************************************************
void BabyMEG::comFLL(QString t_sFLLControlCommand)
{
    qDebug()<<"FLL commands";

    qDebug() << "BabyMeg Received" << t_sFLLControlCommand;
    int strlen = t_sFLLControlCommand.size();
    QByteArray Scmd = m_pMyClientComm->MGH_LM_Int2Byte(strlen);
    QByteArray SC = QByteArray("COMS")+Scmd;
    SC.append(t_sFLLControlCommand);
    m_pMyClientComm->SendCommandToBabyMEGShortConnection(SC);
}

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

bool BabyMEG::start()
{
    //Check if the thread is already or still running. This can happen if the start button is pressed immediately after the stop button was pressed. In this case the stopping process is not finished yet but the start process is initiated.
    if(this->isRunning())
        QThread::wait();

    if(!m_pRTMSABabyMEG)
        initConnector();

    // Start threads
    m_bIsRunning = true;

    if(!m_pMyClient->isConnected())
        m_pMyClient->ConnectToBabyMEG();
    // Start threads
    QThread::start();

    return true;
}

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

bool BabyMEG::stop()
{
    if(m_pMyClient->isConnected())
        m_pMyClient->DisConnectBabyMEG();

    m_bIsRunning = false;

    //In case the semaphore blocks the thread -> Release the QSemaphore and let it exit from the pop function (acquire statement)
    m_pRawMatrixBuffer->releaseFromPop();

    //Clear Buffers
    m_pRawMatrixBuffer->clear();

    return true;
}

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

IPlugin::PluginType BabyMEG::getType() const
{
    return _ISensor;
}

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

QString BabyMEG::getName() const
{
    return "BabyMEG";
}

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

QWidget* BabyMEG::setupWidget()
{
    if(!m_pMyClient->isConnected())
        m_pMyClient->ConnectToBabyMEG();

    BabyMEGSetupWidget* widget = new BabyMEGSetupWidget(this);//widget is later distroyed by CentralWidget - so it has to be created everytime new

    //init dialog

    return widget;
}

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

void BabyMEG::run()
{
    MatrixXf matValue;

    qint32 size = 0;

    while(m_bIsRunning)
    {
        if(m_pRawMatrixBuffer)
        {
            //pop matrix
            matValue = m_pRawMatrixBuffer->pop();

            //create digital trigger information
            //QElapsedTimer time;
            //time.start();
            createDigTrig(matValue);
            //qDebug()<<"BabyMEG::run - createDigTrig took: "<<time.elapsed();

            //Write raw data to fif file
            if(m_bWriteToFile)
            {
                size += matValue.rows()*matValue.cols() * 4;

                if(size > MAX_DATA_LEN)
                {
                    size = 0;
                    this->splitRecordingFile();
                }

                mutex.lock();
                m_pOutfid->write_raw_buffer(matValue.cast<double>());
                mutex.unlock();
            }
            else
            {
                size = 0;
            }

            if(m_pRTMSABabyMEG)
            {
                m_pRTMSABabyMEG->data()->setValue(this->calibrate(matValue));
            }
        }
    }

    //Close the fif output stream
    if(m_bWriteToFile)
    {
        this->toggleRecordingFile();
    }
}

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

void BabyMEG::createDigTrig(MatrixXf& data)
{
    //Look for triggers in all trigger channels

    //m_qMapDetectedTrigger = DetectTrigger::detectTriggerFlanksMax(data.at(b), m_lTriggerChannelIndices, m_iCurrentSample-nCol, m_dTriggerThreshold, true);
    QMap<int,QList<QPair<int,double> > > qMapDetectedTrigger = DetectTrigger::detectTriggerFlanksGrad(data.cast<double>(), m_lTriggerChannelIndices, 0, 3.0, false, "Rising");

    //Combine and write results into data block's digital trigger channel
    QMapIterator<int,QList<QPair<int,double> >> i(qMapDetectedTrigger);
    int counter = 0;
    int idxDigTrig = m_pFiffInfo->ch_names.indexOf("DTRG01");

    while (i.hasNext())
    {
        i.next();

        QList<QPair<int,double> > lDetectedTriggers = i.value();

        for(int k = 0; k < lDetectedTriggers.size(); ++k)
        {
            if(lDetectedTriggers.at(k).first < data.cols() && lDetectedTriggers.at(k).first >= 0)
            {
                data(idxDigTrig,lDetectedTriggers.at(k).first) = data(idxDigTrig,lDetectedTriggers.at(k).first) + pow(2,counter);
            }
        }

        counter++;
    }
}

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

MatrixXd BabyMEG::calibrate(const MatrixXf& data)
{
    MatrixXd one;
    if(m_pFiffInfo && m_sparseMatCals.cols() == m_pFiffInfo->nchan)
        one = m_sparseMatCals*data.cast<double>();
    else
        one = data.cast<double>();

    return one;
}

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

bool BabyMEG::readProjectors()
{
    QFile t_projFiffFile(m_sFiffProjections);

    //
    //   Open the file
    //
    FiffStream::SPtr t_pStream(new FiffStream(&t_projFiffFile));
    QString t_sFileName = t_pStream->streamName();

    printf("Opening header data %s...\n",t_sFileName.toUtf8().constData());

    FiffDirTree t_Tree;
    QList<FiffDirEntry> t_Dir;

    if(!t_pStream->open(t_Tree, t_Dir))
        return false;

    QList<FiffProj> q_ListProj = t_pStream->read_proj(t_Tree);

    //Set all projectors to zero
    for(int i = 0; i<q_ListProj.size(); i++)
        q_ListProj[i].active = false;

    if (q_ListProj.size() == 0)
    {
        printf("Could not find projectors\n");
        return false;
    }

    m_pFiffInfo->projs = q_ListProj;

    //garbage collecting
    t_pStream->device()->close();

    return true;
}

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

bool BabyMEG::readCompensators()
{
    QFile t_compFiffFile(m_sFiffCompensators);

    //
    //   Open the file
    //
    FiffStream::SPtr t_pStream(new FiffStream(&t_compFiffFile));
    QString t_sFileName = t_pStream->streamName();

    printf("Opening compensator data %s...\n",t_sFileName.toUtf8().constData());

    FiffDirTree t_Tree;
    QList<FiffDirEntry> t_Dir;

    if(!t_pStream->open(t_Tree, t_Dir))
        return false;

    QList<FiffCtfComp> q_ListComp = t_pStream->read_ctf_comp(t_Tree, m_pFiffInfo->chs);

    if (q_ListComp.size() == 0)
    {
        printf("Could not find compensators\n");
        return false;
    }

    m_pFiffInfo->comps = q_ListComp;

    //garbage collecting
    t_pStream->device()->close();

    return true;
}

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

bool BabyMEG::readBadChannels()
{
    //
    // Bad Channels
    //
//    //Read bad channels from header/projection fif
//    QFile t_headerFiffFile(m_sFiffProjections);

//    if(!t_headerFiffFile.exists()) {
//        printf("Could not open fif file for copying bad channels to babyMEG fiff_info\n");
//        return false;
//    }

//    FiffRawData raw(t_headerFiffFile);
//    m_pFiffInfo->bads = raw.info.bads;

//    t_headerFiffFile.close();

//    return true;

    //Read bad channels from
    QFile t_badChannelsFile(m_sBadChannels);

    if (!t_badChannelsFile.open(QIODevice::ReadOnly | QIODevice::Text))
        return false;

    printf("Reading bad channels from %s...\n", m_sBadChannels.toUtf8().constData());

    QTextStream in(&t_badChannelsFile);
    qint32 count = 0;
    QStringList t_sListbads;
    while (!in.atEnd()) {
        QString channel = in.readLine();
        if(channel.isEmpty())
            continue;
        ++count;
        printf("Channel %i: %s\n",count,channel.toUtf8().constData());
        t_sListbads << channel;
    }

    m_pFiffInfo->bads = t_sListbads;

    return true;
}

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

void BabyMEG::changeRecordingButton()
{
    if(m_iBlinkStatus == 0)
    {
        m_pActionRecordFile->setIcon(QIcon(":/images/record.png"));
        m_iBlinkStatus = 1;
    }
    else
    {
        m_pActionRecordFile->setIcon(QIcon(":/images/record_active.png"));
        m_iBlinkStatus = 0;
    }
}

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

void BabyMEG::setRecordingTimerChanged(int timeMSecs)
{
    //If the recording time is changed during the recording, change the timer
    if(m_bWriteToFile)
        m_pRecordTimer->setInterval(timeMSecs-m_recordingStartedTime.elapsed());

    m_iRecordingMSeconds = timeMSecs;
}

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

void BabyMEG::setRecordingTimerStateChanged(bool state)
{
    m_bUseRecordTimer = state;
}

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

void BabyMEG::onRecordingRemainingTimeChange()
{
    m_pBabyMEGProjectDialog->setRecordingElapsedTime(m_recordingStartedTime.elapsed());
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Mario Romano - Resume / CV / Portfolio">
    <meta name="author" content="Mario Romano">
    <title>Mario Romano - Resume / CV / Portfolio</title>
    <link rel="shortcut icon" type="image/png" href="/favicon.png">

    <meta property="og:title" content="Mario Romano - Online Portfolio" />
    <meta property="og:type" content="article" />
    <meta property="og:image" content="http://magemello.github.io/img/share.png" />
    <meta property="og:url" content="http://magemello.github.io" />
    <meta property="og:description" content="My fields of expertise are: Java, Javascript, Android, Html, Asp and C++. I'm also a big fan of microservices, TDD, REST and Clean Coding" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Mario Romano - Online Portfolio" />
    <meta name="twitter:description" content="My fields of expertise are: Java, Javascript, Android, Html, Asp and C++. I'm also a big fan of microservices, TDD, REST and Clean Coding" />
    <meta name="twitter:image" content="http://magemello.github.io/img/share.png" />

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

    <link href="css/freelancer.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="css/nyan.css" />
    <link rel="stylesheet" href="src/blockrain.css">
    <link rel="stylesheet" href="css/devicon.min.css">
    <link rel="stylesheet" href="css/animate.css">
    <link rel="stylesheet" href="css/custom.css">
    <link rel="stylesheet" href="assets/css/style.css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Mario Romano

                        Experience

                        Skills

                    c

                        Talks

                        Pubblications

                        Side projects

                        About

                        Social

                        Blog

                                Donate

                           Mario Romano

Director

-

Architect

-

Full Stack Developer

WORK EXPERIENCE

                    <input class='radio' id='work5' name='works' type='radio' checked>

                         2017 to Cuurent Job London

Opensource - I'm the Director of Engineering for the London office. Responsible for delivery and execution of the product strategy.
                             Java, JavaScript, TypeScript, Spring, Angular, Angular 2, Matirial Desing, Bootstrap, Mysql, H2, Elastic Search, Docker, Microservices, BPM, ECM, REST, TDD, Agile, Docker, kubernetes.

                    <input class='radio' id='work5' name='works' type='radio'>

                         2016 to 2017

Opensource - Architect of Activiti BPM and Application Development Framework . Responsible for the design and implementation of new functionalities for the Front End / Back End application |
                             Java, JavaScript, TypeScript, Spring, Angular, Angular 2, Matirial Desing, Bootstrap, Mysql, H2, Elastic Search, Docker, Microservices, BPM, ECM, REST, TDD, Agile.

                    <input class='radio' id='work5' name='works' type='radio'>

                         2015 to 2016

                            Opensource - Technical Leader and Full Stack Developer in an on-going BPM/ECM project |   Java, Javascript, Spring, Angular, Bootstrap, Mysql, H2, Elastic Search, Microservices, BPM, ECM, REST, TDD, Agile.

                    <input class='radio' id='work4' name='works' type='radio'>

                         2013 to 2015 London

                            StartUp - Full Stack Developer |  Java, Javascript, , Guice, Guava, Backbone, Bootstrap, Mysql, MongoDv, H2, Redis, Microservices, REST, TDD, Agile.

                    <input class='radio' id='work3' name='works' type='radio'>

                         2012 to 2013 London

                            Consultancy - Full Stack Developer |  Java, Javascript, Spring, JQuery, Bootstrap, Mysql, Microservices, REST, TDD, Agile.

                    <input class='radio' id='work2' name='works' type='radio'>

                         2008 to 2012 Naples, Rome, Milan

                            Consultancy - Architect |  Java, Javascript, Spring, Hibernate, Bootstrap, Oracle.

                    <input class='radio' id='work1' name='works' type='radio'>

                         Federico II Naples
                         2002 to 2007 Naples

                            University - Computer Science Engineer

Skills

Java

Javascript

Android

Node Js

Angular

Backbone Js

Html

Css

Bootstrap

less

Grunt

Jquery

Heroku

AWS

Bower

Nginx

Redis

Git

Mysql

Oracle

Mongodb

Linux

Apache

jetbrains

                        More:

                        Polymer,
                        Web Components,
                        Spring,
                        Guava,
                        Dropwizard,
                        Microservices,
                        TDD,
                        Clean Coding,
                        Agile,
                        Maven,
                        Jenkins,
                        AWS,
                        Kubernates,
                        Docker,
                        Blockchain

Talks

                        JBCN Conf 2017 -  Tomorrow's Model Driven Development

                        Beecon  -  Building the ADF application for your needs

                        Devcon 2018 -  Unified Javascript API

                        JBCN Conf 2018 - Distributed System explained (with Java Microservices)

                        Devoxx - Blockchain By Code examples

Pubblications

Side Projects

About Me

I'm Director of Engineering in Alfresco but I'm still really much involved
                        with coding and product strategy. In Alfresco I helped the company to
                        grow the London team from 3 developers to 40 developers, creating a
                        really motivated team focused on delivering value. I have also helped
                        the company accelerating the development phase establishing good
                        practices like: scrum, continuous delivery, TDD, peer review, clean
                        coding and automation testing.

Before Alfresco, I have accumulated
                        nearly 10 years of experience in developing software for large
                        organisations and startups. I'm also the author of the Packt video
                        course series about Angular 2 and Spring 5, I like to speak to
                        conferences, contribute to open source projects and passionate about
                        microservices and blockchain.

                         Download My CV

And Now your daily dose of nyan cat

Where I'm Based

London

West Hampstead

Me on social

Contacts

Drop me an email.

                        Thank you for taking the time to read my CV.

    <audio loop="true" id="nyan-sound">
        <source src="audio/nyan-cat.ogg" type="audio/ogg" />
        <source src="audio/nyan-cat.mp3" type="audio/mpeg" />
    </audio>

Are you up for a game?

                                            Use only arrows

                                        Previous
                                        Next

                                    Video games are one of my favorite hobbies. Do you like video games? Then check also my project, how to make a cocktail arcade table, realized with my brother Eugenio Romano.

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

Marble Boing

Marble Boing is a most fun labyrinth game with easy gameplay, realistic physics and harder levels! Marble Boing requires cold logic, grace under pressure, and a steady dead-eye aim. Do you have what it takes? Guide your Boing Ball out of the labyrinth and collect all the stars before the time runs out.Hurry Up! If you want discover the exit of labyrinth , trasform you marble ball in an 8ball,basketball or summerball.

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

Dice & Dragons

Dice & Dragons is the best dice application on the market! D & D fans and role-playing gamers (RPG), Dragon Dice is the app you were expecting. A 3D graphics and realistic physics make Dragon Dice the best application and is completely FREE.

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

Halloween Slice

Love Fruit Ninja? Do you liked Fruit Slice? You'll love this. It's time to try something different. Halloween Slice is the first "slice" game which delivers 3D HD scrolling capability. Become a Ninja, using your fingers to slice wolves, zombies, vampires, mummies and other terrifying creatures. Be careful...slicing the venom potions will get you into trouble. Collect the enchantments on your adventure to use against the malefic monsters!

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

Rage Meme Camera Free

Troll your friends! Take a photo from camera or gallery , replace the face of your friends with Rage faces , and share the result through email, Facebook, Twitter, Flickr or Bluetooth. Make your funny rage comics FFFFFFFUUUUUUUUUUUUUU!!

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

Facebook Drive

Facebook Drive is a personal cloud storage service that lets users store and synchronize digital content across computers, laptops and mobile devices, and share it with their facebook friends.

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

Easy Facebook Android sdk

Those who tried to integrate facebook features into his own Android application knows that it's not an easy thing to do. We tested many libraries: FbRocket, FbConnect and even facebook's official sdk, but their implementation was very complicated or they had very few features. That's why we decided to create our own library from scratch

Github:

                                    Link

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

Building a Web Application with Spring and Angular

Time in software development is a key factor, this is the reason why you should be using standards frameworks like Angular and Spring that reduce the use of boilerplate code and offer most of the functionality that you need out of the box. We will build a sign-up form, using Angular for the front end layer and Spring 5 for the backend layer, the two layers will be communicating over REST APIs and the information will be persisted in a database using Spring Data.

The course will teach you how to use Angular and Spring to create a fully working data form storage web application.

The first of the three sections of this course is about front-end technologies. In this part, you will learn the basic concept of Angular such as templating and directives and how to use them to create a form component.

Moving to the second section we will focus on the backend part, at the end of it you will know how to use Spring 5 to develop a data storage service.

In the last section, we will bring together the concepts of the previous two sections to create a data storage application.

Packt:

                                    Link

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

Learning Web Application with Spring 5 and Angular 2

This course will teach you to use Angular 2 and Spring 5 to create a fully working login web application. The first of the three sections of this course is about front-end technologies, and in this part, you will learn the basic concepts of Angular 2 such as Services, Components, and how to use it to create a login component.

Moving to the second section, we will focus on the backend, and by the end of it, you will know what Spring 5 is and how to use it to develop a web reactive or web MVC application.

In the last section, we will bring together the concepts of the previous two sections to create a login application. This course focuses on the practical aspects of these two frameworks, and you'll get your hands dirty.

Packt:

                                    Link

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

Using Spring and Angular for Web Application

This course teaches you how to use Angular and Spring to create a fully working messaging web application.

The first sections of this course are about frontend technologies; here, you will learn advanced concepts of Angular such as routing, observables, material design, and how to use it to create a messaging/notification component.

In the second section, we focus on the backend part; after completing it, you will know how to use Spring 5 to develop a Web Socket notification service.

In the third section, we bring together the concepts of the previous two sections to create a messaging/notification application.

The last section covers tools that will help you to publish and maintain your application in production.

Finally, you will also learn the new features of Angular 5. By the end of the course, you'll be ready to launch your own creations into the World.

Packt:

                                    Link

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


text:
class Gws::StaffRecord::Year
  include SS::Document
  include Gws::Referenceable
  include Gws::Reference::User
  include Gws::Reference::Site
  include Gws::Addon::ReadableSetting
  include Gws::Addon::GroupPermission
  include Gws::Addon::History

  seqid :id
  field :name, type: String
  field :code, type: String
  field :start_date, type: Date
  field :close_date, type: Date

  has_many :yearly_groups, class_name: 'Gws::StaffRecord::Group', dependent: :destroy
  has_many :yearly_users, class_name: 'Gws::StaffRecord::User', dependent: :destroy
  has_many :yearly_seatings, class_name: 'Gws::StaffRecord::Seating', dependent: :destroy

  permit_params :code, :name, :start_date, :close_date

  validates :code, presence: true, uniqueness: { scope: :site_id }
  validates :name, presence: true, uniqueness: { scope: :site_id }
  validates :start_date, presence: true, datetime: true
  validates :close_date, presence: true, datetime: true

  default_scope -> { order_by start_date: -1 }

  scope :search, ->(params) {
    criteria = where({})
    return criteria if params.blank?

    if params[:keyword].present?
      criteria = criteria.keyword_in params[:keyword], :code, :name
    end
    criteria
  }

  def name_with_code
    "#{name} (#{code})"
  end
end


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>web-base</artifactId>
    <groupId>org.sakaiproject</groupId>
    <version>21-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>
  <name>sakai-web-portlet</name>
  <groupId>org.sakaiproject</groupId>
  <artifactId>sakai-web-portlet</artifactId>
  <packaging>war</packaging>
  <dependencies>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-kernel-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-kernel-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.kernel</groupId>
            <artifactId>sakai-component-manager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.sakaiproject.portal</groupId>
            <artifactId>sakai-portal-util</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>3.1</version>
        </dependency>
		<!-- remove when KNL-1105 is handled -->
        <dependency>
             <groupId>commons-validator</groupId>
             <artifactId>commons-validator</artifactId>
         </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
    <dependency>
      <groupId>javax.portlet</groupId>
      <artifactId>portlet-api</artifactId>
    </dependency>
<!-- velocity and dependencies (logkit, oro, collections) -->
    <dependency>
      <groupId>org.apache.velocity</groupId>
      <artifactId>velocity</artifactId>
      <version>${sakai.velocity.version}</version>
    </dependency>
    <dependency>
      <groupId>org.sakaiproject.velocity</groupId>
      <artifactId>sakai-velocity-util</artifactId>
    </dependency>
    <dependency>
      <groupId>logkit</groupId>
      <artifactId>logkit</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>oro</groupId>
      <artifactId>oro</artifactId>
      <version>2.0.8</version>
    </dependency>
  </dependencies>
  <build>
    <resources>
      <resource>
        <directory>${basedir}/src/bundle</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
          <include>**/*.vm</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>


text:
title: Connect Apps to Shopify
connection: Shopify
image: /media/connections/shopify.png
seo_alias: shopify
toc: true
public: true
index: 30
description: Learn how to add login functionality to your app with Shopify. You will need to generate keys, copy these into your Auth0 settings, and enable the connection.
topics:
  - authentication
  - connections
  - social
  - shopify
contentType: how-to
useCase:
  - add-login
  - customize-connections
  - add-idp
---
<%= include('../../../snippets/social/shopify/0') %>
<%= include('../../../snippets/social/shopify/1') %>
<%= include('../../../snippets/social/shopify/2') %>
<%= include('../../../snippets/social/shopify/3') %>
<%= include('../../../snippets/social/shopify/4') %>
<%= include('../../../snippets/social/shopify/5') %>
<%= include('../_quickstart-links.md') %>


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace DesignPatterns.Behavioral.Strategy
{
    public class AdditionStrategy : IStrategy
    {
        public AdditionStrategy() { }

        public int Execute(int left, int right) => left + right;
    }
}


text:
package org.drools.core.rule.builder.dialect.asm;

public interface InvokerDataProvider {
    String getPackageName();
    String getRuleClassName();
    String getInternalRuleClassName();
    String getMethodName();
    String getInvokerClassName();
    String[] getGlobals();
    String[] getGlobalTypes();
}


text:
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Phone.Controls;

namespace Xamarin.Forms.Platform.WinPhone
{
	public class PickerRenderer : ViewRenderer<Picker, FrameworkElement>
	{
		bool _isChanging;
		FormsListPicker _listPicker;
		Brush _defaultBrush;

		protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
		{
			_listPicker = new FormsListPicker();

			UpdateAlignment();
			UpdateIsEnabled();

			base.OnElementChanged(e);

			if (e.OldElement != null)
				((ObservableList<string>)Element.Items).CollectionChanged -= ItemsCollectionChanged;

			((ObservableList<string>)Element.Items).CollectionChanged += ItemsCollectionChanged;

			_listPicker.ItemTemplate = (System.Windows.DataTemplate)System.Windows.Application.Current.Resources["PickerItemTemplate"];
			_listPicker.FullModeItemTemplate = (System.Windows.DataTemplate)System.Windows.Application.Current.Resources["PickerFullItemTemplate"];
			_listPicker.ExpansionMode = ExpansionMode.FullScreenOnly;
			_listPicker.Items.Add(new ItemViewModel(" ") { MaxHeight = 0 });

			_listPicker.ListPickerModeChanged += ListPickerModeChanged;
			_listPicker.Loaded += (sender, args) => {
				// The defaults from the control template won't be available
				// right away; we have to wait until after the template has been applied
				_defaultBrush = _listPicker.Foreground;
				UpdateTextColor();
			};

			var grid = new System.Windows.Controls.Grid { Children = { _listPicker }, MaxWidth = Device.Info.PixelScreenSize.Width };
			SetNativeControl(grid);

			UpdatePicker();
			_listPicker.SelectionChanged += PickerSelectionChanged;
		}

		protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			base.OnElementPropertyChanged(sender, e);

			if (e.PropertyName == Picker.TitleProperty.PropertyName)
			{
				_listPicker.FullModeHeader = Element.Title;
			}
			else if (e.PropertyName == VisualElement.IsEnabledProperty.PropertyName)
			{
				UpdateIsEnabled();
				UpdateTextColor();
			}
			else if (e.PropertyName == Picker.SelectedIndexProperty.PropertyName)
			{
				if (Element.SelectedIndex >= 0 && Element.SelectedIndex < Element.Items.Count)
					_listPicker.SelectedIndex = Element.SelectedIndex + 1;
			}
			else if (e.PropertyName == View.HorizontalOptionsProperty.PropertyName)
			{
				UpdateAlignment();
			}
			else if (e.PropertyName == Picker.TextColorProperty.PropertyName)
			{
				UpdateTextColor();
			}
		}

		protected override void OnGotFocus(object sender, RoutedEventArgs args)
		{
			// Do nothing. ListPickerModeChanged is handling the IsFocusProperty setter
			// Required because FrameworkElement.GotFocus and FrameworkElement.LostFocus () are fired by ListPicker.Open ()
		}

		protected override void OnLostFocus(object sender, RoutedEventArgs args)
		{
			// Do nothing. ListPickerModeChanged is handling the IsFocusProperty setter
			// Required because FrameworkElement.GotFocus and FrameworkElement.LostFocus () are fired by ListPicker.Open ()
		}

		protected override void UpdateNativeWidget()
		{
			base.UpdateNativeWidget();
			UpdateIsEnabled();
		}

		internal override void OnModelFocusChangeRequested(object sender, VisualElement.FocusRequestArgs args)
		{
			if (Control == null)
				return;

			if (args.Focus)
				args.Result = OpenPickerPage();
			else
			{
				args.Result = ClosePickerPage();
				UnfocusControl(_listPicker);
			}
		}

		bool ClosePickerPage()
		{
			FieldInfo pickerPageField = typeof(ListPicker).GetField("_listPickerPage", BindingFlags.NonPublic | BindingFlags.Instance);
			var pickerPage = pickerPageField.GetValue(Control) as ListPickerPage;
			typeof(ListPickerPage).InvokeMember("ClosePickerPage", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, Type.DefaultBinder, pickerPage, null);

			return true;
		}

		void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			UpdateItems();
		}

		void ListPickerModeChanged(object sender, DependencyPropertyChangedEventArgs e)
		{
			if (e.OldValue == null || e.NewValue == null)
				return;

			var oldVal = (ListPickerMode)e.OldValue;
			var newVal = (ListPickerMode)e.NewValue;

			if (oldVal == ListPickerMode.Normal && newVal == ListPickerMode.Full)
			{
				// Picker Page is now showing
				((IElementController)Element).SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, true);
			}
			else if (oldVal == ListPickerMode.Full && newVal == ListPickerMode.Normal)
			{
				// PickerPage is now dismissed
				((IElementController)Element).SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
			}
		}

		bool OpenPickerPage()
		{
			bool result = _listPicker.Open();

			if (result)
				return true;

			return false;
		}

		void PickerSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (_isChanging)
				return;

			var picker = (ListPicker)sender;

			// initializing picker
			if (picker.SelectedIndex == -1)
				return;

			int elementSelectedIndex = picker.SelectedIndex - 1;
			((IElementController)Element).SetValueFromRenderer(Picker.SelectedIndexProperty, elementSelectedIndex);
		}

		void UpdateAlignment()
		{
			if (Element.HorizontalOptions.Alignment != LayoutAlignment.Fill)
				_listPicker.HorizontalAlignment = HorizontalAlignment.Left;
		}

		void UpdateIsEnabled()
		{
			if (_listPicker != null)
				_listPicker.IsEnabled = Element.IsEnabled;
		}

		void UpdateItems()
		{
			// supress notification of non-user generated events (e.g. adding\syncing list values)
			_isChanging = true;
			FormsListPicker picker = _listPicker;
			// add/remove slots from control to match element
			while (picker.Items.Count < Element.Items.Count + 1)
				picker.Items.Add(new ItemViewModel(string.Empty));

			while (picker.Items.Count > Element.Items.Count + 1)
				picker.Items.RemoveAt(picker.Items.Count - 1);

			// update all control values to match element values
			for (var i = 0; i < Element.Items.Count; i++)
			{
				var item = (ItemViewModel)picker.Items[i + 1];
				if (item.Data == Element.Items[i])
					continue;

				item.Data = Element.Items[i];
			}

			picker.SelectedIndex = Element.SelectedIndex + 1;

			_isChanging = false;
		}

		void UpdatePicker()
		{
			_listPicker.FullModeHeader = Element.Title;
			UpdateItems();
			_listPicker.SelectedIndex = Element.SelectedIndex + 1;
		}

		void UpdateTextColor()
		{
			if (!_listPicker.IsEnabled)
			{
				return;
			}

			Color color = Element.TextColor;
			_listPicker.Foreground = color.IsDefault ? (_defaultBrush ?? color.ToBrush()) : color.ToBrush();
		}

		class ItemViewModel : INotifyPropertyChanged
		{
			string _data;
			int _maxHeight;
			float _opacity;

			public ItemViewModel(string item)
			{
				_opacity = 1;
				_data = item;
				_maxHeight = int.MaxValue;
			}

			public string Data
			{
				get { return _data; }
				set
				{
					if (value == _data)
						return;

					_data = value;
					PropertyChanged(this, new PropertyChangedEventArgs("Data"));
				}
			}

			public int MaxHeight
			{
				get { return _maxHeight; }
				set
				{
					if (value == _maxHeight)
						return;

					_maxHeight = value;
					PropertyChanged(this, new PropertyChangedEventArgs("MaxHeight"));
				}
			}

			public float Opacity
			{
				get { return _opacity; }
				set
				{
					if (value == _opacity)
						return;

					_opacity = value;
					PropertyChanged(this, new PropertyChangedEventArgs("Opacity"));
				}
			}

			public event PropertyChangedEventHandler PropertyChanged = delegate { };
		}
	}
}


text:
<?php

namespace frontend\controllers;

use Yii;
use frontend\models\Queen;
use frontend\models\QueenSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * QueenController implements the CRUD actions for Queen model.
 */
class QueenController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Queen models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new QueenSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Queen model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Queen model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Queen();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Queen model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Queen model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Queen model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Queen the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Queen::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package com.tlf.msg.api;

/**
 * API前置检查异常。
 */
public class ApiRuleException extends ApiException {

    private static final long serialVersionUID = -7787145910600194272L;

    public ApiRuleException(String errCode, String errMsg) {
        super(errCode, errMsg);
    }

}


text:
#ifndef ALEXA_CLIENT_SDK_AVSCOMMON_AVS_INCLUDE_AVSCOMMON_AVS_ATTACHMENT_ATTACHMENTMANAGER_H_
#define ALEXA_CLIENT_SDK_AVSCOMMON_AVS_INCLUDE_AVSCOMMON_AVS_ATTACHMENT_ATTACHMENTMANAGER_H_

#include <mutex>
#include <unordered_map>

#include "AVSCommon/AVS/Attachment/AttachmentManagerInterface.h"

namespace alexaClientSDK {
namespace avsCommon {
namespace avs {
namespace attachment {

/**
 * This class allows the decoupling of attachment readers and writers from the management of attachments.
 *
 * This class is thread safe.
 *
 * A design principle of the @c Attachment class is that each attachment will have at most one reader and writer.
 *
 * Application code may query the manager for a reader and writer object at any time, and in any order.
 *
 * @note Resource management is currently implemented by a timeout approach.  This does have the following limitations:
 *
 *  @li An AttachmentReader or AttachmentWriter has reference to a shared buffer resource for the actual data.  This
 *    buffer will remain in existence until both the Reader and Writer have been destroyed.
 *  @li Therefore, application code should ensure that Readers and Writers are destroyed when no longer needed.
 *  @li The AttachmentManager will always satisfy a request to create a Reader or Writer - it will not currently
 *    enforce a maximum resource limit.
 *  @li ACSDK-254 will address this by enforcing such limits.  It should also be noted however, that a well
 *    behaving application may not observe much difference - the future implementation will forcibly close
 *    the oldest Attachment to make space for the new one.  For a system reading and writing a small set of attachments
 *    at any given time, the AttachmentManager should not need to step in and take such action.
 */
class AttachmentManager : public AttachmentManagerInterface {
public:
    /**
     * This is the default timeout value for attachments.  Any attachment which is inspected in the
     * @c removeExpiredAttachmentsLocked() call, and whose lifetime exceeds this value, will be released.
     */
    static constexpr std::chrono::minutes ATTACHMENT_MANAGER_TIMOUT_MINUTES_DEFAULT = std::chrono::hours(12);

    /**
     * This is the minimum timeout value for attachments.  @c setAttachmentTimeoutMinutes() will not accept a
     * value lower than this.
     */
    static constexpr std::chrono::minutes ATTACHMENT_MANAGER_TIMOUT_MINUTES_MINIMUM = std::chrono::minutes(1);

    /**
     * A local enumeration allowing the createReader call to act as a factory function for the underlying
     * attachments.  This enumeration need not include all specializations of the @c Attachment class, only the ones
     * that make sense for the @c AttachmentManager to manage.
     */
    enum class AttachmentType {
        /// This value corresponds to the @c InProcessAttachment class.
        IN_PROCESS
    };

    /**
     * Factory for creating IN_PROCESS instances of AttachmentManagerInterface.
     *
     * @return An IN_PROCESS instances of AttachmentManagerInterface.
     */
    static std::shared_ptr<AttachmentManagerInterface> createInProcessAttachmentManagerInterface();

    /**
     * Constructor.
     *
     * @deprecated
     * @param attachmentType The type of attachments which will be managed.
     */
    AttachmentManager(AttachmentType attachmentType);

    std::string generateAttachmentId(const std::string& contextId, const std::string& contentId) const override;

    bool setAttachmentTimeoutMinutes(std::chrono::minutes timeoutMinutes) override;

    std::unique_ptr<AttachmentWriter> createWriter(
        const std::string& attachmentId,
        utils::sds::WriterPolicy policy = avsCommon::utils::sds::WriterPolicy::ALL_OR_NOTHING) override;

    std::unique_ptr<AttachmentReader> createReader(const std::string& attachmentId, utils::sds::ReaderPolicy policy)
        override;

private:
    /**
     * A utility structure to encapsulate an @c Attachment, its creation time, and other appropriate data fields.
     */
    struct AttachmentManagementDetails {
        /**
         * Constructor.  This sets the creationTime to the time of instantiation.
         */
        AttachmentManagementDetails();

        /// The time this structure instance was created.
        std::chrono::steady_clock::time_point creationTime;
        /// The Attachment this object is managing.
        std::unique_ptr<Attachment> attachment;
    };

    /**
     * A utility function to acquire the details object for an attachment being managed.  This function
     * encapsulates logic to set up the object if it does not already exist, before returning it.
     *
     * @note The class mutex @c m_mutex must be locked before calling this function.
     *
     * @param attachmentId The attachment id for the attachment detail being requested.
     * @return The attachment detail object.
     */
    AttachmentManagementDetails& getDetailsLocked(const std::string& attachmentId);

    /**
     * A cleanup function, which will release an @c AttachmentManagementDetails from the map if either both a writer
     * and reader have been created, or if its lifetime has exceeded the timeout.
     * @note: @c m_mutex must be acquired before calling this function.
     */
    void removeExpiredAttachmentsLocked();

    /// The type of attachments that this manager will create.
    AttachmentType m_attachmentType;
    /// The timeout in minutes.  Any attachment whose lifetime exceeds this value will be released.
    std::chrono::minutes m_attachmentExpirationMinutes;
    /// The mutex to ensure the non-static public APIs are thread safe.
    std::mutex m_mutex;
    /// The map of attachment details.
    std::unordered_map<std::string, AttachmentManagementDetails> m_attachmentDetailsMap;
};

}  // namespace attachment
}  // namespace avs
}  // namespace avsCommon
}  // namespace alexaClientSDK

#endif  // ALEXA_CLIENT_SDK_AVSCOMMON_AVS_INCLUDE_AVSCOMMON_AVS_ATTACHMENT_ATTACHMENTMANAGER_H_