text:
//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2010 Alessandro Tasora
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//

///////////////////////////////////////////////////
//
//   Demo code about
//
//     - testing the simulation speed for
//       profiling and optimizing purposes.
//       NOTE: this benchmark uses IRRLICHT to
//       make the 3d display.
//
//	 CHRONO
//   ------
//   Multibody dinamics engine
//
// ------------------------------------------------
//             www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////

#include "chrono/core/ChTimer.h"
#include "chrono/core/ChRealtimeStep.h"
#include "chrono/physics/ChSystem.h"
#include "chrono/physics/ChContactContainerBase.h"
#include "chrono/lcp/ChLcpIterativeJacobi.h"
#include "chrono/geometry/ChCSphere.h"
#include "chrono/geometry/ChCBox.h"

#include "chrono_irrlicht/ChBodySceneNode.h"
#include "chrono_irrlicht/ChBodySceneNodeTools.h"
#include "chrono_irrlicht/ChIrrAppInterface.h"

#include <irrlicht.h>

// Use the namespaces of Chrono
using namespace chrono;
using namespace chrono::collision;
using namespace chrono::irrlicht;

// Use the main namespaces of Irrlicht
using namespace irr;
using namespace irr::core;
using namespace irr::scene;
using namespace irr::video;
using namespace irr::io;
using namespace irr::gui;

// defaults
int STATIC_lcp_iters = 20;
int STATIC_lcp_iters_stab = 20;
double SPHERE_RAD = 0.35;  // 0.9
double SPHERE_MASS = 1.0;
int SPHERE_NUM = 1000;  // 400

void create_some_falling_items(ChSystem& mphysicalSystem,
                               ISceneManager* msceneManager,
                               IVideoDriver* driver,
                               ISceneNode* mparent,
                               int numspheres,
                               double sphereradius,
                               double spheremass,
                               double mwidth = 20.0) {
    ChBodySceneNode* mrigidBody;

    double flock_height = ((4. / 3.) * CH_C_PI * pow(sphereradius, 3) * numspheres * (1.0 / 0.40)) / (mwidth * mwidth);
    double flock_size = mwidth - sphereradius;
    float mfriction = 0.4f;

    ChCollisionModel::SetDefaultSuggestedEnvelope(sphereradius * 0.2);

    for (int bi = 0; bi < numspheres; bi++) {
        // Create many ChronoENGINE rigid bodies which will fall..
        // Bodies are Irrlicht nodes of the special class ChBodySceneNode,
        // which encapsulates ChBody items).

        //***OSOLETE*** the addChBodySceneNode_easyXXX functions are deprecated, use ChBodyEasyXXX instead.
        mrigidBody = (ChBodySceneNode*)addChBodySceneNode_easySphere(
            &mphysicalSystem, msceneManager, spheremass,
            ChVector<>(-flock_size * 0.5 + ChRandom() * flock_size,
                       2. + flock_height * ((double)bi / (double)numspheres),
                       -flock_size * 0.5 + ChRandom() * flock_size),
            sphereradius, 15, 10, mparent);
        /*
                mrigidBody = (ChBodySceneNode*)addChBodySceneNode_easyBox(
                                                    &mphysicalSystem, msceneManager,
                                                    spheremass,
                                                    ChVector<>( -flock_size*0.5+ChRandom()*flock_size,
                                                                4.+ flock_height*((double)bi/(double)numspheres),
                                                                -flock_size*0.5+ChRandom()*flock_size),
                                                    ChQuaternion<>(1,0,0,0),
                                                    ChVector<>(sphereradius,sphereradius,sphereradius) ,
                                                    mparent);
        */

        // set additional ChronoENGINE specific properties for the body...
        mrigidBody->GetBody()->GetMaterialSurface()->SetFriction(mfriction);
        double inertia = (2. / 5.) * sphereradius * sphereradius * spheremass;
        mrigidBody->GetBody()->SetInertiaXX(ChVector<>(inertia, inertia, inertia));

        video::ITexture* sphereMap = driver->getTexture(GetChronoDataFile("pinkwhite.png").c_str());
        mrigidBody->setMaterialTexture(0, sphereMap);
    }

    // Create the four walls

    //***OSOLETE*** the addChBodySceneNode_easyXXX functions are deprecated, use ChBodyEasyXXX instead.
    mrigidBody =
        (ChBodySceneNode*)addChBodySceneNode_easyBox(&mphysicalSystem, msceneManager, 200.0, ChVector<>(0, -2, 0),
                                                     ChQuaternion<>(1, 0, 0, 0), ChVector<>(60, 4, 60), mparent);
    mrigidBody->GetBody()->SetBodyFixed(true);
    mrigidBody->GetBody()->GetMaterialSurface()->SetFriction(mfriction);
    mrigidBody->GetBody()->SetInertiaXX(ChVector<>(200, 200, 200));

    mrigidBody = (ChBodySceneNode*)addChBodySceneNode_easyBox(
        &mphysicalSystem, msceneManager, 200.0, ChVector<>(-0.5 * mwidth - 1.0, mwidth, 0), ChQuaternion<>(1, 0, 0, 0),
        ChVector<>(2, 80, mwidth), mparent);
    mrigidBody->GetBody()->SetBodyFixed(true);
    mrigidBody->GetBody()->GetMaterialSurface()->SetFriction(mfriction);
    mrigidBody->GetBody()->SetInertiaXX(ChVector<>(200, 200, 200));

    mrigidBody = (ChBodySceneNode*)addChBodySceneNode_easyBox(
        &mphysicalSystem, msceneManager, 200.0, ChVector<>(0.5 * mwidth + 1.0, mwidth, 0), ChQuaternion<>(1, 0, 0, 0),
        ChVector<>(2, 80, mwidth), mparent);
    mrigidBody->GetBody()->SetBodyFixed(true);
    mrigidBody->GetBody()->GetMaterialSurface()->SetFriction(mfriction);
    mrigidBody->GetBody()->SetInertiaXX(ChVector<>(200, 200, 200));

    mrigidBody = (ChBodySceneNode*)addChBodySceneNode_easyBox(
        &mphysicalSystem, msceneManager, 200.0, ChVector<>(0, mwidth, 0.5 * mwidth + 1.0), ChQuaternion<>(1, 0, 0, 0),
        ChVector<>(mwidth, 80, 2), mparent);
    mrigidBody->GetBody()->SetBodyFixed(true);
    mrigidBody->GetBody()->GetMaterialSurface()->SetSfriction(mfriction);
    mrigidBody->GetBody()->GetMaterialSurface()->SetKfriction(mfriction);
    mrigidBody->GetBody()->SetInertiaXX(ChVector<>(200, 200, 200));

    mrigidBody = (ChBodySceneNode*)addChBodySceneNode(&mphysicalSystem, msceneManager, 0, 200.0,
                                                      ChVector<>(0, mwidth, -0.5 * mwidth - 1.0),
                                                      ChQuaternion<>(1, 0, 0, 0), mparent);
    mrigidBody->GetBody()->SetBodyFixed(true);
    mrigidBody->GetBody()->GetMaterialSurface()->SetFriction(mfriction);
    mrigidBody->GetBody()->SetInertiaXX(ChVector<>(200, 200, 200));

    mrigidBody->GetBody()->SetCollide(true);
    mrigidBody->GetBody()->GetCollisionModel()->ClearModel();
    // Describe the (invisible) colliding shape by adding boxes
    mrigidBody->GetBody()->GetCollisionModel()->AddBox(mwidth, 80, 2);
    // Complete the description.
    mrigidBody->GetBody()->GetCollisionModel()->BuildModel();
}

