<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkShapedFloodFilledImageFunctionConditionalConstIteratorTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// Test itk::ShapedFloodFilledImageFunctionConditionalConstIterator on a 2D
// image using the fully connected option.

#include "itkImageFileReader.h"
#include "itkBinaryThresholdImageFunction.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkFloodFilledImageFunctionConditionalConstIterator.h"

#include "itkShapedFloodFilledImageFunctionConditionalConstIterator.h"

int itkShapedFloodFilledImageFunctionConditionalConstIteratorTest1(int argc, char **argv)
{
  try
    {
    const unsigned int ImageDimension = 2;
    typedef unsigned char PixelType;

    typedef itk::Image<PixelType, ImageDimension> ImageType;
    typedef ImageType::RegionType                 RegionType;
    typedef ImageType::IndexType                  IndexType;

    typedef itk::BinaryThresholdImageFunction<ImageType> FunctionType;
    typedef itk::ShapedFloodFilledImageFunctionConditionalConstIterator<
                  ImageType, FunctionType> ShapedFloodFilledIteratorType;

    typedef itk::ImageFileReader<ImageType> ReaderType;

    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(argv[1]);
    reader->Update();

    const IndexType index = {29, 47};

    std::vector<IndexType> seedList;
    seedList.push_back(index);

    RegionType region = reader->GetOutput()->GetBufferedRegion();

    FunctionType::Pointer function = FunctionType::New();

    function->SetInputImage ( reader->GetOutput() );
    function->ThresholdAbove ( 1 ); // >= 1

    ShapedFloodFilledIteratorType shapedFloodIt(
        reader->GetOutput(), function, seedList);
    shapedFloodIt.SetFullyConnected(true); // 8-connected, default

    ImageType::Pointer visitedImage = ImageType::New();
    visitedImage->SetRegions(region);
    visitedImage->Allocate();
    visitedImage->FillBuffer(0);

    for (; !shapedFloodIt.IsAtEnd(); ++shapedFloodIt)
      {
      const IndexType& index = shapedFloodIt.GetIndex();
      visitedImage->SetPixel(index, 255);
      }

    typedef itk::ImageRegionConstIterator<ImageType> ConstIteratorType;

    ConstIteratorType inIt(reader->GetOutput(), region);
    ConstIteratorType outIt(visitedImage, region);

    for (; !inIt.IsAtEnd(); ++inIt, ++outIt)
      {
      if (inIt.Get() != outIt.Get())
        {
        return EXIT_FAILURE;
        }
      }
    }
  catch (itk::ExceptionObject& e)
    {
    e.Print(std::cerr);
    return EXIT_FAILURE;
    }
  catch (...)
    {
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<commit_msg>COMP: Fixing initialization of Index. Warning in gcc4.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkShapedFloodFilledImageFunctionConditionalConstIteratorTest1.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// Test itk::ShapedFloodFilledImageFunctionConditionalConstIterator on a 2D
// image using the fully connected option.

#include "itkImageFileReader.h"
#include "itkBinaryThresholdImageFunction.h"
#include "itkImageLinearIteratorWithIndex.h"
#include "itkFloodFilledImageFunctionConditionalConstIterator.h"

#include "itkShapedFloodFilledImageFunctionConditionalConstIterator.h"

int itkShapedFloodFilledImageFunctionConditionalConstIteratorTest1(int argc, char **argv)
{
  try
    {
    const unsigned int ImageDimension = 2;
    typedef unsigned char PixelType;

    typedef itk::Image<PixelType, ImageDimension> ImageType;
    typedef ImageType::RegionType                 RegionType;
    typedef ImageType::IndexType                  IndexType;

    typedef itk::BinaryThresholdImageFunction<ImageType> FunctionType;
    typedef itk::ShapedFloodFilledImageFunctionConditionalConstIterator<
                  ImageType, FunctionType> ShapedFloodFilledIteratorType;

    typedef itk::ImageFileReader<ImageType> ReaderType;

    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(argv[1]);
    reader->Update();

    IndexType index;

    index[0] = 29;
    index[1] = 47;

    std::vector<IndexType> seedList;
    seedList.push_back(index);

    RegionType region = reader->GetOutput()->GetBufferedRegion();

    FunctionType::Pointer function = FunctionType::New();

    function->SetInputImage ( reader->GetOutput() );
    function->ThresholdAbove ( 1 ); // >= 1

    ShapedFloodFilledIteratorType shapedFloodIt(
        reader->GetOutput(), function, seedList);
    shapedFloodIt.SetFullyConnected(true); // 8-connected, default

    ImageType::Pointer visitedImage = ImageType::New();
    visitedImage->SetRegions(region);
    visitedImage->Allocate();
    visitedImage->FillBuffer(0);

    for (; !shapedFloodIt.IsAtEnd(); ++shapedFloodIt)
      {
      const IndexType& index = shapedFloodIt.GetIndex();
      visitedImage->SetPixel(index, 255);
      }

    typedef itk::ImageRegionConstIterator<ImageType> ConstIteratorType;

    ConstIteratorType inIt(reader->GetOutput(), region);
    ConstIteratorType outIt(visitedImage, region);

    for (; !inIt.IsAtEnd(); ++inIt, ++outIt)
      {
      if (inIt.Get() != outIt.Get())
        {
        return EXIT_FAILURE;
        }
      }
    }
  catch (itk::ExceptionObject& e)
    {
    e.Print(std::cerr);
    return EXIT_FAILURE;
    }
  catch (...)
    {
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "../include/selector_numeric.hpp"

selector_numeric::selector_numeric(const std::string &label, ALLEGRO_FONT *font, const int min, const int max):
    font_(font),
    label_(label),
    value_(min),
    max_(max),
    min_(min),
    x_(0),
    y_(0),
    r_mouse_inside_(false),
    r_mouse_pressed_(false),
    r_mouse_realased_(false),
    l_mouse_inside_(false),
    l_mouse_pressed_(false),
    l_mouse_realased_(false),
    last_mouse_z_(0)
{}

selector_numeric::~selector_numeric()
{}

void selector_numeric::moveTo(const double x, const double y)
{
    x_ = x;
    y_ = y;
}

void selector_numeric::update()
{
    double labelw = al_get_text_width(font_, label_.c_str());
    double lw = al_get_bitmap_width(arrow_image);
    double w = al_get_text_width(font_, std::to_string(int(value_)).c_str());

    l_mouse_inside_ = mouse.insideBox(x_+labelw+10, y_-5, x_+labelw+lw+40, y_+30);
    r_mouse_inside_ = mouse.insideBox(x_+labelw+lw+w+50, y_-5, x_+labelw+lw+w+80, y_+30);

    if (!l_mouse_inside_)
        l_mouse_realased_ = l_mouse_pressed_ = false;

    else
    {
        if (!mouse.isPressed(1))
            l_mouse_realased_ = true;

        if (mouse.isPressed(1) && l_mouse_realased_)
        {
            l_mouse_pressed_  = true;
            l_mouse_realased_ = false;
        }

        if (l_mouse_pressed_ && l_mouse_realased_)
        {
            if (value_ > min_) value_--;
            l_mouse_pressed_  = false;
            l_mouse_realased_ = false;
        }
    }

    if (!r_mouse_inside_)
        r_mouse_realased_ = r_mouse_pressed_ = false;

    else
    {
        if (!mouse.isPressed(1))
            r_mouse_realased_ = true;

        if (mouse.isPressed(1) && r_mouse_realased_)
        {
            r_mouse_pressed_  = true;
            r_mouse_realased_ = false;
        }

        if (r_mouse_pressed_ && r_mouse_realased_)
        {
            value_++;
            r_mouse_pressed_  = false;
            r_mouse_realased_ = false;
        }
    }

    if (last_mouse_z_ && mouse.insideBox(x_+labelw+10, y_-5, x_+labelw+lw+w+80, y_+30) && last_mouse_z_ != mouse.getZ())
    {
        value_ += (mouse.getZ() - last_mouse_z_)*2;
    }

    if (value_ > max_) value_ = max_;
    if (value_ < min_) value_ = min_;

    last_mouse_z_ = mouse.getZ();
}

void selector_numeric::draw() const
{
    double labelw = al_get_text_width(font_, label_.c_str());
    double w = al_get_text_width(font_, std::to_string(int(value_)).c_str());
    double lw = al_get_bitmap_width(arrow_image);

    al_draw_bitmap(arrow_image, x_+labelw+20, y_+4, 0);
    al_draw_bitmap(arrow_image, x_+labelw+lw+w+60, y_+4, ALLEGRO_FLIP_HORIZONTAL);

    al_draw_text(font_, GRAY, x_, y_,ALLEGRO_ALIGN_LEFT, label_.c_str());
    al_draw_text(font_, GRAY, x_+labelw+lw+40+w/2, y_,ALLEGRO_ALIGN_CENTER, std::to_string(int(value_)).c_str());
}

bool selector_numeric::mouseOverArrow() const
{
    return r_mouse_inside_ || l_mouse_inside_;
}

void selector_numeric::setLabel(const std::string &label)
{
    label_ = label;
}

int selector_numeric::getValue() const
{
    return value_;
}
<commit_msg>Add/Delete water<commit_after>#include "../include/selector_numeric.hpp"

selector_numeric::selector_numeric(const std::string &label, ALLEGRO_FONT *font, const int min, const int max):
    font_(font),
    label_(label),
    value_((min+max)/2),
    max_(max),
    min_(min),
    x_(0),
    y_(0),
    r_mouse_inside_(false),
    r_mouse_pressed_(false),
    r_mouse_realased_(false),
    l_mouse_inside_(false),
    l_mouse_pressed_(false),
    l_mouse_realased_(false),
    last_mouse_z_(0)
{}

selector_numeric::~selector_numeric()
{}

void selector_numeric::moveTo(const double x, const double y)
{
    x_ = x;
    y_ = y;
}

void selector_numeric::update()
{
    double labelw = al_get_text_width(font_, label_.c_str());
    double lw = al_get_bitmap_width(arrow_image);
    double w = al_get_text_width(font_, std::to_string(int(value_)).c_str());

    l_mouse_inside_ = mouse.insideBox(x_+labelw+10, y_-5, x_+labelw+lw+40, y_+30);
    r_mouse_inside_ = mouse.insideBox(x_+labelw+lw+w+50, y_-5, x_+labelw+lw+w+80, y_+30);

    if (!l_mouse_inside_)
        l_mouse_realased_ = l_mouse_pressed_ = false;

    else
    {
        if (!mouse.isPressed(1))
            l_mouse_realased_ = true;

        if (mouse.isPressed(1) && l_mouse_realased_)
        {
            l_mouse_pressed_  = true;
            l_mouse_realased_ = false;
        }

        if (l_mouse_pressed_ && l_mouse_realased_)
        {
            if (value_ > min_) value_--;
            l_mouse_pressed_  = false;
            l_mouse_realased_ = false;
        }
    }

    if (!r_mouse_inside_)
        r_mouse_realased_ = r_mouse_pressed_ = false;

    else
    {
        if (!mouse.isPressed(1))
            r_mouse_realased_ = true;

        if (mouse.isPressed(1) && r_mouse_realased_)
        {
            r_mouse_pressed_  = true;
            r_mouse_realased_ = false;
        }

        if (r_mouse_pressed_ && r_mouse_realased_)
        {
            value_++;
            r_mouse_pressed_  = false;
            r_mouse_realased_ = false;
        }
    }

    if (last_mouse_z_ && mouse.insideBox(x_+labelw+10, y_-5, x_+labelw+lw+w+80, y_+30) && last_mouse_z_ != mouse.getZ())
    {
        value_ += (mouse.getZ() - last_mouse_z_)*2;
    }

    if (value_ > max_) value_ = max_;
    if (value_ < min_) value_ = min_;

    last_mouse_z_ = mouse.getZ();
}

void selector_numeric::draw() const
{
    double labelw = al_get_text_width(font_, label_.c_str());
    double w = al_get_text_width(font_, std::to_string(int(value_)).c_str());
    double lw = al_get_bitmap_width(arrow_image);

    al_draw_bitmap(arrow_image, x_+labelw+20, y_+4, 0);
    al_draw_bitmap(arrow_image, x_+labelw+lw+w+60, y_+4, ALLEGRO_FLIP_HORIZONTAL);

    al_draw_text(font_, GRAY, x_, y_,ALLEGRO_ALIGN_LEFT, label_.c_str());
    al_draw_text(font_, GRAY, x_+labelw+lw+40+w/2, y_,ALLEGRO_ALIGN_CENTER, std::to_string(int(value_)).c_str());
}

bool selector_numeric::mouseOverArrow() const
{
    return r_mouse_inside_ || l_mouse_inside_;
}

void selector_numeric::setLabel(const std::string &label)
{
    label_ = label;
}

int selector_numeric::getValue() const
{
    return value_;
}
<|endoftext|>


<commit_before>/** accuracy.cc
    Jeremy Barnes, 16 December 2014
    Copyright (c) 2014 Datacratic Inc.  All rights reserved.

    This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.

    Implementation of an ACCURACY algorithm for embedding of a dataset.
*/

#include "accuracy.h"
#include "matrix.h"
#include "mldb/server/mldb_server.h"
#include "mldb/core/dataset.h"
#include "mldb/server/bound_queries.h"
#include "mldb/sql/sql_expression.h"
#include "mldb/jml/stats/distribution.h"
#include <boost/multi_array.hpp>
#include "mldb/jml/utils/guard.h"
#include "mldb/jml/utils/worker_task.h"
#include "mldb/jml/utils/pair_utils.h"
#include "mldb/arch/timers.h"
#include "mldb/arch/simd_vector.h"
#include "mldb/jml/utils/vector_utils.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/ml/value_descriptions.h"
#include "mldb/ml/separation_stats.h"
#include "mldb/server/analytics.h"
#include "mldb/types/any_impl.h"
#include "mldb/server/per_thread_accumulator.h"
#include "mldb/types/optional_description.h"
#include "mldb/http/http_exception.h"
#include "mldb/plugins/sql_config_validator.h"
#include "mldb/plugins/sql_expression_extractors.h"

using namespace std;

namespace Datacratic {
namespace MLDB {

DEFINE_STRUCTURE_DESCRIPTION(AccuracyConfig);

AccuracyConfigDescription::
AccuracyConfigDescription()
{
    Optional<PolyConfigT<Dataset> > optionalOutputDataset;
    optionalOutputDataset.emplace(PolyConfigT<Dataset>().
                                  withType(AccuracyConfig::defaultOutputDatasetType));

    addField("testingData", &AccuracyConfig::testingData,
             "Specification of the data for input to the accuracy procedure. "
             "The select expression must contain these sub-expressions: one scalar expression "
             "to identify the label and one scalar expression to identify the score. "
             "The type of the label expression must match "
             "that of the classifier mode from which the model was trained. "
             "Labels with a null value will have their row skipped. "
             "The expression to generate the score represents the output "
             "of whatever is having its accuracy tested.  This needs to be "
             "a number, and normally should be a floating point number that "
             "represents the degree of confidence in the prediction, not "
             "just the class. This is typically, the training function returned "
             "by a classifier.train procedure. "
             "The select expression can also contain an optional weight sub-expression. "
             "This expression generates the relative weight for each example.  In some "
             "circumstances it is necessary to calculate accuracy statistics "
             "with uneven weighting, for example to counteract the effect of "
             "non-uniform sampling in dataset.  By default, each class will "
             "get the same weight.  This value is relative to the other "
             "examples, in other words having all examples weighted 1 or all "
             "examples weighted 10 will have the same effect.  That being "
             "said, it is a good idea to keep the weights centered around 1 "
             "to avoid numeric errors in the calculations."
             "The select statement does not support groupby and having clauses.");
    addField("outputDataset", &AccuracyConfig::outputDataset,
             "Output dataset for scored examples. The score for each "
             "example will be written to this dataset. Specifying a "
             "dataset is optional", optionalOutputDataset);
    addParent<ProcedureConfig>();

    onPostValidate = validate<AccuracyConfig,
                              InputQuery,
                              NoGroupByHaving,
                              PlainColumnSelect,
                              ScoreLabelSelect>(&AccuracyConfig::testingData, "accuracy");

}

/*****************************************************************************/
/* ACCURACY PROCEDURE                                                         */
/*****************************************************************************/

AccuracyProcedure::
AccuracyProcedure(MldbServer * owner,
                 PolyConfig config,
                 const std::function<bool (const Json::Value &)> & onProgress)
    : Procedure(owner)
{
    this->accuracyConfig = config.params.convert<AccuracyConfig>();
    if (!accuracyConfig.testingData.stm)
        throw HttpReturnException(400, "Classifier testing procedure requires 'testingData' to be set",
                                  "config", this->accuracyConfig);
}

Any
AccuracyProcedure::
getStatus() const
{
    return Any();
}

RunOutput
AccuracyProcedure::
run(const ProcedureRunConfig & run,
    const std::function<bool (const Json::Value &)> & onProgress) const
{
    auto runAccuracyConf = applyRunConfOverProcConf(accuracyConfig, run);

    // 1.  Get the input dataset
    SqlExpressionMldbContext context(server);

    auto dataset = runAccuracyConf.testingData.stm->from->bind(context).dataset;

    // 3.  Create our aggregator function, which records the output of
    //     this row.

    PerThreadAccumulator<ScoredStats> accum;

    auto aggregator = [&] (const MatrixNamedRow & row,
                           const std::vector<ExpressionValue> & scoreLabelWeight)
        {
            //cerr << "got vals " << labelWeight << " " << score << endl;

            double score = scoreLabelWeight[0].toDouble();
            bool label = scoreLabelWeight[1].asBool();
            double weight = scoreLabelWeight[2].toDouble();

            accum.get().update(label, score, weight, row.rowName);

            return true;
        };

    // 5.  Run it
    auto score = extractNamedSubSelect("score", runAccuracyConf.testingData.stm->select)->expression;
    auto label = extractNamedSubSelect("label", runAccuracyConf.testingData.stm->select)->expression;
    auto weightSubSelect = extractNamedSubSelect("weight", runAccuracyConf.testingData.stm->select);
    shared_ptr<SqlExpression> weight = weightSubSelect ? weightSubSelect->expression : SqlExpression::ONE;

    std::vector<std::shared_ptr<SqlExpression> > calc = {
        score,
        label,
        weight
    };

    BoundSelectQuery({} /* select */, *dataset, "" /* table alias */,
                     runAccuracyConf.testingData.stm->when, runAccuracyConf.testingData.stm->where,
                     runAccuracyConf.testingData.stm->orderBy,
                     calc,
                     false /* implicit order by row hash */)
        .execute(aggregator, runAccuracyConf.testingData.stm->offset, runAccuracyConf.testingData.stm->limit,
                 nullptr /* progress */);

    // Now merge out stats together

    ScoredStats stats;

    accum.forEach([&] (ScoredStats * thrStats)
                  {
                      thrStats->sort();
                      stats.add(*thrStats);
                  });

    //stats.sort();
    stats.calculate();

    if(runAccuracyConf.outputDataset) {
        std::shared_ptr<Dataset> output;

        PolyConfigT<Dataset> outputDataset = *runAccuracyConf.outputDataset;
        if (outputDataset.type.empty())
            outputDataset.type = AccuracyConfig::defaultOutputDatasetType;

        output = createDataset(server, outputDataset, nullptr, true /*overwrite*/);

        Date recordDate = Date::now();

        int prevIncludedPop = 0;

        std::vector<std::pair<RowName, std::vector<std::tuple<ColumnName, CellValue, Date> > > > rows;

        for (unsigned i = 1, j = 0;  i < stats.stats.size();  ++i) {
            auto & bstats = stats.stats[i];
            auto & entry = stats.entries[j];

            // the difference between included population of the current versus
            // last stats.stats represents the number of exemples included in the stats.
            // examples get grouped when they have the same score
            j += (bstats.includedPopulation() - prevIncludedPop);
            prevIncludedPop = bstats.includedPopulation();

            ExcAssertEqual(bstats.threshold, entry.score);

            std::vector<std::tuple<RowName, CellValue, Date> > row;

            row.emplace_back(ColumnName("index"), i, recordDate);
            row.emplace_back(ColumnName("label"), entry.label, recordDate);
            row.emplace_back(ColumnName("score"), entry.score, recordDate);
            row.emplace_back(ColumnName("weight"), entry.weight, recordDate);
            row.emplace_back(ColumnName("truePositives"), bstats.truePositives(), recordDate);
            row.emplace_back(ColumnName("falsePositives"), bstats.falsePositives(), recordDate);
            row.emplace_back(ColumnName("trueNegatives"), bstats.trueNegatives(), recordDate);
            row.emplace_back(ColumnName("falseNegatives"), bstats.falseNegatives(), recordDate);
            row.emplace_back(ColumnName("precision"), bstats.precision(), recordDate);
            row.emplace_back(ColumnName("recall"), bstats.recall(), recordDate);
            row.emplace_back(ColumnName("truePositiveRate"), bstats.truePositiveRate(), recordDate);
            row.emplace_back(ColumnName("falsePositiveRate"), bstats.falsePositiveRate(), recordDate);

            rows.emplace_back(boost::any_cast<RowName>(entry.key), std::move(row));
            if (rows.size() > 1000) {
                output->recordRows(rows);
                rows.clear();
            }
        }

        output->recordRows(rows);

        output->commit();
    }

    cerr << "stats are " << endl;

    cerr << stats.toJson();

    cerr << stats.atPercentile(0.50).toJson();

    cerr << stats.atPercentile(0.20).toJson();

    cerr << stats.atPercentile(0.10).toJson();

    cerr << stats.atPercentile(0.05).toJson();

    cerr << stats.atPercentile(0.01).toJson();

    return Any(stats.toJson());
}

namespace {

RegisterProcedureType<AccuracyProcedure, AccuracyConfig>
regAccuracy(builtinPackage(),
            "classifier.test",
            "Calculate the accuracy of a classifier on held-out data",
            "procedures/Accuracy.md.html");

} // file scope

} // namespace MLDB
} // namespace Datacratic
<commit_msg>[MLDB-1206] Clarified accuracy procedure documentation with regards to outputDataset<commit_after>/** accuracy.cc
    Jeremy Barnes, 16 December 2014
    Copyright (c) 2014 Datacratic Inc.  All rights reserved.

    This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.

    Implementation of an ACCURACY algorithm for embedding of a dataset.
*/

#include "accuracy.h"
#include "matrix.h"
#include "mldb/server/mldb_server.h"
#include "mldb/core/dataset.h"
#include "mldb/server/bound_queries.h"
#include "mldb/sql/sql_expression.h"
#include "mldb/jml/stats/distribution.h"
#include <boost/multi_array.hpp>
#include "mldb/jml/utils/guard.h"
#include "mldb/jml/utils/worker_task.h"
#include "mldb/jml/utils/pair_utils.h"
#include "mldb/arch/timers.h"
#include "mldb/arch/simd_vector.h"
#include "mldb/jml/utils/vector_utils.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/ml/value_descriptions.h"
#include "mldb/ml/separation_stats.h"
#include "mldb/server/analytics.h"
#include "mldb/types/any_impl.h"
#include "mldb/server/per_thread_accumulator.h"
#include "mldb/types/optional_description.h"
#include "mldb/http/http_exception.h"
#include "mldb/plugins/sql_config_validator.h"
#include "mldb/plugins/sql_expression_extractors.h"

using namespace std;

namespace Datacratic {
namespace MLDB {

DEFINE_STRUCTURE_DESCRIPTION(AccuracyConfig);

AccuracyConfigDescription::
AccuracyConfigDescription()
{
    Optional<PolyConfigT<Dataset> > optionalOutputDataset;
    optionalOutputDataset.emplace(PolyConfigT<Dataset>().
                                  withType(AccuracyConfig::defaultOutputDatasetType));

    addField("testingData", &AccuracyConfig::testingData,
             "Specification of the data for input to the accuracy procedure. "
             "The select expression must contain these sub-expressions: one scalar expression "
             "to identify the label and one scalar expression to identify the score. "
             "The type of the label expression must match "
             "that of the classifier mode from which the model was trained. "
             "Labels with a null value will have their row skipped. "
             "The expression to generate the score represents the output "
             "of whatever is having its accuracy tested.  This needs to be "
             "a number, and normally should be a floating point number that "
             "represents the degree of confidence in the prediction, not "
             "just the class. This is typically, the training function returned "
             "by a classifier.train procedure. "
             "The select expression can also contain an optional weight sub-expression. "
             "This expression generates the relative weight for each example.  In some "
             "circumstances it is necessary to calculate accuracy statistics "
             "with uneven weighting, for example to counteract the effect of "
             "non-uniform sampling in dataset.  By default, each class will "
             "get the same weight.  This value is relative to the other "
             "examples, in other words having all examples weighted 1 or all "
             "examples weighted 10 will have the same effect.  That being "
             "said, it is a good idea to keep the weights centered around 1 "
             "to avoid numeric errors in the calculations."
             "The select statement does not support groupby and having clauses.");
    addField("outputDataset", &AccuracyConfig::outputDataset,
             "Output dataset for scored examples. The score for the test "
             "example will be written to this dataset. Examples get grouped when "
              "they have the same score. Specifying a "
             "dataset is optional.", optionalOutputDataset);
    addParent<ProcedureConfig>();

        // the difference between included population of the current versus
            // last stats.stats represents the number of exemples included in the stats.
            // examples get grouped when they have the same score

    onPostValidate = validate<AccuracyConfig,
                              InputQuery,
                              NoGroupByHaving,
                              PlainColumnSelect,
                              ScoreLabelSelect>(&AccuracyConfig::testingData, "accuracy");

}

/*****************************************************************************/
/* ACCURACY PROCEDURE                                                         */
/*****************************************************************************/

AccuracyProcedure::
AccuracyProcedure(MldbServer * owner,
                 PolyConfig config,
                 const std::function<bool (const Json::Value &)> & onProgress)
    : Procedure(owner)
{
    this->accuracyConfig = config.params.convert<AccuracyConfig>();
    if (!accuracyConfig.testingData.stm)
        throw HttpReturnException(400, "Classifier testing procedure requires 'testingData' to be set",
                                  "config", this->accuracyConfig);
}

Any
AccuracyProcedure::
getStatus() const
{
    return Any();
}

RunOutput
AccuracyProcedure::
run(const ProcedureRunConfig & run,
    const std::function<bool (const Json::Value &)> & onProgress) const
{
    auto runAccuracyConf = applyRunConfOverProcConf(accuracyConfig, run);

    // 1.  Get the input dataset
    SqlExpressionMldbContext context(server);

    auto dataset = runAccuracyConf.testingData.stm->from->bind(context).dataset;

    // 3.  Create our aggregator function, which records the output of
    //     this row.

    PerThreadAccumulator<ScoredStats> accum;

    auto aggregator = [&] (const MatrixNamedRow & row,
                           const std::vector<ExpressionValue> & scoreLabelWeight)
        {
            //cerr << "got vals " << labelWeight << " " << score << endl;

            double score = scoreLabelWeight[0].toDouble();
            bool label = scoreLabelWeight[1].asBool();
            double weight = scoreLabelWeight[2].toDouble();

            accum.get().update(label, score, weight, row.rowName);

            return true;
        };

    // 5.  Run it
    auto score = extractNamedSubSelect("score", runAccuracyConf.testingData.stm->select)->expression;
    auto label = extractNamedSubSelect("label", runAccuracyConf.testingData.stm->select)->expression;
    auto weightSubSelect = extractNamedSubSelect("weight", runAccuracyConf.testingData.stm->select);
    shared_ptr<SqlExpression> weight = weightSubSelect ? weightSubSelect->expression : SqlExpression::ONE;

    std::vector<std::shared_ptr<SqlExpression> > calc = {
        score,
        label,
        weight
    };

    BoundSelectQuery({} /* select */, *dataset, "" /* table alias */,
                     runAccuracyConf.testingData.stm->when, runAccuracyConf.testingData.stm->where,
                     runAccuracyConf.testingData.stm->orderBy,
                     calc,
                     false /* implicit order by row hash */)
        .execute(aggregator, runAccuracyConf.testingData.stm->offset, runAccuracyConf.testingData.stm->limit,
                 nullptr /* progress */);

    // Now merge out stats together

    ScoredStats stats;

    accum.forEach([&] (ScoredStats * thrStats)
                  {
                      thrStats->sort();
                      stats.add(*thrStats);
                  });

    //stats.sort();
    stats.calculate();

    if(runAccuracyConf.outputDataset) {
        std::shared_ptr<Dataset> output;

        PolyConfigT<Dataset> outputDataset = *runAccuracyConf.outputDataset;
        if (outputDataset.type.empty())
            outputDataset.type = AccuracyConfig::defaultOutputDatasetType;

        output = createDataset(server, outputDataset, nullptr, true /*overwrite*/);

        Date recordDate = Date::now();

        int prevIncludedPop = 0;

        std::vector<std::pair<RowName, std::vector<std::tuple<ColumnName, CellValue, Date> > > > rows;

        for (unsigned i = 1, j = 0;  i < stats.stats.size();  ++i) {
            auto & bstats = stats.stats[i];
            auto & entry = stats.entries[j];

            // the difference between included population of the current versus
            // last stats.stats represents the number of exemples included in the stats.
            // examples get grouped when they have the same score
            j += (bstats.includedPopulation() - prevIncludedPop);
            prevIncludedPop = bstats.includedPopulation();

            ExcAssertEqual(bstats.threshold, entry.score);

            std::vector<std::tuple<RowName, CellValue, Date> > row;

            row.emplace_back(ColumnName("index"), i, recordDate);
            row.emplace_back(ColumnName("label"), entry.label, recordDate);
            row.emplace_back(ColumnName("score"), entry.score, recordDate);
            row.emplace_back(ColumnName("weight"), entry.weight, recordDate);
            row.emplace_back(ColumnName("truePositives"), bstats.truePositives(), recordDate);
            row.emplace_back(ColumnName("falsePositives"), bstats.falsePositives(), recordDate);
            row.emplace_back(ColumnName("trueNegatives"), bstats.trueNegatives(), recordDate);
            row.emplace_back(ColumnName("falseNegatives"), bstats.falseNegatives(), recordDate);
            row.emplace_back(ColumnName("precision"), bstats.precision(), recordDate);
            row.emplace_back(ColumnName("recall"), bstats.recall(), recordDate);
            row.emplace_back(ColumnName("truePositiveRate"), bstats.truePositiveRate(), recordDate);
            row.emplace_back(ColumnName("falsePositiveRate"), bstats.falsePositiveRate(), recordDate);

            rows.emplace_back(boost::any_cast<RowName>(entry.key), std::move(row));
            if (rows.size() > 1000) {
                output->recordRows(rows);
                rows.clear();
            }
        }

        output->recordRows(rows);

        output->commit();
    }

    cerr << "stats are " << endl;

    cerr << stats.toJson();

    cerr << stats.atPercentile(0.50).toJson();

    cerr << stats.atPercentile(0.20).toJson();

    cerr << stats.atPercentile(0.10).toJson();

    cerr << stats.atPercentile(0.05).toJson();

    cerr << stats.atPercentile(0.01).toJson();

    return Any(stats.toJson());
}

namespace {

RegisterProcedureType<AccuracyProcedure, AccuracyConfig>
regAccuracy(builtinPackage(),
            "classifier.test",
            "Calculate the accuracy of a classifier on held-out data",
            "procedures/Accuracy.md.html");

} // file scope

} // namespace MLDB
} // namespace Datacratic
<|endoftext|>


<commit_before>/* Copyright (C) 2010-2011, Snares <snares@users.sourceforge.net>
   Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>
   Copyright (C) 2011, Ryan Austin <ryan@gameforcecenters.com>
   Copyright (C) 2012, Bojan Hartmann <bogie@bawki.de>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Mumble Developers nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "../mumble_plugin_win32.h"
static bool ptr_chain_valid = false;
static BYTE *pmodule_bf3;

// Magic ptrs
static BYTE* const state_ptr = (BYTE *) 0x023C7A9C;

// Vector ptrs
static BYTE* const avatar_pos_ptr = (BYTE *) 0x023C7A30;
static BYTE* const avatar_front_ptr = (BYTE *) 0x023C7A60;
static BYTE* const avatar_top_ptr = (BYTE *) 0x023C7A50;

// Context ptrs
static BYTE* const ipport_ptr = (BYTE *) 0x02396F40;

// Identity ptrs
static BYTE *team_state_ptr;
static BYTE *squad_state_ptr;
static BYTE *squad_lead_state_ptr;

// Offsets
static const int base_offset = 0x01F24F58;
static const int identity_offset1 = 0x1C;
static const int identity_offset2 = 0xBC;
static const int identity_offset3 = 0x36C;
static const int identity_offset4 = 0x8;
static const int squad_state_offset = 0x104;
static const int squad_lead_state_offset = 0x108;
static const int team_state_offset = 0x31C;

enum state_values {
    STATE_UNKN = 0,
    STATE_LOADING = 1,
    STATE_IN_GAME = 2,
    STATE_IN_MENU = 3
};

inline bool resolve_ptrs() {
    team_state_ptr = squad_state_ptr = squad_lead_state_ptr = NULL;

    /*
    Magic:
        state : 0x023C7A9C                                                      BYTE        2 when playing
                                                                                3 while in menu/dead

    Context:
        IP:Port of server: 0x02396F40                                           char[128]   ip:port of the server

    Identity:
        Squad state: BF3.exe+0x01F24F58 + 0x1C + 0xBC + 0x36C + 0x8 + 0x104     BYTE        0 is not in squad; 1 is in Alpha squad, 2 Bravo, ... , 9 India
        SLead state: BF3.exe+0x01F24F58 + 0x1c + 0xBC + 0x36C + 0x8 + 0x108     BYTE        0 is not lead; 1 is lead
        Team state:  BF3.exe+0x01F24F58 + 0x1C + 0xBC + 0x31C                   BYTE        1 is blufor (US team, for example), 2 is opfor (RU), 0 is probably upcoming spec mode
    */

    BYTE *base_bf3 = peekProc<BYTE *>(pmodule_bf3 + base_offset);
    if (!base_bf3)
        return false;

    BYTE *offset_ptr1 = peekProc<BYTE *>(base_bf3 + identity_offset1);
    if (!offset_ptr1) return false;
    BYTE *offset_ptr2 = peekProc<BYTE *>(offset_ptr1 + identity_offset2);
    if (!offset_ptr2) return false;
    BYTE *offset_ptr3 = peekProc<BYTE *>(offset_ptr2 + identity_offset3);
    if (!offset_ptr3) return false;
    BYTE *offset_ptr4 = peekProc<BYTE *>(offset_ptr3 + identity_offset4);
    if (!offset_ptr4) return false;

    squad_state_ptr = offset_ptr4 + squad_state_offset;
    squad_lead_state_ptr = offset_ptr4 + squad_lead_state_offset;
    team_state_ptr = offset_ptr2 + team_state_offset;

    return true;
}

static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
    for (int i=0;i<3;i++)
        avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f;

    char ccontext[128];
    char state;
    BYTE squad_state;
    BYTE is_squadleader;
    BYTE team_state;
    bool ok;

    ok = peekProc(state_ptr, &state, 1); // State value
    if (! ok)
        return false;

    if (state != STATE_IN_GAME && state != STATE_IN_MENU) {
        ptr_chain_valid = false;
        context.clear();
        identity.clear();
        return true;
    } else if (!ptr_chain_valid) {
        if (!resolve_ptrs())
            return false;
        ptr_chain_valid = true;
    }

    ok = peekProc(avatar_pos_ptr, avatar_pos, 12) &&
        peekProc(avatar_front_ptr, avatar_front, 12) &&
        peekProc(avatar_top_ptr, avatar_top, 12) &&
        peekProc(squad_state_ptr,&squad_state,1) &&
        peekProc(squad_lead_state_ptr, &is_squadleader,1) &&
        peekProc(team_state_ptr,&team_state,1) &&
        peekProc(ipport_ptr,ccontext,128);

    if (! ok)
        return false;

    ccontext[sizeof(ccontext) - 1] = 0;
    if (ccontext[0] != '0') {
        std::ostringstream ocontext;
        ocontext << "{ \"ipport\": \"" << ccontext << "\" }";

        context = ocontext.str();

        /*
            Get identity string.
        */
        std::wostringstream oidentity;
        oidentity << "{"
        << "\"squad\":" << static_cast<unsigned int>(squad_state) << ","
        << "\"squad_leader\":" << (is_squadleader ? "true" : "false") << ",";
        if (team_state == 0)
            oidentity << "\"team\": \"SPEC\"";
        else if (team_state == 1)
            oidentity << "\"team\": \"US\"";
        else if (team_state == 2)
            oidentity << "\"team\": \"RU\"";
        oidentity << "}";
        identity = oidentity.str();
    }

    // Flip our front vector
    for (int i=0;i<3;i++) {
        avatar_front[i] = -avatar_front[i];
    }

    // Convert from right to left handed
    avatar_pos[0] = -avatar_pos[0];
    avatar_front[0] = -avatar_front[0];
    avatar_top[0] = -avatar_top[0];

    for (int i=0;i<3;i++) {
        camera_pos[i] = avatar_pos[i];
        camera_front[i] = avatar_front[i];
        camera_top[i] = avatar_top[i];
    }

    return ok;
}

static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) {

    if (! initialize(pids, L"bf3.exe"))
        return false;

    pmodule_bf3 = getModuleAddr(L"bf3.exe");
    if (!pmodule_bf3)
        return false;

    float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];
    std::string context;
    std::wstring identity;

    if (!fetch(apos, afront, atop, cpos, cfront, ctop, context, identity)) {
        generic_unlock();
        return false;
    }

    return true;
}

