<commit_before>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/framework/ir/identity_scale_op_clean_pass.h"

#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/op_version_registry.h"

namespace paddle {
namespace framework {
namespace ir {

class Graph;

void IdentityScaleOpCleanPass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init("identity_scale_op_clean", graph);

  // pre_op -> scale_in -> scale_op -> scale_out
  // ->
  // pre_op -> scale_out
  GraphPatternDetector detector;
  auto scale_in =
      detector.mutable_pattern()
          ->NewNode("scale_in")
          ->assert_is_op_input("scale")
          ->assert_more([](Node* x) { return x->outputs.size() == 1UL; });
  auto scale_op = detector.mutable_pattern()
                      ->NewNode("scale_fuse")
                      ->assert_is_op("scale")
                      ->assert_op_attr<float>("scale", 1.)
                      ->assert_op_attr<float>("bias", 0.);
  auto scale_out = detector.mutable_pattern()
                       ->NewNode("scale_out")
                       ->assert_is_op_output("scale");

  scale_op->LinksFrom({scale_in}).LinksTo({scale_out});

  int found_subgraph_count = 0;
  GraphPatternDetector::handle_t handler =
      [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* graph) {
        Node* scale_op_var = subgraph.at(scale_op);
        Node* scale_in_var = subgraph.at(scale_in);
        Node* scale_out_var = subgraph.at(scale_out);
        const std::string scale_in_name = scale_in_var->Name();
        const std::string scale_out_name = scale_out_var->Name();
        // Remove links in graph
        GraphSafeRemoveNodes(graph, {scale_in_var, scale_op_var});
        // Modify pre_op_desc
        // Link pre_op directly to scale_out
        for (auto& node : graph->Nodes()) {
          if (node->IsOp()) {
            auto* op_desc = node->Op();
            auto out_vars_map = op_desc->Outputs();
            for (auto out_var_map : out_vars_map) {
              auto names = out_var_map.second;
              bool reset = false;
              for (size_t i = 0; i < names.size(); i++) {
                if (names[i] == scale_in_name) {
                  reset = true;
                  names[i] = scale_out_name;
                  break;
                }
              }
              if (reset) {
                op_desc->SetOutput(out_var_map.first, names);
                op_desc->Flush();
                IR_NODE_LINK_TO(node, scale_out_var);
                break;
              }
            }
          }
        }
        found_subgraph_count++;
      };

  detector(graph, handler);
  AddStatis(found_subgraph_count);
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(identity_scale_op_clean_pass,
              paddle::framework::ir::IdentityScaleOpCleanPass);
REGISTER_PASS_CAPABILITY(identity_scale_op_clean_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination().EQ(
            "scale", 0));
<commit_msg>fix scale pass when "conditional_block" or "while" is before "scale" (#43323)<commit_after>// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/framework/ir/identity_scale_op_clean_pass.h"

#include "paddle/fluid/framework/ir/graph_pattern_detector.h"
#include "paddle/fluid/framework/op_version_registry.h"

namespace paddle {
namespace framework {
namespace ir {

class Graph;

void IdentityScaleOpCleanPass::ApplyImpl(ir::Graph* graph) const {
  FusePassBase::Init("identity_scale_op_clean", graph);

  // pre_op -> scale_in -> scale_op -> scale_out
  // ->
  // pre_op -> scale_out
  GraphPatternDetector detector;
  auto scale_in =
      detector.mutable_pattern()
          ->NewNode("scale_in")
          ->assert_is_op_input("scale")
          ->assert_has_n_outputs(1)
          ->assert_more([](Node* x) {
            for (auto* op : x->inputs) {
              auto op_type = op->Op()->Type();
              if (op_type == "conditional_block" || op_type == "while") {
                return false;
              }
            }
            return true;
          });
  auto scale_op = detector.mutable_pattern()
                      ->NewNode("scale_fuse")
                      ->assert_is_op("scale")
                      ->assert_op_attr<float>("scale", 1.)
                      ->assert_op_attr<float>("bias", 0.);
  auto scale_out = detector.mutable_pattern()
                       ->NewNode("scale_out")
                       ->assert_is_op_output("scale");

  scale_op->LinksFrom({scale_in}).LinksTo({scale_out});

  int found_subgraph_count = 0;
  GraphPatternDetector::handle_t handler =
      [&](const GraphPatternDetector::subgraph_t& subgraph, Graph* graph) {
        Node* scale_op_var = subgraph.at(scale_op);
        Node* scale_in_var = subgraph.at(scale_in);
        Node* scale_out_var = subgraph.at(scale_out);
        const std::string scale_in_name = scale_in_var->Name();
        const std::string scale_out_name = scale_out_var->Name();
        // Remove links in graph
        GraphSafeRemoveNodes(graph, {scale_in_var, scale_op_var});
        // Modify pre_op_desc
        // Link pre_op directly to scale_out
        for (auto& node : graph->Nodes()) {
          if (node->IsOp()) {
            auto* op_desc = node->Op();
            auto out_vars_map = op_desc->Outputs();
            for (auto out_var_map : out_vars_map) {
              auto names = out_var_map.second;
              bool reset = false;
              for (size_t i = 0; i < names.size(); i++) {
                if (names[i] == scale_in_name) {
                  reset = true;
                  names[i] = scale_out_name;
                  break;
                }
              }
              if (reset) {
                op_desc->SetOutput(out_var_map.first, names);
                op_desc->Flush();
                IR_NODE_LINK_TO(node, scale_out_var);
                break;
              }
            }
          }
        }
        found_subgraph_count++;
      };

  detector(graph, handler);
  AddStatis(found_subgraph_count);
}

}  // namespace ir
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(identity_scale_op_clean_pass,
              paddle::framework::ir::IdentityScaleOpCleanPass);
REGISTER_PASS_CAPABILITY(identity_scale_op_clean_pass)
    .AddCombination(
        paddle::framework::compatible::OpVersionComparatorCombination().EQ(
            "scale", 0));
<|endoftext|>


<commit_before>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "stx/test/unittest.h"
#include "tsdb/RecordIDSet.h"

using namespace stx;
using namespace tsdb;

UNIT_TEST(RecordIDSetTest);

TEST_CASE(RecordIDSetTest, TestInsertIntoEmptySet, [] () {
  FileUtil::rm("/tmp/_fnord_testrecidset.idx");
  RecordIDSet recset("/tmp/_fnord_testrecidset.idx");

  EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x42424242")));
  EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x23232323")));
  EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));

  EXPECT_EQ(recset.fetchRecordIDs().size(), 0);

  recset.addRecordID(SHA1::compute("0x42424242"));
  recset.addRecordID(SHA1::compute("0x23232323"));

  EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
  EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
  EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));

  auto ids = recset.fetchRecordIDs();
  EXPECT_EQ(ids.size(), 2);
  EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
  EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
});

TEST_CASE(RecordIDSetTest, TestReopen, [] () {
  FileUtil::rm("/tmp/_fnord_testrecidset.idx");

  {
    RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
    EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x42424242")));
    EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x23232323")));
    EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));

    EXPECT_EQ(recset.fetchRecordIDs().size(), 0);
    recset.addRecordID(SHA1::compute("0x42424242"));
    recset.addRecordID(SHA1::compute("0x23232323"));
  }

  {
    RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
    EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));

    auto ids = recset.fetchRecordIDs();
    EXPECT_EQ(ids.size(), 2);
    EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
    EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);

    recset.addRecordID(SHA1::compute("0x52525252"));
  }

  {
    RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x52525252")));

    auto ids = recset.fetchRecordIDs();
    EXPECT_EQ(ids.size(), 3);
    EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
    EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
    EXPECT_EQ(ids.count(SHA1::compute("0x52525252")), 1);
  }
});