int main(int argc, char* argv[]) {
    // Create a ChronoENGINE physical system
    ChSystem mphysicalSystem;

    // Create the Irrlicht visualization (open the Irrlicht device,
    // bind a simple user interface, etc. etc.)
    ChIrrAppInterface application(&mphysicalSystem, L"Benchmark application", core::dimension2d<u32>(800, 600), false);

    // Easy shortcuts to add logo, camera, lights and sky in Irrlicht scene:
    ChIrrWizard::add_typical_Lights(application.GetDevice());
    ChIrrWizard::add_typical_Camera(application.GetDevice(), core::vector3df(0, 14, -40));

    //
    // CREATE THE MECHANICAL SYSTEM OF CHRONO...
    //

    application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
    application.GetVideoDriver()->endScene();
    GetLog() << "  ** PLEASE WAIT FOR INITIALIZATION! \n  ** This may take seconds or minutes..\n\n";

    // Prepare the physical system for the simulation

    // mphysicalSystem.SetIntegrationType(ChSystem::INT_EULER_IMPLICIT_LINEARIZED);

    // mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SYMMSOR); // here would be the better choiche since the
    // wall is build ground up.
    // mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
    // mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_JACOBI);
    // mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR_MULTITHREAD);
    // mphysicalSystem.SetParallelThreadNumber(4);

    mphysicalSystem.SetMaxPenetrationRecoverySpeed(1.6);  // used by Anitescu stepper only
    mphysicalSystem.SetIterLCPmaxItersSpeed(20);
    mphysicalSystem.SetIterLCPmaxItersStab(10);  // unuseful for Anitescu, only Tasora uses this
    // mphysicalSystem.SetIterLCPwarmStarting(true);

    // raw tests, all the same, only for profiling
    if (true) {
        GetLog() << "Raw tests for profiling... \n\n";
        ChTimer<double> timer;

        int plotframe = 500;
        int ntestspheres = 120;

        mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
        mphysicalSystem.SetIterLCPmaxItersSpeed(50);
        mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

        ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
        msolver->SetRecordViolation(true);

        for (int ntest = 0; ntest < 4; ++ntest) {
            ISceneNode* parent = application.GetSceneManager()->addEmptySceneNode();

            mphysicalSystem.SetIterLCPsharpnessLambda(1.0);
            mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

            // create spheres and walls, and insert into that scene node
            ChSetRandomSeed(123);
            create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver(),
                                      parent, ntestspheres, 1.6, 10);

            int totframes = 0;

            timer.start();

            // ------- begin simulation loop -----
            while (application.GetDevice()->run()) {
                totframes++;

                application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
                application.DrawAll();

                if (totframes == plotframe) {
                    mphysicalSystem.SetIterLCPsharpnessLambda(0.7);
                    mphysicalSystem.SetMaxPenetrationRecoverySpeed(0.0);
                }

                // integrate
                mphysicalSystem.DoStepDynamics(0.01);

                application.GetVideoDriver()->endScene();

                if (totframes > plotframe)
                    break;

            }  // ------- end of simulation loop -----

            timer.stop();

            // remove the root scene node (contains walls & spheres but no camera no lights)
            // to reset and prepare for new scene at next for() loop.
            parent->remove();

            // Now the system should already have no bodies, because of full removal from Irrlicht scene.
            // Then, the following clearing should be unuseful...(do it anyway..)
            mphysicalSystem.Clear();
        }
        GetLog() << "Time spent: " << timer() << "\n";
        system("pause");
        return 0;
    }  // end test

    // Test convergence for varying omega
    //
    // (solver:SOR)
    //
    if (false) {
        ChStreamOutAsciiFile data_err_SOR_Niter("data_err_SOR_Niter.dat");
        ChStreamOutAsciiFile data_dgamma_SOR_Niter("data_dgamma_SOR_Niter.dat");
        int plotframe = 500;
        int ntestspheres = 220;

        mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
        mphysicalSystem.SetIterLCPmaxItersSpeed(80);
        mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

        ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
        msolver->SetRecordViolation(true);

        for (double momega = 0.2; (momega <= 1.401 && application.GetDevice()->run()); momega += 0.2) {
            ISceneNode* parent = application.GetSceneManager()->addEmptySceneNode();

            mphysicalSystem.SetIterLCPomega(0.8);
            mphysicalSystem.SetIterLCPsharpnessLambda(1.0);
            mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

            // create spheres and walls, and insert into that scene node
            ChSetRandomSeed(123);
            create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver(),
                                      parent, ntestspheres, 1.6, 10);

            int totframes = 0;
            // ------- begin simulation loop -----
            while (application.GetDevice()->run()) {
                totframes++;

                application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
                application.DrawAll();

                if (totframes == plotframe) {
                    mphysicalSystem.SetIterLCPomega(momega);
                    mphysicalSystem.SetIterLCPsharpnessLambda(0.7);
                    mphysicalSystem.SetMaxPenetrationRecoverySpeed(0.0);
                }

                // integrate
                mphysicalSystem.DoStepDynamics(0.01);

                application.GetVideoDriver()->endScene();

                //***PLOT***
                if (totframes == plotframe) {
                    GetLog() << "Saving data\n";
                    ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
                    for (int k = 0; k < msolver->GetViolationHistory().size(); k++) {
                        data_err_SOR_Niter << msolver->GetViolationHistory()[k] << " ";
                    }
                    for (int j = 0; j < msolver->GetDeltalambdaHistory().size(); j++) {
                        data_dgamma_SOR_Niter << msolver->GetDeltalambdaHistory()[j] << " ";
                    }
                }

                if (totframes > plotframe)
                    break;

            }  // ------- end of simulation loop -----

            GetLog() << "  num contacts " << mphysicalSystem.GetNcontacts() << "\n";

            data_err_SOR_Niter << "\n";
            data_dgamma_SOR_Niter << "\n";

            // remove the root scene node (contains walls & spheres but no camera no lights)
            // to reset and prepare for new scene at next for() loop.
            parent->remove();

            // Now the system should already have no bodies, because of full removal from Irrlicht scene.
            // Then, the following clearing should be unuseful...(do it anyway..)
            mphysicalSystem.Clear();
        }

    }  // end test

    // Test convergence for varying omega
    //
    // (solver:JACOBI)
    //
    if (false) {
        ChStreamOutAsciiFile data_err_JACOBI_Niter("data_err_JACOBI_Niter_L10_at500_ok.dat");
        ChStreamOutAsciiFile data_dgamma_JACOBI_Niter("data_dgamma_JACOBI_Niter_L10_at500_ok.dat");
        int plotframe = 500;
        int ntestspheres = 220;

        mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
        mphysicalSystem.SetIterLCPomega(0.8);
        mphysicalSystem.SetIterLCPmaxItersSpeed(80);
        mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

        ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
        msolver->SetRecordViolation(true);

        for (double momega = 0.1; (momega <= 0.71 && application.GetDevice()->run()); momega += 0.1) {
            ISceneNode* parent = application.GetSceneManager()->addEmptySceneNode();

            mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
            mphysicalSystem.SetIterLCPomega(0.8);
            mphysicalSystem.SetIterLCPmaxItersSpeed(80);
            mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);
            mphysicalSystem.SetIterLCPsharpnessLambda(1.0);

            // create spheres and walls, and insert into that scene node
            ChSetRandomSeed(123);
            create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver(),
                                      parent, ntestspheres, 1.6, 10);

            int totframes = 0;
            // ------- begin simulation loop -----
            while (application.GetDevice()->run()) {
                totframes++;

                application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
                application.DrawAll();

                if (totframes == plotframe) {
                    mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_JACOBI);
                    ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
                    msolver->SetRecordViolation(true);
                    mphysicalSystem.SetIterLCPomega(momega);
                    mphysicalSystem.SetIterLCPsharpnessLambda(1.0);
                    mphysicalSystem.SetMaxPenetrationRecoverySpeed(0.0);
                }

                // integrate
                mphysicalSystem.DoStepDynamics(0.01);

                application.GetVideoDriver()->endScene();

                //***PLOT***
                if (totframes == plotframe) {
                    GetLog() << "Saving data\n";
                    ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
                    for (int k = 0; k < msolver->GetViolationHistory().size(); k++) {
                        data_err_JACOBI_Niter << msolver->GetViolationHistory()[k] << " ";
                    }
                    for (int j = 0; j < msolver->GetDeltalambdaHistory().size(); j++) {
                        data_dgamma_JACOBI_Niter << msolver->GetDeltalambdaHistory()[j] << " ";
                    }
                }

                if (totframes > plotframe)
                    break;

            }  // ------- end of simulation loop -----

            GetLog() << "  num contacts " << mphysicalSystem.GetNcontacts() << "\n";

            data_err_JACOBI_Niter << "\n";
            data_dgamma_JACOBI_Niter << "\n";

            // remove the root scene node (contains walls & spheres but no camera no lights)
            // to reset and prepare for new scene at next for() loop.
            parent->remove();

            // Now the system should already have no bodies, because of full removal from Irrlicht scene.
            // Then, the following clearing should be unuseful...(do it anyway..)
            mphysicalSystem.Clear();
        }

    }  // end test

    // Test lambda effect
    //
    // Velocity error  vs.  Num. velocity iterations  vs. Lambda
    // (solver:SOR)
    //
    if (false) {
        ChStreamOutAsciiFile data_err_SOR_Niter("data_err_SOR_Niter_om1.dat");
        ChStreamOutAsciiFile data_dgamma_SOR_Niter("data_dgamma_SOR_Niter_om1.dat");
        int plotframe = 500;
        int ntestspheres = 220;

        mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
        mphysicalSystem.SetIterLCPmaxItersSpeed(80);
        mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

        ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
        msolver->SetRecordViolation(true);

        for (double mlambda = 0.2; (mlambda <= 1.01 && application.GetDevice()->run()); mlambda += 0.2) {
            ISceneNode* parent = application.GetSceneManager()->addEmptySceneNode();

            mphysicalSystem.SetIterLCPomega(0.8);
            mphysicalSystem.SetIterLCPsharpnessLambda(1.0);
            mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

            // create spheres and walls, and insert into that scene node
            ChSetRandomSeed(123);
            create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver(),
                                      parent, ntestspheres, 1.6, 10);

            int totframes = 0;
            // ------- begin simulation loop -----
            while (application.GetDevice()->run()) {
                totframes++;

                application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
                application.DrawAll();

                if (totframes == plotframe) {
                    mphysicalSystem.SetIterLCPomega(1.0);
                    mphysicalSystem.SetIterLCPsharpnessLambda(mlambda);
                    mphysicalSystem.SetMaxPenetrationRecoverySpeed(0.0);
                }

                // integrate
                mphysicalSystem.DoStepDynamics(0.01);

                application.GetVideoDriver()->endScene();

                //***PLOT***
                if (totframes == plotframe) {
                    GetLog() << "Saving data\n";
                    ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
                    for (int k = 0; k < msolver->GetViolationHistory().size(); k++) {
                        data_err_SOR_Niter << msolver->GetViolationHistory()[k] << " ";
                    }
                    for (int j = 0; j < msolver->GetDeltalambdaHistory().size(); j++) {
                        data_dgamma_SOR_Niter << msolver->GetDeltalambdaHistory()[j] << " ";
                    }
                }

                if (totframes > plotframe)
                    break;

            }  // ------- end of simulation loop -----

            GetLog() << "  num contacts " << mphysicalSystem.GetNcontacts() << "\n";

            data_err_SOR_Niter << "\n";
            data_dgamma_SOR_Niter << "\n";

            // remove the root scene node (contains walls & spheres but no camera no lights)
            // to reset and prepare for new scene at next for() loop.
            parent->remove();

            // Now the system should already have no bodies, because of full removal from Irrlicht scene.
            // Then, the following clearing should be unuseful...(do it anyway..)
            mphysicalSystem.Clear();
        }

    }  // end test

    // Test stack aspect ratio
    //
    //
    if (false) {
        ChStreamOutAsciiFile data_err_SOR_Niter("data_err_aspectratio3.dat");
        int plotframe = 500;
        int ntestspheres = 220;

        mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
        mphysicalSystem.SetIterLCPmaxItersSpeed(30);
        mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

        ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
        msolver->SetRecordViolation(true);

        for (int mspheres = 10; (mspheres <= 330 && application.GetDevice()->run()); mspheres += 40) {
            for (int nviters = 20; (nviters <= 101 && application.GetDevice()->run()); nviters += 20) {
                ISceneNode* parent = application.GetSceneManager()->addEmptySceneNode();

                mphysicalSystem.SetIterLCPomega(0.9);
                mphysicalSystem.SetIterLCPsharpnessLambda(1.0);
                mphysicalSystem.SetIterLCPmaxItersSpeed(30);
                mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

                // create spheres and walls, and insert into that scene node
                ChSetRandomSeed(13);
                create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver(),
                                          parent, mspheres, 1.6, 10, 20.1);

                int totframes = 0;
                // ------- begin simulation loop -----
                while (application.GetDevice()->run()) {
                    totframes++;

                    application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
                    application.DrawAll();

                    if (totframes == plotframe) {
                        mphysicalSystem.SetIterLCPomega(0.9);
                        mphysicalSystem.SetIterLCPmaxItersSpeed(nviters);
                        mphysicalSystem.SetMaxPenetrationRecoverySpeed(0.0);
                    }

                    application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
                    application.DrawAll();

                    // integrate
                    mphysicalSystem.DoStepDynamics(0.01);

                    application.GetVideoDriver()->endScene();

                    //***PLOT***
                    if (totframes == plotframe) {
                        GetLog() << "Saving data\n";
                        ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
                        data_err_SOR_Niter << msolver->GetViolationHistory()[msolver->GetViolationHistory().size() - 1]
                                           << " ";
                    }

                    if (totframes > plotframe)
                        break;

                }  // ------- end of simulation loop -----

                // remove the root scene node (contains walls & spheres but no camera no lights)
                // to reset and prepare for new scene at next for() loop.
                parent->remove();

                // Now the system should already have no bodies, because of full removal from Irrlicht scene.
                // Then, the following clearing should be unuseful...(do it anyway..)
                mphysicalSystem.Clear();
            }

            data_err_SOR_Niter << "\n";
        }

    }  // end test

    // Test pos error
    //
    //
    if (false) {
        ChStreamOutAsciiFile data_err_pos("data_err_pos.dat");
        int plotframe = 500;
        int ntestspheres = 120;
        double mystep = 0;

        for (double mdt = 0.01; (mdt > 0.00015 && application.GetDevice()->run()); mdt *= 0.5) {
            GetLog() << "\n\nDT = " << mdt << "\n";

            for (int nviters = 20; (nviters <= 81 && application.GetDevice()->run()); nviters += 20) {
                GetLog() << "  nviters = " << nviters << "\n";

                ISceneNode* parent = application.GetSceneManager()->addEmptySceneNode();

                mystep = 0.01;
                mphysicalSystem.SetChTime(0.0);
                mphysicalSystem.SetIterLCPsharpnessLambda(0.8);
                mphysicalSystem.SetIterLCPomega(0.8);
                mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
                mphysicalSystem.SetIterLCPmaxItersSpeed(30);
                mphysicalSystem.SetMaxPenetrationRecoverySpeed(2.0);

                // create spheres and walls, and insert into that scene node
                ChSetRandomSeed(13);
                create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver(),
                                          parent, ntestspheres, 1.6, 10);

                int totframes = 0;
                int averagecnt = 0;
                double average = 0;
                // ------- begin simulation loop -----
                while (application.GetDevice()->run()) {
                    totframes++;

                    application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
                    application.DrawAll();

                    // start mode
                    if (mphysicalSystem.GetChTime() > 2.4) {
                        mphysicalSystem.SetIterLCPmaxItersSpeed(nviters);
                        mystep = mdt;
                    }

                    // start average
                    if (mphysicalSystem.GetChTime() > 2.6) {
                        class _label_reporter_class : public chrono::ChReportContactCallback {
                          public:
                            virtual bool ReportContactCallback(const chrono::ChVector<>& pA,
                                                               const chrono::ChVector<>& pB,
                                                               const chrono::ChMatrix33<>& plane_coord,
                                                               const double& distance,
                                                               const float& mfriction,
                                                               const chrono::ChVector<>& react_forces,
                                                               const chrono::ChVector<>& react_torques,
                                                               chrono::collision::ChCollisionModel* modA,
                                                               chrono::collision::ChCollisionModel* modB) {
                                if (distance < maxpen)
                                    maxpen = distance;
                                return true;  // to continue scanning contacts
                            }
                            // Data
                            double maxpen;
                        };

                        _label_reporter_class my_label_rep;

                        my_label_rep.maxpen = 0;

                        // scan all contacts
                        mphysicalSystem.GetContactContainer()->ReportAllContacts(&my_label_rep);
                        // GetLog() << "        p: " << my_label_rep.maxpen << "\n";
                        averagecnt++;
                        average += my_label_rep.maxpen;
                    }

                    // stop average & loop
                    if (mphysicalSystem.GetChTime() > 2.8) {
                        average /= (double)averagecnt;
                        GetLog() << "     avg.err: " << average << "\n";
                        data_err_pos << average << " ";
                        break;
                    }

                    // integrate
                    mphysicalSystem.DoStepDynamics(mystep);

                    application.GetVideoDriver()->endScene();

                }  // ------- end of simulation loop -----

                // remove the root scene node (contains walls & spheres but no camera no lights)
                // to reset and prepare for new scene at next for() loop.
                parent->remove();

                // Now the system should already have no bodies, because of full removal from Irrlicht scene.
                // Then, the following clearing should be unuseful...(do it anyway..)
                mphysicalSystem.Clear();
            }

            data_err_pos << "\n";
        }

    }  // end test

    // Test pos error with Tasora stabilization
    //
    //
    if (false) {
        ChStreamOutAsciiFile data_err_pos("data_err_tasora.dat");
        int ntestspheres = 120;

        for (int npiters = 20; (npiters <= 81 && application.GetDevice()->run()); npiters += 20) {
            GetLog() << "  npiters = " << npiters << "\n";

            for (int nviters = 20; (nviters <= 81 && application.GetDevice()->run()); nviters += 20) {
                GetLog() << "  nviters = " << nviters << "\n";

                ISceneNode* parent = application.GetSceneManager()->addEmptySceneNode();

                mphysicalSystem.SetChTime(0.0);
                mphysicalSystem.SetIterLCPsharpnessLambda(0.8);
                mphysicalSystem.SetIterLCPomega(0.8);
                mphysicalSystem.SetLcpSolverType(ChSystem::LCP_ITERATIVE_SOR);
                mphysicalSystem.SetIntegrationType(ChSystem::INT_EULER_IMPLICIT_PROJECTED);
                mphysicalSystem.SetIterLCPmaxItersSpeed(30);
                mphysicalSystem.SetIterLCPmaxItersStab(30);
                mphysicalSystem.SetMaxPenetrationRecoverySpeed(0.0);

                // create spheres and walls, and insert into that scene node
                ChSetRandomSeed(13);
                create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver(),
                                          parent, ntestspheres, 1.6, 10);

                int totframes = 0;
                int averagecnt = 0;
                double average = 0;
                // ------- begin simulation loop -----
                while (application.GetDevice()->run()) {
                    totframes++;

                    application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));
                    application.DrawAll();

                    // start mode
                    if (mphysicalSystem.GetChTime() > 3) {
                        mphysicalSystem.SetIterLCPmaxItersSpeed(nviters);
                        mphysicalSystem.SetIterLCPmaxItersStab(npiters);
                    }

                    // start average
                    if (mphysicalSystem.GetChTime() > 4.2) {
                        class _label_reporter_class : public chrono::ChReportContactCallback {
                          public:
                            virtual bool ReportContactCallback(const chrono::ChVector<>& pA,
                                                               const chrono::ChVector<>& pB,
                                                               const chrono::ChMatrix33<>& plane_coord,
                                                               const double& distance,
                                                               const float& mfriction,
                                                               const chrono::ChVector<>& react_forces,
                                                               const chrono::ChVector<>& react_torques,
                                                               chrono::collision::ChCollisionModel* modA,
                                                               chrono::collision::ChCollisionModel* modB) {
                                if (distance < maxpen)
                                    maxpen = distance;
                                return true;  // to continue scanning contacts
                            }
                            // Data
                            double maxpen;
                        };

                        _label_reporter_class my_label_rep;

                        my_label_rep.maxpen = 0;

                        // scan all contacts
                        mphysicalSystem.GetContactContainer()->ReportAllContacts(&my_label_rep);
                        averagecnt++;
                        average += my_label_rep.maxpen;
                    }

                    // stop average & loop
                    if (mphysicalSystem.GetChTime() > 4.5) {
                        average /= (double)averagecnt;
                        GetLog() << "     avg.err: " << average << "\n";
                        data_err_pos << average << " ";
                        break;
                    }

                    // integrate
                    mphysicalSystem.DoStepDynamics(0.01);

                    application.GetVideoDriver()->endScene();

                }  // ------- end of simulation loop -----

                // remove the root scene node (contains walls & spheres but no camera no lights)
                // to reset and prepare for new scene at next for() loop.
                parent->remove();

                // Now the system should already have no bodies, because of full removal from Irrlicht scene.
                // Then, the following clearing should be unuseful...(do it anyway..)
                mphysicalSystem.Clear();
            }

            data_err_pos << "\n";
        }

    }  // end test

    getchar();

    //
    // loop of tests:each time test more spheres!
    //
    ChStreamOutAsciiFile data_spheres_times("data_spheres_times.dat");
    ChStreamOutAsciiFile data_contacts_times("data_contact_times.dat");
    ChStreamOutAsciiFile data_ncontacts("data_ncontacts.dat");
    ChStreamOutAsciiFile data_timexconstr("data_timexconstr.dat");

    for (int nspheres = 1; (nspheres <= 1 && application.GetDevice()->run()); nspheres += 1) {
        ChStreamOutAsciiFile data_timing("data_timing1k.dat");

        //
        // Create all the  rigid bodies!!!!
        //

        // the root scene node containing all dynamic objects
        ISceneNode* parent = application.GetSceneManager()->addEmptySceneNode();

        // create spheres and walls, and insert into that scene node
        create_some_falling_items(mphysicalSystem, application.GetSceneManager(), application.GetVideoDriver(), parent,
                                  SPHERE_NUM, SPHERE_RAD, SPHERE_MASS);

        //
        // THE SOFT-REAL-TIME CYCLE
        //

        int mdelay = 0;
        int lastFPS = -1;

        ChTimer<double> mtimer;

        ChRealtimeStepTimer m_realtime_timer;

        // ChStreamOutAsciiFile data_deltares("data_pNviolation_i80.dat");

        int totframes = 0;
        while (application.GetDevice()->run()) {
            totframes++;

            if (totframes == 400)
                mtimer.start();

            // Irrlicht must prepare frame to draw
            application.GetVideoDriver()->beginScene(true, true, SColor(255, 140, 161, 192));

            // Irrlicht draws all 3D objects and all GUI items
            application.DrawAll();

            // HERE CHRONO INTEGRATION IS PERFORMED: THE
            // TIME OF THE SIMULATION ADVANCES FOR A SINGLE
            // STEP:
            mphysicalSystem.DoStepDynamics(0.01);

            application.GetVideoDriver()->endScene();

            if (totframes > 600)
                data_timing << mphysicalSystem.GetChTime() - 3.0 << " " << mphysicalSystem.GetTimerStep() << " "
                            << mphysicalSystem.GetTimerLcp() + mphysicalSystem.GetTimerCollisionBroad() << " "
                            << mphysicalSystem.GetTimerLcp() << "\n";

            /*
            //***PLOT*** plot max constr.normal violation
            if ((totframes<600)&&(totframes>300))
            {
                ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverStab();
                if (msolver->GetViolationHistory().size()>1)
                    data_deltares <<  msolver->GetViolationHistory()[msolver->GetViolationHistory().size()-1] << "\n";
            }

            //***PLOT*** plot deltalambda corrections for varying omega
            if (totframes==999)
            {
                ChLcpIterativeSymmSOR* msolver = (ChLcpIterativeSymmSOR*)mphysicalSystem.GetLcpSolverSpeed();
                msolver->SetOmega(1.0);
            }
            if (totframes==1000)
            {
                GetLog()<< "Saving plot data\n";
                ChLcpIterativeSolver* msolver = (ChLcpIterativeSolver*)mphysicalSystem.GetLcpSolverSpeed();
                ChStreamOutAsciiFile data_deltalambda("data_deltalambda_om80.dat");
                for (int k=0; k< msolver->GetDeltalambdaHistory().size(); k++)
                {
                    data_deltalambda <<  msolver->GetDeltalambdaHistory()[k] << "\n";
                }
            }
            */

            if ((totframes > 200) && (totframes <= 500)) {
                // data_timexconstr << mphysicalSystem.GetTimerLcp()/(double)mphysicalSystem.GetNcontacts() << "\n";
                // GetLog()<< "  avg time/contacts " <<
                // mphysicalSystem.GetTimerLcp()/(double)mphysicalSystem.GetNcontacts() << "\n";
                // GetLog()<< "  ncontacts " << (double)mphysicalSystem.GetNcontacts() << "\n";
            }

            if (totframes > 500)
                break;

        }  // ------- end of simulation loop -----

        mtimer.stop();
        GetLog() << "Time used for simulating/viewing first 500 steps: " << mtimer() << "\n";
        GetLog() << "  num contacts " << mphysicalSystem.GetNcontacts() << "\n";
        GetLog() << "  avg time/contacts " << mtimer() / (double)mphysicalSystem.GetNcontacts() << "\n";
        data_spheres_times << nspheres << "  " << mtimer() << "\n";
        data_contacts_times << mphysicalSystem.GetNcontacts() << "  " << mtimer() << "\n";

        // remove the root scene node (contains walls & spheres but no camera no lights)
        // to reset and prepare for new scene at next for() loop.
        parent->remove();

        // Now the system should already have no bodies, because of full removal from Irrlicht scene.
        // Then, the following clearing should be unuseful...(do it anyway..)
        mphysicalSystem.Clear();
    }

    getchar();

    return 0;
}