static const std::wstring longdesc() {
    return std::wstring(L"Supports Battlefield 3 with context and identity support.");
}

static std::wstring description(L"Battlefield 3 v944019");
static std::wstring shortname(L"Battlefield 3");

static int trylock1() {
    return trylock(std::multimap<std::wstring, unsigned long long int>());
}

static MumblePlugin bf3plug = {
    MUMBLE_PLUGIN_MAGIC,
    description,
    shortname,
    NULL,
    NULL,
    trylock1,
    generic_unlock,
    longdesc,
    fetch
};

static MumblePlugin2 bf3plug2 = {
    MUMBLE_PLUGIN_MAGIC_2,
    MUMBLE_PLUGIN_VERSION,
    trylock
};

extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() {
    return &bf3plug;
}

extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() {
    return &bf3plug2;
}
<commit_msg>updated plugins/bf3/bf3.cpp for DLC Armored Kill(build 981420)<commit_after>/* Copyright (C) 2010-2011, Snares <snares@users.sourceforge.net>
   Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>
   Copyright (C) 2011, Ryan Austin <ryan@gameforcecenters.com>
   Copyright (C) 2012, Bojan Hartmann <bogie@bawki.de>

   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   - Neither the name of the Mumble Developers nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "../mumble_plugin_win32.h"
static bool ptr_chain_valid = false;
static BYTE *pmodule_bf3;

// Magic ptrs
static BYTE* const state_ptr = (BYTE *) 0x0234A36C;

// Vector ptrs
static BYTE* const avatar_pos_ptr = (BYTE *) 0x0234A340;
static BYTE* const avatar_front_ptr = (BYTE *) 0x234A320;
static BYTE* const avatar_top_ptr = (BYTE *) 0x234A330;

// Context ptrs
static BYTE* const ipport_ptr = (BYTE *) 0x023344D0;

// Identity ptrs
static BYTE *team_state_ptr;
static BYTE *squad_state_ptr;
static BYTE *squad_lead_state_ptr;

// Offsets
static const int base_offset = 0x01F4583C;
static const int identity_offset1 = 0x43C;
static const int identity_offset2 = 0xBC;
static const int identity_offset3 = 0x348;
static const int identity_offset4 = 0x4;
static const int squad_state_offset = 0x48;
static const int squad_lead_state_offset = 0x4C;
static const int team_state_offset = 0x31C;

enum state_values {
    STATE_UNKN = 0,
    STATE_LOADING = 1,
    STATE_IN_GAME = 2,
    STATE_IN_MENU = 3
};

inline bool resolve_ptrs() {
    team_state_ptr = squad_state_ptr = squad_lead_state_ptr = NULL;

    /*
    Magic:
        state : 0x0234A36C                                                       BYTE        2 when playing
                                                                                3 while in menu/dead

    Context:
        IP:Port of server: 0x023344D0                                            char[128]   ip:port of the server

    Identity:
        Squad state: BF3.exe+0x01F4583C + 0x43C + 0xBC + 0x348 + 0x4 + 0x48      BYTE        0 is not in squad; 1 is in Alpha squad, 2 Bravo, ... , 9 India
        SLead state: BF3.exe+0x01F4583C + 0x43C + 0xBC + 0x348 + 0x4 + 0x4C      BYTE        0 is not lead; 1 is lead
        Team state:  BF3.exe+0x01F4583C + 0x43C + 0xBC + 0x31C                   BYTE        1 is blufor (US team, for example), 2 is opfor (RU), 0 is probably upcoming spec mode
    */

    BYTE *base_bf3 = peekProc<BYTE *>(pmodule_bf3 + base_offset);
    if (!base_bf3)
        return false;

    BYTE *offset_ptr1 = peekProc<BYTE *>(base_bf3 + identity_offset1);
    if (!offset_ptr1) return false;
    BYTE *offset_ptr2 = peekProc<BYTE *>(offset_ptr1 + identity_offset2);
    if (!offset_ptr2) return false;
    BYTE *offset_ptr3 = peekProc<BYTE *>(offset_ptr2 + identity_offset3);
    if (!offset_ptr3) return false;
    BYTE *offset_ptr4 = peekProc<BYTE *>(offset_ptr3 + identity_offset4);
    if (!offset_ptr4) return false;

    squad_state_ptr = offset_ptr4 + squad_state_offset;
    squad_lead_state_ptr = offset_ptr4 + squad_lead_state_offset;
    team_state_ptr = offset_ptr2 + team_state_offset;

    return true;
}

