text:
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "InsertSourceBlocks.h"

#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/utility/string_view.hpp>
#include <cstdint>
#include <fstream>
#include <mutex>

#include "ConfigFiles.h"
#include "DexClass.h"
#include "DexStore.h"
#include "IRCode.h"
#include "Macros.h"
#include "MethodProfiles.h"
#include "PassManager.h"
#include "RedexContext.h"
#include "RedexMappedFile.h"
#include "ScopedCFG.h"
#include "Show.h"
#include "SourceBlockConsistencyCheck.h"
#include "SourceBlocks.h"
#include "Trace.h"
#include "Walkers.h"

using namespace cfg;

namespace {
source_blocks::InsertResult source_blocks(
    DexMethod* method,
    IRCode* code,
    const std::vector<source_blocks::ProfileData>& profiles,
    bool serialize,
    bool exc_inject) {
  ScopedCFG cfg(code);
  return source_blocks::insert_source_blocks(method, cfg.get(), profiles,
                                             serialize, exc_inject);
}

using namespace boost::multi_index;

struct ProfileFile {
  RedexMappedFile mapped_file;
  std::string interaction;

  using StringPos = std::pair<size_t, size_t>;

  using MethodMeta = std::unordered_map<const DexMethodRef*, StringPos>;
  MethodMeta method_meta;

  // Consider std::string_view in C++17.
  struct StringViewEquals {
    bool operator()(const std::string& s1, const std::string& s2) const {
      return s1 == s2;
    }
    bool operator()(const std::string& s1, const boost::string_view& v2) const {
      return v2 == s1;
    }
    bool operator()(const boost::string_view& v1, const std::string& s2) const {
      return v1 == s2;
    }
    bool operator()(const boost::string_view& v1,
                    const boost::string_view& v2) const {
      return v1 == v2;
    }
  };
  using UnresolvedMethodMeta = multi_index_container<
      std::pair<boost::string_view, StringPos>,
      indexed_by<hashed_unique<
          member<std::pair<boost::string_view, StringPos>,
                 boost::string_view,
                 &std::pair<boost::string_view, StringPos>::first>,
          boost::hash<boost::string_view>,
          StringViewEquals>>>;

  UnresolvedMethodMeta unresolved_method_meta;

  ProfileFile(RedexMappedFile mapped_file,
              std::string interaction,
              MethodMeta method_meta,
              UnresolvedMethodMeta unresolved_method_meta)
      : mapped_file(std::move(mapped_file)),
        interaction(std::move(interaction)),
        method_meta(std::move(method_meta)),
        unresolved_method_meta(std::move(unresolved_method_meta)) {}