text:
package org.apache.deltaspike.playground;

import javax.enterprise.inject.Specializes;
import javax.faces.context.FacesContext;
import org.apache.deltaspike.jsf.spi.scope.window.DefaultClientWindowConfig;

@Specializes
public class PlaygroundClientWindowConfig extends DefaultClientWindowConfig
{
    @Override
    public ClientWindowRenderMode getClientWindowRenderMode(FacesContext facesContext)
    {
        String path = facesContext.getExternalContext().getRequestPathInfo();
        if (path == null)
        {
            path = facesContext.getExternalContext().getRequestServletPath();
        }

        ClientWindowRenderMode mode;

        if (path.contains("/windowhandling/clientwindow/"))
        {
            mode = ClientWindowRenderMode.CLIENTWINDOW;
        }
        else if (path.contains("/windowhandling/lazy/"))
        {
            mode = ClientWindowRenderMode.LAZY;
        }
        else if (path.contains("/windowhandling/none/"))
        {
            mode = ClientWindowRenderMode.NONE;
        }
        else if (path.contains("/windowhandling/delegated/"))
        {
            mode = ClientWindowRenderMode.DELEGATED;
        }
        else
        {
            mode = ClientWindowRenderMode.CLIENTWINDOW;
        }

        return mode;
    }
}