static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) {
    for (int i=0;i<3;i++)
        avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f;

    char ccontext[128];
    char state;
    BYTE squad_state;
    BYTE is_squadleader;
    BYTE team_state;
    bool ok;

    ok = peekProc(state_ptr, &state, 1); // State value
    if (! ok)
        return false;

    if (state != STATE_IN_GAME && state != STATE_IN_MENU) {
        ptr_chain_valid = false;
        context.clear();
        identity.clear();
        return true;
    } else if (!ptr_chain_valid) {
        if (!resolve_ptrs())
            return false;
        ptr_chain_valid = true;
    }

    ok = peekProc(avatar_pos_ptr, avatar_pos, 12) &&
        peekProc(avatar_front_ptr, avatar_front, 12) &&
        peekProc(avatar_top_ptr, avatar_top, 12) &&
        peekProc(squad_state_ptr,&squad_state,1) &&
        peekProc(squad_lead_state_ptr, &is_squadleader,1) &&
        peekProc(team_state_ptr,&team_state,1) &&
        peekProc(ipport_ptr,ccontext,128);

    if (! ok)
        return false;

    ccontext[sizeof(ccontext) - 1] = 0;
    if (ccontext[0] != '0') {
        std::ostringstream ocontext;
        ocontext << "{ \"ipport\": \"" << ccontext << "\" }";

        context = ocontext.str();

        /*
            Get identity string.
        */
        std::wostringstream oidentity;
        oidentity << "{"
        << "\"squad\":" << static_cast<unsigned int>(squad_state) << ","
        << "\"squad_leader\":" << (is_squadleader ? "true" : "false") << ",";
        if (team_state == 0)
            oidentity << "\"team\": \"SPEC\"";
        else if (team_state == 1)
            oidentity << "\"team\": \"US\"";
        else if (team_state == 2)
            oidentity << "\"team\": \"RU\"";
        oidentity << "}";
        identity = oidentity.str();
    }

    // Flip our front vector
    for (int i=0;i<3;i++) {
        avatar_front[i] = -avatar_front[i];
    }

    // Convert from right to left handed
    avatar_pos[0] = -avatar_pos[0];
    avatar_front[0] = -avatar_front[0];
    avatar_top[0] = -avatar_top[0];

    for (int i=0;i<3;i++) {
        camera_pos[i] = avatar_pos[i];
        camera_front[i] = avatar_front[i];
        camera_top[i] = avatar_top[i];
    }

    return ok;
}