  static std::unique_ptr<ProfileFile> prepare_profile_file(
      const std::string& profile_file_name) {
    if (profile_file_name.empty()) {
      return std::unique_ptr<ProfileFile>();
    }
    auto file = RedexMappedFile::open(profile_file_name, /*read_only=*/true);
    MethodMeta meta;
    UnresolvedMethodMeta unresolved_meta;

    boost::string_view data{file.const_data(), file.size()};
    size_t pos = 0;
    std::string interaction;

    // Read header.
    {
      auto next_line_fn = [&data, &pos]() {
        always_assert(pos < data.size());
        size_t newline_pos = data.find('\n', pos);
        always_assert(newline_pos != std::string::npos);
        auto ret = data.substr(pos, newline_pos - pos);
        pos = newline_pos + 1;
        return ret;
      };
      auto check_components = [](const auto& line, size_t num = 0,
                                 const std::vector<std::string>& exp = {}) {
        std::vector<std::string> split_vec;
        boost::split(split_vec, line, [](const auto& c) { return c == ','; });
        always_assert_log(num == 0 ? split_vec == exp : split_vec.size() == num,
                          "Unexpected line: %s (%s). Expected %s/%zu.",
                          line.to_string().c_str(),
                          boost::join(split_vec, "'").c_str(),
                          boost::join(exp, ",").c_str(), num);
        return split_vec;
      };
      check_components(next_line_fn(), 0, {"interaction", "appear#"});
      {
        auto line = next_line_fn();
        std::vector<std::string> split_vec;
        boost::split(split_vec, line, [](const auto& c) { return c == ','; });
        always_assert(split_vec.size() == 2);
        interaction = std::move(split_vec[0]);
      }
      check_components(next_line_fn(), 0, {"name", "profiled_srcblks_exprs"});
    }

    while (pos < data.length()) {
      const size_t src_pos = pos;

      // Find the next '\n' or EOF.
      size_t linefeed_pos = data.find('\n', src_pos);
      if (linefeed_pos == std::string::npos) {
        linefeed_pos = data.length();
      }
      pos = linefeed_pos + 1;
      // Do not use pos anymore! Ensure by scope from lambda.
      [&data, &src_pos, &linefeed_pos, &meta, &unresolved_meta]() {
        size_t comma_pos = data.find(',', src_pos);
        always_assert(comma_pos < linefeed_pos);

        auto string_pos =
            std::make_pair(comma_pos + 1, linefeed_pos - comma_pos - 1);

        auto method_view = data.substr(src_pos, comma_pos - src_pos);
        // Would be nice to avoid the conversion.
        auto mref = DexMethod::get_method</*kCheckFormat=*/true>(
            method_view.to_string());
        if (mref == nullptr) {
          TRACE(METH_PROF,
                6,
                "failed to resolve %s",
                method_view.to_string().c_str());
          unresolved_meta.emplace(method_view, string_pos);
          return;
        }
        meta.emplace(mref, string_pos);
      }();
    }

    return std::make_unique<ProfileFile>(
        std::move(file), std::move(interaction), std::move(meta),
        std::move(unresolved_meta));
  }
};

boost::optional<SourceBlock::Val> maybe_val_from_mp(
    const method_profiles::MethodProfiles& method_profiles,
    const std::string& interaction,
    const DexMethodRef* mref) {
  if (!method_profiles.has_stats()) {
    return boost::none;
  }

  const auto& mp_map = method_profiles.all_interactions();
  const auto& inter_it = mp_map.find(interaction);
  if (inter_it == mp_map.end()) {
    return boost::none;
  }

  const auto& inter_map = inter_it->second;
  auto it = inter_map.find(mref);
  if (it == inter_map.end()) {
    return boost::none;
  }

  // For now, just convert to coverage. Having stats means it's not zero.
  redex_assert(it->second.call_count > 0);
  return SourceBlock::Val(1, it->second.appear_percent);
}

void run_source_blocks(DexStoresVector& stores,
                       ConfigFiles& conf,
                       PassManager& mgr,
                       bool serialize,
                       bool exc_inject,
                       bool always_inject,
                       std::vector<std::unique_ptr<ProfileFile>>& profile_files,
                       const method_profiles::MethodProfiles& method_profiles,
                       const std::vector<std::string>& interactions) {
  auto scope = build_class_scope(stores);

  std::mutex serialized_guard;
  std::vector<std::pair<const DexMethod*, std::string>> serialized;
  size_t blocks{0};
  size_t profile_count{0};

  std::atomic<size_t> skipped{0};

  auto find_profiles = [&profile_files, &always_inject, &method_profiles,
                        &interactions](const DexMethodRef* mref) {
    std::vector<source_blocks::ProfileData> profiles;
    profiles.reserve(profile_files.size());

    auto val_to_str = [](const auto& v) -> std::string {
      if (!v) {
        return "x";
      }
      return std::to_string(v->val) + ":" + std::to_string(v->appear100);
    };
    auto maybe_val_to_str = [&val_to_str](const auto& val_opt) {
      return val_opt ? val_to_str(*val_opt) : "n/a";
    };

    if (profile_files.empty()) {
      if (always_inject) {
        // Some effort to recover from method profiles in general.
        redex_assert(method_profiles.has_stats() || interactions.empty());

        for (const auto& inter : interactions) {
          auto val_opt = maybe_val_from_mp(method_profiles, inter, mref);
          profiles.emplace_back(val_opt ? *val_opt : SourceBlock::Val(0, 0));
        }
      }
      return std::make_pair(std::move(profiles), false);
    }

    bool found_one = false;
    for (auto& profile_file : profile_files) {
      auto val_opt =
          maybe_val_from_mp(method_profiles, profile_file->interaction, mref);

      auto it = profile_file->method_meta.find(mref);
      if (it == profile_file->method_meta.end()) {
        if (always_inject) {
          TRACE(METH_PROF, 3,
                "No basic block profile for %s. Always-inject=true, falling "
                "back to method profiles: %s",
                SHOW(mref),
                [&]() {
                  if (!val_opt) {
                    return "no-profile=" + val_to_str(SourceBlock::Val(0, 0));
                  }
                  return "profile=" + val_to_str(*val_opt);
                }()
                    .c_str());
          profiles.emplace_back(val_opt ? *val_opt : SourceBlock::Val(0, 0));
        } else {
          TRACE(METH_PROF, 3,
                "No basic block profile for %s. Always-inject=false, not "
                "injecting.",
                SHOW(mref));
          profiles.emplace_back(std::nullopt);
        }
        continue;
      }
      found_one = true;
      const auto& pos = it->second;
      profiles.emplace_back(std::make_pair(
          std::string(profile_file->mapped_file.const_data() + pos.first,
                      pos.second),
          val_opt));
      TRACE(METH_PROF, 3,
            "Found basic block profile for %s. Error fallback is %s.",
            SHOW(mref), maybe_val_to_str(val_opt).c_str());
    }

    if (!found_one) {
      TRACE(METH_PROF, 2, "No basic block profile for %s!", SHOW(mref));
    }
    return std::make_pair(std::move(profiles), found_one);
  };

  walk::parallel::methods(scope, [&](DexMethod* method) {
    auto code = method->get_code();
    if (code != nullptr) {
      auto profiles = find_profiles(method);
      if (!profiles.second && !always_inject) {
        // Skip without profile.
        skipped.fetch_add(1);
        return;
      }

      auto res =
          source_blocks(method, code, profiles.first, serialize, exc_inject);
      std::unique_lock<std::mutex> lock(serialized_guard);
      serialized.emplace_back(method, std::move(res.serialized));
      blocks += res.block_count;
      profile_count += profiles.second ? 1 : 0;
    }
  });

  if (mgr.get_assessor_config().run_sb_consistency) {
    source_blocks::get_sbcc().initialize(scope);
  }

  mgr.set_metric("inserted_source_blocks", blocks);
  mgr.set_metric("handled_methods", serialized.size());
  mgr.set_metric("skipped_methods", skipped.load());
  mgr.set_metric("methods_with_profiles", profile_count);

  if (!serialize) {
    return;
  }

  std::sort(serialized.begin(),
            serialized.end(),
            [](const auto& lhs, const auto& rhs) {
              return compare_dexmethods(lhs.first, rhs.first);
            });

  std::ofstream ofs(conf.metafile("redex-source-blocks.csv"));
  ofs << "type,version\nredex-source-blocks,1\nname,serialized\n";
  for (const auto& p : serialized) {
    ofs << show(p.first) << "," << p.second << "\n";
  }
}

template <typename T, typename Fn>
void sort_coldstart_and_set_indices(T& container, const Fn& fn) {
  std::sort(container.begin(), container.end(),
            [&fn](const auto& lhs_in, const auto& rhs_in) {
              if (lhs_in == rhs_in) {
                return false;
              }
              const auto& lhs = fn(lhs_in);
              const auto& rhs = fn(rhs_in);
              if (lhs == rhs) {
                return false;
              }
              if (lhs == "ColdStart") {
                return true;
              }
              if (rhs == "ColdStart") {
                return false;
              }
              return lhs < rhs;
            });

  std::unordered_map<std::string, size_t> interaction_indices;
  for (size_t i = 0; i != container.size(); ++i) {
    interaction_indices[fn(container[i])] = i;
  }
  g_redex->set_sb_interaction_index(interaction_indices);
}

std::pair<std::vector<std::unique_ptr<ProfileFile>>, std::vector<std::string>>
prepare_profile_files_and_interactions(const std::string& profile_files_str,
                                       ConfigFiles& conf,
                                       bool always_inject) {
  std::vector<std::unique_ptr<ProfileFile>> profile_files;
  std::vector<std::string> interactions;

  if (!profile_files_str.empty()) {
    Timer t("reading files");
    std::vector<std::string> files;
    boost::split(files, profile_files_str, [](const auto& c) {
      constexpr char separator =
#if IS_WINDOWS
          ';';
#else
          ':';
#endif
      return c == separator;
    });

    profile_files.resize(files.size());
    std::vector<size_t> indices(files.size());
    std::iota(indices.begin(), indices.end(), 0);
    workqueue_run<size_t>(
        [&](size_t i) {
          profile_files.at(i) = ProfileFile::prepare_profile_file(files.at(i));
          TRACE(METH_PROF, 1, "Loaded basic block profile %s",
                profile_files.at(i)->interaction.c_str());
        },
        indices);

    // Sort the interactions.
    sort_coldstart_and_set_indices(
        profile_files,
        [](const auto& u) -> const std::string& { return u->interaction; });

    std::transform(profile_files.begin(), profile_files.end(),
                   std::back_inserter(interactions),
                   [](const auto& p) { return p->interaction; });
  } else if (always_inject) {
    // Need to recover interaction names from method profiles.
    if (conf.get_method_profiles().has_stats()) {
      const auto& mp_map = conf.get_method_profiles().all_interactions();
      std::transform(mp_map.begin(), mp_map.end(),
                     std::back_inserter(interactions),
                     [](const auto& p) { return p.first; });
      sort_coldstart_and_set_indices(
          interactions, [](const auto& s) -> const std::string& { return s; });
    }
  }

  return std::make_pair(std::move(profile_files), std::move(interactions));
}

} // namespace