redpajama_set_name: RedPajamaGithub


text:
const int PAGESIZE = 0x1000;

const IRType TyMachReg = TyInt32;
const IRType TyMachPtr = TyUint32;
const IRType TyMachDouble = TyFloat64;
const IRType TyMachSimd128F4 = TySimd128F4;
const IRType TyMachSimd128I4 = TySimd128I4;
const IRType TyMachSimd128I8 = TySimd128I8;
const IRType TyMachSimd128I16 = TySimd128I16;
const IRType TyMachSimd128U4 = TySimd128U4;
const IRType TyMachSimd128U8 = TySimd128U8;
const IRType TyMachSimd128U16 = TySimd128U16;
const IRType TyMachSimd128B4 = TySimd128B4;
const IRType TyMachSimd128B8 = TySimd128B8;
const IRType TyMachSimd128B16 = TySimd128B16;
const IRType TyMachSimd128D2  = TySimd128D2;
const IRType TyMachSimd128I2 = TySimd128I2;

const DWORD EMIT_BUFFER_ALIGNMENT = 16;
const DWORD INSTR_ALIGNMENT = 1;


text:
/**
 * elFinder command prototype
 *
 * @type  elFinder.command
 * @author  Dmitry (dio) Levashov
 */
elFinder.prototype.command = function(fm) {

	/**
	 * elFinder instance
	 *
	 * @type  elFinder
	 */
	this.fm = fm;

	/**
	 * Command name, same as class name
	 *
	 * @type  String
	 */
	this.name = '';

	/**
	 * Short command description
	 *
	 * @type  String
	 */
	this.title = '';

	/**
	 * Current command state
	 *
	 * @example
	 * this.state = -1; // command disabled
	 * this.state = 0;  // command enabled
	 * this.state = 1;  // command active (for example "fullscreen" command while elfinder in fullscreen mode)
	 * @default -1
	 * @type  Number
	 */
	this.state = -1;

	/**
	 * If true, command can not be disabled by connector.
	 * @see this.update()
	 *
	 * @type  Boolen
	 */
	this.alwaysEnabled = false;

	/**
	 * If true, this means command was disabled by connector.
	 * @see this.update()
	 *
	 * @type  Boolen
	 */
	this._disabled = false;

	this.disableOnSearch = false;

	this.updateOnSelect = true;

	/**
	 * elFinder events defaults handlers.
	 * Inside handlers "this" is current command object
	 *
	 * @type  Object
	 */
	this._handlers = {
		enable  : function() { this.update(void(0), this.value); },
		disable : function() { this.update(-1, this.value); },
		'open reload load'    : function() {
			this._disabled = !(this.alwaysEnabled || this.fm.isCommandEnabled(this.name));
			this.update(void(0), this.value)
			this.change();
		}
	};

	/**
	 * elFinder events handlers.
	 * Inside handlers "this" is current command object
	 *
	 * @type  Object
	 */
	this.handlers = {}

	/**
	 * Shortcuts
	 *
	 * @type  Array
	 */
	this.shortcuts = [];

	/**
	 * Command options
	 *
	 * @type  Object
	 */
	this.options = {ui : 'button'};

	/**
	 * Prepare object -
	 * bind events and shortcuts
	 *
	 * @return void
	 */
	this.setup = function(name, opts) {
		var self = this,
			fm   = this.fm, i, s;

		this.name      = name;
		this.title     = fm.messages['cmd'+name] ? fm.i18n('cmd'+name) : name,
		this.options   = $.extend({}, this.options, opts);
		this.listeners = [];

		if (this.updateOnSelect) {
			this._handlers.select = function() { this.update(void(0), this.value); }
		}

		$.each($.extend({}, self._handlers, self.handlers), function(cmd, handler) {
			fm.bind(cmd, $.proxy(handler, self));
		});

		for (i = 0; i < this.shortcuts.length; i++) {
			s = this.shortcuts[i];
			s.callback = $.proxy(s.callback || function() { this.exec() }, this);
			!s.description && (s.description = this.title);
			fm.shortcut(s);
		}

		if (this.disableOnSearch) {
			fm.bind('search searchend', function(e) {
				self._disabled = e.type == 'search';
				self.update(void(0), self.value);
			});
		}

		this.init();
	}

	/**
	 * Command specific init stuffs
	 *
	 * @return void
	 */
	this.init = function() { }

	/**
	 * Exec command
	 *
	 * @param  Array         target files hashes
	 * @param  Array|Object  command value
	 * @return $.Deferred
	 */
	this.exec = function(files, opts) {
		return $.Deferred().reject();
	}

	/**
	 * Return true if command disabled.
	 *
	 * @return Boolen
	 */
	this.disabled = function() {
		return this.state < 0;
	}

	/**
	 * Return true if command enabled.
	 *
	 * @return Boolen
	 */
	this.enabled = function() {
		return this.state > -1;
	}

	/**
	 * Return true if command active.
	 *
	 * @return Boolen
	 */
	this.active = function() {
		return this.state > 0;
	}

	/**
	 * Return current command state.
	 * Must be overloaded in most commands
	 *
	 * @return Number
	 */
	this.getstate = function() {
		return -1;
	}

	/**
	 * Update command state/value
	 * and rize 'change' event if smth changed
	 *
	 * @param  Number  new state or undefined to auto update state
	 * @param  mixed   new value
	 * @return void
	 */
	this.update = function(s, v) {
		var state = this.state,
			value = this.value;

		if (this._disabled) {
			this.state = -1;
		} else {
			this.state = s !== void(0) ? s : this.getstate();
		}

		this.value = v;

		if (state != this.state || value != this.value) {
			this.change();
		}
	}

	/**
	 * Bind handler / fire 'change' event.
	 *
	 * @param  Function|undefined  event callback
	 * @return void
	 */
	this.change = function(c) {
		var cmd, i;

		if (typeof(c) === 'function') {
			this.listeners.push(c);
		} else {
			for (i = 0; i < this.listeners.length; i++) {
				cmd = this.listeners[i];
				try {
					cmd(this.state, this.value);
				} catch (e) {
					this.fm.debug('error', e)
				}
			}
		}
		return this;
	}

	/**
	 * With argument check given files hashes and return list of existed files hashes.
	 * Without argument return selected files hashes.
	 *
	 * @param  Array|String|void  hashes
	 * @return Array
	 */
	this.hashes = function(hashes) {
		return hashes
			? $.map($.isArray(hashes) ? hashes : [hashes], function(hash) { return fm.file(hash) ? hash : null; })
			: fm.selected();
	}

	/**
	 * Return only existed files from given fils hashes | selected files
	 *
	 * @param  Array|String|void  hashes
	 * @return Array
	 */
	this.files = function(hashes) {
		var fm = this.fm;

		return hashes
			? $.map($.isArray(hashes) ? hashes : [hashes], function(hash) { return fm.file(hash) || null })
			: fm.selectedFiles();
	}
}


text:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.IO;

namespace Cassandra.Connections
{
    internal interface ITcpSocket : IDisposable
    {
        IConnectionEndPoint EndPoint { get; }

        SocketOptions Options { get; }

        SSLOptions SSLOptions { get; set; }

        /// <summary>
        /// Event that gets fired when new data is received.
        /// </summary>
        event Action<byte[], int> Read;

        /// <summary>
        /// Event that gets fired when a write async request have been completed.
        /// </summary>
        event Action WriteCompleted;

        /// <summary>
        /// Event that is fired when the host is closing the connection.
        /// </summary>
        event Action Closing;

        event Action<Exception, SocketError?> Error;

        /// <summary>
        /// Get this socket's local address.
        /// </summary>
        /// <returns>The socket's local address.</returns>
        IPEndPoint GetLocalIpEndPoint();

        /// <summary>
        /// Connects asynchronously to the host and starts reading
        /// </summary>
        /// <exception cref="SocketException">Throws a SocketException when the connection could not be established with the host</exception>
        Task<bool> Connect();

        /// <summary>
        /// Sends data asynchronously
        /// </summary>
        void Write(RecyclableMemoryStream stream, Action onBufferFlush);
    }
}