static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) {

    if (! initialize(pids, L"bf3.exe"))
        return false;

    pmodule_bf3 = getModuleAddr(L"bf3.exe");
    if (!pmodule_bf3)
        return false;

    float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3];
    std::string context;
    std::wstring identity;

    if (!fetch(apos, afront, atop, cpos, cfront, ctop, context, identity)) {
        generic_unlock();
        return false;
    }

    return true;
}

static const std::wstring longdesc() {
    return std::wstring(L"Supports Battlefield 3 with context and identity support.");
}

static std::wstring description(L"Battlefield 3 v981420 - Armored Kill");
static std::wstring shortname(L"Battlefield 3");

static int trylock1() {
    return trylock(std::multimap<std::wstring, unsigned long long int>());
}

static MumblePlugin bf3plug = {
    MUMBLE_PLUGIN_MAGIC,
    description,
    shortname,
    NULL,
    NULL,
    trylock1,
    generic_unlock,
    longdesc,
    fetch
};

static MumblePlugin2 bf3plug2 = {
    MUMBLE_PLUGIN_MAGIC_2,
    MUMBLE_PLUGIN_VERSION,
    trylock
};

extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() {
    return &bf3plug;
}

extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() {
    return &bf3plug2;
}
<|endoftext|>


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

#include "chrome/browser/extensions/api/networking_private/networking_private_api.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/event_names.h"
#include "chrome/browser/extensions/event_router.h"
#include "chrome/browser/extensions/extension_function_registry.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/api/networking_private.h"