void InsertSourceBlocksPass::bind_config() {
  bind("always_inject",
       m_always_inject,
       m_always_inject,
       "Always inject source blocks, even if profiles are missing.");
  bind("force_run", m_force_run, m_force_run);
  bind("force_serialize",
       m_force_serialize,
       m_force_serialize,
       "Force serialization of the CFGs. Testing only.");
  bind("insert_after_excs", m_insert_after_excs, m_insert_after_excs);
  bind("profile_files", "", m_profile_files);
}

void InsertSourceBlocksPass::run_pass(DexStoresVector& stores,
                                      ConfigFiles& conf,
                                      PassManager& mgr) {
  bool is_instr_mode = mgr.get_redex_options().instrument_pass_enabled;
  bool always_inject = m_always_inject || m_force_serialize || is_instr_mode;

  auto prep = prepare_profile_files_and_interactions(m_profile_files, conf,
                                                     always_inject);

  run_source_blocks(stores,
                    conf,
                    mgr,
                    /* serialize= */ m_force_serialize || is_instr_mode,
                    m_insert_after_excs,
                    /* always_inject= */ always_inject,
                    /* profile_files= */ prep.first,
                    conf.get_method_profiles(),
                    /* interactions= */ prep.second);
}

static InsertSourceBlocksPass s_pass;