/*

TEST_CASE(RecordSetTest, TestDuplicateRowsInCommitlog, [] () {
  auto schema = testSchema();
  RecordSet recset("/tmp", "_fnord_testrecset");

  recset.addRecord(SHA1::compute("0x42424242"), testObject(schema, "1a", "1b"));
  recset.addRecord(SHA1::compute("0x42424242"), testObject(schema, "2a", "2b"));
  EXPECT_EQ(recset.commitlogSize(), 1);

  recset.rollCommitlog();
  EXPECT_EQ(recset.commitlogSize(), 1);

  recset.addRecord(SHA1::compute("0x42424242"), testObject(schema, "3a", "3b"));
  recset.addRecord(SHA1::compute("0x32323232"), testObject(schema, "2a", "2b"));
  EXPECT_EQ(recset.commitlogSize(), 2);

  recset.rollCommitlog();
  recset.compact();
  EXPECT_EQ(recset.commitlogSize(), 0);

  auto res = recset.listRecords();
  EXPECT_EQ(res.size(), 2);
  EXPECT_EQ(res.count(SHA1::compute("x42424242")), 1);
  EXPECT_EQ(res.count(SHA1::compute("x32323232")), 1);
});

TEST_CASE(RecordSetTest, TestCompactionWithExistingTable, [] () {
  auto schema = testSchema();
  RecordSet recset("/tmp", "_fnord_testrecset");

  recset.addRecord(SHA1::compute("0x42424242"), testObject(schema, "1a", "1b"));
  recset.addRecord(SHA1::compute("0x23232323"), testObject(schema, "2a", "2b"));
  recset.rollCommitlog();
  recset.compact();

  recset.addRecord(SHA1::compute("0x52525252"), testObject(schema, "3a", "3b"));
  recset.addRecord(SHA1::compute("0x12121212"), testObject(schema, "4a", "4b"));
  recset.rollCommitlog();
  recset.compact();
  EXPECT_EQ(recset.commitlogSize(), 0);

  auto msgids = recset.listRecords();

  EXPECT_EQ(msgids.size(), 4);
  EXPECT_EQ(msgids.count(SHA1::compute("0x42424242")), 1);
  EXPECT_EQ(msgids.count(SHA1::compute("0x23232323")), 1);
  EXPECT_EQ(msgids.count(SHA1::compute("0x52525252")), 1);
  EXPECT_EQ(msgids.count(SHA1::compute("0x12121212")), 1);
});

TEST_CASE(RecordSetTest, TestInsert10kRows, [] () {
  Random rnd;
  auto schema = testSchema();
  RecordSet recset("/tmp", "_fnord_testrecset");

  for (int i = 0; i < 10; ++i) {
    for (int i = 0; i < 1000; ++i) {
      recset.addRecord(
          SHA1::compute(rnd.hex64()),
          testObject(schema, "1a", "1b"));
    }

    recset.rollCommitlog();
  }

  EXPECT_EQ(recset.getState().old_commitlogs.size(), 10);
  recset.compact();
  EXPECT_EQ(recset.commitlogSize(), 0);
  EXPECT_EQ(recset.getState().datafiles.size(), 1);
  EXPECT_EQ(recset.listRecords().size(), 10000);
});

TEST_CASE(RecordSetTest, TestSplitIntoMultipleDatafiles, [] () {
  Random rnd;
  auto schema = testSchema();
  RecordSet recset("/tmp", "_fnord_testrecset");
  recset.setMaxDatafileSize(1024 * 60);

  int n = 0;
  for (int j = 0; j < 10; ++j) {
    for (int i = 0; i < 1000; ++i) {
      recset.addRecord(
          SHA1::compute(StringUtil::toString(++n)),
          testObject(schema, "1a", "1b"));
    }

    recset.rollCommitlog();
    recset.compact();
    EXPECT_EQ(recset.commitlogSize(), 0);
  }

  EXPECT_EQ(recset.getState().datafiles.size(), 4);
  EXPECT_EQ(recset.getState().datafiles[0].num_records, 3000);
  EXPECT_EQ(recset.getState().datafiles[0].offset, 0);
  EXPECT_EQ(recset.getState().datafiles[1].num_records, 3000);
  EXPECT_EQ(recset.getState().datafiles[1].offset, 3000);
  EXPECT_EQ(recset.getState().datafiles[2].num_records, 3000);
  EXPECT_EQ(recset.getState().datafiles[2].offset, 6000);
  EXPECT_EQ(recset.getState().datafiles[3].num_records, 1000);
  EXPECT_EQ(recset.getState().datafiles[3].offset, 9000);

  auto msgids = recset.listRecords();
  EXPECT_EQ(msgids.size(), 10000);
  for (int i = 1; i <= 10000; ++i) {
    EXPECT_EQ(msgids.count(SHA1::compute(StringUtil::toString(i))), 1);
  }
});
*/

<commit_msg>TestDuplicateRecordIDs<commit_after>/**
 * This file is part of the "libfnord" project
 *   Copyright (c) 2015 Paul Asmuth
 *
 * FnordMetric is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License v3.0. You should have received a
 * copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "stx/test/unittest.h"
#include "tsdb/RecordIDSet.h"

using namespace stx;
using namespace tsdb;

UNIT_TEST(RecordIDSetTest);

TEST_CASE(RecordIDSetTest, TestInsertIntoEmptySet, [] () {
  FileUtil::rm("/tmp/_fnord_testrecidset.idx");
  RecordIDSet recset("/tmp/_fnord_testrecidset.idx");

  EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x42424242")));
  EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x23232323")));
  EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));

  EXPECT_EQ(recset.fetchRecordIDs().size(), 0);

  recset.addRecordID(SHA1::compute("0x42424242"));
  recset.addRecordID(SHA1::compute("0x23232323"));

  EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
  EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
  EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));

  auto ids = recset.fetchRecordIDs();
  EXPECT_EQ(ids.size(), 2);
  EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
  EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
});

TEST_CASE(RecordIDSetTest, TestReopen, [] () {
  FileUtil::rm("/tmp/_fnord_testrecidset.idx");

  {
    RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
    EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x42424242")));
    EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x23232323")));
    EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));

    EXPECT_EQ(recset.fetchRecordIDs().size(), 0);
    recset.addRecordID(SHA1::compute("0x42424242"));
    recset.addRecordID(SHA1::compute("0x23232323"));
  }

  {
    RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
    EXPECT_FALSE(recset.hasRecordID(SHA1::compute("0x52525252")));

    auto ids = recset.fetchRecordIDs();
    EXPECT_EQ(ids.size(), 2);
    EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
    EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);

    recset.addRecordID(SHA1::compute("0x52525252"));
  }

  {
    RecordIDSet recset("/tmp/_fnord_testrecidset.idx");
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x42424242")));
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x23232323")));
    EXPECT_TRUE(recset.hasRecordID(SHA1::compute("0x52525252")));

    auto ids = recset.fetchRecordIDs();
    EXPECT_EQ(ids.size(), 3);
    EXPECT_EQ(ids.count(SHA1::compute("0x42424242")), 1);
    EXPECT_EQ(ids.count(SHA1::compute("0x23232323")), 1);
    EXPECT_EQ(ids.count(SHA1::compute("0x52525252")), 1);
  }
});

TEST_CASE(RecordIDSetTest, TestDuplicateRecordIDs, [] () {
  FileUtil::rm("/tmp/_fnord_testrecidset.idx");
  RecordIDSet recset("/tmp/_fnord_testrecidset.idx");

  recset.addRecordID(SHA1::compute("0x42424242"));
  recset.addRecordID(SHA1::compute("0x42424242"));
  EXPECT_EQ(recset.fetchRecordIDs().size(), 1);

  recset.addRecordID(SHA1::compute("0x42424242"));
  recset.addRecordID(SHA1::compute("0x32323232"));
  EXPECT_EQ(recset.fetchRecordIDs().size(), 2);

  auto res = recset.fetchRecordIDs();
  EXPECT_EQ(res.size(), 2);
  EXPECT_EQ(res.count(SHA1::compute("0x42424242")), 1);
  EXPECT_EQ(res.count(SHA1::compute("0x32323232")), 1);
});

/*
TEST_CASE(RecordSetTest, TestInsert10kRows, [] () {
  Random rnd;
  auto schema = testSchema();
  RecordSet recset("/tmp", "_fnord_testrecset");

  for (int i = 0; i < 10; ++i) {
    for (int i = 0; i < 1000; ++i) {
      recset.addRecord(
          SHA1::compute(rnd.hex64()),
          testObject(schema, "1a", "1b"));
    }

    recset.rollCommitlog();
  }

  EXPECT_EQ(recset.getState().old_commitlogs.size(), 10);
  recset.compact();
  EXPECT_EQ(recset.commitlogSize(), 0);
  EXPECT_EQ(recset.getState().datafiles.size(), 1);
  EXPECT_EQ(recset.listRecords().size(), 10000);
});
*/

<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include <cmath>
#include <fstream>
#include <numeric>

#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/map/proto/map_lane.pb.h"

namespace apollo {
namespace prediction {

using HDMapLane = apollo::hdmap::Lane;

MLPEvaluator::MLPEvaluator() {
  LoadModel(FLAGS_vehicle_model_file);
}

void MLPEvaluator::Clear() {
  obstacle_feature_values_map_.clear();
}

void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {
  AINFO << "Start mlp evaluate";
  Clear();
  if (obstacle_ptr == nullptr) {
    AERROR << "Invalid obstacle.";
    return;
  }

  int id = obstacle_ptr->id();
  Feature latest_feature = obstacle_ptr->latest_feature();
  if (!latest_feature.IsInitialized()) {
    ADEBUG << "Obstacle [" << id << "] has no latest feature.";
    return;
  }

  Lane* lane_ptr = latest_feature.mutable_lane();
  if (!latest_feature.has_lane() || lane_ptr == nullptr) {
    ADEBUG << "Obstacle [" << id << "] has no lane feature.";
    return;
  }

  LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();
  if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {
    ADEBUG << "Obstacle [" << id << "] has no lane graph.";
    return;
  }

  if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {
    ADEBUG << "Obstacle [" << id << "] has no lane sequences.";
    return;
  }

  AINFO << "Start for-loop on lane sequences";
  for (int i = 0;
      i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {
    LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
    CHECK(lane_sequence_ptr != nullptr);
    AINFO << "Start to extract feature values";
    ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);
    AINFO << "Start to compute probability";
    double probability = ComputeProbability();
    AINFO << "probability = " << probability;
    lane_sequence_ptr->set_probability(probability);
    AINFO << "probability set done";
  }
}

void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
                                        LaneSequence* lane_sequence_ptr) {
  feature_values_.clear();
  int id = obstacle_ptr->id();
  std::vector<double> obstacle_feature_values;
  if (obstacle_feature_values_map_.find(id) ==
      obstacle_feature_values_map_.end()) {
    SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
  } else {
    obstacle_feature_values = obstacle_feature_values_map_[id];
  }

  if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
    ADEBUG << "Obstacle [" << id << "] has fewer than "
           << "expected obstacle feature_values "
           << obstacle_feature_values.size() << ".";
    return;
  }

  std::vector<double> lane_feature_values;
  SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
  if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
    ADEBUG << "Obstacle [" << id << "] has fewer than "
           << "expected lane feature_values"
           << lane_feature_values.size() << ".";
    return;
  }

  feature_values_.insert(feature_values_.end(),
      lane_feature_values.begin(), lane_feature_values.end());
  feature_values_.insert(feature_values_.end(),
      lane_feature_values.begin(), lane_feature_values.end());
}