using extensions::event_names::kOnNetworkListChanged;
using extensions::event_names::kOnNetworksChanged;
using extensions::EventRouter;
using extensions::ExtensionSystem;
namespace api = extensions::api::networking_private;

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateGetPropertiesFunction

const char kNetworkingPrivateProperties[] = "NetworkingPrivateProperties";

struct NetworkingPrivatePropertiesData : base::SupportsUserData::Data {
  explicit NetworkingPrivatePropertiesData(const base::DictionaryValue* prop) :
    properties_(prop->DeepCopy()) { }
  scoped_ptr<base::DictionaryValue> properties_;
};

NetworkingPrivateGetPropertiesFunction::
  ~NetworkingPrivateGetPropertiesFunction() {
}

bool NetworkingPrivateGetPropertiesFunction::RunImpl() {
  scoped_ptr<api::GetProperties::Params> params =
      api::GetProperties::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);

  // If there are properties set by SetProperties function, use those.
  NetworkingPrivatePropertiesData* stored_properties =
    static_cast<NetworkingPrivatePropertiesData*> (
        profile()->GetUserData(kNetworkingPrivateProperties));
  if (stored_properties != NULL) {
    SetResult(stored_properties->properties_.release());
    SendResponse(true);
    return true;
  }

  const std::string network_properties =
    "{\"ConnectionState\":\"NotConnected\","
     "\"GUID\":\"stub_wifi2\","
     "\"Name\":\"wifi2_PSK\","
     "\"Type\":\"WiFi\","
     "\"WiFi\":{"
       "\"Frequency\":5000,"
       "\"FrequencyList\":[2400,5000],"
       "\"SSID\":\"stub_wifi2\","
       "\"Security\":\"WPA-PSK\","
       "\"SignalStrength\":80}}";

  if (params->network_guid == "nonexistent_path") {
    error_ = "Error.DBusFailed";
    SendResponse(false);
  } else {
    SetResult(base::JSONReader::Read(network_properties));
    SendResponse(true);
  }
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateGetManagedPropertiesFunction

NetworkingPrivateGetManagedPropertiesFunction::
  ~NetworkingPrivateGetManagedPropertiesFunction() {
}