max_stars_repo_name: dmitryvinn/redex

max_issues_repo_name: dmitryvinn/redex

max_forks_repo_name: dmitryvinn/redex


text:
/*
 * Copyright 2012 CarCV Development Team
 *
 * 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 "carcv.hpp"
#include "tools.hpp"

#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"

#include <boost/lexical_cast.hpp>

using namespace std;
using namespace cv;

namespace fs = boost::filesystem;

/*
 * Prints help information to cout
 */
void help()
{
	cout << "\nThis program demonstrates the cascade recognizer. Now you can use Haar or LBP features.\n"
			"This classifier can recognize many kinds of rigid objects, once the appropriate classifier is trained.\n"
			"It's most known use is for cars.\n"
			"Usage:\n"
			"./carcv [--cascade=<cascade_path> this is the primary trained classifier such as cars]\n"
			//"   [--nested-cascade[=nested_cascade_path this an optional secondary classifier such as headlights]]\n"
			"	[--scale=<image scale greater or equal to 1, try 1.3 for example> DO NOT EDIT, KEEP scale=1!]\n"
			//"   [--try-flip]\n"
			"   	[--method=<DETECTSORT+SORTUNIQUE+INSIDE+SPEED+> choose one or any combination, with +]\n"
			"   	[--speedbox=<x+y+width+height+> of Speed Box Rectangle (needed for method INSIDE)]\n"
			"	[--list=<list_path> path to list of images for given method(s)]\n"
			"   	[--posdir=<pos_dir> path where to put positive images]\n"
			"   	[--negdir=<neg_dir> path where to put negative images]\n"
			"   	[--cardir=<car_dir> path where to put unique car images]\n"
			"   	[--insidedir=<inside_dir> path where to put car images which are inside the SpeedBox]\n"
			"\n\n"
			"Example call:\n"
			"./carcv --cascade=\"haarcascade_cars.xml\" --scale=1 --list=list.txt --method=DETECTSORT+SORTUNIQUE\n\n"
			"During execution:\n\tHit any key to quit.\n"
			"\tUsing OpenCV version " << CV_VERSION << "\n" << endl;
}