void MLPEvaluator::SetObstacleFeatureValues(
    Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
  feature_values->clear();
  feature_values->reserve(OBSTACLE_FEATURE_SIZE);

  std::vector<double> thetas;
  std::vector<double> lane_ls;
  std::vector<double> dist_lbs;
  std::vector<double> dist_rbs;
  std::vector<int> lane_types;
  std::vector<double> speeds;
  std::vector<double> timestamps;

  double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;
  int count = 0;
  for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
    const Feature& feature = obstacle_ptr->feature(i);
    if (!feature.IsInitialized()) {
      continue;
    }
    if (apollo::common::math::DoubleCompare(
            feature.timestamp(), duration) < 0) {
      break;
    }
    if (feature.has_lane() && feature.lane().has_lane_feature()) {
      thetas.push_back(feature.lane().lane_feature().angle_diff());
      lane_ls.push_back(feature.lane().lane_feature().lane_l());
      dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
      dist_rbs.push_back(
          feature.lane().lane_feature().dist_to_right_boundary());
      lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
      timestamps.push_back(feature.timestamp());
      if (FLAGS_enable_kf_tracking) {
        speeds.push_back(feature.t_speed());
      } else {
        speeds.push_back(feature.speed());
      }
      ++count;
    }
  }
  if (count <= 0) {
    return;
  }
  double theta_mean =
      std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size();
  double theta_filtered =
      (thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0];
  double lane_l_mean =
      std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size();
  double lane_l_filtered =
      (lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0];
  double speed_mean =
      std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size();
  double speed_lateral = sin(theta_filtered) * speed_mean;
  double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;
  double time_to_lb = (abs(speed_lateral) > 0.05)
                          ? dist_lbs[0] / speed_lateral
                          : 20 * dist_lbs[0] * speed_sign;
  double time_to_rb = (abs(speed_lateral) > 0.05)
                          ? -1 * dist_rbs[0] / speed_lateral
                          : -20 * dist_rbs[0] * speed_sign;
  double time_diff = timestamps.front() - timestamps.back();
  double dist_lb_rate = (timestamps.size() > 1)
                            ? (dist_lbs.front() - dist_lbs.back()) / time_diff
                            : 0.0;
  double dist_rb_rate = (timestamps.size() > 1)
                            ? (dist_rbs.front() - dist_rbs.back()) / time_diff
                            : 0.0;
  // setup obstacle feature values
  feature_values->push_back(theta_filtered);
  feature_values->push_back(theta_mean);
  feature_values->push_back(theta_filtered - theta_mean);
  feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]
                                            : thetas[0]);
  feature_values->push_back(lane_l_filtered);
  feature_values->push_back(lane_l_mean);
  feature_values->push_back(lane_l_filtered - lane_l_mean);
  feature_values->push_back(speed_mean);
  feature_values->push_back(dist_lbs.front());
  feature_values->push_back(dist_lb_rate);
  feature_values->push_back(time_to_lb);
  feature_values->push_back(dist_rbs.front());
  feature_values->push_back(dist_rb_rate);
  feature_values->push_back(time_to_rb);
  feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0
                                                                     : 0.0);
  feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0
                                                                      : 0.0);
  feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0
                                                                    : 0.0);
  feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0
                                                                    : 0.0);
}

void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
    LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
  feature_values->clear();
  feature_values->reserve(LANE_FEATURE_SIZE);
  const Feature& feature = obstacle_ptr->latest_feature();
  if (!feature.IsInitialized()) {
    ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
    return;
  } else if (!feature.has_position()) {
    ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
    return;
  }

  double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()
                                            : feature.theta();
  for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
    if (feature_values->size() >= LANE_FEATURE_SIZE) {
      break;
    }
    const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
    for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
      if (feature_values->size() >= LANE_FEATURE_SIZE) {
        break;
      }
      const LanePoint& lane_point = lane_segment.lane_point(j);
      if (!lane_point.has_position()) {
        AERROR << "Lane point has no position.";
        continue;
      }
      double diff_x = lane_point.position().x() - feature.position().x();
      double diff_y = lane_point.position().y() - feature.position().y();
      double angle = std::atan2(diff_x, diff_y);
      feature_values->push_back(std::sin(angle - heading));
      feature_values->push_back(lane_point.relative_l());
      feature_values->push_back(lane_point.heading());
      feature_values->push_back(lane_point.angle_diff());
    }
  }

  std::size_t size = feature_values->size();
  while (size >= 4 && size < LANE_FEATURE_SIZE) {
    double heading_diff = feature_values->operator[](size - 4);
    double lane_l_diff = feature_values->operator[](size - 3);
    double heading = feature_values->operator[](size - 2);
    double angle_diff = feature_values->operator[](size - 1);
    feature_values->push_back(heading_diff);
    feature_values->push_back(lane_l_diff);
    feature_values->push_back(heading);
    feature_values->push_back(angle_diff);
    size = feature_values->size();
  }
}

void MLPEvaluator::LoadModel(const std::string& model_file) {
  model_ptr_.reset(new FnnVehicleModel());
  CHECK(model_ptr_ != nullptr);
  std::fstream file_stream(model_file, std::ios::in | std::ios::binary);
  if (!file_stream.good()) {
    AERROR << "Unable to open the model file: " << model_file << ".";
    return;
  }
  if (!model_ptr_->ParseFromIstream(&file_stream)) {
    AERROR << "Unable to load the model file: " << model_file << ".";
    return;
  }
  ADEBUG << "Succeeded in loading the model file: " << model_file << ".";
}

double MLPEvaluator::ComputeProbability() {
  CHECK(model_ptr_.get() != nullptr);
  double probability = 0.0;

  if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {
    AERROR << "Model feature size not consistent with model proto definition.";
    return probability;
  }
  std::vector<double> layer_input;
  layer_input.reserve(model_ptr_->dim_input());
  std::vector<double> layer_output;

  // normalization
  for (int i = 0; i < model_ptr_->dim_input(); ++i) {
    double mean = model_ptr_->samples_mean().columns(i);
    double std = model_ptr_->samples_std().columns(i);
    layer_input.push_back(
        apollo::prediction::util::Normalize(feature_values_[i], mean, std));
  }

  for (int i = 0; i < model_ptr_->num_layer(); ++i) {
    if (i > 0) {
      layer_input.clear();
      layer_output.swap(layer_output);
    }
    const Layer& layer = model_ptr_->layer(i);
    for (int col = 0; col < layer.layer_output_dim(); ++col) {
      double neuron_output = layer.layer_bias().columns(col);
      for (int row = 0; row < layer.layer_input_dim(); ++row) {
        double weight = layer.layer_input_weight().rows(row).columns(col);
        neuron_output += (layer_input[row] * weight);
      }
      if (layer.layer_activation_type() == "relu") {
        neuron_output = apollo::prediction::util::Relu(neuron_output);
      } else if (layer.layer_activation_type() == "sigmoid") {
        neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
      } else if (layer.layer_activation_type() == "tanh") {
        neuron_output = std::tanh(neuron_output);
      } else {
        LOG(ERROR) << "Undefined activation func: "
                   << layer.layer_activation_type()
                   << ", and default sigmoid will be used instead.";
        neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
      }
      layer_output.push_back(neuron_output);
    }
  }

  if (layer_output.size() != 1) {
    AERROR << "Model output layer has incorrect # outputs: "
           << layer_output.size();
  } else {
    probability = layer_output[0];
  }

  return probability;
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>fix a bug in prediction module<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include <cmath>
#include <fstream>
#include <numeric>

#include "modules/prediction/evaluator/vehicle/mlp_evaluator.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/common/math/math_utils.h"
#include "modules/prediction/common/prediction_util.h"
#include "modules/map/proto/map_lane.pb.h"

namespace apollo {
namespace prediction {

using HDMapLane = apollo::hdmap::Lane;

MLPEvaluator::MLPEvaluator() {
  LoadModel(FLAGS_vehicle_model_file);
}

void MLPEvaluator::Clear() {
  obstacle_feature_values_map_.clear();
}

void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) {
  AINFO << "Start mlp evaluate";
  Clear();
  if (obstacle_ptr == nullptr) {
    AERROR << "Invalid obstacle.";
    return;
  }

  int id = obstacle_ptr->id();
  Feature latest_feature = obstacle_ptr->latest_feature();
  if (!latest_feature.IsInitialized()) {
    ADEBUG << "Obstacle [" << id << "] has no latest feature.";
    return;
  }

  Lane* lane_ptr = latest_feature.mutable_lane();
  if (!latest_feature.has_lane() || lane_ptr == nullptr) {
    ADEBUG << "Obstacle [" << id << "] has no lane feature.";
    return;
  }

  LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph();
  if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) {
    ADEBUG << "Obstacle [" << id << "] has no lane graph.";
    return;
  }

  if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) {
    ADEBUG << "Obstacle [" << id << "] has no lane sequences.";
    return;
  }

  AINFO << "Start for-loop on lane sequences";
  for (int i = 0;
      i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) {
    LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i);
    CHECK(lane_sequence_ptr != nullptr);
    AINFO << "Start to extract feature values";
    ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr);
    AINFO << "Start to compute probability";
    double probability = ComputeProbability();
    AINFO << "probability = " << probability;
    lane_sequence_ptr->set_probability(probability);
    AINFO << "probability set done";
  }
}

void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr,
                                        LaneSequence* lane_sequence_ptr) {
  feature_values_.clear();
  int id = obstacle_ptr->id();
  std::vector<double> obstacle_feature_values;
  if (obstacle_feature_values_map_.find(id) ==
      obstacle_feature_values_map_.end()) {
    SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values);
  } else {
    obstacle_feature_values = obstacle_feature_values_map_[id];
  }

  if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) {
    ADEBUG << "Obstacle [" << id << "] has fewer than "
           << "expected obstacle feature_values "
           << obstacle_feature_values.size() << ".";
    return;
  }

  std::vector<double> lane_feature_values;
  SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values);
  if (lane_feature_values.size() != LANE_FEATURE_SIZE) {
    ADEBUG << "Obstacle [" << id << "] has fewer than "
           << "expected lane feature_values"
           << lane_feature_values.size() << ".";
    return;
  }

  feature_values_.insert(feature_values_.end(),
      obstacle_feature_values.begin(), obstacle_feature_values.end());
  feature_values_.insert(feature_values_.end(),
      lane_feature_values.begin(), lane_feature_values.end());
}