bool NetworkingPrivateGetManagedPropertiesFunction::RunImpl() {
  scoped_ptr<api::GetManagedProperties::Params> params =
      api::GetManagedProperties::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  const std::string network_properties =
      "{"
      "  \"ConnectionState\": {"
      "    \"Active\": \"NotConnected\","
      "    \"Effective\": \"Unmanaged\""
      "  },"
      "  \"GUID\": \"stub_wifi2\","
      "  \"Name\": {"
      "    \"Active\": \"wifi2_PSK\","
      "    \"Effective\": \"UserPolicy\","
      "    \"UserPolicy\": \"My WiFi Network\""
      "  },"
      "  \"Type\": {"
      "    \"Active\": \"WiFi\","
      "    \"Effective\": \"UserPolicy\","
      "    \"UserPolicy\": \"WiFi\""
      "  },"
      "  \"WiFi\": {"
      "    \"AutoConnect\": {"
      "      \"Active\": false,"
      "      \"UserEditable\": true"
      "    },"
      "    \"Frequency\" : {"
      "      \"Active\": 5000,"
      "      \"Effective\": \"Unmanaged\""
      "    },"
      "    \"FrequencyList\" : {"
      "      \"Active\": [2400, 5000],"
      "      \"Effective\": \"Unmanaged\""
      "    },"
      "    \"Passphrase\": {"
      "      \"Effective\": \"UserSetting\","
      "      \"UserEditable\": true,"
      "      \"UserSetting\": \"FAKE_CREDENTIAL_VPaJDV9x\""
      "    },"
      "    \"SSID\": {"
      "      \"Active\": \"stub_wifi2\","
      "      \"Effective\": \"UserPolicy\","
      "      \"UserPolicy\": \"stub_wifi2\""
      "    },"
      "    \"Security\": {"
      "      \"Active\": \"WPA-PSK\","
      "      \"Effective\": \"UserPolicy\","
      "      \"UserPolicy\": \"WPA-PSK\""
      "    },"
      "    \"SignalStrength\": {"
      "      \"Active\": 80,"
      "      \"Effective\": \"Unmanaged\""
      "    }"
      "  }"
      "}";

  SetResult(base::JSONReader::Read(network_properties));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateGetStateFunction

NetworkingPrivateGetStateFunction::
  ~NetworkingPrivateGetStateFunction() {
}

bool NetworkingPrivateGetStateFunction::RunImpl() {
  scoped_ptr<api::GetState::Params> params =
      api::GetState::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  const std::string network_state =
      "{"
      "  \"ConnectionState\": \"NotConnected\","
      "  \"GUID\": \"stub_wifi2\","
      "  \"Name\": \"wifi2_PSK\","
      "  \"Type\": \"WiFi\","
      "  \"WiFi\": {"
      "    \"AutoConnect\": false,"
      "    \"FrequencyList\": [2400, 5000],"
      "    \"Security\": \"WPA-PSK\","
      "    \"SignalStrength\": 80"
      "  }"
      "}";
  SetResult(base::JSONReader::Read(network_state));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateSetPropertiesFunction

NetworkingPrivateSetPropertiesFunction::
  ~NetworkingPrivateSetPropertiesFunction() {
}

bool NetworkingPrivateSetPropertiesFunction::RunImpl() {
  scoped_ptr<api::SetProperties::Params> params =
      api::SetProperties::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  scoped_ptr<base::DictionaryValue> properties_dict(
      params->properties.ToValue());

  // Store properties_dict in profile to return from GetProperties.
  profile()->SetUserData(kNetworkingPrivateProperties,
    new NetworkingPrivatePropertiesData(properties_dict.get()));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateGetVisibleNetworksFunction

NetworkingPrivateGetVisibleNetworksFunction::
  ~NetworkingPrivateGetVisibleNetworksFunction() {
}

bool NetworkingPrivateGetVisibleNetworksFunction::RunImpl() {
  scoped_ptr<api::GetVisibleNetworks::Params> params =
      api::GetVisibleNetworks::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  const std::string networks_json =
      "[{"
      "    \"ConnectionState\": \"Connected\","
      "    \"GUID\": \"stub_ethernet\","
      "    \"Name\": \"eth0\","
      "    \"Type\": \"Ethernet\""
      "  },"
      "  {"
      "    \"ConnectionState\": \"Connected\","
      "    \"GUID\": \"stub_wifi1\","
      "    \"Name\": \"wifi1\","
      "    \"Type\": \"WiFi\","
      "    \"WiFi\": {"
      "      \"AutoConnect\": false,"
      "      \"FrequencyList\": [2400],"
      "      \"Security\": \"WEP-PSK\","
      "      \"SignalStrength\": 0"
      "    }"
      "  },"
      "  {"
      "    \"ConnectionState\": \"NotConnected\","
      "    \"GUID\": \"stub_wifi2\","
      "    \"Name\": \"wifi2_PSK\","
      "    \"Type\": \"WiFi\","
      "    \"WiFi\": {"
      "      \"AutoConnect\": false,"
      "      \"FrequencyList\": [2400, 5000],"
      "      \"Security\": \"WPA-PSK\","
      "      \"SignalStrength\": 80"
      "    }"
      "  },"
      "  {"
      "    \"Cellular\": {"
      "      \"ActivateOverNonCellularNetwork\": false,"
      "      \"ActivationState\": \"not-activated\","
      "      \"NetworkTechnology\": \"GSM\","
      "      \"RoamingState\": \"home\""
      "    },"
      "    \"ConnectionState\": \"NotConnected\","
      "    \"GUID\": \"stub_cellular1\","
      "    \"Name\": \"cellular1\","
      "    \"Type\": \"Cellular\""
      "  },"
      "  {"
      "    \"ConnectionState\": \"Connected\","
      "    \"GUID\": \"stub_vpn1\","
      "    \"Name\": \"vpn1\","
      "    \"Type\": \"VPN\","
      "    \"VPN\": {"
      "      \"AutoConnect\": false"
      "    }"
      "  }]";
  ListValue* visible_networks =
      static_cast<ListValue*>(base::JSONReader::Read(networks_json));
  // If caller only needs WiFi networks, then remove all other networks.
  if (params->type == api::GetVisibleNetworks::Params::TYPE_WIFI) {
    visible_networks->Remove(4, NULL);
    visible_networks->Remove(3, NULL);
    visible_networks->Remove(0, NULL);
  }

  SetResult(visible_networks);
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateRequestNetworkScanFunction

NetworkingPrivateRequestNetworkScanFunction::
  ~NetworkingPrivateRequestNetworkScanFunction() {
}

bool NetworkingPrivateRequestNetworkScanFunction::RunImpl() {
  // Generate onNetworkListChanged event.
  std::vector<std::string> changes;
  changes.push_back("stub_ethernet");
  changes.push_back("stub_wifi1");
  changes.push_back("stub_wifi2");
  changes.push_back("stub_cellular1");
  changes.push_back("stub_vpn1");

  EventRouter* event_router = ExtensionSystem::Get(profile_)->event_router();
  scoped_ptr<base::ListValue> args(api::OnNetworkListChanged::Create(changes));
  scoped_ptr<extensions::Event> extension_event(new extensions::Event(
      kOnNetworkListChanged, args.Pass()));
  event_router->BroadcastEvent(extension_event.Pass());

  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateStartConnectFunction

NetworkingPrivateStartConnectFunction::
  ~NetworkingPrivateStartConnectFunction() {
}

bool NetworkingPrivateStartConnectFunction::RunImpl() {
  scoped_ptr<api::StartConnect::Params> params =
      api::StartConnect::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  if (params->network_guid == "nonexistent_path") {
    error_ = "not-found";
    SendResponse(false);
  } else {
    SendResponse(true);
    // Set Properties to reflect connected state
    const std::string network_properties =
      "{\"ConnectionState\":\"Connected\","
       "\"GUID\":\"stub_wifi2\","
       "\"Name\":\"wifi2_PSK\","
       "\"Type\":\"WiFi\","
       "\"WiFi\":{"
         "\"Frequency\":5000,"
         "\"FrequencyList\":[2400,5000],"
         "\"SSID\":\"stub_wifi2\","
         "\"Security\":\"WPA-PSK\","
         "\"SignalStrength\":80}}";

    // Store network_properties in profile to return from GetProperties.
    profile()->SetUserData(kNetworkingPrivateProperties,
      new NetworkingPrivatePropertiesData(
        static_cast<DictionaryValue*>(
          base::JSONReader::Read(network_properties))));

    // Broadcast NetworksChanged Event that network is connected
    EventRouter* event_router = ExtensionSystem::Get(profile_)->event_router();
    scoped_ptr<base::ListValue> args(api::OnNetworksChanged::Create(
        std::vector<std::string>(1, params->network_guid)));
    scoped_ptr<extensions::Event> netchanged_event(
        new extensions::Event(kOnNetworksChanged, args.Pass()));
    event_router->BroadcastEvent(netchanged_event.Pass());

    // Generate NetworkListChanged event.
    std::vector<std::string> list;
    list.push_back("stub_wifi2");
    list.push_back("stub_ethernet");
    list.push_back("stub_wifi1");
    list.push_back("stub_cellular1");
    list.push_back("stub_vpn1");

    scoped_ptr<base::ListValue> arg2(api::OnNetworkListChanged::Create(list));
    scoped_ptr<extensions::Event> netlist_event(new extensions::Event(
        kOnNetworkListChanged, arg2.Pass()));
    event_router->BroadcastEvent(netlist_event.Pass());
  }
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateStartDisconnectFunction

NetworkingPrivateStartDisconnectFunction::
  ~NetworkingPrivateStartDisconnectFunction() {
}

bool NetworkingPrivateStartDisconnectFunction::RunImpl() {
  scoped_ptr<api::StartDisconnect::Params> params =
      api::StartDisconnect::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  if (params->network_guid == "nonexistent_path") {
    error_ = "not-found";
    SendResponse(false);
  } else {
    SendResponse(true);

    // Send Event that network is disconnected. Listener will use GetProperties.
    EventRouter* event_router = ExtensionSystem::Get(profile_)->event_router();
    scoped_ptr<base::ListValue> args(api::OnNetworksChanged::Create(
        std::vector<std::string>(1, params->network_guid)));
    scoped_ptr<extensions::Event> extension_event(
        new extensions::Event(kOnNetworksChanged, args.Pass()));
    event_router->BroadcastEvent(extension_event.Pass());
  }
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateVerifyDestinationFunction

NetworkingPrivateVerifyDestinationFunction::
  ~NetworkingPrivateVerifyDestinationFunction() {
}

bool NetworkingPrivateVerifyDestinationFunction::RunImpl() {
  scoped_ptr<api::VerifyDestination::Params> params =
      api::VerifyDestination::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  SetResult(new base::FundamentalValue(true));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateVerifyAndEncryptCredentialsFunction

NetworkingPrivateVerifyAndEncryptCredentialsFunction::
  ~NetworkingPrivateVerifyAndEncryptCredentialsFunction() {
}

bool NetworkingPrivateVerifyAndEncryptCredentialsFunction::RunImpl() {
  scoped_ptr<api::VerifyAndEncryptCredentials::Params> params =
      api::VerifyAndEncryptCredentials::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  SetResult(new base::StringValue("encrypted_credentials"));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateVerifyAndEncryptDataFunction

NetworkingPrivateVerifyAndEncryptDataFunction::
  ~NetworkingPrivateVerifyAndEncryptDataFunction() {
}

bool NetworkingPrivateVerifyAndEncryptDataFunction::RunImpl() {
  scoped_ptr<api::VerifyAndEncryptData::Params> params =
      api::VerifyAndEncryptData::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  SetResult(new base::StringValue("encrypted_data"));
  SendResponse(true);
  return true;
}

<commit_msg>Fix NetworkingPrivate API tests on non-chromeos<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/networking_private/networking_private_api.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/event_names.h"
#include "chrome/browser/extensions/event_router.h"
#include "chrome/browser/extensions/extension_function_registry.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/api/networking_private.h"

using extensions::event_names::kOnNetworkListChanged;
using extensions::event_names::kOnNetworksChanged;
using extensions::EventRouter;
using extensions::ExtensionSystem;
namespace api = extensions::api::networking_private;

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateGetPropertiesFunction

const char kNetworkingPrivateProperties[] = "NetworkingPrivateProperties";

struct NetworkingPrivatePropertiesData : base::SupportsUserData::Data {
  explicit NetworkingPrivatePropertiesData(const base::DictionaryValue* prop) :
    properties_(prop->DeepCopy()) { }
  scoped_ptr<base::DictionaryValue> properties_;
};

NetworkingPrivateGetPropertiesFunction::
  ~NetworkingPrivateGetPropertiesFunction() {
}

bool NetworkingPrivateGetPropertiesFunction::RunImpl() {
  scoped_ptr<api::GetProperties::Params> params =
      api::GetProperties::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);

  // If there are properties set by SetProperties function, use those.
  NetworkingPrivatePropertiesData* stored_properties =
    static_cast<NetworkingPrivatePropertiesData*> (
        profile()->GetUserData(kNetworkingPrivateProperties));
  if (stored_properties != NULL) {
    SetResult(stored_properties->properties_.release());
    SendResponse(true);
    return true;
  }

  const std::string network_properties =
    "{\"ConnectionState\":\"NotConnected\","
     "\"GUID\":\"stub_wifi2\","
     "\"Name\":\"wifi2_PSK\","
     "\"Type\":\"WiFi\","
     "\"WiFi\":{"
       "\"Frequency\":5000,"
       "\"FrequencyList\":[2400,5000],"
       "\"SSID\":\"stub_wifi2\","
       "\"Security\":\"WPA-PSK\","
       "\"SignalStrength\":80}}";

  if (params->network_guid == "nonexistent_path") {
    error_ = "Error.DBusFailed";
    SendResponse(false);
  } else {
    SetResult(base::JSONReader::Read(network_properties));
    SendResponse(true);
  }
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateGetManagedPropertiesFunction

NetworkingPrivateGetManagedPropertiesFunction::
  ~NetworkingPrivateGetManagedPropertiesFunction() {
}

bool NetworkingPrivateGetManagedPropertiesFunction::RunImpl() {
  scoped_ptr<api::GetManagedProperties::Params> params =
      api::GetManagedProperties::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  const std::string network_properties =
      "{"
      "  \"ConnectionState\": {"
      "    \"Active\": \"NotConnected\","
      "    \"Effective\": \"Unmanaged\""
      "  },"
      "  \"GUID\": \"stub_wifi2\","
      "  \"Name\": {"
      "    \"Active\": \"wifi2_PSK\","
      "    \"Effective\": \"UserPolicy\","
      "    \"UserPolicy\": \"My WiFi Network\""
      "  },"
      "  \"Type\": {"
      "    \"Active\": \"WiFi\","
      "    \"Effective\": \"UserPolicy\","
      "    \"UserPolicy\": \"WiFi\""
      "  },"
      "  \"WiFi\": {"
      "    \"AutoConnect\": {"
      "      \"Active\": false,"
      "      \"UserEditable\": true"
      "    },"
      "    \"Frequency\" : {"
      "      \"Active\": 5000,"
      "      \"Effective\": \"Unmanaged\""
      "    },"
      "    \"FrequencyList\" : {"
      "      \"Active\": [2400, 5000],"
      "      \"Effective\": \"Unmanaged\""
      "    },"
      "    \"Passphrase\": {"
      "      \"Effective\": \"UserSetting\","
      "      \"UserEditable\": true,"
      "      \"UserSetting\": \"FAKE_CREDENTIAL_VPaJDV9x\""
      "    },"
      "    \"SSID\": {"
      "      \"Active\": \"stub_wifi2\","
      "      \"Effective\": \"UserPolicy\","
      "      \"UserPolicy\": \"stub_wifi2\""
      "    },"
      "    \"Security\": {"
      "      \"Active\": \"WPA-PSK\","
      "      \"Effective\": \"UserPolicy\","
      "      \"UserPolicy\": \"WPA-PSK\""
      "    },"
      "    \"SignalStrength\": {"
      "      \"Active\": 80,"
      "      \"Effective\": \"Unmanaged\""
      "    }"
      "  }"
      "}";

  SetResult(base::JSONReader::Read(network_properties));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateGetStateFunction

NetworkingPrivateGetStateFunction::
  ~NetworkingPrivateGetStateFunction() {
}

bool NetworkingPrivateGetStateFunction::RunImpl() {
  scoped_ptr<api::GetState::Params> params =
      api::GetState::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  const std::string network_state =
      "{"
      "  \"ConnectionState\": \"NotConnected\","
      "  \"GUID\": \"stub_wifi2\","
      "  \"Name\": \"wifi2_PSK\","
      "  \"Type\": \"WiFi\","
      "  \"WiFi\": {"
      "    \"AutoConnect\": false,"
      "    \"Security\": \"WPA-PSK\","
      "    \"SignalStrength\": 80"
      "  }"
      "}";
  SetResult(base::JSONReader::Read(network_state));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateSetPropertiesFunction

NetworkingPrivateSetPropertiesFunction::
  ~NetworkingPrivateSetPropertiesFunction() {
}

bool NetworkingPrivateSetPropertiesFunction::RunImpl() {
  scoped_ptr<api::SetProperties::Params> params =
      api::SetProperties::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  scoped_ptr<base::DictionaryValue> properties_dict(
      params->properties.ToValue());

  // Store properties_dict in profile to return from GetProperties.
  profile()->SetUserData(kNetworkingPrivateProperties,
    new NetworkingPrivatePropertiesData(properties_dict.get()));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateGetVisibleNetworksFunction

NetworkingPrivateGetVisibleNetworksFunction::
  ~NetworkingPrivateGetVisibleNetworksFunction() {
}

bool NetworkingPrivateGetVisibleNetworksFunction::RunImpl() {
  scoped_ptr<api::GetVisibleNetworks::Params> params =
      api::GetVisibleNetworks::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  const std::string networks_json =
      "[{"
      "    \"ConnectionState\": \"Connected\","
      "    \"GUID\": \"stub_ethernet\","
      "    \"Name\": \"eth0\","
      "    \"Type\": \"Ethernet\""
      "  },"
      "  {"
      "    \"ConnectionState\": \"Connected\","
      "    \"GUID\": \"stub_wifi1\","
      "    \"Name\": \"wifi1\","
      "    \"Type\": \"WiFi\","
      "    \"WiFi\": {"
      "      \"AutoConnect\": false,"
      "      \"Security\": \"WEP-PSK\","
      "      \"SignalStrength\": 0"
      "    }"
      "  },"
      "  {"
      "    \"ConnectionState\": \"NotConnected\","
      "    \"GUID\": \"stub_wifi2\","
      "    \"Name\": \"wifi2_PSK\","
      "    \"Type\": \"WiFi\","
      "    \"WiFi\": {"
      "      \"AutoConnect\": false,"
      "      \"Security\": \"WPA-PSK\","
      "      \"SignalStrength\": 80"
      "    }"
      "  },"
      "  {"
      "    \"Cellular\": {"
      "      \"ActivateOverNonCellularNetwork\": false,"
      "      \"ActivationState\": \"not-activated\","
      "      \"NetworkTechnology\": \"GSM\","
      "      \"RoamingState\": \"home\""
      "    },"
      "    \"ConnectionState\": \"NotConnected\","
      "    \"GUID\": \"stub_cellular1\","
      "    \"Name\": \"cellular1\","
      "    \"Type\": \"Cellular\""
      "  },"
      "  {"
      "    \"ConnectionState\": \"Connected\","
      "    \"GUID\": \"stub_vpn1\","
      "    \"Name\": \"vpn1\","
      "    \"Type\": \"VPN\","
      "    \"VPN\": {"
      "      \"AutoConnect\": false"
      "    }"
      "  }]";
  ListValue* visible_networks =
      static_cast<ListValue*>(base::JSONReader::Read(networks_json));
  // If caller only needs WiFi networks, then remove all other networks.
  if (params->type == api::GetVisibleNetworks::Params::TYPE_WIFI) {
    visible_networks->Remove(4, NULL);
    visible_networks->Remove(3, NULL);
    visible_networks->Remove(0, NULL);
  }

  SetResult(visible_networks);
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateRequestNetworkScanFunction

NetworkingPrivateRequestNetworkScanFunction::
  ~NetworkingPrivateRequestNetworkScanFunction() {
}

bool NetworkingPrivateRequestNetworkScanFunction::RunImpl() {
  // Generate onNetworkListChanged event.
  std::vector<std::string> changes;
  changes.push_back("stub_ethernet");
  changes.push_back("stub_wifi1");
  changes.push_back("stub_wifi2");
  changes.push_back("stub_cellular1");
  changes.push_back("stub_vpn1");

  EventRouter* event_router = ExtensionSystem::Get(profile_)->event_router();
  scoped_ptr<base::ListValue> args(api::OnNetworkListChanged::Create(changes));
  scoped_ptr<extensions::Event> extension_event(new extensions::Event(
      kOnNetworkListChanged, args.Pass()));
  event_router->BroadcastEvent(extension_event.Pass());

  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateStartConnectFunction

NetworkingPrivateStartConnectFunction::
  ~NetworkingPrivateStartConnectFunction() {
}

bool NetworkingPrivateStartConnectFunction::RunImpl() {
  scoped_ptr<api::StartConnect::Params> params =
      api::StartConnect::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  if (params->network_guid == "nonexistent_path") {
    error_ = "not-found";
    SendResponse(false);
  } else {
    SendResponse(true);
    // Set Properties to reflect connected state
    const std::string network_properties =
      "{\"ConnectionState\":\"Connected\","
       "\"GUID\":\"stub_wifi2\","
       "\"Name\":\"wifi2_PSK\","
       "\"Type\":\"WiFi\","
       "\"WiFi\":{"
         "\"SSID\":\"stub_wifi2\","
         "\"Security\":\"WPA-PSK\","
         "\"SignalStrength\":80}}";

    // Store network_properties in profile to return from GetProperties.
    profile()->SetUserData(kNetworkingPrivateProperties,
      new NetworkingPrivatePropertiesData(
        static_cast<DictionaryValue*>(
          base::JSONReader::Read(network_properties))));

    // Broadcast NetworksChanged Event that network is connected
    EventRouter* event_router = ExtensionSystem::Get(profile_)->event_router();
    scoped_ptr<base::ListValue> args(api::OnNetworksChanged::Create(
        std::vector<std::string>(1, params->network_guid)));
    scoped_ptr<extensions::Event> netchanged_event(
        new extensions::Event(kOnNetworksChanged, args.Pass()));
    event_router->BroadcastEvent(netchanged_event.Pass());

    // Generate NetworkListChanged event.
    std::vector<std::string> list;
    list.push_back("stub_wifi2");
    list.push_back("stub_ethernet");
    list.push_back("stub_wifi1");
    list.push_back("stub_cellular1");
    list.push_back("stub_vpn1");

    scoped_ptr<base::ListValue> arg2(api::OnNetworkListChanged::Create(list));
    scoped_ptr<extensions::Event> netlist_event(new extensions::Event(
        kOnNetworkListChanged, arg2.Pass()));
    event_router->BroadcastEvent(netlist_event.Pass());
  }
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateStartDisconnectFunction

NetworkingPrivateStartDisconnectFunction::
  ~NetworkingPrivateStartDisconnectFunction() {
}

bool NetworkingPrivateStartDisconnectFunction::RunImpl() {
  scoped_ptr<api::StartDisconnect::Params> params =
      api::StartDisconnect::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  if (params->network_guid == "nonexistent_path") {
    error_ = "not-found";
    SendResponse(false);
  } else {
    SendResponse(true);

    // Send Event that network is disconnected. Listener will use GetProperties.
    EventRouter* event_router = ExtensionSystem::Get(profile_)->event_router();
    scoped_ptr<base::ListValue> args(api::OnNetworksChanged::Create(
        std::vector<std::string>(1, params->network_guid)));
    scoped_ptr<extensions::Event> extension_event(
        new extensions::Event(kOnNetworksChanged, args.Pass()));
    event_router->BroadcastEvent(extension_event.Pass());
  }
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateVerifyDestinationFunction

NetworkingPrivateVerifyDestinationFunction::
  ~NetworkingPrivateVerifyDestinationFunction() {
}

bool NetworkingPrivateVerifyDestinationFunction::RunImpl() {
  scoped_ptr<api::VerifyDestination::Params> params =
      api::VerifyDestination::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  SetResult(new base::FundamentalValue(true));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateVerifyAndEncryptCredentialsFunction

NetworkingPrivateVerifyAndEncryptCredentialsFunction::
  ~NetworkingPrivateVerifyAndEncryptCredentialsFunction() {
}

bool NetworkingPrivateVerifyAndEncryptCredentialsFunction::RunImpl() {
  scoped_ptr<api::VerifyAndEncryptCredentials::Params> params =
      api::VerifyAndEncryptCredentials::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  SetResult(new base::StringValue("encrypted_credentials"));
  SendResponse(true);
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// NetworkingPrivateVerifyAndEncryptDataFunction

NetworkingPrivateVerifyAndEncryptDataFunction::
  ~NetworkingPrivateVerifyAndEncryptDataFunction() {
}

bool NetworkingPrivateVerifyAndEncryptDataFunction::RunImpl() {
  scoped_ptr<api::VerifyAndEncryptData::Params> params =
      api::VerifyAndEncryptData::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  SetResult(new base::StringValue("encrypted_data"));
  SendResponse(true);
  return true;
}
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "stdafx.h"
#include <sofa/component/engine/TestEngine.h>
#include "Sofa_test.h"

namespace sofa {

/**  Test suite for engine using TestEngine class.
This class has a counter which shows how many times the update method is called.
Add inputs to engine.
Check that the output is updated only if necessary.
Check that update method is called only 1 time
  */
struct Engine_test : public Sofa_test<>
{
    typedef sofa::component::engine::TestEngine TestEngine;
    TestEngine::SPtr engine1;
    TestEngine::SPtr engine2;

    /// Create the engines
    void SetUp()
    {
       // Engine 1
       engine1 = sofa::core::objectmodel::New<TestEngine>();
       engine1->f_numberToMultiply.setValue(1);
       engine1->f_factor.setValue(2);
       engine1->init();

       // Engine 2 linked to the ouput of engine 1
       engine2 = sofa::core::objectmodel::New<TestEngine>();
       sofa::modeling::setDataLink(&engine1->f_result,&engine2->f_numberToMultiply);
       engine2->f_factor.setValue(3);
       engine2->init();

    }

    // Test if the output is updated only if necessary
    void testUpdate()
    {
       //std::cout << "************Get Value Ouput E2*******************"<< std::endl;
       SReal result2 = engine2->f_result.getValue();

       // Test if update method of engine1 is called 1 time
       if(engine1->getCounterUpdate()!=1)
       {
           ADD_FAILURE() << "Update method of engine1 was called " << engine1->getCounterUpdate() << " times instead of 1 time " << std::endl;
       }

       // Test if update method of engine2 is called 1 time
       if(engine2->getCounterUpdate()!=1)
       {
           ADD_FAILURE() << "Update method of engine2 was called " << engine2->getCounterUpdate() << " times instead of 1 time " << std::endl;
       }

       // Test if result is correct
       ASSERT_EQ(result2,6);

    }

};

// first test case
TEST_F(Engine_test , check_engine_update )
{
    this->testUpdate();
}

}// namespace sofa<commit_msg>FIX: Forget include file.<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU General Public License as published by the Free  *
* Software Foundation; either version 2 of the License, or (at your option)   *
* any later version.                                                          *
*                                                                             *
* This program is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for    *
* more details.                                                               *
*                                                                             *
* You should have received a copy of the GNU General Public License along     *
* with this program; if not, write to the Free Software Foundation, Inc., 51  *
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.                   *
*******************************************************************************
*                            SOFA :: Applications                             *
*                                                                             *
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include "stdafx.h"
#include <sofa/component/engine/TestEngine.h>
#include <plugins/SceneCreator/SceneCreator.h>
#include "Sofa_test.h"

namespace sofa {

/**  Test suite for engine using TestEngine class.
This class has a counter which shows how many times the update method is called.
Add inputs to engine.
Check that the output is updated only if necessary.
Check that update method is called only 1 time
  */
struct Engine_test : public Sofa_test<>
{
    typedef sofa::component::engine::TestEngine TestEngine;
    TestEngine::SPtr engine1;
    TestEngine::SPtr engine2;

    /// Create the engines
    void SetUp()
    {
       // Engine 1
       engine1 = sofa::core::objectmodel::New<TestEngine>();
       engine1->f_numberToMultiply.setValue(1);
       engine1->f_factor.setValue(2);
       engine1->init();

       // Engine 2 linked to the ouput of engine 1
       engine2 = sofa::core::objectmodel::New<TestEngine>();
       sofa::modeling::setDataLink(&engine1->f_result,&engine2->f_numberToMultiply);
       engine2->f_factor.setValue(3);
       engine2->init();

    }

    // Test if the output is updated only if necessary
    void testUpdate()
    {
       //std::cout << "************Get Value Ouput E2*******************"<< std::endl;
       SReal result2 = engine2->f_result.getValue();

       // Test if update method of engine1 is called 1 time
       if(engine1->getCounterUpdate()!=1)
       {
           ADD_FAILURE() << "Update method of engine1 was called " << engine1->getCounterUpdate() << " times instead of 1 time " << std::endl;
       }

       // Test if update method of engine2 is called 1 time
       if(engine2->getCounterUpdate()!=1)
       {
           ADD_FAILURE() << "Update method of engine2 was called " << engine2->getCounterUpdate() << " times instead of 1 time " << std::endl;
       }

       // Test if result is correct
       ASSERT_EQ(result2,6);

    }

};

// first test case
TEST_F(Engine_test , check_engine_update )
{
    this->testUpdate();
}

}// namespace sofa<|endoftext|>