string cascadeName = "/home/odenkos/soc/car_project/test/current.xml";
fs::path cascadePath = fs::absolute(cascadeName);

string listName = "list.txt";
fs::path listPath = fs::absolute(listName);

string methodName = "DETECTSORT";
string speedBoxStr = "0+0+0+0";

string posdir = "pos";
fs::path posDirPath = fs::absolute(posdir);

string negdir = "neg";
fs::path negDirPath = fs::absolute(negdir);

string cardir = "cars";
fs::path carDirPath = fs::absolute(cardir);

string insidedir = "inside";
fs::path insideDirPath = fs::absolute(insidedir);

const double scale = 1;

/*
 * Starting method that manages input arguments and the program flow
 */
int starter(int argc, char** argv) {
	const string scaleOpt = "--scale=";
	size_t scaleOptLen = scaleOpt.length();

	const string cascadeOpt = "--cascade=";
	size_t cascadeOptLen = cascadeOpt.length();

	const string methodOpt = "--method=";
	size_t methodOptLen = methodOpt.length();

	const string listOpt = "--list=";
	size_t listOptLen = listOpt.length();

	const string speedBoxOpt = "--speedbox=";
	size_t speedBoxOptLen = speedBoxOpt.length();

	const string posDirOpt = "--posdir=";
	size_t posDirOptLen = posDirOpt.length();

	const string negDirOpt = "--negdir=";
	size_t negDirOptLen = negDirOpt.length();

	const string carDirOpt = "--cardir=";
	size_t carDirOptLen = carDirOpt.length();

	const string insideDirOpt = "--insidedir=";
	size_t insideDirOptLen = insideDirOpt.length();

	string inputName;

	help();

	Rect speedBox;
	CascadeClassifier cascade;
	double scale = 1;

	for( int i = 1; i < argc; i++ )
	{
		cout << "Processing " << i << " " <<  argv[i] << endl;
		if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 )
		{
			cascadeName.assign( argv[i] + cascadeOptLen );
			cascadePath = fs::absolute(fs::path(cascadeName));
			cout << "  from which we have cascade=" << cascadePath.c_str() << endl;
		}
		else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 )
		{
			if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 )
				scale = 1;
			cout << " from which we read scale = " << scale << endl;
		}
		else if( methodOpt.compare( 0, methodOptLen, argv[i], methodOptLen ) == 0 )
		{
			methodName.assign( argv[i] + methodOptLen );
			cout << "  from which we have method=" << methodName << endl;
		}
		else if( speedBoxOpt.compare( 0, speedBoxOptLen, argv[i], speedBoxOptLen ) == 0 )
		{
			speedBoxStr.assign( argv[i] + speedBoxOptLen );
			double dimensions[4];
			int index = 0;
			ostringstream oss;
			for (string::iterator i = speedBoxStr.begin(); i != speedBoxStr.end(); i++) {
				if(*i == '+') {
					dimensions[index] = atof(oss.str().c_str());
					index++;
					oss.str("");
					continue;
				}
				oss << *i;
			}

			double x = dimensions[0];
			double y = dimensions[1];
			double width = dimensions[2];
			double height = dimensions[3];

			speedBox = Rect(x, y, width, height);

			cout << "  from which we have speedbox=" << x << "," << y << "," << width << "," << height << endl;
		}
		else if( listOpt.compare( 0, listOptLen, argv[i], listOptLen ) == 0 )
		{
			listName.assign( argv[i] + listOptLen );
			listPath = fs::absolute(fs::path(listName));
			cout << "  from which we have list=" << listPath.c_str() << endl;
		}
		else if( posDirOpt.compare( 0, posDirOptLen, argv[i], posDirOptLen ) == 0 )
		{
			posdir.assign( argv[i] + posDirOptLen );
			posDirPath = fs::absolute(fs::path(posdir));
			cout << "  from which we have posdir=" << posDirPath.c_str() << endl;
		}
		else if( negDirOpt.compare( 0, negDirOptLen, argv[i], negDirOptLen ) == 0 )
		{
			negdir.assign( argv[i] + negDirOptLen );
			negDirPath = fs::absolute(fs::path(negdir));
			cout << "  from which we have negdir=" << negDirPath.c_str() << endl;
		}
		else if( carDirOpt.compare( 0, carDirOptLen, argv[i], carDirOptLen ) == 0 )
		{
			cardir.assign( argv[i] + carDirOptLen );
			carDirPath = fs::absolute(fs::path(cardir));
			cout << "  from which we have cardir=" << carDirPath.c_str() << endl;
		}
		else if( insideDirOpt.compare( 0, insideDirOptLen, argv[i], insideDirOptLen ) == 0 )
		{
			insidedir.assign( argv[i] + insideDirOptLen );
			insideDirPath = fs::absolute(fs::path(insidedir));
			cout << "  from which we have insidedir=" << insideDirPath.c_str() << endl;
		}
		else if( argv[i][0] == '-' )
		{
			cerr << "WARNING: Unknown option %s" << argv[i] << endl;
		}
		else
			inputName.assign( argv[i] );
	}

	if( !cascade.load( cascadeName ) )
	{
		Tools::errorMessage("Could not load classifier cascade at path: " + boost::lexical_cast<string>(cascadePath));
		return 1;
	}
	else if(!fs::exists(listPath)) {
		Tools::errorMessage("List at path: "+ boost::lexical_cast<string>(listPath) + " doesn't exist");
		return 1;
	}
	else if(!fs::is_regular_file(listPath)) {
		Tools::errorMessage("List at path: " + boost::lexical_cast<string>(listPath) + " isn't a valid file");
		return 1;
	}

	cout << endl << endl << endl;
	Tools::debugMessage("LOADING FINISHED");

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

	double t1, t2, Tstart, Tend;
	double tickspersecond=cvGetTickFrequency() * 1.0e6;
	Tstart = (double) cvGetTickCount();

	if(methodName.find("DETECTSORT")!=string::npos)
	{

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START parseList()");
		list<string> strImgList = Tools::parseList(listPath); //parse image list file to list<string>
		Tools::debugMessage("END parseList()");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START loadCarImgList()");
		list<CarImg> imgList = FileIO::loadCarImgList(strImgList); //load CarImg objects from the list
		Tools::debugMessage("END loadCarImgList()");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

		list<CarImg> negList;

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START detect_sortPOS_AND_NEG()");
		list<CarImg> posCarImgList = CarCV::detect_sortPOS_AND_NEG(imgList, cascade, &negList, scale);//detect and sort objects in images of imgList
		Tools::debugMessage("END detect_sortPOS_AND_NEG()");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

		//printing lists
		/*
		cout << endl << endl << endl;
		cout << "-------------------------------------------------" << endl;
		cout << "POSITIVE IMAGES" << endl;
		cout << "-------------------------------------------------" << endl;
		int index = 0;
		for (list<CarImg>::iterator i = posCarImgList.begin(); i != posCarImgList.end(); i++) {
			cout << index << ". " << (*i).getPath() << endl;

			index++;
		}

		cout << endl << endl << endl;
		cout << "-------------------------------------------------" << endl;
		cout << "NEGATIVE IMAGES" << endl;
		cout << "-------------------------------------------------" << endl;
		index = 0;
		for (list<CarImg>::iterator i = negList.begin(); i != negList.end(); i++) {
			cout << index << ". " << (*i).getPath() << endl;

			index++;
		}
		 */
		//printing lists

		//saveing
		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START saveCarImgList(pos)");
		FileIO::saveCarImgList(posCarImgList, posDirPath);
		Tools::debugMessage("END saveCarImgList(pos)");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START saveCarImgList(neg)");
		FileIO::saveCarImgList(negList, negDirPath);
		Tools::debugMessage("END saveCarImgList(neg)");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

	}

	if(methodName.find("SORTUNIQUE")!=string::npos)
	{

		list<CarImg> posCarImgList = FileIO::loadCarImgList(posDirPath);

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START sortUnique(pos)");
		list<list<CarImg> > cars = CarCV::sortUnique(posCarImgList, cascade, 0.2);
		Tools::debugMessage("END sortUnique(pos)");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

		//printing lists

		cout << endl << endl << endl;
		cout << "-------------------------------------------------" << endl;
		cout << "CARS" << endl;
		cout << "-------------------------------------------------" << endl;
		int indexi = 0;
		int indexj = 0;
		list<CarImg> line;
		for (list<list<CarImg> >::iterator i = cars.begin(); i != cars.end(); i++) {
			line = *i;
			for (list<CarImg>::iterator j = line.begin(); j != line.end(); j++){
				cout << "[" << indexi << ":" << indexj << "]	 " << (*j).getPath() << endl;
				indexj++;
			}
			indexj = 0;
			indexi++;
		}
		//printing lists

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START saveCars()");
		FileIO::saveCars(cars, carDirPath);
		Tools::debugMessage("END saveCars()");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

	}

	if(methodName.find("INSIDE") != string::npos)
	{

		list<list<CarImg> > cars = FileIO::loadCars(carDirPath);

		list<CarImg> * carlist;
		const int carsSize = cars.size();

		list<list<CarImg> > carsInSpeedBox;

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START isInSpeedBox()");

		for (int i = 0; i < carsSize; i++) {
			carlist = Tools::atList(&cars, i);
			carlist->sort();

			carsInSpeedBox.push_back(CarCV::inSpeedBox(*carlist, cascade, speedBox, scale));
		}

		Tools::debugMessage("END isInSpeedBox()");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START saveCarsInside()");
		FileIO::saveCars(carsInSpeedBox, insideDirPath);
		Tools::debugMessage("END saveCarsInside()");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

		//printing lists

		cout << endl << endl << endl;
		cout << "-------------------------------------------------" << endl;
		cout << "INSIDE CARS" << endl;
		cout << "-------------------------------------------------" << endl;
		int indexi = 0;
		int indexj = 0;
		list<CarImg> line;
		for (list<list<CarImg> >::iterator i = carsInSpeedBox.begin(); i != carsInSpeedBox.end(); i++) {
			line = *i;
			for (list<CarImg>::iterator j = line.begin(); j != line.end(); j++){
				cout << "[" << indexi << ":" << indexj << "]	 " << (*j).getPath() << endl;
				indexj++;
			}
			indexj = 0;
			indexi++;
		}
		//printing lists

		cout << endl << endl << endl;

	}

	if(methodName.find("SPEED") != string::npos)
	{

		list<list<CarImg> > carsInSpeedBox = FileIO::loadCars(insideDirPath);

		list<CarImg> * carlist;

		const int carsInSpeedBoxSize = carsInSpeedBox.size();
		double speed;

		t1 = (double) cvGetTickCount();
		Tools::debugMessage("START calcSpeed()");
		for (int i = 0; i < carsInSpeedBoxSize; i++) {
			carlist = Tools::atList(&carsInSpeedBox, i);

			speed = CarCV::calcSpeed(*carlist, SP_ID_DIFF, 30, 10);
			cout << "Car" << i << " speed:	" << speed << " km/h" << endl;
		}
		Tools::debugMessage("END calcSpeed()");
		t2 = (double) cvGetTickCount() - t1;
		cout << "TIME:		" << (t2/(double)tickspersecond) << "s" << endl;
		cout << endl;

	}

	cout << endl << endl;
	Tend = (double) cvGetTickCount() - Tstart;
	cout << "TOTALTIME:		" << (Tend/(double)tickspersecond) << "s" << endl;

	return 0;

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

}

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

	return starter(argc, argv);
}