void MLPEvaluator::SetObstacleFeatureValues(
    Obstacle* obstacle_ptr, std::vector<double>* feature_values) {
  feature_values->clear();
  feature_values->reserve(OBSTACLE_FEATURE_SIZE);

  std::vector<double> thetas;
  std::vector<double> lane_ls;
  std::vector<double> dist_lbs;
  std::vector<double> dist_rbs;
  std::vector<int> lane_types;
  std::vector<double> speeds;
  std::vector<double> timestamps;

  double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration;
  int count = 0;
  for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) {
    const Feature& feature = obstacle_ptr->feature(i);
    if (!feature.IsInitialized()) {
      continue;
    }
    if (apollo::common::math::DoubleCompare(
            feature.timestamp(), duration) < 0) {
      break;
    }
    if (feature.has_lane() && feature.lane().has_lane_feature()) {
      thetas.push_back(feature.lane().lane_feature().angle_diff());
      lane_ls.push_back(feature.lane().lane_feature().lane_l());
      dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary());
      dist_rbs.push_back(
          feature.lane().lane_feature().dist_to_right_boundary());
      lane_types.push_back(feature.lane().lane_feature().lane_turn_type());
      timestamps.push_back(feature.timestamp());
      if (FLAGS_enable_kf_tracking) {
        speeds.push_back(feature.t_speed());
      } else {
        speeds.push_back(feature.speed());
      }
      ++count;
    }
  }
  if (count <= 0) {
    return;
  }
  double theta_mean =
      std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size();
  double theta_filtered =
      (thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0];
  double lane_l_mean =
      std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size();
  double lane_l_filtered =
      (lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0];
  double speed_mean =
      std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size();
  double speed_lateral = sin(theta_filtered) * speed_mean;
  double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0;
  double time_to_lb = (abs(speed_lateral) > 0.05)
                          ? dist_lbs[0] / speed_lateral
                          : 20 * dist_lbs[0] * speed_sign;
  double time_to_rb = (abs(speed_lateral) > 0.05)
                          ? -1 * dist_rbs[0] / speed_lateral
                          : -20 * dist_rbs[0] * speed_sign;
  double time_diff = timestamps.front() - timestamps.back();
  double dist_lb_rate = (timestamps.size() > 1)
                            ? (dist_lbs.front() - dist_lbs.back()) / time_diff
                            : 0.0;
  double dist_rb_rate = (timestamps.size() > 1)
                            ? (dist_rbs.front() - dist_rbs.back()) / time_diff
                            : 0.0;
  // setup obstacle feature values
  feature_values->push_back(theta_filtered);
  feature_values->push_back(theta_mean);
  feature_values->push_back(theta_filtered - theta_mean);
  feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1]
                                            : thetas[0]);
  feature_values->push_back(lane_l_filtered);
  feature_values->push_back(lane_l_mean);
  feature_values->push_back(lane_l_filtered - lane_l_mean);
  feature_values->push_back(speed_mean);
  feature_values->push_back(dist_lbs.front());
  feature_values->push_back(dist_lb_rate);
  feature_values->push_back(time_to_lb);
  feature_values->push_back(dist_rbs.front());
  feature_values->push_back(dist_rb_rate);
  feature_values->push_back(time_to_rb);
  feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0
                                                                     : 0.0);
  feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0
                                                                      : 0.0);
  feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0
                                                                    : 0.0);
  feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0
                                                                    : 0.0);
}

void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr,
    LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) {
  feature_values->clear();
  feature_values->reserve(LANE_FEATURE_SIZE);
  const Feature& feature = obstacle_ptr->latest_feature();
  if (!feature.IsInitialized()) {
    ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature.";
    return;
  } else if (!feature.has_position()) {
    ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position.";
    return;
  }

  double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading()
                                            : feature.theta();
  for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) {
    if (feature_values->size() >= LANE_FEATURE_SIZE) {
      break;
    }
    const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i);
    for (int j = 0; j < lane_segment.lane_point_size(); ++j) {
      if (feature_values->size() >= LANE_FEATURE_SIZE) {
        break;
      }
      const LanePoint& lane_point = lane_segment.lane_point(j);
      if (!lane_point.has_position()) {
        AERROR << "Lane point has no position.";
        continue;
      }
      double diff_x = lane_point.position().x() - feature.position().x();
      double diff_y = lane_point.position().y() - feature.position().y();
      double angle = std::atan2(diff_x, diff_y);
      feature_values->push_back(std::sin(angle - heading));
      feature_values->push_back(lane_point.relative_l());
      feature_values->push_back(lane_point.heading());
      feature_values->push_back(lane_point.angle_diff());
    }
  }

  std::size_t size = feature_values->size();
  while (size >= 4 && size < LANE_FEATURE_SIZE) {
    double heading_diff = feature_values->operator[](size - 4);
    double lane_l_diff = feature_values->operator[](size - 3);
    double heading = feature_values->operator[](size - 2);
    double angle_diff = feature_values->operator[](size - 1);
    feature_values->push_back(heading_diff);
    feature_values->push_back(lane_l_diff);
    feature_values->push_back(heading);
    feature_values->push_back(angle_diff);
    size = feature_values->size();
  }
}

void MLPEvaluator::LoadModel(const std::string& model_file) {
  model_ptr_.reset(new FnnVehicleModel());
  CHECK(model_ptr_ != nullptr);
  std::fstream file_stream(model_file, std::ios::in | std::ios::binary);
  if (!file_stream.good()) {
    AERROR << "Unable to open the model file: " << model_file << ".";
    return;
  }
  if (!model_ptr_->ParseFromIstream(&file_stream)) {
    AERROR << "Unable to load the model file: " << model_file << ".";
    return;
  }
  ADEBUG << "Succeeded in loading the model file: " << model_file << ".";
}

double MLPEvaluator::ComputeProbability() {
  CHECK(model_ptr_.get() != nullptr);
  double probability = 0.0;

  if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) {
    AERROR << "Model feature size not consistent with model proto definition.";
    return probability;
  }
  std::vector<double> layer_input;
  layer_input.reserve(model_ptr_->dim_input());
  std::vector<double> layer_output;

  // normalization
  for (int i = 0; i < model_ptr_->dim_input(); ++i) {
    double mean = model_ptr_->samples_mean().columns(i);
    double std = model_ptr_->samples_std().columns(i);
    layer_input.push_back(
        apollo::prediction::util::Normalize(feature_values_[i], mean, std));
  }

  for (int i = 0; i < model_ptr_->num_layer(); ++i) {
    if (i > 0) {
      layer_input.clear();
      layer_output.swap(layer_output);
    }
    const Layer& layer = model_ptr_->layer(i);
    for (int col = 0; col < layer.layer_output_dim(); ++col) {
      double neuron_output = layer.layer_bias().columns(col);
      for (int row = 0; row < layer.layer_input_dim(); ++row) {
        double weight = layer.layer_input_weight().rows(row).columns(col);
        neuron_output += (layer_input[row] * weight);
      }
      if (layer.layer_activation_type() == "relu") {
        neuron_output = apollo::prediction::util::Relu(neuron_output);
      } else if (layer.layer_activation_type() == "sigmoid") {
        neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
      } else if (layer.layer_activation_type() == "tanh") {
        neuron_output = std::tanh(neuron_output);
      } else {
        LOG(ERROR) << "Undefined activation func: "
                   << layer.layer_activation_type()
                   << ", and default sigmoid will be used instead.";
        neuron_output = apollo::prediction::util::Sigmoid(neuron_output);
      }
      layer_output.push_back(neuron_output);
    }
  }

  if (layer_output.size() != 1) {
    AERROR << "Model output layer has incorrect # outputs: "
           << layer_output.size();
  } else {
    probability = layer_output[0];
  }

  return probability;
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "call/version.h"