text: An *EXPERIMENTAL* command-line tools for [Datadog](https://www.datadoghq.com/) API.


text:
import { Confirm } from "reactjs-components";
import PropTypes from "prop-types";
import * as React from "react";
import { Trans, t } from "@lingui/macro";
import { withI18n, i18nMark } from "@lingui/react";

import ModalHeading from "#SRC/js/components/modals/ModalHeading";
import StringUtil from "#SRC/js/utils/StringUtil";

import AppLockedMessage from "./AppLockedMessage";
import Pod from "../../structs/Pod";

const ACTION_DISPLAY_NAMES = {
  restart: i18nMark("Restart"),
  stop: i18nMark("Stop"),
};

const ACTION_DISPLAY_NAMES_CONTINUOUS = {
  restart: i18nMark("Restarting..."),
  stop: i18nMark("Stopping..."),
};

class KillPodInstanceModal extends React.PureComponent {
  static defaultProps = {
    action: "restart",
    killPodInstances: () => {},
    pod: new Pod(),
    selectedItems: [],
  };
  static propTypes = {
    action: PropTypes.string,
    errors: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
    isPending: PropTypes.bool.isRequired,
    killPodInstances: PropTypes.func,
    onClose: PropTypes.func.isRequired,
    open: PropTypes.bool.isRequired,
    pod: PropTypes.instanceOf(Pod),
    selectedItems: PropTypes.array,
  };

  state = { errorMsg: null };

  UNSAFE_componentWillUpdate(nextProps) {
    const requestCompleted = this.props.isPending && !nextProps.isPending;

    const shouldClose = requestCompleted && !nextProps.errors;

    if (shouldClose) {
      this.props.onClose();
    }
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { errors } = nextProps;
    if (!errors) {
      this.setState({ errorMsg: null });

      return;
    }

    if (typeof errors === "string") {
      this.setState({ errorMsg: errors });

      return;
    }

    let { message: errorMsg = "", details } = errors;
    const hasDetails = details && details.length !== 0;

    if (hasDetails) {
      errorMsg = details.reduce(
        (memo, error) => `${memo} ${error.errors.join(" ")}`,
        ""
      );
    }

    if (!errorMsg || !errorMsg.length) {
      errorMsg = null;
    }

    this.setState({ errorMsg });
  }

  shouldForceUpdate() {
    return this.state.errorMsg && /force=true/.test(this.state.errorMsg);
  }

  getErrorMessage() {
    const { errorMsg } = this.state;

    if (!errorMsg) {
      return null;
    }

    if (this.shouldForceUpdate()) {
      return <AppLockedMessage />;
    }

    return
{errorMsg}
;
  }

  getModalContents() {
    const { i18n } = this.props;
    const selectedItemsLength = this.props.selectedItems.length;
    const action = ACTION_DISPLAY_NAMES[this.props.action];
    // L10NTODO: Pluralize
    const instanceCountContent = `${selectedItemsLength} ${StringUtil.pluralize(
      "Instance",
      selectedItemsLength
    )}`;

    return (

        <Trans render="p">
          You are about to {i18n._(action).toLowerCase()} {instanceCountContent}
          . Are you sure you want to continue?
        </Trans>
        {this.getErrorMessage()}

    );
  }

  render() {
    const {
      action,
      isPending,
      killPodInstances,
      onClose,
      open,
      pod,
      selectedItems,
      i18n,
    } = this.props;

    let buttonText = i18n._(ACTION_DISPLAY_NAMES[action]);

    if (this.shouldForceUpdate()) {
      buttonText = i18n._(t`Force`) + " " + buttonText;
    }

    if (isPending) {
      buttonText = i18n._(ACTION_DISPLAY_NAMES_CONTINUOUS[action]);
    }

    const killAction = () =>
      killPodInstances(
        pod,
        selectedItems.map((item) => item.id),
        this.shouldForceUpdate()
      );

    // L10NTODO: Pluralize
    const header = (
      <ModalHeading className="text-danger">
        {i18n._(ACTION_DISPLAY_NAMES[action])}{" "}
        {StringUtil.pluralize("Instance", selectedItems.length)}
      </ModalHeading>
    );

    return (
      <Confirm
        closeByBackdropClick={true}
        disabled={isPending}
        header={header}
        open={open}
        onClose={onClose}
        leftButtonText={i18n._(t`Cancel`)}
        leftButtonClassName="button button-primary-link flush-left"
        leftButtonCallback={onClose}
        rightButtonText={buttonText}
        rightButtonClassName="button button-danger"
        rightButtonCallback={killAction}
        showHeader={true}
      >
        {this.getModalContents()}
      </Confirm>
    );
  }
}

export default withI18n()(KillPodInstanceModal);


text:
package org.batfish.datamodel;

import static com.google.common.base.Preconditions.checkArgument;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;

/** A line in an AsPathAccessList */
@ParametersAreNonnullByDefault
public final class AsPathAccessListLine implements Serializable, Comparable<AsPathAccessListLine> {
  private static final String PROP_ACTION = "action";
  private static final String PROP_REGEX = "regex";

  @Nonnull private LineAction _action;

  @Nonnull private String _regex;

  @JsonCreator
  private static AsPathAccessListLine jsonCreator(
      @Nullable @JsonProperty(PROP_ACTION) LineAction action,
      @Nullable @JsonProperty(PROP_REGEX) String regex) {
    checkArgument(action != null, "%s must be provided", PROP_ACTION);
    checkArgument(regex != null, "%s must be provided", PROP_REGEX);
    return new AsPathAccessListLine(action, regex);
  }

  public AsPathAccessListLine(LineAction action, String regex) {
    _action = action;
    _regex = regex;
  }

  @Override
  public int compareTo(AsPathAccessListLine rhs) {
    int ret = _regex.compareTo(rhs._regex);
    return ret;
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    } else if (!(o instanceof AsPathAccessListLine)) {
      return false;
    }
    AsPathAccessListLine other = (AsPathAccessListLine) o;
    return _action == other._action && _regex.equals(other._regex);
  }

  /** The action the underlying access-list will take when this line matches a route. */
  @JsonProperty(PROP_ACTION)
  @Nonnull
  public LineAction getAction() {
    return _action;
  }

  /** The regex against which a route's AS-path will be compared. */
  @JsonProperty(PROP_REGEX)
  @Nonnull
  public String getRegex() {
    return _regex;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + _action.ordinal();
    result = prime * result + _regex.hashCode();
    return result;
  }

  public void setAction(LineAction action) {
    _action = action;
  }

  public void setRegex(String regex) {
    _regex = regex;
  }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Paurocotylis fulva var. zaelandica Cooke

### Remarks
null


text:
package net.q3aiml.dbdata.morph;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Ordering;
import net.q3aiml.dbdata.DataSpec;
import net.q3aiml.dbdata.model.DatabaseMetadata;
import net.q3aiml.dbdata.model.Table;

/**
 * Sorts rows in a {@link DataSpec} so as to avoid forward references.
 */
public class SortDataSpec {
    public void sortRowTables(DataSpec dataSpec, DatabaseMetadata db) {
        ImmutableList<Table> tableOrdering = db.tablesOrderedByReferences();
        dataSpec.tableRows.sort(Ordering.explicit(tableOrdering)
                .onResultOf(row -> db.tableByNameNoCreate(row.getTable())));
    }
}


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

<title>ElementData (ARX API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.deidentifier.arx.certificate.elements

Class ElementData

java.lang.Object

org.deidentifier.arx.certificate.elements.ElementData

All Implemented Interfaces:

Element

public class ElementData
extends java.lang.Object
implements Element

Complex element of data items

Constructor Summary

Constructors

Constructor and Description

ElementData(java.lang.String text)

Creates a new instance

Method Summary

Methods

Modifier and Type
Method and Description

ElementData
addItem(java.lang.String item)

Adds an item

ElementData
addPercentProperty(java.lang.String property,
                  double value)

Adds a number between 0 and 1 as precentage

ElementData
addProperty(java.lang.String property,
           ARXLattice.Anonymity value)

Adds a property

ElementData
addProperty(java.lang.String property,
           boolean value)

Adds a property

ElementData
addProperty(java.lang.String property,
           double value)

Adds a property

ElementData
addProperty(java.lang.String property,
           ElementData value)

Adds a property

ElementData
addProperty(java.lang.String property,
           int value)

Adds a property

ElementData
addProperty(java.lang.String property,
           long value)

Adds a property

ElementData
addProperty(java.lang.String property,
           java.lang.String value)

Adds a property

ElementList
asList()

Returns a list

ElementList
asList(java.lang.String prefix)

Returns a list

java.lang.String
getText()

Returns the text

void
render(rst.pdfbox.layout.elements.Document target,
      int indent,
      CertificateStyle style)

Renders the element to the given target

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ElementData

public ElementData(java.lang.String text)

Creates a new instance

Parameters:

text -

Method Detail

addItem

public ElementData addItem(java.lang.String item)

Adds an item

Parameters:

item -

addProperty

public ElementData addProperty(java.lang.String property,
                      ARXLattice.Anonymity value)

Adds a property

Parameters:

property -

value -

addProperty

public ElementData addProperty(java.lang.String property,
                      boolean value)

Adds a property

Parameters:

property -

value -

addProperty

public ElementData addProperty(java.lang.String property,
                      double value)

Adds a property

Parameters:

property -

value -

addProperty

public ElementData addProperty(java.lang.String property,
                      int value)

Adds a property

Parameters:

property -

value -

addProperty

public ElementData addProperty(java.lang.String property,
                      long value)

Adds a property

Parameters:

property -

value -

addProperty

public ElementData addProperty(java.lang.String property,
                      java.lang.String value)

Adds a property

Parameters:

property -

value -

addProperty

public ElementData addProperty(java.lang.String property,
                      ElementData value)

Adds a property

Parameters:

property -

value -

addPercentProperty

public ElementData addPercentProperty(java.lang.String property,
                             double value)

Adds a number between 0 and 1 as precentage

Parameters:

property -

value -

asList

public ElementList asList()

Returns a list

Returns:

asList

public ElementList asList(java.lang.String prefix)

Returns a list

Parameters:

prefix -

Returns:

getText

public java.lang.String getText()

Returns the text

Returns:

render

public void render(rst.pdfbox.layout.elements.Document target,
          int indent,
          CertificateStyle style)
            throws java.io.IOException

Description copied from interface: Element

Renders the element to the given target

Specified by:

render in interface Element

Throws:

java.io.IOException

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace ArneGroskurth\Symgrid\Grid;

class DataOrder {

    use DataPathTrait;

    /**
     * @var string
     */
    protected $path;

    /**
     * @var string
     */
    protected $direction;

    /**
     * DataOrder constructor.
     *
     * @param string $path
     * @param string $direction
     *
     * @throws Exception
     */
    public function __construct($path, $direction) {

        $this->path = $this->validatePath($path);
        $this->direction = Constants::validateOrderDirection($direction);
    }

    /**
     * @return string
     */
    public function getPath() {

        return $this->path;
    }

    /**
     * @return string
     */
    public function getDirection() {

        return $this->direction;
    }
}


text:
package com.athena.chameleon.engine.core.analyzer.parser;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.Assert;

import com.athena.chameleon.common.utils.ThreadLocalUtil;
import com.athena.chameleon.engine.constant.ChameleonConstants;
import com.athena.chameleon.engine.entity.pdf.AnalyzeDefinition;
import com.athena.chameleon.engine.entity.pdf.CommonAnalyze;
import com.athena.chameleon.engine.entity.pdf.ExceptionInfo;
import com.athena.chameleon.engine.entity.pdf.PDFMetadataDefinition;
import com.athena.chameleon.engine.utils.JaxbUtils;
import com.athena.peacock.engine.common.StackTracer;

/**
 *

 * web.xml 파일을 web-app 버젼별로 unmarshalling 하고 인코딩 관련 필터의 존재 여부 확인 후 재 저장한다.
 *

 *
 * @author Sang-cheon Park
 * @version 1.0
 */
public class WebXMLParser extends Parser {

	/* (non-Javadoc)
	 * @see com.athena.chameleon.engine.core.analyzer.parser.Parser#parse(java.io.File, com.athena.chameleon.engine.entity.pdf.AnalyzeDefinition)
	 */
	@Override
	public Object parse(File file, AnalyzeDefinition analyzeDefinition) {
		Assert.notNull(file, "file cannot be null.");
		Assert.notNull(analyzeDefinition, "analyzeDefinition cannot be null.");

		this.analyzeDefinition = analyzeDefinition;

        // only zip and war
        String key = ChameleonConstants.ZIP_ROOT_DIR;

        if(StringUtils.isEmpty((String)ThreadLocalUtil.get(key))) {
        	key = ChameleonConstants.WAR_ROOT_DIR;
        }

		CommonAnalyze commonAnalyze = null;
        try {
            commonAnalyze = new CommonAnalyze();
            commonAnalyze.setItem(file.getName());
            commonAnalyze.setLocation(removeTempDir(file.getParent(), key));
            commonAnalyze.setContents(fileToString(file.getAbsolutePath()));

            analyzeDefinition.getDescripterList().add(commonAnalyze);
        } catch (IOException e) {
            logger.error("IOException has occurred.", e);
        }

    	Object obj = null;

    	try {
        	// http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd
			obj = checkEncodignFilter(((JAXBElement<?>)JaxbUtils.unmarshal(com.athena.chameleon.engine.entity.xml.webapp.v2_5.WebAppType.class.getPackage().getName(), file)).getValue(), file.getParentFile().getAbsolutePath());
		} catch (JAXBException e1) {
        	try {
            	// http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd
				obj = checkEncodignFilter(((JAXBElement<?>)JaxbUtils.unmarshal(com.athena.chameleon.engine.entity.xml.webapp.v2_4.WebAppType.class.getPackage().getName(), file)).getValue(), file.getParentFile().getAbsolutePath());
			} catch (JAXBException e2) {
            	try {
        			// http://java.sun.com/dtd/web-app_2_3.dtd
	        		removeDoctype(file);
					obj = checkEncodignFilter(JaxbUtils.unmarshal(com.athena.chameleon.engine.entity.xml.webapp.v2_3.WebApp.class.getPackage().getName(), file), file.getParentFile().getAbsolutePath());
					rewrite(file, commonAnalyze.getContents());
            	} catch (JAXBException e3) {
					logger.error("JAXBException has occurred.", e3);
		    		location = removeTempDir(file.getAbsolutePath(), key);
		    		stackTrace = StackTracer.getStackTrace(e1);
		    		comments = "지원하지 않는 버젼의 파일이거나 인코딩 필터 추가 작업 시 에러가 발생하였습니다.";
    			} catch (IOException e3) {
    				logger.error("IOException has occurred.", e3);
    	    		location = removeTempDir(file.getAbsolutePath(), key);
    	    		stackTrace = StackTracer.getStackTrace(e1);
    			} catch (Exception e3) {
    				logger.error("Unhandled Exception has occurred.", e3);
    	    		location = removeTempDir(file.getAbsolutePath(), key);
    	    		stackTrace = StackTracer.getStackTrace(e1);
    			}
			} catch (IOException e2) {
				logger.error("IOException has occurred.", e2);
	    		location = removeTempDir(file.getAbsolutePath(), key);
	    		stackTrace = StackTracer.getStackTrace(e1);
			} catch (Exception e2) {
				logger.error("Unhandled Exception has occurred.", e2);
	    		location = removeTempDir(file.getAbsolutePath(), key);
	    		stackTrace = StackTracer.getStackTrace(e1);
			}
		} catch (IOException e1) {
			logger.error("IOException has occurred.", e1);
    		location = removeTempDir(file.getAbsolutePath(), key);
    		stackTrace = StackTracer.getStackTrace(e1);
		} catch (Exception e1) {
			logger.error("Unhandled Exception has occurred.", e1);
    		location = removeTempDir(file.getAbsolutePath(), key);
    		stackTrace = StackTracer.getStackTrace(e1);
		} finally {
			if(StringUtils.isNotEmpty(stackTrace)) {
				exceptionInfo = new ExceptionInfo();
				exceptionInfo.setLocation(location);
				exceptionInfo.setStackTrace(stackTrace);
				exceptionInfo.setComments(comments);
				((PDFMetadataDefinition)ThreadLocalUtil.get(ChameleonConstants.PDF_METADATA_DEFINITION)).getExceptionInfoList().add(exceptionInfo);
			}
		}

		return obj;
	}//end of parse()

	/**
	 *

	 * web.xml 파일에 인코딩 관련 filter 및 filter-mapping이 있고, UTF-8에 대한 filter 인지 확인하고
	 * filter 가 없거나 UTF-8이 아닌 경우 새로운 filter 및 filter-mapping을 추가한다.
	 *

	 * @param obj
	 * @param path
	 * @return
	 * @throws JAXBException
	 * @throws IOException
	 */
	private Object checkEncodignFilter(Object obj, String path) throws JAXBException, IOException {
        String[] charSet = {"UTF-8", "UTF8"};
        boolean hasEncodingFilter = false;
        boolean hasUTF8EncodingFilter = false;

		if (obj instanceof com.athena.chameleon.engine.entity.xml.webapp.v2_5.WebAppType) {
			com.athena.chameleon.engine.entity.xml.webapp.v2_5.WebAppType webApp = (com.athena.chameleon.engine.entity.xml.webapp.v2_5.WebAppType) obj;

			// webApp에 <filter />, <filter-mapping />이 존재하는지 확인
            List<JAXBElement<?>> elementList = webApp.getDescriptionAndDisplayNameAndIcon();

            Object o = null;
            List<com.athena.chameleon.engine.entity.xml.webapp.v2_5.ParamValueType> paramList = null;
            com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterNameType filtername = null;

            for(JAXBElement<?> element : elementList) {
            	o = element.getValue();

            	if(o instanceof com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterType) {
            		filtername = ((com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterType)o).getFilterName();

            		paramList = ((com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterType)o).getInitParam();
            		for(com.athena.chameleon.engine.entity.xml.webapp.v2_5.ParamValueType param : paramList) {
                		// init-param의 param-name이 encoding이 존재하는지 확인
            			if(param.getParamName().getValue().toLowerCase().equals("encoding")) {
                			hasEncodingFilter = true;

                    		// param-value가 UTF-8인지 확인
            				if(ArrayUtils.contains(charSet, param.getParamValue().getValue().toUpperCase())) {
            					hasUTF8EncodingFilter = true;
                    			break;
                			}
            			}
            		}

            		if(hasEncodingFilter) {
            			break;
            		}
            	}
            }

            // encoding filter는 존재하지만 UTF-8이 아닐 경우 해당 filter 및 filter-mapping 엘리먼트를 삭제한다.
            if(hasEncodingFilter && !hasUTF8EncodingFilter) {
                JAXBElement<?> f = null;
                JAXBElement<?> fm = null;

	            for(JAXBElement<?> element : elementList) {
	            	o = element.getValue();

	            	if(o instanceof com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterType) {
	            		if(((com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterType)o).getFilterName().getValue().equals(filtername.getValue())) {
	            			f = element;
	            		}
	            	} else if(o instanceof com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterMappingType) {
	            		if(((com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterMappingType)o).getFilterName().getValue().equals(filtername.getValue())) {
	            			fm = element;
	            		}
	            	}
	            }

	            webApp.getDescriptionAndDisplayNameAndIcon().remove(f);
	            webApp.getDescriptionAndDisplayNameAndIcon().remove(fm);
            }

            if(!hasUTF8EncodingFilter) {
	            // <filter> element 추가
            	com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterType filter = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterType();

            	com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterNameType filterName = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterNameType();
	            filterName.setValue("UTF_EncodingFilter");
	            filter.setFilterName(filterName);

	            com.athena.chameleon.engine.entity.xml.webapp.v2_5.FullyQualifiedClassType filterClass = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.FullyQualifiedClassType();
	            filterClass.setValue("com.osc.filters.SetCharacterEncodingFilter");
	            filter.setFilterClass(filterClass);

	            // <init-param> element 추가
	            com.athena.chameleon.engine.entity.xml.webapp.v2_5.ParamValueType paramValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.ParamValueType();
	            com.athena.chameleon.engine.entity.xml.webapp.v2_5.String strName = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.String();
	            strName.setValue("encoding");
	            com.athena.chameleon.engine.entity.xml.webapp.v2_5.XsdStringType strValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.XsdStringType();
	            strValue.setValue("UTF-8");
	            paramValue.setParamName(strName);
	            paramValue.setParamValue(strValue);

	            filter.getInitParam().add(paramValue);

	            paramValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.ParamValueType();
	            strName = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.String();
	            strName.setValue("forceEncoding");
	            strValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.XsdStringType();
	            strValue.setValue("UTF-8");
	            paramValue.setParamName(strName);
	            paramValue.setParamValue(strValue);

	            filter.getInitParam().add(paramValue);

	            // <filter-mapping> elemnet 추가
	            com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterMappingType filterMapping = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.FilterMappingType();
	            com.athena.chameleon.engine.entity.xml.webapp.v2_5.UrlPatternType urlPattern = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.UrlPatternType();
	            urlPattern.setValue("/*");
	            filterMapping.getUrlPatternOrServletName().add(urlPattern);
	            filterMapping.setFilterName(filterName);

	            // <web-app>에 filter 추가
	            com.athena.chameleon.engine.entity.xml.webapp.v2_5.ObjectFactory factory = new com.athena.chameleon.engine.entity.xml.webapp.v2_5.ObjectFactory();
	            webApp.getDescriptionAndDisplayNameAndIcon().add(factory.createWebAppTypeFilter(filter));
	            webApp.getDescriptionAndDisplayNameAndIcon().add(factory.createWebAppTypeFilterMapping(filterMapping));

	            try {
		            // Filter 관련 라이브러리 복사
		            fileCopy(new File(WebXMLParser.class.getResource("/lib/osc-filters.jar").getFile()), new File(path, "lib/osc-filters.jar"));

		            // web.xml 저장
					String xmlData = JaxbUtils.marshal(com.athena.chameleon.engine.entity.xml.webapp.v2_5.WebAppType.class.getPackage().getName(), webApp, new String[]{"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"});
					rewrite(new File(path, "web.xml"), xmlData.replaceAll(" standalone=\"yes\"", "").replaceAll(" standalone=\"true\"", ""));
					logger.debug("web.xml has been modified.\n{}", xmlData);
				} catch (JAXBException e) {
					logger.error("JAXBException has occurred.", e);
					throw e;
				} catch (IOException e) {
					logger.error("IOException has occurred.", e);
					throw e;
				}
            }

            return webApp;
		} else if (obj instanceof com.athena.chameleon.engine.entity.xml.webapp.v2_4.WebAppType) {
			com.athena.chameleon.engine.entity.xml.webapp.v2_4.WebAppType webApp = (com.athena.chameleon.engine.entity.xml.webapp.v2_4.WebAppType) obj;

			// webApp에 <filter />, <filter-mapping />이 존재하는지 확인
            List<Object> elementList = webApp.getDescriptionAndDisplayNameAndIcon();

            List<com.athena.chameleon.engine.entity.xml.webapp.v2_4.ParamValueType> paramList = null;
            com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterNameType filtername = null;

            for(Object element : elementList) {
            	if(element instanceof com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType) {
            		filtername = ((com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType)element).getFilterName();

            		paramList = ((com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType)element).getInitParam();
            		for(com.athena.chameleon.engine.entity.xml.webapp.v2_4.ParamValueType param : paramList) {
                		// init-param의 param-name이 encoding이 존재하는지 확인
            			if(param.getParamName().getValue().toLowerCase().equals("encoding")) {
                			hasEncodingFilter = true;

                    		// param-value가 UTF-8인지 확인
            				if(ArrayUtils.contains(charSet, param.getParamValue().getValue().toUpperCase())) {
            					hasUTF8EncodingFilter = true;
                    			break;
                			}
            			}
            		}

            		if(hasEncodingFilter) {
            			break;
            		}
            	}
            }

            // encoding filter는 존재하지만 UTF-8이 아닐 경우 해당 filter 및 filter-mapping 엘리먼트를 삭제한다.
            if(hasEncodingFilter && !hasUTF8EncodingFilter) {
            	com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType f = null;
            	com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterMappingType fm = null;

	            for(Object element : elementList) {
	            	if(element instanceof com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType) {
	            		if(((com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType)element).getFilterName().getValue().equals(filtername.getValue())) {
	            			f = (com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType)element;
	            		}
	            	} else if(element instanceof com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterMappingType) {
	            		if(((com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterMappingType)element).getFilterName().getValue().equals(filtername.getValue())) {
	            			fm = (com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterMappingType)element;
	            		}
	            	}
	            }

	            webApp.getDescriptionAndDisplayNameAndIcon().remove(f);
	            webApp.getDescriptionAndDisplayNameAndIcon().remove(fm);
            }

            if(!hasUTF8EncodingFilter) {
	            // <filter> element 추가
            	com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType filter = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterType();

            	com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterNameType filterName = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterNameType();
	            filterName.setValue("UTF_EncodingFilter");
	            filter.setFilterName(filterName);

	            com.athena.chameleon.engine.entity.xml.webapp.v2_4.FullyQualifiedClassType filterClass = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.FullyQualifiedClassType();
	            filterClass.setValue("com.osc.filters.SetCharacterEncodingFilter");
	            filter.setFilterClass(filterClass);

	            // <init-param> element 추가
	            com.athena.chameleon.engine.entity.xml.webapp.v2_4.ParamValueType paramValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.ParamValueType();
	            com.athena.chameleon.engine.entity.xml.webapp.v2_4.String strName = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.String();
	            strName.setValue("encoding");
	            com.athena.chameleon.engine.entity.xml.webapp.v2_4.XsdStringType strValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.XsdStringType();
	            strValue.setValue("UTF-8");
	            paramValue.setParamName(strName);
	            paramValue.setParamValue(strValue);

	            filter.getInitParam().add(paramValue);

	            paramValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.ParamValueType();
	            strName = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.String();
	            strName.setValue("forceEncoding");
	            strValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.XsdStringType();
	            strValue.setValue("UTF-8");
	            paramValue.setParamName(strName);
	            paramValue.setParamValue(strValue);

	            filter.getInitParam().add(paramValue);

	            // <filter-mapping> elemnet 추가
	            com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterMappingType filterMapping = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.FilterMappingType();
	            com.athena.chameleon.engine.entity.xml.webapp.v2_4.UrlPatternType urlPattern = new com.athena.chameleon.engine.entity.xml.webapp.v2_4.UrlPatternType();
	            urlPattern.setValue("/*");
	            filterMapping.setUrlPattern(urlPattern);
	            filterMapping.setFilterName(filterName);

	            // <web-app>에 filter 추가
	            webApp.getDescriptionAndDisplayNameAndIcon().add(filter);
	            webApp.getDescriptionAndDisplayNameAndIcon().add(filterMapping);

	            try {
		            // Filter 관련 라이브러리 복사
		            fileCopy(new File(WebXMLParser.class.getResource("/lib/osc-filters.jar").getFile()), new File(path, "lib/osc-filters.jar"));

		            // web.xml 저장
					String xmlData = JaxbUtils.marshal(com.athena.chameleon.engine.entity.xml.webapp.v2_4.WebAppType.class.getPackage().getName(), webApp, new String[]{"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"});
					rewrite(new File(path, "web.xml"), xmlData.replaceAll(" standalone=\"yes\"", "").replaceAll(" standalone=\"true\"", ""));
					logger.debug("web.xml has been modified.\n{}", xmlData);
				} catch (JAXBException e) {
					logger.error("JAXBException has occurred.", e);
					throw e;
				} catch (IOException e) {
					logger.error("IOException has occurred.", e);
					throw e;
				}
            }

            return webApp;
		} else {
			com.athena.chameleon.engine.entity.xml.webapp.v2_3.WebApp webApp = (com.athena.chameleon.engine.entity.xml.webapp.v2_3.WebApp) obj;

			// webApp에 <filter />, <filter-mapping />이 존재하는지 확인
			List<com.athena.chameleon.engine.entity.xml.webapp.v2_3.Filter> filterList = webApp.getFilter();

            com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterName filtername = null;
            List<com.athena.chameleon.engine.entity.xml.webapp.v2_3.InitParam> initParamList = null;
            for(com.athena.chameleon.engine.entity.xml.webapp.v2_3.Filter filter : filterList) {
            	filtername = filter.getFilterName();

            	initParamList = filter.getInitParam();
            	for(com.athena.chameleon.engine.entity.xml.webapp.v2_3.InitParam initParam : initParamList) {
            		if(initParam.getParamName().getvalue().toLowerCase().equals("encoding")) {
            			hasEncodingFilter = true;

                		// param-value가 UTF-8인지 확인
        				if(ArrayUtils.contains(charSet, initParam.getParamValue().getvalue().toUpperCase())) {
        					hasUTF8EncodingFilter = true;
                			break;
            			}
            		}
            	}

        		if(hasEncodingFilter) {
        			break;
        		}
            }

            // encoding filter는 존재하지만 UTF-8이 아닐 경우 해당 filter 및 filter-mapping 엘리먼트를 삭제한다.
            if(hasEncodingFilter && !hasUTF8EncodingFilter) {
            	com.athena.chameleon.engine.entity.xml.webapp.v2_3.Filter filter = null;

                for(com.athena.chameleon.engine.entity.xml.webapp.v2_3.Filter f : filterList) {
                	if(f.getFilterName().getvalue().equals(filtername.getvalue())) {
                		filter = f;
                	}
                }

    			List<com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterMapping> filterMappingList = webApp.getFilterMapping();
            	com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterMapping filterMapping = null;
                for(com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterMapping fm : filterMappingList) {
                	if(fm.getFilterName().getvalue().equals(filtername.getvalue())) {
                		filterMapping = fm;
                	}
                }

                webApp.getFilter().remove(filter);
                webApp.getFilterMapping().remove(filterMapping);
            }

            if(!hasUTF8EncodingFilter) {
	            // <filter> element 추가
            	com.athena.chameleon.engine.entity.xml.webapp.v2_3.Filter filter = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.Filter();
            	com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterName filterName = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterName();

	            filterName.setvalue("UTF_EncodingFilter");
	            filter.setFilterName(filterName);

	            com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterClass filterClass = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterClass();
	            filterClass.setvalue("com.osc.filters.SetCharacterEncodingFilter");
	            filter.setFilterClass(filterClass);

	            // <init-param> element 추가
	            com.athena.chameleon.engine.entity.xml.webapp.v2_3.InitParam initParam = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.InitParam();
	            com.athena.chameleon.engine.entity.xml.webapp.v2_3.ParamName paramName = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.ParamName();
	            com.athena.chameleon.engine.entity.xml.webapp.v2_3.ParamValue paramValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.ParamValue();

	            paramName.setvalue("encoding");
	            paramValue.setvalue("UTF-8");

	            initParam.setParamName(paramName);
	            initParam.setParamValue(paramValue);

	            filter.getInitParam().add(initParam);

	            initParam = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.InitParam();
	            paramName = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.ParamName();
	            paramValue = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.ParamValue();

	            paramName.setvalue("forceEncoding");
	            paramValue.setvalue("UTF-8");

	            initParam.setParamName(paramName);
	            initParam.setParamValue(paramValue);

	            filter.getInitParam().add(initParam);

	            // <filter-mapping> elemnet 추가
	            com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterMapping filterMapping = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.FilterMapping();
	            com.athena.chameleon.engine.entity.xml.webapp.v2_3.UrlPattern urlPattern = new com.athena.chameleon.engine.entity.xml.webapp.v2_3.UrlPattern();
	            urlPattern.setvalue("/*");
	            filterMapping.getUrlPatternOrServletName().add(urlPattern);
	            filterMapping.setFilterName(filterName);

	            // <web-app>에 filter 추가
	            webApp.getFilter().add(filter);
	            webApp.getFilterMapping().add(filterMapping);

	            try {
		            // Filter 관련 라이브러리 복사
		            fileCopy(new File(WebXMLParser.class.getResource("/lib/osc-filters.jar").getFile()), new File(path, "lib/osc-filters.jar"));

		            // web.xml 저장
					String xmlData = JaxbUtils.marshal(com.athena.chameleon.engine.entity.xml.webapp.v2_3.WebApp.class.getPackage().getName(), webApp, "<!DOCTYPE web-app PUBLIC \"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\" \"http://java.sun.com/dtd/web-app_2_3.dtd\">");
					rewrite(new File(path, "web.xml"), xmlData.replaceAll(" standalone=\"yes\"", "").replaceAll(" standalone=\"true\"", ""));
					logger.debug("web.xml has been modified.\n{}", xmlData);
				} catch (JAXBException e) {
					logger.error("JAXBException has occurred.", e);
					throw e;
				} catch (IOException e) {
					logger.error("IOException has occurred.", e);
					throw e;
				}
            }

            return webApp;
		}
	}//end of checkEncodignFilter()

}//end of WebXMLParser.java


text:
package bio

import (
	"bytes"
	"encoding/binary"
	"io"

	"github.com/chzyer/logex"
)

var (
	ErrShortRead        = logex.Define("short read")
	ErrShortWrite       = logex.Define("short write")
	ErrReaderBufferFull = logex.Define("reader buffer is full")
	ErrWriterBufferFull = logex.Define("reader writer is full")
)

type Reader struct {
	data   []byte
	offset int
}

func ReadAt(r io.ReaderAt, offset int64, d Diskable) error {
	blk := make([]byte, d.Size())
	n, err := r.ReadAt(blk, offset)
	if err != nil {
		return logex.Trace(err)
	}
	if n != len(blk) {
		return logex.Trace(io.EOF)
	}
	return logex.Trace(d.ReadDisk(NewReader(blk)))
}

func WriteAt(w io.WriterAt, offset int64, d Diskable) error {
	blk := make([]byte, d.Size())
	d.WriteDisk(NewWriter(blk))
	n, err := w.WriteAt(blk, offset)
	if n != len(blk) {
		return ErrShortWrite.Trace(n, len(blk))
	}
	return logex.Trace(err)
}

func ReadDiskable(raw RawDiskerReader, addr int64, disk Diskable) error {
	ret := make([]byte, disk.Size())
	n, err := raw.ReadAt(ret, addr)
	if err != nil {
		return logex.Trace(err)
	}
	if n != len(ret) {
		return ErrShortRead.Trace()
	}
	if err := disk.ReadDisk(NewReader(ret)); err != nil {
		return logex.Trace(err)
	}
	return nil
}

func NewReader(data []byte) *Reader {
	return &Reader{data: data}
}

func (r *Reader) Offset() int {
	return r.offset
}

func (r *Reader) Verify(b []byte) bool {
	return bytes.Equal(r.Byte(len(b)), b)
}

func (r *Reader) Skip(n int) {
	r.offset += n
}

func (r *Reader) Byte(n int) []byte {
	ret := r.data[r.offset : r.offset+n]
	r.offset += n
	return ret
}

func (r *Reader) Available() int {
	return len(r.data) - r.offset
}

func (r *Reader) Check(d Diskable, n int) error {
	if r.Available() < d.Size()*n {
		return ErrReaderBufferFull.Trace()
	}
	return nil
}

func (r *Reader) ReadDisk(d Diskable) error {
	if r.Available() < d.Size() {
		return ErrReaderBufferFull.Trace()
	}
	return d.ReadDisk(r)
}

func (r *Reader) Int32() int32 {
	ret := int32(binary.BigEndian.Uint32(r.data[r.offset:]))
	r.offset += 4
	return ret
}

func (r *Reader) Int64() int64 {
	ret := int64(binary.BigEndian.Uint64(r.data[r.offset:]))
	r.offset += 8
	return ret
}


text:
'use strict'

import { EventEmitter } from 'events'
import SimpleDialog from './simple-dialog'
import Prompt from './prompt/prompt'
import consts from '../constants'
import { waterfall } from '../utils'

class DialogCollection extends EventEmitter {
  constructor () {
    super()
    this.middleware = []
    this.dialogs = {}
    DialogCollection.systemDialogs[consts.DialogId.Prompt] = new Prompt()
    this.add(DialogCollection.systemDialogs)
  }

  add (id, dialog) {
    let dialogs = null
    if (typeof id === 'string') {
      if (Array.isArray(dialog)) {
        dialog = new SimpleDialog(waterfall(dialog))
      } else if (typeof dialog === 'function') {
        dialog = new SimpleDialog(waterfall([dialog]))
      }
      let _a = null
      dialogs = (_a = {}, _a[id] = dialog, _a)
    } else {
      dialogs = id
    }
    for (let key in dialogs) {
      if (!this.dialogs.hasOwnProperty(key)) {
        this.dialogs[key] = dialogs[key]
      } else {
        throw new Error(`Dialog[${key}] already exists.`)
      }
    }
    return this
  }

  getDialog (id) {
    return this.dialogs[id]
  }

  getMiddleware () {
    return this.middleware
  }

  hasDialog (id) {
    return this.dialogs.hasOwnProperty(id)
  }

  use (fn) {
    this.middleware.push(fn)
    return this
  }
}

DialogCollection.systemDialogs = {}

export default DialogCollection


text:
var assert = chai.assert;
declare function fixture(id: string): void; window.HTMLImports.whenReady(() => {

  Polymer({
    is: 'autoreload-test-element',
    behaviors: [TF.TensorBoard.AutoReloadBehavior],
  });

  describe('autoReload-behavior', function() {
    var testElement;
    var ls = window.localStorage;
    var key = TF.TensorBoard.AUTORELOAD_LOCALSTORAGE_KEY;
    var clock;
    var callCount: number;

    // Promise that returns immediately. Useful to allow other async activity
    // (e.g. element lifecycle callbacks in Firefox) to occur before a test.
    var waitAsync = () => new Promise((resolve, reject) => resolve());

    beforeEach(function() {
      ls.setItem(key, 'false');  // start it turned off so we can mutate fns
      testElement = fixture('autoReloadFixture');
      callCount = 0;
      testElement.reload = function() { callCount++; };
    });

    before(function() { clock = sinon.useFakeTimers(); });

    after(function() { clock.restore(); });

    it('reads and writes autoReload state from localStorage', function() {
      ls.removeItem(key);
      testElement = fixture('autoReloadFixture');
      assert.isTrue(
          testElement.autoReloadEnabled, 'autoReload defaults to true');
      assert.equal(ls.getItem(key), 'true', 'autoReload setting saved');
      testElement = fixture('autoReloadFixture');
      assert.isTrue(
          testElement.autoReloadEnabled, 'read true from localStorage');
      testElement.autoReloadEnabled = false;
      assert.equal(ls.getItem(key), 'false', 'autoReload setting saved');
      testElement = fixture('autoReloadFixture');
      assert.isFalse(
          testElement.autoReloadEnabled, 'read false setting properly');
      testElement.autoReloadEnabled = true;
      assert.equal(ls.getItem(key), 'true', 'saved true setting');
    });

    it('reloads every interval secs when autoReloading', function() {
      testElement.autoReloadIntervalSecs = 1;
      testElement.autoReloadEnabled = true;
      clock.tick(1000);
      assert.equal(callCount, 1, 'ticking clock triggered call');
      clock.tick(20 * 1000);
      assert.equal(callCount, 21, 'ticking clock 20s triggered 20 calls');
    });

    it('can cancel pending autoReload', function() {
      testElement.autoReloadIntervalSecs = 10;
      testElement.autoReloadEnabled = true;
      clock.tick(5 * 1000);
      testElement.autoReloadEnabled = false;
      clock.tick(20 * 1000);
      assert.equal(callCount, 0, 'callCount is 0');
    });

    it('turns off autoReload when component is detatched', function(done) {
      testElement.autoReloadIntervalSecs = 1;
      testElement.autoReloadEnabled = true;
      testElement.remove();
      waitAsync().then(function() {
        clock.tick(20 * 1000);
        assert.equal(callCount, 0, 'callCount still 0');
        done();
      });
    });

    it('throws an error in absence of reload method', function() {
      testElement.reload = undefined;
      testElement.autoReloadIntervalSecs = 1;
      testElement.autoReloadEnabled = true;
      assert.throws(function() {
        clock.tick(5000);
      });
    });
  });
});


text:
$:.push File.join(File.dirname(__FILE__), '..', 'lib')
require 'merb-core'
require 'merb-core/test'
require 'merb-core/test/helpers'

Merb::BootLoader.before_app_loads do
  require "merb/session/active_record_session"
end

Merb.start_environment( :environment => 'test', :adapter => 'runner',
                        :session_store => 'activerecord')

Spec::Runner.configure do |config|
  config.include Merb::Test::RequestHelper
end

require 'merb_activerecord'
ActiveRecord::Base.establish_connection(:adapter => "sqlite3",
                                        :dbfile => ":memory:")

ActiveRecord::Schema.define do
  create_table :sessions do |t|
    t.column :session_id, :string
    t.column :data,       :text
    t.column :created_at, :datetime
  end
end

# Load up the shared specs from merb-core
if (gem_spec = Gem.source_index.search(Gem::Dependency.new('merb-core', '>=0.9.6')).last) &&
  gem_spec.files.include?('spec/public/session/controllers/sessions.rb')
  require gem_spec.full_gem_path / 'spec/public/session/controllers/sessions.rb'
  require gem_spec.full_gem_path / 'spec/public/session/session_spec.rb'
end

describe Merb::ActiveRecordSession do

  before do
    @session_class = Merb::ActiveRecordSession
    @session = @session_class.generate
  end

  it_should_behave_like "All session-store backends"

  it "should have a session_store_type class attribute" do
    @session.class.session_store_type.should == :activerecord
  end

end

describe Merb::ActiveRecordSession, "mixed into Merb::Controller" do

  before(:all) { @session_class = Merb::ActiveRecordSession }

  it_should_behave_like "All session-stores mixed into Merb::Controller"

end


text:
std::ostream &print(std::ostream &os, const std::vector<std::string> &vs) {
  for (const auto &i : vs)
    os << i << " ";
  return os;
}

void elimDups(std::vector<std::string> &words) {
  print(std::cout, words) << words.size() << std::endl;
  std::sort(words.begin(), words.end());
  print(std::cout, words) << words.size() << std::endl;
  auto end_unique = std::unique(words.begin(), words.end());
  print(std::cout, words) << words.size() << std::endl;
  words.erase(end_unique, words.end());
  print(std::cout, words) << words.size() << std::endl;
}

bool isShorter(const std::string &s1, const std::string &s2) {
  return s1.size() < s2.size();
}

int main() {
  std::vector<std::string> words;
  for (std::string s; std::cin >> s; words.push_back(s)) {}
  elimDups(words);
  std::stable_sort(words.begin(), words.end(), isShorter);
  print(std::cout, words) << words.size() << std::endl;

  return 0;
}


text:
Su Doku (Japanese meaning number place) is the name given to a popular puzzle concept.
Its origin is unclear, but credit must be attributed to Leonhard Euler who invented a similar, and much more difficult,
puzzle idea called Latin Squares.

The objective of Su Doku puzzles, however, is to replace the blanks (or zeros)
in a 9 by 9 grid in such that each row, column, and 3 by 3 box contains each of the digits 1 to 9.
Below is an example of a typical starting puzzle grid and its solution grid.

[ Two Puzzles Here]

A well constructed Su Doku puzzle has a unique solution and can be solved by logic,
although it may be necessary to employ "guess and test" methods in order to eliminate options (there is much contested opinion over this).
The complexity of the search determines the difficulty of the puzzle;
the example above is considered easy because it can be solved by straight forward direct deduction.

The 6K text file, sudoku.txt (right click and 'Save Link/Target As...'),
contains fifty different Su Doku puzzles ranging in difficulty, but all with unique solutions (the first puzzle in the file is the example above).

By solving all fifty puzzles find the sum of the 3-digit numbers found in the top left corner of each solution grid;
for example, 483 is the 3-digit number found in the top left corner of the solution grid above.
=#
include("projecteulerutils.jl")
using DelimitedFiles

function valuesinrow(grid, row)
  a = Array{Int64, 1}()
  for x in 1:9
    if grid[row, x] != 0 push!(a, grid[row, x]) end
  end
  a
end

function valuesincolumn(grid, column)
  a = Array{Int64, 1}()
  for y in 1:9
    if grid[y, column] != 0 push!(a, grid[y, column]) end
  end
  a
end

function valuesincurrentcell(grid, x, y)
  result = Array{Int64, 1}()
  startx = round(Int64, (3 * ceil(x / 3)) - 2)
  starty = round(Int64, (3 * ceil(y / 3)) - 2)
  for x in startx:startx+2, y in starty:starty+2
    if grid[y, x] != 0 push!(result, grid[y, x]) end
  end
  result
end

function emptycell(grid)
  for x in 1:9, y in 1:9
    if grid[y, x] == 0 return x, y end
  end
end

function solve(grid)
  if all(x -> x != 0, grid) # grid is full
    return true
  else
    x, y = emptycell(grid)
    for value in setdiff(collect(1:9), append!([], [valuesincolumn(grid, x); valuesinrow(grid, y); valuesincurrentcell(grid, x, y)])) # valid values for cell
      grid[y, x] = value
      if solve(grid)
        return true
      end
      grid[y, x] = 0
    end
  end
  false
end

function calc()
  x, total = readdlm(dirname(@__FILE__()) * "/../Resources/p96.txt", ',', Int64), 0
  for i in 1:9:450
    grid = x[i:i+8, 1:9]; solve(grid)
    total += nd(grid[1, 1:3])
  end
  total
end
@time println(calc())