ext: cpp

max_stars_repo_name: oskopek/carcv

max_issues_repo_name: oskopek/carcv

max_forks_repo_name: oskopek/carcv


text: #include <boost/test/results_reporter.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright 2014 Jonathan Graehl-http://graehl.org/
//
// 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.
#ifndef GRAEHL__SHARED__TIME_REPORT_HPP
#define GRAEHL__SHARED__TIME_REPORT_HPP
#pragma once

#ifndef USE_BOOST_TIMER_TIMER
#if (BOOST_VERSION / 100000) >= 1 && ((BOOST_VERSION / 100) % 1000) >= 48
#define USE_BOOST_TIMER_TIMER 1
#else
#define USE_BOOST_TIMER_TIMER 0
#endif
#endif

#include <graehl/shared/auto_report.hpp>
#if USE_BOOST_TIMER_TIMER
//# include <boost/time/cpu_timer.hpp>
#ifndef BOOST_SYSTEM_NO_DEPRECATED
#define BOOST_SYSTEM_NO_DEPRECATED 1
#endif
#include <boost/chrono/chrono.hpp>
#include <boost/config.hpp>
#include <boost/timer/timer.hpp>
#else
#include <graehl/shared/stopwatch.hpp>
#endif
#include <graehl/shared/print_read.hpp>
#include <graehl/shared/print_width.hpp>