namespace webrtc {

// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-27T04:02:39";

void LoadWebRTCVersionInRegister() {
  // Using volatile to instruct the compiler to not optimize `p` away even
  // if it looks unused.
  const char* volatile p = kSourceTimestamp;
  static_cast<void>(p);
}

}  // namespace webrtc
<commit_msg>Update WebRTC code version (2021-01-29T04:02:57).<commit_after>/*
 *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "call/version.h"

namespace webrtc {

// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-29T04:02:57";

void LoadWebRTCVersionInRegister() {
  // Using volatile to instruct the compiler to not optimize `p` away even
  // if it looks unused.
  const char* volatile p = kSourceTimestamp;
  static_cast<void>(p);
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/* Copyright (c) 2017-2022 hors<horsicq@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include "subdevice.h"

SubDevice::SubDevice(QIODevice *pDevice, qint64 nOffset, qint64 nSize, QObject *pParent) : QIODevice(pParent)
{
    if(nOffset>pDevice->size())
    {
        nOffset=pDevice->size();
    }

    if(nOffset<0)
    {
        nOffset=0;
    }

    if((nSize+nOffset>pDevice->size())||(nSize==-1)) // TODO Check
    {
        nSize=pDevice->size()-nOffset;
    }

    if(nSize+nOffset<0)
    {
        nSize=0;
    }

    this->g_pDevice=pDevice;
    this->g_nOffset=nOffset;
    this->g_nSize=nSize;

    //    reset();
    pDevice->seek(nOffset);
}

SubDevice::~SubDevice()
{
    if(isOpen())
    {
        _close();
    }
}

qint64 SubDevice::getInitOffset()
{
    return g_nOffset;
}

qint64 SubDevice::size() const
{
    return g_nSize;
}

//qint64 SubDevice::bytesAvailable() const
//{
//    return nSize;
//}

bool SubDevice::isSequential() const
{
    return false;
}

bool SubDevice::seek(qint64 nPos)
{
    bool bResult=false;

    if((nPos<g_nSize)&&(nPos>=0))
    {
        if(g_pDevice->seek(g_nOffset+nPos))
        {
            bResult=QIODevice::seek(nPos);
        }
    }

    return bResult;
}

bool SubDevice::reset()
{
    return seek(0);
}

bool SubDevice::open(QIODevice::OpenMode mode)
{
    setOpenMode(mode);

    return true;
}

bool SubDevice::atEnd() const
{
    return (bytesAvailable()==0);
}

void SubDevice::close()
{
    _close();
}

qint64 SubDevice::pos() const
{
//    return pDevice->pos()-nOffset;
    return QIODevice::pos();
}

void SubDevice::_close()
{
    setOpenMode(NotOpen);
}

qint64 SubDevice::readData(char *pData, qint64 nMaxSize)
{
    nMaxSize=qMin(nMaxSize,g_nSize-pos());

    qint64 nLen=g_pDevice->read(pData,nMaxSize);

    return nLen;
}

qint64 SubDevice::writeData(const char *pData,qint64 nMaxSize)
{
    nMaxSize=qMin(nMaxSize,g_nSize-pos());

    qint64 nLen=g_pDevice->write(pData,nMaxSize);

    return nLen;
}

void SubDevice::setErrorString(const QString &sString)
{
    QIODevice::setErrorString(sString);
}
<commit_msg>Fix: 2022-02-25<commit_after>/* Copyright (c) 2017-2022 hors<horsicq@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include "subdevice.h"

SubDevice::SubDevice(QIODevice *pDevice,qint64 nOffset,qint64 nSize,QObject *pParent) : QIODevice(pParent)
{
    if(nOffset>pDevice->size())
    {
        nOffset=pDevice->size();
    }

    if(nOffset<0)
    {
        nOffset=0;
    }

    if((nSize+nOffset>pDevice->size())||(nSize==-1)) // TODO Check
    {
        nSize=pDevice->size()-nOffset;
    }

    if(nSize+nOffset<0)
    {
        nSize=0;
    }

    this->g_pDevice=pDevice;
    this->g_nOffset=nOffset;
    this->g_nSize=nSize;

    //    reset();
    pDevice->seek(nOffset);
}

SubDevice::~SubDevice()
{
    if(isOpen())
    {
        _close();
    }
}

qint64 SubDevice::getInitOffset()
{
    return g_nOffset;
}

qint64 SubDevice::size() const
{
    return g_nSize;
}

//qint64 SubDevice::bytesAvailable() const
//{
//    return nSize;
//}

bool SubDevice::isSequential() const
{
    return false;
}

bool SubDevice::seek(qint64 nPos)
{
    bool bResult=false;

    if((nPos<g_nSize)&&(nPos>=0))
    {
        if(g_pDevice->seek(g_nOffset+nPos))
        {
            bResult=QIODevice::seek(nPos);
        }
    }

    return bResult;
}

bool SubDevice::reset()
{
    return seek(0);
}

bool SubDevice::open(QIODevice::OpenMode mode)
{
    setOpenMode(mode);

    return true;
}

bool SubDevice::atEnd() const
{
    return (bytesAvailable()==0);
}

void SubDevice::close()
{
    _close();
}

qint64 SubDevice::pos() const
{
//    return pDevice->pos()-nOffset;
    return QIODevice::pos();
}

void SubDevice::_close()
{
    setOpenMode(NotOpen);
}

qint64 SubDevice::readData(char *pData, qint64 nMaxSize)
{
    nMaxSize=qMin(nMaxSize,g_nSize-pos());

    qint64 nLen=g_pDevice->read(pData,nMaxSize);

    return nLen;
}

qint64 SubDevice::writeData(const char *pData,qint64 nMaxSize)
{
    nMaxSize=qMin(nMaxSize,g_nSize-pos());

    qint64 nLen=g_pDevice->write(pData,nMaxSize);

    return nLen;
}

void SubDevice::setErrorString(const QString &sString)
{
    QIODevice::setErrorString(sString);
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "call/version.h"

namespace webrtc {

// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-24T04:03:52";

void LoadWebRTCVersionInRegister() {
  // Using volatile to instruct the compiler to not optimize `p` away even
  // if it looks unused.
  const char* volatile p = kSourceTimestamp;
  static_cast<void>(p);
}

}  // namespace webrtc
<commit_msg>Update WebRTC code version (2021-01-25T04:04:10).<commit_after>/*
 *  Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "call/version.h"

namespace webrtc {

// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-25T04:04:10";

void LoadWebRTCVersionInRegister() {
  // Using volatile to instruct the compiler to not optimize `p` away even
  // if it looks unused.
  const char* volatile p = kSourceTimestamp;
  static_cast<void>(p);
}

}  // namespace webrtc
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>

#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/objects.h>

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "base64.h"

using namespace std;
using namespace rapidjson;

#define MACHINE_IP  inet_addr("127.0.0.1")

vector<string> split(string str, char delimiter) {
	vector<string> internal;
	stringstream ss(str);
	string tok;

	while(getline(ss, tok, delimiter)) {
		internal.push_back(tok);
	}

	return internal;
}

int sign(Document* d)
{

	const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401";
	const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1";

	ECDSA_SIG *sig;
	char sig_str[B64SIZE];
	BN_CTX *ctx;
	BIGNUM *a;
	EVP_MD_CTX* mdctx;
	const EVP_MD* md;
	unsigned char md_value[EVP_MAX_MD_SIZE];
	unsigned int md_len;
	EC_KEY* auth_key;
	Value si;

	auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);
	if (auth_key == NULL) {
		printf("failed to initialize curve\n");
		return 1;
  	}

	ctx = BN_CTX_new();
	if(!ctx) {
		printf("failed to create bn ctx\n");
		return 1;
  	}

	EC_KEY_set_public_key(auth_key,
	EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx));
	a = BN_new();
	BN_hex2bn(&a, private_key);
	EC_KEY_set_private_key(auth_key, a);

	BN_CTX_free(ctx);

	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d->Accept(writer);

	printf("sig is signing: %s\n", buffer.GetString());

	OpenSSL_add_all_digests();
	md = EVP_get_digestbyname("sha256");
	if(md == 0) {
		printf("Unknown message digest\n");
		return 1;
	}

	mdctx = EVP_MD_CTX_create();
	EVP_DigestInit_ex(mdctx, md, NULL);
	EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize());
	EVP_DigestFinal_ex(mdctx, md_value, &md_len);
	EVP_MD_CTX_destroy(mdctx);

	printf("digest: ");
	dump_mem(md_value, md_len);

	sig = ECDSA_do_sign(md_value, md_len, auth_key);

	if (sig == NULL) {
		printf("Signing failed\n");
		return 1;
  	}

	base64encode(sig_str, sig->r, sig->s);
	si.SetString(sig_str, B64SIZE, d->GetAllocator());
	d->AddMember("si", si, d->GetAllocator());

	printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s));
	return 0;
}

//////////////////////////////////////////////////////////////////////////////////////

int get_request(int fd, int choice, const char* port_mode) {

          char* message;
          size_t size = TOKENSIZE;
          int offset;

          // step 1: read request from client, common for both mode1 and mode2

          message = (char*) realloc(NULL, sizeof(char)*size);
          if(!message) {
            printf("get_request: Failure to realloc\n");
            exit(1);
          }

          offset = -1;
          do {
                offset++;
                if (offset == size) {

                        message = (char*) realloc(message, sizeof(char)*(size += 16));
                        if(!message) {
                            printf("get_request: Failure to realloc\n");
	                        exit(1);
                        }
                    }

                if(read(fd, message+offset, 1) <= 0) {
                        printf("get_request: EOF encountered\n");
                        char c = message[offset];
                        message[offset] = 0;
                        printf("story so far (%d): %s%c\n", offset, message, c);
                        exit(1);
                }
          } while (message[offset] != 0);

            printf("get_request: message at %p: %s\n", message, message);

	        vector<string> sep = split(message, '\n');
	        const char * pub_key = sep[0].c_str();
	        const char * res_add = sep[1].c_str();

	        cout << "public key (b64): " << pub_key << "\n";
	        cout << "resource address: " << res_add << "\n";

            // step 2: create token 'd', common for both mode1 and mode2
	        Document d;
	        Value ii, nb, na, suv, dev,id;
            unsigned int now;

	        d.Parse("{}");

	        now = time(NULL);
	        ii.SetInt(now);
	        nb.SetInt(now);
	        na.SetInt(1600000000);

            //random 16 byte ID
            char id_buffer[17];
            int j;
            srand(time(NULL));
            for (j = 0; j < sizeof(id_buffer); j++) {
//                itoa(rand()%10, id_buffer+j,10);
//                  snprintf(id_buffer+j, 1, "%d", rand()%10);

                   id_buffer[j] = 'A' + rand()%24;

            }
             id_buffer[16] = '\0';

            cout << " id_buffer" <<  id_buffer << "\n";

            char const * id_buf2 = (char const *)id_buffer;

            id.SetString(id_buffer, strlen(id_buffer), d.GetAllocator());

	        suv.SetString(pub_key, strlen(pub_key), d.GetAllocator());
	        dev.SetString(res_add, strlen(res_add), d.GetAllocator());

	        d.AddMember("id", id, d.GetAllocator());
	        d.AddMember("ii", ii, d.GetAllocator());
	        d.AddMember("is", "fake issuer", d.GetAllocator());
	        d.AddMember("su", suv, d.GetAllocator());
	        d.AddMember("de", dev, d.GetAllocator());
	        d.AddMember("ar", "fake access rights", d.GetAllocator());
	        d.AddMember("nb", nb, d.GetAllocator());
	        d.AddMember("na", na, d.GetAllocator());

	        sign(&d);

	        // Step 3: Mode choice dependent
	        // (Mode 1, return token to client)
	        if (choice == 1) {
		        StringBuffer buffer;
		        Writer<StringBuffer> writer(buffer);
	            d.Accept(writer);

                cout << "buffer data : " << buffer.GetString();
		        cout << "\n buffer len:" << buffer.GetSize();

                if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {
                    printf("Failed to write to socket\n");
              	}
                return 1;
	        }

	        // (Mode 2, return token to resource, token ID to client)

	        else if(choice == 2 ){

                cout << "Mode 2\n";

                int soc2;
                uint16_t port = strtol(port_mode, NULL, 10);
                char null_string[17];

                soc2 = socket(AF_INET, SOCK_STREAM, 0);
                if(soc2 < 0) {
	                printf("failed to create socket: %s\n", strerror(errno));
                }

                struct sockaddr_in connectAddress;
                memset(&connectAddress, 0, sizeof(connectAddress));
                connectAddress.sin_family = AF_INET;
                connectAddress.sin_addr.s_addr = MACHINE_IP;
                connectAddress.sin_port = htons(port);

                if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
		                printf("send token to resource: failed to connect to resource: %s\n", strerror(errno));
                }

		        // insert code for null string here
               	int i;

		        // add 17 NULLS before sending the json to resource -- one socket
                for (i = 0; i <=17; i++){
                    null_string[i] = (char) 0;
                }

                if(write(soc2, null_string, 17) < 0) {
                    printf("Failed to write null string to resource socket\n");
                }

                //send token to resource here
                StringBuffer buffer;
                Writer<StringBuffer> writer(buffer);
                d.Accept(writer);

                cout << "buffer data : "<< buffer.GetString() ;
                cout << "\n buffer len:" << buffer.GetSize() << "\n";

                if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {
                     printf("Failed to write to token to resource socket\n");
                }

                //send token ID to client

                char const *tokenID_str = d["id"].GetString();
                cout << "string token ID: " << tokenID_str << "\n";

                if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {

                     printf("Failed to write to socket\n");
                }

                return 1;
	      }// end of mode 2
}

int bootstrap_network(const char* port_sub){

	int soc;
	uint16_t port = strtol(port_sub, NULL, 10);   // from arguments

	soc = socket(AF_INET, SOCK_STREAM, 0);
	if (soc == -1)	{
		printf("Failed to open socket\n");
		return 1;
  	}

 	struct sockaddr_in connectAddress;
	memset(&connectAddress, 0, sizeof(connectAddress));
	connectAddress.sin_family = AF_INET;
	connectAddress.sin_addr.s_addr = MACHINE_IP;
	connectAddress.sin_port = htons(port);

	if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) {
		printf("bootstrap: Failed to bind\n");
		exit(1);
  	}

	if(listen(soc, 5) == -1) {
		printf( "bootstrap: Failed to listen\n");
		exit(1);
  	}

	return soc;
}

int listen_block(int soc,int choice, const char* port_mode){

	int fd;
	socklen_t peer_addr_size = sizeof(struct sockaddr_in);
	struct sockaddr_in retAddress;
    int req1;

	printf("DEBUG: entering network loop\n");

	while(true) {
		printf("DEBUG: network loop: accepting connection...\n");
		fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);
		printf("fd value: %d\n",fd);
		if( fd == -1) {
			printf("listen: Failed to accept: %s\n", strerror(errno));
			exit(1);
    		}

		printf( "DEBUG: network loop: connection accepted, getting request from subject...\n");

		req1 = get_request(fd,choice,port_mode);
		close(fd);
	}

}

int main(int argc, char *argv[]){

	if(argc <= 3){
		printf("insufficient arguments\n");
		printf("sample argument: ./auth <mode> <port_client> <port_resource>\n {Enter dummy value for port_resource in Mode 1}");
		return 1;
  	}

	int fd1, soc1;
  	soc1 = bootstrap_network(argv[2]);

	const char* port_client = argv[2];
	const char* port_resource = argv[3];

  	if(!strcmp(argv[1], "1"))
		listen_block(soc1,1,port_resource);

    	else if(!strcmp(argv[1], "2"))
		listen_block(soc1,2,port_resource);

	else{
		printf("Invalid mode: %s", argv[1]);
		exit(1);
  	}

	return 1;
}
<commit_msg>Verifier port appended to access request<commit_after>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <errno.h>

#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/objects.h>

#include "rapidjson/document.h"
#include "rapidjson/prettywriter.h"
#include "base64.h"

using namespace std;
using namespace rapidjson;

#define MACHINE_IP  inet_addr("127.0.0.1")

vector<string> split(string str, char delimiter) {
	vector<string> internal;
	stringstream ss(str);
	string tok;

	while(getline(ss, tok, delimiter)) {
		internal.push_back(tok);
	}

	return internal;
}

int sign(Document* d)
{

	const char private_key[] = "F2506E09D4153EED5ACBE1D620C93CA0D5580EF41AC0A401";
	const char pub_key[] = "027134EE605CB10FAE017BDD9FD88C96C8C080F08271637BB1";

	ECDSA_SIG *sig;
	char sig_str[B64SIZE];
	BN_CTX *ctx;
	BIGNUM *a;
	EVP_MD_CTX* mdctx;
	const EVP_MD* md;
	unsigned char md_value[EVP_MAX_MD_SIZE];
	unsigned int md_len;
	EC_KEY* auth_key;
	Value si;

	auth_key = EC_KEY_new_by_curve_name(NID_X9_62_prime192v3);
	if (auth_key == NULL) {
		printf("failed to initialize curve\n");
		return 1;
  	}

	ctx = BN_CTX_new();
	if(!ctx) {
		printf("failed to create bn ctx\n");
		return 1;
  	}

	EC_KEY_set_public_key(auth_key,
	EC_POINT_hex2point(EC_KEY_get0_group(auth_key),pub_key, NULL, ctx));
	a = BN_new();
	BN_hex2bn(&a, private_key);
	EC_KEY_set_private_key(auth_key, a);

	BN_CTX_free(ctx);

	StringBuffer buffer;
	Writer<StringBuffer> writer(buffer);
	d->Accept(writer);

	printf("sig is signing: %s\n", buffer.GetString());

	OpenSSL_add_all_digests();
	md = EVP_get_digestbyname("sha256");
	if(md == 0) {
		printf("Unknown message digest\n");
		return 1;
	}

	mdctx = EVP_MD_CTX_create();
	EVP_DigestInit_ex(mdctx, md, NULL);
	EVP_DigestUpdate(mdctx, buffer.GetString(), buffer.GetSize());
	EVP_DigestFinal_ex(mdctx, md_value, &md_len);
	EVP_MD_CTX_destroy(mdctx);

	printf("digest: ");
	dump_mem(md_value, md_len);

	sig = ECDSA_do_sign(md_value, md_len, auth_key);

	if (sig == NULL) {
		printf("Signing failed\n");
		return 1;
  	}

	base64encode(sig_str, sig->r, sig->s);
	si.SetString(sig_str, B64SIZE, d->GetAllocator());
	d->AddMember("si", si, d->GetAllocator());

	printf("sig: %s, %s\n", BN_bn2hex(sig->r), BN_bn2hex(sig->s));
	return 0;
}

//////////////////////////////////////////////////////////////////////////////////////

int get_request(int fd, int choice, const char* port_mode) {

          char* message;
          size_t size = TOKENSIZE;
          int offset;

          // step 1: read request from client, common for both mode1 and mode2

          message = (char*) realloc(NULL, sizeof(char)*size);
          if(!message) {
            printf("get_request: Failure to realloc\n");
            exit(1);
          }

          offset = -1;
          do {
                offset++;
                if (offset == size) {

                        message = (char*) realloc(message, sizeof(char)*(size += 16));
                        if(!message) {
                            printf("get_request: Failure to realloc\n");
	                        exit(1);
                        }
                    }

                if(read(fd, message+offset, 1) <= 0) {
                        printf("get_request: EOF encountered\n");
                        char c = message[offset];
                        message[offset] = 0;
                        printf("story so far (%d): %s%c\n", offset, message, c);
                        exit(1);
                }
          } while (message[offset] != 0);

            printf("get_request: message at %p: %s\n", message, message);

	        vector<string> sep = split(message, '\n');
	        const char * pub_key = sep[0].c_str();
	        const char * res_add = sep[1].c_str();

	        cout << "public key (b64): " << pub_key << "\n";
	        cout << "resource address: " << res_add << "\n";

            // step 2: create token 'd', common for both mode1 and mode2
	        Document d;
	        Value ii, nb, na, suv, dev,id;
            unsigned int now;

	        d.Parse("{}");

	        now = time(NULL);
	        ii.SetInt(now);
	        nb.SetInt(now);
	        na.SetInt(1600000000);

            //random 16 byte ID
            char id_buffer[17];
            int j;
            srand(time(NULL));
            for (j = 0; j < sizeof(id_buffer); j++) {
//                itoa(rand()%10, id_buffer+j,10);
//                  snprintf(id_buffer+j, 1, "%d", rand()%10);

                   id_buffer[j] = 'A' + rand()%24;

            }
             id_buffer[16] = '\0';

            cout << " id_buffer" <<  id_buffer << "\n";

            char const * id_buf2 = (char const *)id_buffer;

            id.SetString(id_buffer, strlen(id_buffer), d.GetAllocator());

	        suv.SetString(pub_key, strlen(pub_key), d.GetAllocator());
	        dev.SetString(res_add, strlen(res_add), d.GetAllocator());

	        d.AddMember("id", id, d.GetAllocator());
	        d.AddMember("ii", ii, d.GetAllocator());
	        d.AddMember("is", "fake issuer", d.GetAllocator());
	        d.AddMember("su", suv, d.GetAllocator());
	        d.AddMember("de", dev, d.GetAllocator());
	        d.AddMember("ar", "fake access rights", d.GetAllocator());
	        d.AddMember("nb", nb, d.GetAllocator());
	        d.AddMember("na", na, d.GetAllocator());

	        sign(&d);

	        // Step 3: Mode choice dependent
	        // (Mode 1, return token to client)
	        if (choice == 1) {
		        StringBuffer buffer;
		        Writer<StringBuffer> writer(buffer);
	            d.Accept(writer);

                cout << "buffer data : " << buffer.GetString();
		        cout << "\n buffer len:" << buffer.GetSize();

                if(write(fd, buffer.GetString(), buffer.GetSize()+1) < 0) {
                    printf("Failed to write to socket\n");
              	}
                return 1;
	        }

	        // (Mode 2, return token to resource, token ID to client)

	        else if(choice == 2 ){

		const char *res_port = sep[2].c_str();
                cout << "Mode 2\n";
		cout << "resource PORT:" << res_port << endl;
                int soc2;
                uint16_t port = strtol(res_port, NULL, 10);
                char null_string[17];

                soc2 = socket(AF_INET, SOCK_STREAM, 0);
                if(soc2 < 0) {
	                printf("failed to create socket: %s\n", strerror(errno));
                }

                struct sockaddr_in connectAddress;
                memset(&connectAddress, 0, sizeof(connectAddress));
                connectAddress.sin_family = AF_INET;
                connectAddress.sin_addr.s_addr = MACHINE_IP;
                connectAddress.sin_port = htons(port);

                if(connect(soc2, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) < 0) {
		                printf("send token to resource: failed to connect to resource: %s\n", strerror(errno));
                }

		        // insert code for null string here
               	int i;

		        // add 17 NULLS before sending the json to resource -- one socket
                for (i = 0; i <=17; i++){
                    null_string[i] = (char) 0;
                }

                if(write(soc2, null_string, 17) < 0) {
                    printf("Failed to write null string to resource socket\n");
                }

                //send token to resource here
                StringBuffer buffer;
                Writer<StringBuffer> writer(buffer);
                d.Accept(writer);

                cout << "buffer data : "<< buffer.GetString() ;
                cout << "\n buffer len:" << buffer.GetSize() << "\n";

                if(write(soc2, buffer.GetString(), buffer.GetSize()+1) < 0) {
                     printf("Failed to write to token to resource socket\n");
                }

                //send token ID to client

                char const *tokenID_str = d["id"].GetString();
                cout << "string token ID: " << tokenID_str << "\n";

                if(write(fd, tokenID_str, strlen(tokenID_str)+1) < 0) {

                     printf("Failed to write to socket\n");
                }

                return 1;
	      }// end of mode 2
}

int bootstrap_network(const char* port_sub){

	int soc;
	uint16_t port = strtol(port_sub, NULL, 10);   // from arguments

	soc = socket(AF_INET, SOCK_STREAM, 0);
	if (soc == -1)	{
		printf("Failed to open socket\n");
		return 1;
  	}

 	struct sockaddr_in connectAddress;
	memset(&connectAddress, 0, sizeof(connectAddress));
	connectAddress.sin_family = AF_INET;
	connectAddress.sin_addr.s_addr = MACHINE_IP;
	connectAddress.sin_port = htons(port);

	if(bind(soc, (struct sockaddr *) &connectAddress, sizeof(connectAddress)) == -1) {
		printf("bootstrap: Failed to bind\n");
		exit(1);
  	}

	if(listen(soc, 5) == -1) {
		printf( "bootstrap: Failed to listen\n");
		exit(1);
  	}

	return soc;
}

int listen_block(int soc,int choice, const char* port_mode){

	int fd;
	socklen_t peer_addr_size = sizeof(struct sockaddr_in);
	struct sockaddr_in retAddress;
    int req1;

	printf("DEBUG: entering network loop\n");

	while(true) {
		printf("DEBUG: network loop: accepting connection...\n");
		fd = accept(soc, (struct sockaddr *) &retAddress, &peer_addr_size);
		printf("fd value: %d\n",fd);
		if( fd == -1) {
			printf("listen: Failed to accept: %s\n", strerror(errno));
			exit(1);
    		}

		printf( "DEBUG: network loop: connection accepted, getting request from subject...\n");

		req1 = get_request(fd,choice,port_mode);
		close(fd);
	}

}

int main(int argc, char *argv[]){

	if(argc <= 3){
		printf("insufficient arguments\n");
		printf("sample argument: ./auth <mode> <port_client> <port_resource>\n {Enter dummy value for port_resource in Mode 1}");
		return 1;
  	}

	int fd1, soc1;
  	soc1 = bootstrap_network(argv[2]);

	const char* port_client = argv[2];
	const char* port_resource = argv[3];

  	if(!strcmp(argv[1], "1"))
		listen_block(soc1,1,port_resource);

    	else if(!strcmp(argv[1], "2"))
		listen_block(soc1,2,port_resource);

	else{
		printf("Invalid mode: %s", argv[1]);
		exit(1);
  	}

	return 1;
}
<|endoftext|>


<commit_before><commit_msg>Commented out all code related to "imageNames" and "img_name" since they aren't being used at the moment.<commit_after><|endoftext|>


<commit_before>AddTask_dNdPtpp_TPCITS(Int_t cutMode =223, char *controString ="default", char* eventTrigger="kINT7"){

   TString stEventTrigger(eventTrigger);
   //TString stParticleMode(particleMode);
   TString stControlString(controlString);

   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {Error("AddTask_dNdPtpp_TPCITS", "No analysis manager found.");return 0;}

   Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

   // Switch off all AliInfo (too much output!!!)
   AliLog::SetGlobalLogLevel(AliLog::kError);
   mgr->SetDebugLevel(0);

   /// Create event cuts
   Float_t zvWindow = 30. ;

   AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
   evtCuts->SetZvRange(-zvWindow,zvWindow);
   evtCuts->SetMeanXYZv(0.0,0.0,0.0);
   evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
   evtCuts->SetTriggerRequired(kTRUE);

   // Create geom. acceptance cuts

   Float_t etaWindow = 1. ;
   Float_t ptMin = 0.10;

   AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
   accCuts->SetEtaRange(-etaWindow,etaWindow);
   accCuts->SetPtRange(ptMin,1.e10);

   gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
   AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode,stControlString);
   if (!esdTrackCuts) { printf("ERROR: esdTrackCuts could not be created\n"); return; }
   esdTrackCuts->SetHistogramsOn(kTRUE);

   // Create task
   AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask");
   task->SetUseMCInfo(hasMC);

   // trigger selection: MB
   if(stEventTrigger.Contains("kINT7")) task->SelectCollisionCandidates(AliVEvent::kINT7);
   else if(stEventTrigger.Contains("kMB")) task->SelectCollisionCandidates(AliVEvent::kMB);

   // Create cut analysis object
   AlidNdPtAnalysis *fdNdPtAnalysispp = new AlidNdPtAnalysis("dNdPtAnalysis","dN/dPt Analysis");
   fdNdPtAnalysispp->SetEventCuts(evtCuts);
   fdNdPtAnalysispp->SetAcceptanceCuts(accCuts);
   fdNdPtAnalysispp->SetTrackCuts(esdTrackCuts);
   fdNdPtAnalysispp->SetAnalysisMode(AlidNdPtHelper::kTPCITS);
   if(stEventTrigger.Contains("kINT7")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kINT7);
   else if(stEventTrigger.Contains("kMB")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kMB);

   // SetParticleMode
   if(stControlString.Contains("Pion"))                 {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCPion);}
   else if (stControlString.Contains("Proton"))         {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCProton);}
   else if (stControlString.Contains("Kaon"))           {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCKaon);}
   else if (stControlString.Contains("RemainingRest"))  {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCRemainingRest);}
   else if (stControlString.Contains("Rest"))           {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCRest);}
   else if (stControlString.Contains("Lambda"))         {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCLambda);}
   else if (stControlString.Contains("SigmaPlus"))      {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCSigmaPlus);}
   else if (stControlString.Contains("SigmaMinus"))     {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCSigmaMinus);}
   else if (stControlString.Contains("XiMinus"))        {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCXiMinus);}
   else if (stControlString.Contains("OmegaMinus"))     {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCOmegaMinus);}
   else if (stControlString.Contains("Plus"))           {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kPlus);}
   else if (stControlString.Contains("Minus"))          {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMinus);}
   else if (stControlString.Contains("Electron"))       {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCElectron);}
   else if (stControlString.Contains("Muon"))           {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCMuon);}
   else if (stControlString.Contains("InclWoSigma"))    {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kInclWoSimga);}
   else {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kAllPart);}

   // Change binning
   const Int_t ptNbins = 81;
   Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
   Double_t* binsPt = new Double_t[82];
   for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
   fdNdPtAnalysispp->SetBinsPt(ptNbins, binsPt);
   fdNdPtAnalysispp->SetBinsPtCorr(ptNbins, binsPt);

   fdNdPtAnalysispp->SetUseMCInfo(hasMC);
   fdNdPtAnalysispp->SetHistogramsOn(hasMC);

   task->AddAnalysisObject( fdNdPtAnalysispp );

   // Add task
   mgr->AddTask(task);

   // Create containers for input
   AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
   mgr->ConnectInput(task, 0, cinput);

   TString stContainerName;
   stContainerName = Form("dNdPt_pp_%d",cutMode);
   if(!stParticleMode.Contains("default")) {
     stContainerName = stContainerName + "_" +stParticleMode;
   }

   AliAnalysisDataContainer *coutput = mgr->CreateContainer(stContainerName,TList::Class(),AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName());

   mgr->ConnectOutput(task, 1, coutput);
 }
<commit_msg>Update in AddTask<commit_after>AddTask_dNdPtpp_TPCITS(Int_t cutMode =223, char *controlString ="default", char* eventTrigger="kINT7"){

   TString stEventTrigger(eventTrigger);
   //TString stParticleMode(particleMode);
   TString stControlString(controlString);

   AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
   if (!mgr) {Error("AddTask_dNdPtpp_TPCITS", "No analysis manager found.");return 0;}

   Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

   // Switch off all AliInfo (too much output!!!)
   AliLog::SetGlobalLogLevel(AliLog::kError);
   mgr->SetDebugLevel(0);

   /// Create event cuts
   Float_t zvWindow = 30. ;

   AlidNdPtEventCuts *evtCuts = new AlidNdPtEventCuts("AlidNdPtEventCuts","Event cuts");
   evtCuts->SetZvRange(-zvWindow,zvWindow);
   evtCuts->SetMeanXYZv(0.0,0.0,0.0);
   evtCuts->SetSigmaMeanXYZv(1.0,1.0,10.0);
   evtCuts->SetTriggerRequired(kTRUE);

   // Create geom. acceptance cuts

   Float_t etaWindow = 1. ;
   Float_t ptMin = 0.10;

   AlidNdPtAcceptanceCuts *accCuts = new AlidNdPtAcceptanceCuts("AlidNdPtAcceptanceCuts","Geom. acceptance cuts");
   accCuts->SetEtaRange(-etaWindow,etaWindow);
   accCuts->SetPtRange(ptMin,1.e10);

   gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/SPECTRA/ChargedHadrons/dNdPt/macros/CreatedNdPtTrackCuts.C");
   AliESDtrackCuts* esdTrackCuts = CreatedNdPtTrackCuts(cutMode,stControlString);
   if (!esdTrackCuts) { printf("ERROR: esdTrackCuts could not be created\n"); return; }
   esdTrackCuts->SetHistogramsOn(kTRUE);

   // Create task
   AlidNdPtTask *task = new AlidNdPtTask("AlidNdPtTask");
   task->SetUseMCInfo(hasMC);

   // trigger selection: MB
   if(stEventTrigger.Contains("kINT7")) task->SelectCollisionCandidates(AliVEvent::kINT7);
   else if(stEventTrigger.Contains("kMB")) task->SelectCollisionCandidates(AliVEvent::kMB);

   // Create cut analysis object
   AlidNdPtAnalysis *fdNdPtAnalysispp = new AlidNdPtAnalysis("dNdPtAnalysis","dN/dPt Analysis");
   fdNdPtAnalysispp->SetEventCuts(evtCuts);
   fdNdPtAnalysispp->SetAcceptanceCuts(accCuts);
   fdNdPtAnalysispp->SetTrackCuts(esdTrackCuts);
   fdNdPtAnalysispp->SetAnalysisMode(AlidNdPtHelper::kTPCITS);
   if(stEventTrigger.Contains("kINT7")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kINT7);
   else if(stEventTrigger.Contains("kMB")) fdNdPtAnalysispp->SetTriggerMask(AliVEvent::kMB);

   // SetParticleMode
   if(stControlString.Contains("Pion"))                 {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCPion);}
   else if (stControlString.Contains("Proton"))         {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCProton);}
   else if (stControlString.Contains("Kaon"))           {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCKaon);}
   else if (stControlString.Contains("RemainingRest"))  {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCRemainingRest);}
   else if (stControlString.Contains("Rest"))           {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCRest);}
   else if (stControlString.Contains("Lambda"))         {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCLambda);}
   else if (stControlString.Contains("SigmaPlus"))      {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCSigmaPlus);}
   else if (stControlString.Contains("SigmaMinus"))     {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCSigmaMinus);}
   else if (stControlString.Contains("XiMinus"))        {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCXiMinus);}
   else if (stControlString.Contains("OmegaMinus"))     {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCOmegaMinus);}
   else if (stControlString.Contains("Plus"))           {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kPlus);}
   else if (stControlString.Contains("Minus"))          {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMinus);}
   else if (stControlString.Contains("Electron"))       {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCElectron);}
   else if (stControlString.Contains("Muon"))           {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kMCMuon);}
   else if (stControlString.Contains("InclWoSigma"))    {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kInclWoSimga);}
   else {fdNdPtAnalysisPbPb->SetParticleMode(AlidNdPtHelper::kAllPart);}

   // Change binning
   const Int_t ptNbins = 81;
   Double_t bins[82] = {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.8, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 18.0, 20.0, 22.0, 24.0, 26.0, 28.0, 30.0, 32.0, 34.0, 36.0, 40.0, 45.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 180.0, 200.0};
   Double_t* binsPt = new Double_t[82];
   for (int i=0; i<82; i++) {binsPt[i] = bins[i];}
   fdNdPtAnalysispp->SetBinsPt(ptNbins, binsPt);
   fdNdPtAnalysispp->SetBinsPtCorr(ptNbins, binsPt);

   fdNdPtAnalysispp->SetUseMCInfo(hasMC);
   fdNdPtAnalysispp->SetHistogramsOn(hasMC);

   task->AddAnalysisObject( fdNdPtAnalysispp );

   // Add task
   mgr->AddTask(task);

   // Create containers for input
   AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
   mgr->ConnectInput(task, 0, cinput);

   TString stContainerName;
   stContainerName = Form("dNdPt_pp_%d",cutMode);
   if(!stParticleMode.Contains("default")) {
     stContainerName = stContainerName + "_" +stParticleMode;
   }

   AliAnalysisDataContainer *coutput = mgr->CreateContainer(stContainerName,TList::Class(),AliAnalysisManager::kOutputContainer, mgr->GetCommonFileName());

   mgr->ConnectOutput(task, 1, coutput);
 }
<|endoftext|>


<commit_before>// @(#)root/hist:$Id$
// Author: David Gonzalez Maline   12/11/09

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TFitResultPtr.h"
#include "TFitResult.h"
#include <cassert>

/**
TFitResultPtr provides an indirection to the TFitResult class and with a semantics
identical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult.
In addition it provides an automatic comversion to an integer. In this way it can be
returned from the TH1::Fit method and the change in TH1::Fit be backward compatible.
The class

 */