namespace graehl {

struct time_change {
  static char const* default_desc() { return "\nelapsed: "; }
#if USE_BOOST_TIMER_TIMER
  boost::timer::cpu_timer time;
  double elapsed_wall() const { return time.elapsed().wall * .000000001; }
  double elapsed() const {
    boost::timer::cpu_times t = time.elapsed();
    return .000000001 * (t.system + t.user);
  }
  void start() { time.start(); }
  void resume() { time.resume(); }
#else
  stopwatch time;
  void start() { time.reset(); }
  void resume() { time.start(); }
  double elapsed() const { return const_cast<stopwatch&>(time).total_time(); }
#endif
  void stop() { time.stop(); }
  void reset() {
#if USE_BOOST_TIMER_TIMER
    start();
    stop();
#else
    time.reset(false);
#endif
  }

  template <class O>
  void print(O& o) const {
    print_width(o, elapsed(), 6) << " sec";
  }

  typedef time_change self_type;
  TO_OSTREAM_PRINT
};

typedef auto_report<time_change> time_report;

}

#endif

max_stars_repo_name: graehl/carmel

max_issues_repo_name: graehl/carmel

max_forks_repo_name: graehl/carmel


text:
// Arguments: Doubles, Doubles, Doubles
#include <stan/math/prim/scal.hpp>
#include <boost/utility/enable_if.hpp>

using stan::math::var;
using std::numeric_limits;
using std::vector;

class AgradDistributionsBeta : public AgradDistributionTest {
 public:
  void valid_values(vector<vector<double> >& parameters,
                    vector<double>& log_prob) {
    vector<double> param(3);

    param[0] = 0.4;  // y
    param[1] = 0.5;  // alpha
    param[2] = 0.5;  // beta
    parameters.push_back(param);
    log_prob.push_back(-0.4311717080293276382896);  // expected log_prob

    param[0] = 0.5;  // y
    param[1] = 2.0;  // alpha
    param[2] = 5.0;  // beta
    parameters.push_back(param);
    log_prob.push_back(-0.06453852113757105324332);  // expected log_prob
  }

  void invalid_values(vector<size_t>& index, vector<double>& value) {
    // y
    index.push_back(0U);
    value.push_back(-1.0);

    index.push_back(0U);
    value.push_back(2.0);

    // alpha
    index.push_back(1U);
    value.push_back(0.0);

    index.push_back(1U);
    value.push_back(-1.0);

    index.push_back(1U);
    value.push_back(numeric_limits<double>::infinity());

    index.push_back(1U);
    value.push_back(-numeric_limits<double>::infinity());

    // beta
    index.push_back(2U);
    value.push_back(0.0);

    index.push_back(2U);
    value.push_back(-1.0);

    index.push_back(2U);
    value.push_back(numeric_limits<double>::infinity());

    index.push_back(2U);
    value.push_back(-numeric_limits<double>::infinity());
  }

  template <typename T_y, typename T_scale1, typename T_scale2, typename T3,
            typename T4, typename T5>
  typename stan::return_type<T_y, T_scale1, T_scale2>::type log_prob(
      const T_y& y, const T_scale1& alpha, const T_scale2& beta, const T3&,
      const T4&, const T5&) {
    return stan::math::beta_log(y, alpha, beta);
  }

  template <bool propto, typename T_y, typename T_scale1, typename T_scale2,
            typename T3, typename T4, typename T5>
  typename stan::return_type<T_y, T_scale1, T_scale2>::type log_prob(
      const T_y& y, const T_scale1& alpha, const T_scale2& beta, const T3&,
      const T4&, const T5&) {
    return stan::math::beta_log<propto>(y, alpha, beta);
  }

  template <typename T_y, typename T_scale1, typename T_scale2, typename T3,
            typename T4, typename T5>
  typename stan::return_type<T_y, T_scale1, T_scale2, T3, T4, T5>::type
  log_prob_function(const T_y& y, const T_scale1& alpha, const T_scale2& beta,
                    const T3&, const T4&, const T5&) {
    using stan::math::log1m;
    using std::log;

    return (alpha - 1.0) * log(y) + (beta - 1.0) * log1m(y)
           + lgamma(alpha + beta) - lgamma(alpha) - lgamma(beta);
  }
};

max_stars_repo_name: jrmie/math

max_issues_repo_name: jrmie/math

max_forks_repo_name: jrmie/math