ClassImp(TFitResultPtr)

TFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) :
   fStatus(rhs.fStatus), fPointer(0)
{
   // copy constructor - create a new TFitResult if needed
   if (rhs.fPointer != 0)  fPointer = new TFitResult(*rhs);
}

TFitResultPtr::~TFitResultPtr()
{
   // destructor - delete the contained TFitResult pointer if needed
   if ( fPointer != 0)
      delete fPointer;
}

TFitResultPtr::operator int() const
{
   // automatic integer conversion. Needed for backward-compatibility with int TH1::FIt
   // The returned integer is the fit status code from FitResult
   if ( fPointer == 0 )
      return fStatus;
   else
      return fPointer->Status();
}

TFitResult& TFitResultPtr::operator*() const
{
   // impelment the de-reference operator to make the class acts as a pointer to a TFitResult
   // assert in case the class does not contain a pointer to TFitResult
   assert (fPointer != 0);
   return *fPointer;
}

TFitResult* TFitResultPtr::operator->() const
{
   // implement the -> operator to make the class acts as a pointer to a TFitResult
   // assert in case the class does not contain a pointer to TFitResult
   assert (fPointer != 0);
   return fPointer;
}

TFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs)
{
   // assignment operator
   // if needed copy the TFitResult  object and delete previous one if existing
   if ( &rhs == this) return *this; // self assignment
   fStatus = rhs.fStatus;
   if ( fPointer ) delete fPointer;
   fPointer = 0;
   if (rhs.fPointer != 0)  fPointer = new TFitResult(*rhs);
}

<commit_msg>fix a warning on Linux<commit_after>// @(#)root/hist:$Id$
// Author: David Gonzalez Maline   12/11/09

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TFitResultPtr.h"
#include "TFitResult.h"
#include <cassert>

/**
TFitResultPtr provides an indirection to the TFitResult class and with a semantics
identical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult.
In addition it provides an automatic comversion to an integer. In this way it can be
returned from the TH1::Fit method and the change in TH1::Fit be backward compatible.
The class

 */

ClassImp(TFitResultPtr)

TFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) :
   fStatus(rhs.fStatus), fPointer(0)
{
   // copy constructor - create a new TFitResult if needed
   if (rhs.fPointer != 0)  fPointer = new TFitResult(*rhs);
}

TFitResultPtr::~TFitResultPtr()
{
   // destructor - delete the contained TFitResult pointer if needed
   if ( fPointer != 0)
      delete fPointer;
}

TFitResultPtr::operator int() const
{
   // automatic integer conversion. Needed for backward-compatibility with int TH1::FIt
   // The returned integer is the fit status code from FitResult
   if ( fPointer == 0 )
      return fStatus;
   else
      return fPointer->Status();
}

TFitResult& TFitResultPtr::operator*() const
{
   // impelment the de-reference operator to make the class acts as a pointer to a TFitResult
   // assert in case the class does not contain a pointer to TFitResult
   assert (fPointer != 0);
   return *fPointer;
}

TFitResult* TFitResultPtr::operator->() const
{
   // implement the -> operator to make the class acts as a pointer to a TFitResult
   // assert in case the class does not contain a pointer to TFitResult
   assert (fPointer != 0);
   return fPointer;
}

TFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs)
{
   // assignment operator
   // if needed copy the TFitResult  object and delete previous one if existing
   if ( &rhs == this) return *this; // self assignment
   fStatus = rhs.fStatus;
   if ( fPointer ) delete fPointer;
   fPointer = 0;
   if (rhs.fPointer != 0)  fPointer = new TFitResult(*rhs);
   return *this;
}

<|endoftext|>