<commit_before>#include "robobo.h"

int main(int argc, char** argv) {
	std::string confDir = argv[0]; // look in directory with robobo executable by default
	confDir = confDir.substr(0, confDir.find_last_of('/'));
	std::string confName = "robobo.conf"; // look for robobo.conf by default
	unsigned short debug = 0;
	if (argc > 1) { // analyze arguments
		bool exitAfter = false;
		for (int i = 1; i < argc; i++) { // iterate through all arguments
			if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {
				std::cout << "RoBoBo-IRC-BoBo IRC Bot Help" << std::endl;
				std::cout << std::endl;
				std::cout << "RoBoBo can connect to IRC servers.  All of its functionality outside of" << std::endl << "connecting to servers is provided by loaded modules." << std::endl;
				std::cout << "See the README file for more information." << std::endl;
				std::cout << std::endl;
				std::cout << "Some command line arguments are provided to perform certain actions.  With no" << std::endl << "parameters, the bot will run as a bot.  With some command line arguments, the" << std::endl << "functionality of the bot can be changed." << std::endl;
				std::cout << "Command Line Arguments:" << std::endl;
				std::cout << "\t--help: display this help and exit" << std::endl;
				std::cout << "\t\t-h: same as --help" << std::endl;
				std::cout << "\t\t-?: same as --help" << std::endl;
				std::cout << "\t--version: display RoBoBo's version and exit" << std::endl;
				std::cout << "\t\t-v: same as --version" << std::endl;
				std::cout << "\t--confdir <directory>: make RoBoBo look in the specified directory for the configuration instead of current directory" << std::endl;
				std::cout << "\t--confname <filename>: make RoBoBo look for the specified file in the conf directory for configuration information" << std::endl;
				std::cout << "\t--debug: make RoBoBo enter debug mode" << std::endl;
				std::cout << "\t\t-d: same as --debug" << std::endl;
				exitAfter = true;
			} else if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
				std::cout << "RoBoBo-IRC-BoBo Version 1.0.0 Alpha 1" << std::endl;
				exitAfter = true;
			} else if (strcmp(argv[i], "--confdir") == 0) {
				if (++i >= argc) {
					std::cout << "An argument was not specified for the --confdir argument." << std::endl;
					return 0;
				}
				confDir = argv[i];
				std::cout << "Looking for the configuration file in " << confDir << std::endl;
			} else if (strcmp(argv[i], "--confname") == 0) {
				if (++i >= argc) {
					std::cout << "An argument was not specified for the --confname argument." << std::endl;
					return 0;
				}
				confName = argv[i];
				std::cout << "Looking for a configuration file named " << confName << std::endl;
			} else if (strcmp(argv[i], "--debug") == 0 || strcmp(argv[i], "-d") == 0) {
				if (i+1 >= argc || !(strcmp(argv[i+1], "0") == 0 || strcmp(argv[i+1], "1") == 0 || strcmp(argv[i+1], "2") == 0 || strcmp(argv[i+1], "3") == 0 || strcmp(argv[i+1], "4") == 0 || strcmp(argv[i+1], "5") == 0))
					debug = 1;
				else {
					std::istringstream debugNum (argv[++i]);
					debugNum >> debug;
				}
				std::cout << "Setting debug mode with level " << debug << std::endl;
			}
			std::cout << std::endl; // add a newline after a parameter's output
		}
		if (exitAfter)
			return 0;
	}
	if (debug == 0)
		daemon(1,0);
	new ModuleInterface (confDir, confName, debug); //run actual bot
	pthread_exit(NULL);
}<commit_msg>Add confirmation that the bot actually started and didn't die or something.<commit_after>#include "robobo.h"

int main(int argc, char** argv) {
	std::string confDir = argv[0]; // look in directory with robobo executable by default
	confDir = confDir.substr(0, confDir.find_last_of('/'));
	std::string confName = "robobo.conf"; // look for robobo.conf by default
	unsigned short debug = 0;
	if (argc > 1) { // analyze arguments
		bool exitAfter = false;
		for (int i = 1; i < argc; i++) { // iterate through all arguments
			if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0) {
				std::cout << "RoBoBo-IRC-BoBo IRC Bot Help" << std::endl;
				std::cout << std::endl;
				std::cout << "RoBoBo can connect to IRC servers.  All of its functionality outside of" << std::endl << "connecting to servers is provided by loaded modules." << std::endl;
				std::cout << "See the README file for more information." << std::endl;
				std::cout << std::endl;
				std::cout << "Some command line arguments are provided to perform certain actions.  With no" << std::endl << "parameters, the bot will run as a bot.  With some command line arguments, the" << std::endl << "functionality of the bot can be changed." << std::endl;
				std::cout << "Command Line Arguments:" << std::endl;
				std::cout << "\t--help: display this help and exit" << std::endl;
				std::cout << "\t\t-h: same as --help" << std::endl;
				std::cout << "\t\t-?: same as --help" << std::endl;
				std::cout << "\t--version: display RoBoBo's version and exit" << std::endl;
				std::cout << "\t\t-v: same as --version" << std::endl;
				std::cout << "\t--confdir <directory>: make RoBoBo look in the specified directory for the configuration instead of current directory" << std::endl;
				std::cout << "\t--confname <filename>: make RoBoBo look for the specified file in the conf directory for configuration information" << std::endl;
				std::cout << "\t--debug: make RoBoBo enter debug mode" << std::endl;
				std::cout << "\t\t-d: same as --debug" << std::endl;
				exitAfter = true;
			} else if (strcmp(argv[i], "--version") == 0 || strcmp(argv[i], "-v") == 0) {
				std::cout << "RoBoBo-IRC-BoBo Version 1.0.0 Alpha 1" << std::endl;
				exitAfter = true;
			} else if (strcmp(argv[i], "--confdir") == 0) {
				if (++i >= argc) {
					std::cout << "An argument was not specified for the --confdir argument." << std::endl;
					return 0;
				}
				confDir = argv[i];
				std::cout << "Looking for the configuration file in " << confDir << std::endl;
			} else if (strcmp(argv[i], "--confname") == 0) {
				if (++i >= argc) {
					std::cout << "An argument was not specified for the --confname argument." << std::endl;
					return 0;
				}
				confName = argv[i];
				std::cout << "Looking for a configuration file named " << confName << std::endl;
			} else if (strcmp(argv[i], "--debug") == 0 || strcmp(argv[i], "-d") == 0) {
				if (i+1 >= argc || !(strcmp(argv[i+1], "0") == 0 || strcmp(argv[i+1], "1") == 0 || strcmp(argv[i+1], "2") == 0 || strcmp(argv[i+1], "3") == 0 || strcmp(argv[i+1], "4") == 0 || strcmp(argv[i+1], "5") == 0))
					debug = 1;
				else {
					std::istringstream debugNum (argv[++i]);
					debugNum >> debug;
				}
				std::cout << "Setting debug mode with level " << debug << std::endl;
			}
			std::cout << std::endl; // add a newline after a parameter's output
		}
		if (exitAfter)
			return 0;
	}
	if (debug == 0) {
		std::cout << "RoBoBo-IRC-BoBo started.  Forking..." << std::endl;
		daemon(1,0);
	}
	new ModuleInterface (confDir, confName, debug); //run actual bot
	pthread_exit(NULL);
}<|endoftext|>


<commit_before>#include "dreal/smt2/driver.h"

#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>

#include <fmt/format.h>
#include <fmt/ostream.h>

#include "dreal/smt2/scanner.h"
#include "dreal/solver/expression_evaluator.h"
#include "dreal/symbolic/prefix_printer.h"
#include "dreal/util/optional.h"

namespace dreal {

using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::istream;
using std::istringstream;
using std::ostream;
using std::ostringstream;
using std::runtime_error;
using std::string;
using std::stringstream;
using std::vector;

namespace {}  // namespace

FunctionDefinition::FunctionDefinition(vector<Variable> parameters,
                                       Sort return_type, Term body)
    : parameters_{std::move(parameters)},
      return_type_{return_type},
      body_{std::move(body)} {}

Term FunctionDefinition::operator()(const vector<Term>& arguments) const {
  if (parameters_.size() != arguments.size()) {
    throw runtime_error{
        fmt::format("This function definition expects {} arguments whereas the "
                    "provided arguments are of length {}.",
                    parameters_.size(), arguments.size())};
  }

  body_.Check(return_type_);
  Term t = body_;
  for (size_t i = 0; i < parameters_.size(); ++i) {
    const Variable& param_i{parameters_[i]};
    const Term& arg_i{arguments[i]};
    arg_i.Check(param_i.get_type());
    t = t.Substitute(param_i, arg_i);
  }

  return t;
}

Smt2Driver::Smt2Driver(Context context) : context_{std::move(context)} {}

bool Smt2Driver::parse_stream(istream& in, const string& sname) {
  streamname_ = sname;

  Smt2Scanner new_scanner(&in);
  new_scanner.set_debug(trace_scanning_);
  this->scanner = &new_scanner;

  Smt2Parser parser(*this);
  parser.set_debug_level(trace_parsing_);
  return (parser.parse() == 0);
}

bool Smt2Driver::parse_file(const string& filename) {
  if (filename.empty()) {
    // Option --in passed to dreal.
    return parse_stream(cin, "(stdin)");
  }
  ifstream in(filename.c_str());
  if (!in.good()) {
    return false;
  }
  return parse_stream(in, filename);
}

bool Smt2Driver::parse_string(const string& input, const string& sname) {
  istringstream iss(input);
  return parse_stream(iss, sname);
}

void Smt2Driver::error(const location& l, const string& m) {
  cerr << l << " : " << m << endl;
}

void Smt2Driver::error(const string& m) { cerr << m << endl; }

void Smt2Driver::CheckSat() {
  const optional<Box> model{context_.CheckSat()};
  if (model) {
    if (context_.config().smtlib2_compliant()) {
      cout << "delta-sat\n";
    } else {
      cout << "delta-sat with delta = " << context_.config().precision()
           << "\n";
      if (context_.config().produce_models()) {
        cout << *model << endl;
      }
    }
  } else {
    cout << "unsat" << endl;
  }
}

namespace {
ostream& PrintModel(ostream& os, const Box& box) {
  os << "(model\n";
  for (int i = 0; i < box.size(); ++i) {
    const Variable& var{box.variable(i)};
    os << "  (define-fun " << var << " () ";
    switch (var.get_type()) {
      case Variable::Type::CONTINUOUS:
        os << Sort::Real;
        break;
      case Variable::Type::BINARY:
        os << Sort::Binary;
        break;
      case Variable::Type::INTEGER:
        os << Sort::Int;
        break;
      case Variable::Type::BOOLEAN:
        os << Sort::Bool;
        break;
    }
    os << " ";
    const Box::Interval& iv{box[i]};
    if (var.get_type() == Variable::Type::BOOLEAN) {
      if (iv == iv.ONE) {
        os << "true";
      } else if (iv == iv.ZERO) {
        os << "false";
      }
    } else {
      if (iv.is_degenerated()) {
        os << iv.lb();
      } else {
        os << iv;
      }
    }
    os << ")\n";
  }
  return os << ")";
}
}  // namespace

void Smt2Driver::GetModel() const {
  const Box& box{context_.get_model()};
  if (box.empty()) {
    cout << "(error \"model is not available\")" << endl;
  } else {
    PrintModel(cout, box) << endl;
  }
}

void Smt2Driver::GetValue(const vector<Term>& term_list) const {
  const Box& box{context_.get_model()};
  fmt::print("(\n");
  for (const auto& term : term_list) {
    string term_str;
    string value_str;
    stringstream ss;
    PrefixPrinter pp{ss};

    switch (term.type()) {
      case Term::Type::EXPRESSION: {
        const Expression& e{term.expression()};
        const ExpressionEvaluator evaluator{e};
        pp.Print(e);
        term_str = ss.str();
        value_str =
            fmt::format("{}", ExpressionEvaluator(term.expression())(box));
        break;
      }
      case Term::Type::FORMULA: {
        const Formula& f{term.formula()};
        pp.Print(f);
        term_str = ss.str();
        if (is_variable(f)) {
          value_str =
              box[get_variable(f)] == Box::Interval::ONE ? "true" : "false";
        } else {
          throw std::runtime_error(fmt::format(
              "get-value does not handle a compound formula {}.", term_str));
        }
        break;
      }
    }

    fmt::print("\t({} {})\n", term_str, value_str);
  }
  fmt::print(")\n");
}

void Smt2Driver::GetOption(const string& key) const {
  const optional<string> value{context_.GetOption(key)};
  if (value) {
    fmt::print("{}\n", *value);
  } else {
    fmt::print("unsupported\n");
  }
}

Variable Smt2Driver::RegisterVariable(const string& name, const Sort sort) {
  const Variable v{ParseVariableSort(name, sort)};
  scope_.insert(v.get_name(), v);
  return v;
}

Variable Smt2Driver::DeclareVariable(const string& name, const Sort sort) {
  Variable v{RegisterVariable(name, sort)};
  context_.DeclareVariable(v);
  return v;
}

void Smt2Driver::DeclareVariable(const string& name, const Sort sort,
                                 const Term& lb, const Term& ub) {
  const Variable v{RegisterVariable(name, sort)};
  context_.DeclareVariable(v, lb.expression(), ub.expression());
}

void Smt2Driver::DefineFun(const string& name,
                           const vector<Variable>& parameters, Sort return_type,
                           const Term& body) {
  FunctionDefinition func{parameters, return_type, body};
  function_definition_map_.insert(name, func);
}

string Smt2Driver::MakeUniqueName(const string& name) {
  ostringstream oss;
  // The \ character ensures that the name cannot occur in an SMT-LIBv2 file.
  oss << "L" << nextUniqueId_++ << "\\" << name;
  return oss.str();
}

Term Smt2Driver::LookupFunction(const string& name,
                                const vector<Term>& arguments) {
  const auto it = function_definition_map_.find(name);
  if (it != function_definition_map_.end()) {
    return it->second(arguments);
  } else {
    throw runtime_error{fmt::format("No function definition for {}.", name)};
  }
}

Variable Smt2Driver::DeclareLocalVariable(const string& name, const Sort sort) {
  const Variable v{ParseVariableSort(MakeUniqueName(name), sort)};
  scope_.insert(name, v);  // v is not inserted under its own name.
  context_.DeclareVariable(
      v, false /* This local variable is not a model variable. */);
  return v;
}

const Variable& Smt2Driver::lookup_variable(const string& name) {
  const auto it = scope_.find(name);
  if (it == scope_.cend()) {
    throw DREAL_RUNTIME_ERROR("{} is an undeclared variable.", name);
  }
  return it->second;
}

Variable Smt2Driver::ParseVariableSort(const string& name, const Sort s) {
  return Variable{name, SortToType(s)};
}

Formula Smt2Driver::EliminateBooleanVariables(const Variables& vars,
                                              const Formula& f) {
  Formula ret{f};
  for (const auto& b : vars) {
    if (b.get_type() == Variable::Type::BOOLEAN) {
      ret = ret.Substitute(b, Formula::True()) &&
            ret.Substitute(b, Formula::False());
    }
  }
  return ret;
}

}  // namespace dreal
<commit_msg>fix(smt2): Flush cout after executing a command<commit_after>#include "dreal/smt2/driver.h"

#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>

#include <fmt/format.h>
#include <fmt/ostream.h>

#include "dreal/smt2/scanner.h"
#include "dreal/solver/expression_evaluator.h"
#include "dreal/symbolic/prefix_printer.h"
#include "dreal/util/optional.h"

namespace dreal {

using std::cerr;
using std::cin;
using std::cout;
using std::ifstream;
using std::istream;
using std::istringstream;
using std::ostream;
using std::ostringstream;
using std::runtime_error;
using std::string;
using std::stringstream;
using std::vector;

namespace {}  // namespace

FunctionDefinition::FunctionDefinition(vector<Variable> parameters,
                                       Sort return_type, Term body)
    : parameters_{std::move(parameters)},
      return_type_{return_type},
      body_{std::move(body)} {}

Term FunctionDefinition::operator()(const vector<Term>& arguments) const {
  if (parameters_.size() != arguments.size()) {
    throw runtime_error{
        fmt::format("This function definition expects {} arguments whereas the "
                    "provided arguments are of length {}.",
                    parameters_.size(), arguments.size())};
  }

  body_.Check(return_type_);
  Term t = body_;
  for (size_t i = 0; i < parameters_.size(); ++i) {
    const Variable& param_i{parameters_[i]};
    const Term& arg_i{arguments[i]};
    arg_i.Check(param_i.get_type());
    t = t.Substitute(param_i, arg_i);
  }

  return t;
}

Smt2Driver::Smt2Driver(Context context) : context_{std::move(context)} {}

bool Smt2Driver::parse_stream(istream& in, const string& sname) {
  streamname_ = sname;

  Smt2Scanner new_scanner(&in);
  new_scanner.set_debug(trace_scanning_);
  this->scanner = &new_scanner;

  Smt2Parser parser(*this);
  parser.set_debug_level(trace_parsing_);
  return (parser.parse() == 0);
}

bool Smt2Driver::parse_file(const string& filename) {
  if (filename.empty()) {
    // Option --in passed to dreal.
    return parse_stream(cin, "(stdin)");
  }
  ifstream in(filename.c_str());
  if (!in.good()) {
    return false;
  }
  return parse_stream(in, filename);
}

bool Smt2Driver::parse_string(const string& input, const string& sname) {
  istringstream iss(input);
  return parse_stream(iss, sname);
}

void Smt2Driver::error(const location& l, const string& m) {
  cerr << l << " : " << m << "\n";
}

void Smt2Driver::error(const string& m) { cerr << m << "\n"; }

void Smt2Driver::CheckSat() {
  const optional<Box> model{context_.CheckSat()};
  if (model) {
    if (context_.config().smtlib2_compliant()) {
      cout << "delta-sat\n";
    } else {
      cout << "delta-sat with delta = " << context_.config().precision()
           << "\n";
      if (context_.config().produce_models()) {
        cout << *model << "\n";
      }
    }
  } else {
    cout << "unsat\n";
  }
  cout.flush();
}

namespace {
ostream& PrintModel(ostream& os, const Box& box) {
  os << "(model\n";
  for (int i = 0; i < box.size(); ++i) {
    const Variable& var{box.variable(i)};
    os << "  (define-fun " << var << " () ";
    switch (var.get_type()) {
      case Variable::Type::CONTINUOUS:
        os << Sort::Real;
        break;
      case Variable::Type::BINARY:
        os << Sort::Binary;
        break;
      case Variable::Type::INTEGER:
        os << Sort::Int;
        break;
      case Variable::Type::BOOLEAN:
        os << Sort::Bool;
        break;
    }
    os << " ";
    const Box::Interval& iv{box[i]};
    if (var.get_type() == Variable::Type::BOOLEAN) {
      if (iv == iv.ONE) {
        os << "true";
      } else if (iv == iv.ZERO) {
        os << "false";
      }
    } else {
      if (iv.is_degenerated()) {
        os << iv.lb();
      } else {
        os << iv;
      }
    }
    os << ")\n";
  }
  return os << ")";
}
}  // namespace

void Smt2Driver::GetModel() const {
  const Box& box{context_.get_model()};
  if (box.empty()) {
    cout << "(error \"model is not available\")\n";
  } else {
    PrintModel(cout, box) << "\n";
  }
  cout.flush();
}

void Smt2Driver::GetValue(const vector<Term>& term_list) const {
  const Box& box{context_.get_model()};
  fmt::print("(\n");
  for (const auto& term : term_list) {
    string term_str;
    string value_str;
    stringstream ss;
    PrefixPrinter pp{ss};

    switch (term.type()) {
      case Term::Type::EXPRESSION: {
        const Expression& e{term.expression()};
        const ExpressionEvaluator evaluator{e};
        pp.Print(e);
        term_str = ss.str();
        value_str =
            fmt::format("{}", ExpressionEvaluator(term.expression())(box));
        break;
      }
      case Term::Type::FORMULA: {
        const Formula& f{term.formula()};
        pp.Print(f);
        term_str = ss.str();
        if (is_variable(f)) {
          value_str =
              box[get_variable(f)] == Box::Interval::ONE ? "true" : "false";
        } else {
          throw std::runtime_error(fmt::format(
              "get-value does not handle a compound formula {}.", term_str));
        }
        break;
      }
    }
    fmt::print("\t({} {})\n", term_str, value_str);
  }
  fmt::print(")\n");
  cout.flush();
}

void Smt2Driver::GetOption(const string& key) const {
  const optional<string> value{context_.GetOption(key)};
  if (value) {
    fmt::print("{}\n", *value);
  } else {
    fmt::print("unsupported\n");
  }
  cout.flush();
}

Variable Smt2Driver::RegisterVariable(const string& name, const Sort sort) {
  const Variable v{ParseVariableSort(name, sort)};
  scope_.insert(v.get_name(), v);
  return v;
}

Variable Smt2Driver::DeclareVariable(const string& name, const Sort sort) {
  Variable v{RegisterVariable(name, sort)};
  context_.DeclareVariable(v);
  return v;
}

void Smt2Driver::DeclareVariable(const string& name, const Sort sort,
                                 const Term& lb, const Term& ub) {
  const Variable v{RegisterVariable(name, sort)};
  context_.DeclareVariable(v, lb.expression(), ub.expression());
}

void Smt2Driver::DefineFun(const string& name,
                           const vector<Variable>& parameters, Sort return_type,
                           const Term& body) {
  FunctionDefinition func{parameters, return_type, body};
  function_definition_map_.insert(name, func);
}

string Smt2Driver::MakeUniqueName(const string& name) {
  ostringstream oss;
  // The \ character ensures that the name cannot occur in an SMT-LIBv2 file.
  oss << "L" << nextUniqueId_++ << "\\" << name;
  return oss.str();
}

Term Smt2Driver::LookupFunction(const string& name,
                                const vector<Term>& arguments) {
  const auto it = function_definition_map_.find(name);
  if (it != function_definition_map_.end()) {
    return it->second(arguments);
  } else {
    throw runtime_error{fmt::format("No function definition for {}.", name)};
  }
}

Variable Smt2Driver::DeclareLocalVariable(const string& name, const Sort sort) {
  const Variable v{ParseVariableSort(MakeUniqueName(name), sort)};
  scope_.insert(name, v);  // v is not inserted under its own name.
  context_.DeclareVariable(
      v, false /* This local variable is not a model variable. */);
  return v;
}

const Variable& Smt2Driver::lookup_variable(const string& name) {
  const auto it = scope_.find(name);
  if (it == scope_.cend()) {
    throw DREAL_RUNTIME_ERROR("{} is an undeclared variable.", name);
  }
  return it->second;
}

Variable Smt2Driver::ParseVariableSort(const string& name, const Sort s) {
  return Variable{name, SortToType(s)};
}

Formula Smt2Driver::EliminateBooleanVariables(const Variables& vars,
                                              const Formula& f) {
  Formula ret{f};
  for (const auto& b : vars) {
    if (b.get_type() == Variable::Type::BOOLEAN) {
      ret = ret.Substitute(b, Formula::True()) &&
            ret.Substitute(b, Formula::False());
    }
  }
  return ret;
}

}  // namespace dreal
<|endoftext|>


<commit_before>/*
 * adplug.cpp - CAdPlug main class implementation, by Simon Peter (dn.tlp@gmx.net)
 */

#include <fstream.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "adplug.h"

// replayers
#include "hsc.h"
#include "mtk.h"
#include "hsp.h"
#include "s3m.h"
#include "raw.h"
#include "d00.h"
#include "sa2.h"
#include "amd.h"
#include "rad.h"
#include "a2m.h"
#include "mid.h"
#include "imf.h"
#include "sng.h"
#include "ksm.h"
#ifndef ADPLAY
	#include "u6m.h"
#endif
//#include "mkj.h"

char *CAdPlug::upstr(char *str)
{
	unsigned int i;

	for(i=0;i<strlen(str);i++)
		str[i] = toupper(str[i]);

	return str;
}

CPlayer *CAdPlug::load_sci(istream &f, char *fn, Copl *opl)
{
	CmidPlayer *mp = new CmidPlayer(opl);
	char *pfn = new char [strlen(fn)+9];
	int j=0;

	strcpy(pfn,fn);
	for (int i=strlen(pfn)-1; i>=0; i--)
		if (pfn[i]=='/' || pfn[i]=='\\') {
			j=i+1;
			i=-1;
		}
	strcpy(pfn+j+3,"patch.003");
	mp->set_sierra_insfile(pfn);
	delete [] pfn;

	if(mp->load(f))
		return mp;
	delete mp;
	f.seekg(0);
	return 0;
}

CPlayer *CAdPlug::load_ksm(istream &f, char *fn, Copl *opl)
{
	CksmPlayer	*mp = new CksmPlayer(opl);
	char		*pfn = new char [strlen(fn)+9];
	int			j=0;

	strcpy(pfn,fn);
	for (int i=strlen(pfn)-1; i>=0; i--)
		if (pfn[i]=='/' || pfn[i]=='\\') {
			j=i+1;
			i=-1;
		}
	strcpy(pfn+j,"insts.dat");
	ifstream insf(pfn, ios::in | ios::nocreate | ios::binary);
	delete [] pfn;
	if(!insf.is_open())
		return 0;
	mp->loadinsts(insf);
	if(mp->load(f))
		return mp;
	delete mp;
	f.seekg(0);
	return 0;
}

CPlayer *CAdPlug::factory(char *fn, Copl *opl)
{
	CPlayer		*p;
	ifstream	f(fn, ios::in | ios::nocreate | ios::binary);

	if(f.is_open()) {
		if(!strcmp(upstr(strrchr(fn,'.')+1),"SCI"))
			return load_sci(f,fn,opl);

		if(!strcmp(upstr(strrchr(fn,'.')+1),"KSM"))
			return load_ksm(f,fn,opl);

		if(p = factory(f,opl))
			return p;

#ifndef ADPLAY
		if(!strcmp(upstr(strrchr(fn,'.')+1),"M")) {
			p = new Cu6mPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
#endif
		if(!strcmp(upstr(strrchr(fn,'.')+1),"D00")) {
			p = new Cd00Player(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
		if(!strcmp(upstr(strrchr(fn,'.')+1),"HSP")) {
			p = new ChspLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
		if(!strcmp(upstr(strrchr(fn,'.')+1),"HSC")) {
			p = new ChscPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
		if(!strcmp(upstr(strrchr(fn,'.')+1),"IMF") || !strcmp(upstr(strrchr(fn,'.')+1),"WLF")) {
			p = new CimfPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
		if(!strcmp(upstr(strrchr(fn,'.')+1),"KSM")) {
			p = new CksmPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
	};

	return 0;
}

CPlayer *CAdPlug::factory(istream &f, Copl *opl)
{
	CPlayer *p;

	p = new CsngPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CmidPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new Ca2mLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CradLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CamdLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new Csa2Loader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CrawPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new Cs3mPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CmtkLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
//	p = new CmkjPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);

	return 0;
}

unsigned long CAdPlug::songlength(CPlayer *p, unsigned int subsong)
{
	float	slength = 0.0f;

	// get song length
	p->rewind(subsong);
	while(p->update() && slength < 600000)	// song length limit: 10 minutes
		slength += 1000/p->getrefresh();
	p->rewind(subsong);

	return (unsigned long)slength;
}

void CAdPlug::seek(CPlayer *p, unsigned long ms)
{
	float pos = 0.0f;

	p->rewind();
	while(pos < ms && p->update())		// seek to new position
		pos += 1000/p->getrefresh();
}
<commit_msg>added MKJamz support to core module.<commit_after>/*
 * adplug.cpp - CAdPlug main class implementation, by Simon Peter (dn.tlp@gmx.net)
 */

#include <fstream.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "adplug.h"

// replayers
#include "hsc.h"
#include "mtk.h"
#include "hsp.h"
#include "s3m.h"
#include "raw.h"
#include "d00.h"
#include "sa2.h"
#include "amd.h"
#include "rad.h"
#include "a2m.h"
#include "mid.h"
#include "imf.h"
#include "sng.h"
#include "ksm.h"
#ifndef ADPLAY
	#include "u6m.h"
#endif
#include "mkj.h"

char *CAdPlug::upstr(char *str)
{
	unsigned int i;

	for(i=0;i<strlen(str);i++)
		str[i] = toupper(str[i]);

	return str;
}

CPlayer *CAdPlug::load_sci(istream &f, char *fn, Copl *opl)
{
	CmidPlayer *mp = new CmidPlayer(opl);
	char *pfn = new char [strlen(fn)+9];
	int j=0;

	strcpy(pfn,fn);
	for (int i=strlen(pfn)-1; i>=0; i--)
		if (pfn[i]=='/' || pfn[i]=='\\') {
			j=i+1;
			i=-1;
		}
	strcpy(pfn+j+3,"patch.003");
	mp->set_sierra_insfile(pfn);
	delete [] pfn;

	if(mp->load(f))
		return mp;
	delete mp;
	f.seekg(0);
	return 0;
}

CPlayer *CAdPlug::load_ksm(istream &f, char *fn, Copl *opl)
{
	CksmPlayer	*mp = new CksmPlayer(opl);
	char		*pfn = new char [strlen(fn)+9];
	int			j=0;

	strcpy(pfn,fn);
	for (int i=strlen(pfn)-1; i>=0; i--)
		if (pfn[i]=='/' || pfn[i]=='\\') {
			j=i+1;
			i=-1;
		}
	strcpy(pfn+j,"insts.dat");
	ifstream insf(pfn, ios::in | ios::nocreate | ios::binary);
	delete [] pfn;
	if(!insf.is_open())
		return 0;
	mp->loadinsts(insf);
	if(mp->load(f))
		return mp;
	delete mp;
	f.seekg(0);
	return 0;
}

CPlayer *CAdPlug::factory(char *fn, Copl *opl)
{
	CPlayer		*p;
	ifstream	f(fn, ios::in | ios::nocreate | ios::binary);

	if(f.is_open()) {
		if(!strcmp(upstr(strrchr(fn,'.')+1),"SCI"))
			return load_sci(f,fn,opl);

		if(!strcmp(upstr(strrchr(fn,'.')+1),"KSM"))
			return load_ksm(f,fn,opl);

		if(p = factory(f,opl))
			return p;

#ifndef ADPLAY
		if(!strcmp(upstr(strrchr(fn,'.')+1),"M")) {
			p = new Cu6mPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
#endif
		if(!strcmp(upstr(strrchr(fn,'.')+1),"D00")) {
			p = new Cd00Player(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
		if(!strcmp(upstr(strrchr(fn,'.')+1),"HSP")) {
			p = new ChspLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
		if(!strcmp(upstr(strrchr(fn,'.')+1),"HSC")) {
			p = new ChscPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
		if(!strcmp(upstr(strrchr(fn,'.')+1),"IMF") || !strcmp(upstr(strrchr(fn,'.')+1),"WLF")) {
			p = new CimfPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
		if(!strcmp(upstr(strrchr(fn,'.')+1),"KSM")) {
			p = new CksmPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
		}
	};

	return 0;
}

CPlayer *CAdPlug::factory(istream &f, Copl *opl)
{
	CPlayer *p;

	p = new CsngPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CmidPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new Ca2mLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CradLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CamdLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new Csa2Loader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CrawPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new Cs3mPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CmtkLoader(opl); if(p->load(f)) return p; delete p; f.seekg(0);
	p = new CmkjPlayer(opl); if(p->load(f)) return p; delete p; f.seekg(0);

	return 0;
}

unsigned long CAdPlug::songlength(CPlayer *p, unsigned int subsong)
{
	float	slength = 0.0f;

	// get song length
	p->rewind(subsong);
	while(p->update() && slength < 600000)	// song length limit: 10 minutes
		slength += 1000/p->getrefresh();
	p->rewind(subsong);

	return (unsigned long)slength;
}

void CAdPlug::seek(CPlayer *p, unsigned long ms)
{
	float pos = 0.0f;

	p->rewind();
	while(pos < ms && p->update())		// seek to new position
		pos += 1000/p->getrefresh();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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 <folly/detail/SingletonStackTrace.h>

#include <folly/experimental/symbolizer/ElfCache.h>
#include <folly/experimental/symbolizer/Symbolizer.h>
#include <folly/portability/Config.h>

namespace folly {
namespace detail {

std::string getSingletonStackTrace() {
#if FOLLY_HAVE_ELF && FOLLY_HAVE_DWARF

  // Get and symbolize stack trace
  constexpr size_t kMaxStackTraceDepth = 100;
  auto addresses =
      std::make_unique<symbolizer::FrameArray<kMaxStackTraceDepth>>();

  if (!getStackTraceSafe(*addresses)) {
    return "";
  } else {
    symbolizer::ElfCache elfCache;

    symbolizer::Symbolizer symbolizer(&elfCache);
    symbolizer.symbolize(*addresses);

    symbolizer::StringSymbolizePrinter printer;
    printer.println(*addresses);
    return printer.str();
  }

#else

  return "";

#endif // FOLLY_HAVE_ELF && FOLLY_HAVE_DWARF
}

} // namespace detail
} // namespace folly
<commit_msg>use faster impl in Singleton stack traces<commit_after>/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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 <folly/detail/SingletonStackTrace.h>

#include <folly/experimental/symbolizer/ElfCache.h>
#include <folly/experimental/symbolizer/Symbolizer.h>
#include <folly/portability/Config.h>

namespace folly {
namespace detail {

std::string getSingletonStackTrace() {
#if FOLLY_HAVE_ELF && FOLLY_HAVE_DWARF

  // Get and symbolize stack trace
  constexpr size_t kMaxStackTraceDepth = 100;
  auto addresses =
      std::make_unique<symbolizer::FrameArray<kMaxStackTraceDepth>>();

  if (!getStackTrace(*addresses)) {
    return "";
  } else {
    symbolizer::ElfCache elfCache;

    symbolizer::Symbolizer symbolizer(&elfCache);
    symbolizer.symbolize(*addresses);

    symbolizer::StringSymbolizePrinter printer;
    printer.println(*addresses);
    return printer.str();
  }

#else

  return "";

#endif // FOLLY_HAVE_ELF && FOLLY_HAVE_DWARF
}

} // namespace detail
} // namespace folly
<|endoftext|>


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

#include <sofa/core/MultiMapping.inl>
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/defaulttype/RigidTypes.h>

namespace sofa
{

namespace core
{

using namespace sofa::defaulttype;
using namespace core::behavior;

#ifndef SOFA_FLOAT
template class SOFA_CORE_API MultiMapping< Vec1dTypes, Vec1dTypes >;
template class SOFA_CORE_API MultiMapping< Vec3dTypes, Vec3dTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3dTypes, Vec3dTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3dTypes, Vec6dTypes >;
#endif

#ifndef SOFA_DOUBLE
template class SOFA_CORE_API MultiMapping< Vec1fTypes, Vec1fTypes >;
template class SOFA_CORE_API MultiMapping< Vec3fTypes, Vec3fTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3fTypes, Vec3fTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3fTypes, Vec6fTypes >;
#endif

#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class MultiMapping< Vec1dTypes, Vec1fTypes >;
template class MultiMapping< Vec1fTypes, Vec1dTypes > ;
template class MultiMapping< Vec3dTypes, Vec3fTypes >;
template class MultiMapping< Vec3fTypes, Vec3dTypes > ;
template class MultiMapping< Rigid3dTypes, Vec3fTypes >;
template class MultiMapping< Rigid3fTypes, Vec3dTypes >;
template class MultiMapping< Rigid3dTypes, Vec6fTypes >;
template class MultiMapping< Rigid3fTypes, Vec6dTypes >;
#endif
#endif

} // namespace core

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

#include <sofa/core/MultiMapping.inl>
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/defaulttype/RigidTypes.h>

namespace sofa
{

namespace core
{

using namespace sofa::defaulttype;
using namespace core::behavior;

#ifndef SOFA_FLOAT
template class SOFA_CORE_API MultiMapping< Vec1dTypes, Vec1dTypes >;
template class SOFA_CORE_API MultiMapping< Vec3dTypes, Vec3dTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3dTypes, Vec3dTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3dTypes, Vec6dTypes >;
#endif

#ifndef SOFA_DOUBLE
template class SOFA_CORE_API MultiMapping< Vec1fTypes, Vec1fTypes >;
template class SOFA_CORE_API MultiMapping< Vec3fTypes, Vec3fTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3fTypes, Vec3fTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3fTypes, Vec6fTypes >;
#endif

#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class SOFA_CORE_API MultiMapping< Vec1dTypes, Vec1fTypes >;
template class SOFA_CORE_API MultiMapping< Vec1fTypes, Vec1dTypes > ;
template class SOFA_CORE_API MultiMapping< Vec3dTypes, Vec3fTypes >;
template class SOFA_CORE_API MultiMapping< Vec3fTypes, Vec3dTypes > ;
template class SOFA_CORE_API MultiMapping< Vec3dTypes, Vec1fTypes >;
template class SOFA_CORE_API MultiMapping< Vec3fTypes, Vec1dTypes > ;
template class SOFA_CORE_API MultiMapping< Rigid3dTypes, Vec3fTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3fTypes, Vec3dTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3dTypes, Vec6fTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3fTypes, Vec6dTypes >;
#endif
#endif

} // namespace core

} // namespace sofa
<|endoftext|>


<commit_before>// Best-first Utility-Guided Search Yes! From:
// "Best-first Utility-Guided Search," Wheeler Ruml and Minh B. Do,
// Proceedings of the Twentieth International Joint Conference on
// Artificial Intelligence (IJCAI-07), 2007

#include "../search/search.hpp"
#include "../structs/binheap.hpp"
#include "../utils/pool.hpp"
#include <cstring>

template <class D> struct Bugsy : public SearchAlgorithm<D> {
	typedef typename D::State State;
	typedef typename D::PackedState PackedState;
	typedef typename D::Cost Cost;
	typedef typename D::Oper Oper;

	struct Node : SearchNode<D> {
		typename D::Cost f, h, d;
		double u, t;

		// The expansion count when this node was
		// generated.
		unsigned long expct;

		// path-based mean expansion delay.
		double avgdelay;
		unsigned long depth;

		static bool pred(Node *a, Node *b) {
			if (a->u != b->u)
				return a->u > b->u;
			if (a->t != b->t)
				return a->t < b->t;
			if (a->f != b->f)
				return a->f < b->f;
			return a->g > b->g;
		}
	};

	enum {
		// Resort1 is the number of expansions to perform
		// before the 1st open list resort.
		Resort1 = 128,
	};

	Bugsy(int argc, const char *argv[]) :
			SearchAlgorithm<D>(argc, argv),
			usehlms(false),
			usehhat(false),
			usedhat(false),
			navg(0),
			herror(0),
			derror(0),
			useexpdelay(false),
			avgdelay(0),
			dropdups(false),
			timeper(0.0),
			nextresort(Resort1),
			nresort(0),
			closed(30000001) {
		wf = wt = -1;
		for (int i = 0; i < argc; i++) {
			if (i < argc - 1 && strcmp(argv[i], "-wf") == 0)
				wf = strtod(argv[++i], NULL);
			else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0)
				wt = strtod(argv[++i], NULL);
			else if (i < argc - 1 && strcmp(argv[i], "-expdelay") == 0)
				useexpdelay = true;
			else if (i < argc - 1 && strcmp(argv[i], "-hhat") == 0)
				usehhat = true;
			else if (i < argc - 1 && strcmp(argv[i], "-dhat") == 0)
				usedhat = true;
			else if (i < argc - 1 && strcmp(argv[i], "-dropdups") == 0)
				dropdups = true;
			else if (i < argc - 1 && strcmp(argv[i], "-interph") == 0)
				interph = usehhat = true;
			else if (i < argc - 1 && strcmp(argv[i], "-hlms") == 0) {
				usehlms = true;
				initlms(sizeof(hcoeffs)/sizeof(hcoeffs[0]), argv[++i], hcoeffs);
			} else if (i < argc - 1 && strcmp(argv[i], "-dlms") == 0) {
				usedlms = true;
				initlms(sizeof(dcoeffs)/sizeof(dcoeffs[0]), argv[++i], dcoeffs);
			}
		}

		if (wf < 0)
			fatal("Must specify non-negative f-weight using -wf");
		if (wt < 0)
			fatal("Must specify non-negative t-weight using -wt");

		nodes = new Pool<Node>();
	}

	~Bugsy() {
		delete nodes;
	}

	void search(D &d, typename D::State &s0) {
		this->start();
		last = walltime();
		closed.init(d);
		Node *n0 = init(d, s0);
		closed.add(n0);
		open.push(n0);

		while (!open.empty() && !SearchAlgorithm<D>::limit()) {
			Node* n = *open.pop();
			State buf, &state = d.unpack(buf, n->packed);
			if (d.isgoal(state)) {
				SearchAlgorithm<D>::res.goal(d, n);
				break;
			}
			expand(d, n, state);
			updatetime();
			updateopen();
		}

		this->finish();
	}

	virtual void reset() {
		SearchAlgorithm<D>::reset();
		open.clear();
		closed.clear();
		delete nodes;
		timeper = 0.0;
		nresort = 0;
		nextresort = Resort1;
		navg = 0;
		herror = derror = 0;
		nodes = new Pool<Node>();
	}

	virtual void output(FILE *out) {
		SearchAlgorithm<D>::output(out);
		closed.prstats(stdout, "closed ");
		dfpair(stdout, "open list type", "%s", "binary heap");
		dfpair(stdout, "node size", "%u", sizeof(Node));
		dfpair(stdout, "wf", "%g", wf);
		dfpair(stdout, "wt", "%g", wt);
		dfpair(stdout, "final time per expand", "%g", timeper);
		dfpair(stdout, "number of resorts", "%lu", nresort);
		if (usehhat)
			dfpair(stdout, "mean single-step h error", "%g", herror);
		if (usedhat)
			dfpair(stdout, "mean single-step d error", "%g", derror);
		if (useexpdelay)
			dfpair(stdout, "mean expansion delay", "%g", avgdelay);
	}

private:

	// Kidinfo holds information about a node used for
	// correcting the heuristic estimates.
	struct Kidinfo {
		Kidinfo() : f(-1), h(-1), d(-1) { }

		Kidinfo(Cost gval, Cost hval, Cost dval) : f(gval + hval), h(hval), d(dval) { }

		Cost f, h, d;
	};

	// expand expands the node, adding its children to the
	// open and closed lists as appropriate.
	void expand(D &d, Node *n, State &state) {
		this->res.expd++;

		if (useexpdelay) {
			unsigned long delay = this->res.expd - n->expct;
			avgdelay = avgdelay + (delay - avgdelay)/this->res.expd;
		}

		Kidinfo bestinfo;
		typename D::Operators ops(d, state);
		for (unsigned int i = 0; i < ops.size(); i++) {
			if (ops[i] == n->pop)
				continue;

			this->res.gend++;

			Kidinfo kinfo = considerkid(d, n, state, ops[i]);
			if (bestinfo.f < Cost(0) || kinfo.f < bestinfo.f)
				bestinfo = kinfo;
		}

		if (bestinfo.f < Cost(0))
			return;

		navg++;
		if (usehhat) {
			double herr = bestinfo.f - n->f;
			if (herr < 0)	// floating point rounding
				herr = 0;
			herror = herror + (herr - herror)/navg;
		}

		if (usedhat) {
			double derr = bestinfo.d + 1 - n->d;
			if (derr < 0)	// floating point rounding
				derr = 0;
			derror = derror + (derr - derror)/navg;
		}
	}

	// considers adding the child to the open and closed lists.
	Kidinfo considerkid(D &d, Node *parent, State &state, Oper op) {
		Node *kid = nodes->construct();
		typename D::Edge e(d, state, op);
		kid->g = parent->g + e.cost;
		kid->depth = parent->depth + 1;
		kid->avgdelay = parent->avgdelay;

		// single step path-max on d
		kid->d = d.d(e.state);
		if (kid->d < parent->d - Cost(1))
			kid->d = parent->d - Cost(1);

		// single step path-max on h
		kid->h = d.h(e.state);
		if (kid->h < parent->h - e.cost)
			kid->h = parent->h - e.cost;

		kid->f = kid->g + kid->h;

		if (useexpdelay)
			kid->expct = this->res.expd;

		Kidinfo kinfo(kid->g, kid->h, kid->d);

		d.pack(kid->packed, e.state);

		unsigned long hash = d.hash(kid->packed);
		Node *dup = static_cast<Node*>(closed.find(kid->packed, hash));
		if (dup) {
			this->res.dups++;
			if (!dropdups && kid->g < dup->g) {
				if (dup->ind < 0)
					this->res.reopnd++;
				dup->f = dup->f - dup->g + kid->g;
				dup->update(kid->g, parent, op, e.revop);
				computeutil(dup);
				open.pushupdate(dup, dup->ind);
			}
			nodes->destruct(kid);
		} else {
			kid->update(kid->g, parent, op, e.revop);
			computeutil(kid);
			closed.add(kid, hash);
			open.push(kid);
		}
		return kinfo;
	}

	Node *init(D &d, State &s0) {
		Node *n0 = nodes->construct();
		d.pack(n0->packed, s0);
		n0->g = Cost(0);
		n0->h = n0->f = d.h(s0);
		n0->d = d.d(s0);
		n0->depth = 0;
		n0->avgdelay = 0;
		computeutil(n0);
		n0->op = n0->pop = D::Nop;
		n0->parent = NULL;
		n0->expct = 0;
		return n0;
	}

	// compututil computes the utility value of the given node
	// using corrected estimates of d and h.
	void computeutil(Node *n) {
		double d = usedlms ? evallms(n, dcoeffs) : n->d;
		if (usedhat)
			d /= (1 - derror);

		double h = usehlms ? evallms(n, hcoeffs) : n->h;
		if (usehhat) {
			if (interph) {
				double hhat = h + d*herror;
				double w = wf/(wf+wt);
				h = n->h*w + hhat*(1-w);
			} else {
				h += d * herror;
			}
		}

		if (useexpdelay && avgdelay > 0)
			d *= avgdelay;

		double f = h + n->g;
		n->t = timeper * d;
		n->u = -(wf * f + wt * n->t);
	}

	// updatetime runs a simple state machine (from Wheeler's BUGSY
	// implementation) that estimates the node expansion rate.
	void updatetime() {
		double t = walltime() - last;
		timeper = timeper + (t - timeper)/this->res.expd;
		last = walltime();
	}

	// updateopen updates the utilities of all nodes on open and
	// reinitializes the heap every 2^i expansions.
	void updateopen() {
		if (this->res.expd < nextresort)
			return;
		nextresort *= 2;
		nresort++;
		for (int i = 0; i < open.size(); i++)
			computeutil(open.at(i));
		open.reinit();
	}

	void initlms(unsigned int n, const char *wts, double coeffs[]) {
		char *cpy = new char[strlen(wts)+1];
		memcpy(cpy, wts, strlen(wts)+1);

		char *tok = strtok(cpy, ",");
		for (unsigned int i = 0; i < n; i++) {
			if (!tok)
				fatal("Expected %u coefficients", n);
			char *end = NULL;
			coeffs[i] = strtod(tok, &end);
			if (end == tok)
				fatal("Coefficient %u (%s) is invalid", i, tok);
			tok = strtok(NULL, ",");
		}

		delete []cpy;
	}

	double evallms(Node *n, double coeffs[]) const {
		return n->h*coeffs[0] +
			n->g*coeffs[1] +
			n->d*coeffs[2] +
			n->depth*coeffs[3];
	}

	bool usehlms;
	// h, g, d, and D coefficients for LMS-based heuristic;
	double hcoeffs[4];

	bool usedlms;
	// h, g, d, and D coefficients for LMS-based heuristic;
	double dcoeffs[4];

	// wf and wt are the cost and time weight respectively.
	double wf, wt;

	// heuristic correction
	bool usehhat, usedhat;
	unsigned long navg;
	double herror, derror;

	// interph — when using heuristic correction,
	// interpolate between h and hhat depending
	// on the ratio of wf to wt.
	bool interph;

	// expansion delay
	bool useexpdelay;
	double avgdelay;

	bool dropdups;

	// for nodes-per-second estimation
	double timeper, last;

	// for resorting the open list
	unsigned long nextresort;
	unsigned int nresort;

	BinHeap<Node, Node*> open;
 	ClosedList<SearchNode<D>, SearchNode<D>, D> closed;
	Pool<Node> *nodes;
};
<commit_msg>search: add -noresort flag to Bugsy.<commit_after>// Best-first Utility-Guided Search Yes! From:
// "Best-first Utility-Guided Search," Wheeler Ruml and Minh B. Do,
// Proceedings of the Twentieth International Joint Conference on
// Artificial Intelligence (IJCAI-07), 2007

#include "../search/search.hpp"
#include "../structs/binheap.hpp"
#include "../utils/pool.hpp"
#include <cstring>

template <class D> struct Bugsy : public SearchAlgorithm<D> {
	typedef typename D::State State;
	typedef typename D::PackedState PackedState;
	typedef typename D::Cost Cost;
	typedef typename D::Oper Oper;

	struct Node : SearchNode<D> {
		typename D::Cost f, h, d;
		double u, t;

		// The expansion count when this node was
		// generated.
		unsigned long expct;

		// path-based mean expansion delay.
		double avgdelay;
		unsigned long depth;

		static bool pred(Node *a, Node *b) {
			if (a->u != b->u)
				return a->u > b->u;
			if (a->t != b->t)
				return a->t < b->t;
			if (a->f != b->f)
				return a->f < b->f;
			return a->g > b->g;
		}
	};

	enum {
		// Resort1 is the number of expansions to perform
		// before the 1st open list resort.
		Resort1 = 128,
	};

	Bugsy(int argc, const char *argv[]) :
			SearchAlgorithm<D>(argc, argv),
			resort(true),
			usehlms(false),
			usehhat(false),
			usedhat(false),
			navg(0),
			herror(0),
			derror(0),
			useexpdelay(false),
			avgdelay(0),
			dropdups(false),
			timeper(0.0),
			nextresort(Resort1),
			nresort(0),
			closed(30000001) {
		wf = wt = -1;
		for (int i = 0; i < argc; i++) {
			if (i < argc - 1 && strcmp(argv[i], "-wf") == 0)
				wf = strtod(argv[++i], NULL);
			else if (i < argc - 1 && strcmp(argv[i], "-wt") == 0)
				wt = strtod(argv[++i], NULL);
			else if (i < argc - 1 && strcmp(argv[i], "-noresort") == 0)
				resort = false;
			else if (i < argc - 1 && strcmp(argv[i], "-expdelay") == 0)
				useexpdelay = true;
			else if (i < argc - 1 && strcmp(argv[i], "-hhat") == 0)
				usehhat = true;
			else if (i < argc - 1 && strcmp(argv[i], "-dhat") == 0)
				usedhat = true;
			else if (i < argc - 1 && strcmp(argv[i], "-dropdups") == 0)
				dropdups = true;
			else if (i < argc - 1 && strcmp(argv[i], "-interph") == 0)
				interph = usehhat = true;
			else if (i < argc - 1 && strcmp(argv[i], "-hlms") == 0) {
				usehlms = true;
				initlms(sizeof(hcoeffs)/sizeof(hcoeffs[0]), argv[++i], hcoeffs);
			} else if (i < argc - 1 && strcmp(argv[i], "-dlms") == 0) {
				usedlms = true;
				initlms(sizeof(dcoeffs)/sizeof(dcoeffs[0]), argv[++i], dcoeffs);
			}
		}

		if (wf < 0)
			fatal("Must specify non-negative f-weight using -wf");
		if (wt < 0)
			fatal("Must specify non-negative t-weight using -wt");

		nodes = new Pool<Node>();
	}

	~Bugsy() {
		delete nodes;
	}

	void search(D &d, typename D::State &s0) {
		this->start();
		last = walltime();
		closed.init(d);
		Node *n0 = init(d, s0);
		closed.add(n0);
		open.push(n0);

		while (!open.empty() && !SearchAlgorithm<D>::limit()) {
			Node* n = *open.pop();
			State buf, &state = d.unpack(buf, n->packed);
			if (d.isgoal(state)) {
				SearchAlgorithm<D>::res.goal(d, n);
				break;
			}
			expand(d, n, state);
			updatetime();
			updateopen();
		}

		this->finish();
	}

	virtual void reset() {
		SearchAlgorithm<D>::reset();
		open.clear();
		closed.clear();
		delete nodes;
		timeper = 0.0;
		nresort = 0;
		nextresort = Resort1;
		navg = 0;
		herror = derror = 0;
		nodes = new Pool<Node>();
	}

	virtual void output(FILE *out) {
		SearchAlgorithm<D>::output(out);
		closed.prstats(stdout, "closed ");
		dfpair(stdout, "open list type", "%s", "binary heap");
		dfpair(stdout, "node size", "%u", sizeof(Node));
		dfpair(stdout, "wf", "%g", wf);
		dfpair(stdout, "wt", "%g", wt);
		dfpair(stdout, "final time per expand", "%g", timeper);
		dfpair(stdout, "number of resorts", "%lu", nresort);
		if (usehhat)
			dfpair(stdout, "mean single-step h error", "%g", herror);
		if (usedhat)
			dfpair(stdout, "mean single-step d error", "%g", derror);
		if (useexpdelay)
			dfpair(stdout, "mean expansion delay", "%g", avgdelay);
	}

private:

	// Kidinfo holds information about a node used for
	// correcting the heuristic estimates.
	struct Kidinfo {
		Kidinfo() : f(-1), h(-1), d(-1) { }

		Kidinfo(Cost gval, Cost hval, Cost dval) : f(gval + hval), h(hval), d(dval) { }

		Cost f, h, d;
	};

	// expand expands the node, adding its children to the
	// open and closed lists as appropriate.
	void expand(D &d, Node *n, State &state) {
		this->res.expd++;

		if (useexpdelay) {
			unsigned long delay = this->res.expd - n->expct;
			avgdelay = avgdelay + (delay - avgdelay)/this->res.expd;
		}

		Kidinfo bestinfo;
		typename D::Operators ops(d, state);
		for (unsigned int i = 0; i < ops.size(); i++) {
			if (ops[i] == n->pop)
				continue;

			this->res.gend++;

			Kidinfo kinfo = considerkid(d, n, state, ops[i]);
			if (bestinfo.f < Cost(0) || kinfo.f < bestinfo.f)
				bestinfo = kinfo;
		}

		if (bestinfo.f < Cost(0))
			return;

		navg++;
		if (usehhat) {
			double herr = bestinfo.f - n->f;
			if (herr < 0)	// floating point rounding
				herr = 0;
			herror = herror + (herr - herror)/navg;
		}

		if (usedhat) {
			double derr = bestinfo.d + 1 - n->d;
			if (derr < 0)	// floating point rounding
				derr = 0;
			derror = derror + (derr - derror)/navg;
		}
	}

	// considers adding the child to the open and closed lists.
	Kidinfo considerkid(D &d, Node *parent, State &state, Oper op) {
		Node *kid = nodes->construct();
		typename D::Edge e(d, state, op);
		kid->g = parent->g + e.cost;
		kid->depth = parent->depth + 1;
		kid->avgdelay = parent->avgdelay;

		// single step path-max on d
		kid->d = d.d(e.state);
		if (kid->d < parent->d - Cost(1))
			kid->d = parent->d - Cost(1);

		// single step path-max on h
		kid->h = d.h(e.state);
		if (kid->h < parent->h - e.cost)
			kid->h = parent->h - e.cost;

		kid->f = kid->g + kid->h;

		if (useexpdelay)
			kid->expct = this->res.expd;

		Kidinfo kinfo(kid->g, kid->h, kid->d);

		d.pack(kid->packed, e.state);

		unsigned long hash = d.hash(kid->packed);
		Node *dup = static_cast<Node*>(closed.find(kid->packed, hash));
		if (dup) {
			this->res.dups++;
			if (!dropdups && kid->g < dup->g) {
				if (dup->ind < 0)
					this->res.reopnd++;
				dup->f = dup->f - dup->g + kid->g;
				dup->update(kid->g, parent, op, e.revop);
				computeutil(dup);
				open.pushupdate(dup, dup->ind);
			}
			nodes->destruct(kid);
		} else {
			kid->update(kid->g, parent, op, e.revop);
			computeutil(kid);
			closed.add(kid, hash);
			open.push(kid);
		}
		return kinfo;
	}

	Node *init(D &d, State &s0) {
		Node *n0 = nodes->construct();
		d.pack(n0->packed, s0);
		n0->g = Cost(0);
		n0->h = n0->f = d.h(s0);
		n0->d = d.d(s0);
		n0->depth = 0;
		n0->avgdelay = 0;
		computeutil(n0);
		n0->op = n0->pop = D::Nop;
		n0->parent = NULL;
		n0->expct = 0;
		return n0;
	}

	// compututil computes the utility value of the given node
	// using corrected estimates of d and h.
	void computeutil(Node *n) {
		double d = usedlms ? evallms(n, dcoeffs) : n->d;
		if (usedhat)
			d /= (1 - derror);

		double h = usehlms ? evallms(n, hcoeffs) : n->h;
		if (usehhat) {
			if (interph) {
				double hhat = h + d*herror;
				double w = wf/(wf+wt);
				h = n->h*w + hhat*(1-w);
			} else {
				h += d * herror;
			}
		}

		if (useexpdelay && avgdelay > 0)
			d *= avgdelay;

		double f = h + n->g;
		n->t = timeper * d;
		n->u = -(wf * f + wt * n->t);
	}

	// updatetime runs a simple state machine (from Wheeler's BUGSY
	// implementation) that estimates the node expansion rate.
	void updatetime() {
		double t = walltime() - last;
		timeper = timeper + (t - timeper)/this->res.expd;
		last = walltime();
	}

	// updateopen updates the utilities of all nodes on open and
	// reinitializes the heap every 2^i expansions.
	void updateopen() {
		if (!resort || this->res.expd < nextresort)
			return;
		nextresort *= 2;
		nresort++;
		for (int i = 0; i < open.size(); i++)
			computeutil(open.at(i));
		open.reinit();
	}

	void initlms(unsigned int n, const char *wts, double coeffs[]) {
		char *cpy = new char[strlen(wts)+1];
		memcpy(cpy, wts, strlen(wts)+1);

		char *tok = strtok(cpy, ",");
		for (unsigned int i = 0; i < n; i++) {
			if (!tok)
				fatal("Expected %u coefficients", n);
			char *end = NULL;
			coeffs[i] = strtod(tok, &end);
			if (end == tok)
				fatal("Coefficient %u (%s) is invalid", i, tok);
			tok = strtok(NULL, ",");
		}

		delete []cpy;
	}

	double evallms(Node *n, double coeffs[]) const {
		return n->h*coeffs[0] +
			n->g*coeffs[1] +
			n->d*coeffs[2] +
			n->depth*coeffs[3];
	}

	// resort the open list sometimes?
	bool resort;

	bool usehlms;
	// h, g, d, and D coefficients for LMS-based heuristic;
	double hcoeffs[4];

	bool usedlms;
	// h, g, d, and D coefficients for LMS-based heuristic;
	double dcoeffs[4];

	// wf and wt are the cost and time weight respectively.
	double wf, wt;

	// heuristic correction
	bool usehhat, usedhat;
	unsigned long navg;
	double herror, derror;

	// interph — when using heuristic correction,
	// interpolate between h and hhat depending
	// on the ratio of wf to wt.
	bool interph;

	// expansion delay
	bool useexpdelay;
	double avgdelay;

	bool dropdups;

	// for nodes-per-second estimation
	double timeper, last;

	// for resorting the open list
	unsigned long nextresort;
	unsigned int nresort;

	BinHeap<Node, Node*> open;
 	ClosedList<SearchNode<D>, SearchNode<D>, D> closed;
	Pool<Node> *nodes;
};
<|endoftext|>


<commit_before>// Copyright ***********************************************************
//
// File ecmdQueryUser.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************
/* $Header$ */

// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************

//----------------------------------------------------------------------
//  Includes
//----------------------------------------------------------------------
#define ecmdQueryUser_C
#include <stdio.h>

#include <ecmdCommandUtils.H>
#include <ecmdReturnCodes.H>
#include <ecmdClientCapi.H>
#include <ecmdUtils.H>
#include <ecmdDataBuffer.H>

#undef ecmdQueryUser_C
//----------------------------------------------------------------------
//  User Types
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Constants
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Macros
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Internal Function Prototypes
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Global Variables
//----------------------------------------------------------------------

//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------

int ecmdQueryUser(int argc, char* argv[]) {
  int rc = ECMD_SUCCESS;
  std::string printed;
  ecmdLooperData looperdata;            ///< Store internal Looper data

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/

  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  if (argc == 0) {
    ecmdOutputError("ecmdquery - Too few arguments specified; you need at least a query mode.\n");
    ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  if (!strcmp(argv[0], "rings")) {

    char invmask = 'N';
    char chkable  = 'N';
    char broadmode = 'N';
    std::list<ecmdRingData> ringdata;
    std::list<ecmdRingData>::iterator ringit;
    std::list<std::string>::iterator strit;

    if (argc < 2) {
      ecmdOutputError("ecmdquery - Too few arguments specified for rings; you need at least a query rings <chipname>.\n");
      ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n");
      return ECMD_INVALID_ARGS;
    }

    ecmdChipData chipdata;

    //Setup the target that will be used to query the system config
    ecmdChipTarget target;
    target.chipType = argv[1];
    target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
    target.cageState = target.nodeState = target.slotState = target.posState = ECMD_TARGET_QUERY_WILDCARD;
    target.threadState = target.coreState = ECMD_TARGET_FIELD_UNUSED;

    /************************************************************************/
    /* Kickoff Looping Stuff                                                */
    /************************************************************************/

    bool validPosFound = false;
    rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
    if (rc) return rc;

    char buf[200];

    while ( ecmdConfigLooperNext(target, looperdata) ) {

      rc = ecmdQueryRing(target, ringdata,argv[2]);
      if (rc == ECMD_TARGET_NOT_CONFIGURED) {
        continue;
      } else if (rc) {
        printed = "ecmdquery - Error occured performing ring query on ";
        printed += ecmdWriteTarget(target);
        printed += "\n";
        ecmdOutputError( printed.c_str() );
        return rc;
      }
      else {
        validPosFound = true;
      }

      /* Let's look up other info about the chip, namely the ec level */
      rc = ecmdGetChipData (target, chipdata);
      if (rc) {
        printed = "ecmdquery - Unable to lookup ec information for chip ";
        printed += ecmdWriteTarget(target);
        printed += "\n";
        ecmdOutputError( printed.c_str() );
        return rc;
      }

      sprintf(buf,"\nAvailable rings for %s ec %d:\n", ecmdWriteTarget(target).c_str(), chipdata.chipEc); ecmdOutput(buf);
      printed = "Ring Names                           Address    Length   Mask Chkable BroadSide ClockState\n"; ecmdOutput(printed.c_str());
      printed = "-----------------------------------  --------   ------   ---- ------- --------- ----------\n"; ecmdOutput(printed.c_str());

      for (ringit = ringdata.begin(); ringit != ringdata.end(); ringit ++) {

        printed = "";
        /* The Ring Names */
        for (strit = ringit->ringNames.begin(); strit != ringit->ringNames.end(); strit ++) {
          if (strit != ringit->ringNames.begin()) printed += ", ";
          printed += (*strit);
        }
        for (int i = printed.length(); i <= 36; i++) {
          printed += " ";
        }

        if(ringit->hasInversionMask) {
          invmask = 'Y';
        } else {
          invmask = 'N';
        }

        if (ringit->isCheckable) {
          chkable = 'Y';
        } else chkable = 'N';

        if (ringit->supportsBroadsideLoad) {
          broadmode = 'Y';
        } else broadmode = 'N';

        sprintf(buf,"0x%.6X\t%d\t  %c     %c         %c     ", ringit->address, ringit->bitLength, invmask, chkable, broadmode);
        printed += buf;

        if (ringit->clockState == ECMD_CLOCKSTATE_UNKNOWN)
          printed += "UNKNOWN\n";
        else if (ringit->clockState == ECMD_CLOCKSTATE_ON)
          printed += "ON\n";
        else if (ringit->clockState == ECMD_CLOCKSTATE_OFF)
          printed += "OFF\n";
        else if (ringit->clockState == ECMD_CLOCKSTATE_NA)
          printed += "NA\n";

        ecmdOutput(printed.c_str());
      }
    }

    if (!validPosFound) {
      ecmdOutputError("ecmdquery - Unable to find a valid chip to execute command on\n");
      return ECMD_TARGET_NOT_CONFIGURED;
    }

  } else if (!strcmp(argv[0],"version")) {

    /* Let's display the dllInfo to the user */
    ecmdDllInfo info;
    rc = ecmdQueryDllInfo(info);
    if (rc) {
      ecmdOutputError("ecmdquery - Problems occurred trying to get Dll Info\n");
      return rc;
    }
    ecmdOutput("================================================\n");
    printed = "Dll Type         : ";
    if (info.dllType == ECMD_DLL_STUB)
      printed += "Stub\n";
    else if (info.dllType == ECMD_DLL_STUB)
      printed += "Stub\n";
    else if (info.dllType == ECMD_DLL_CRONUS)
      printed += "Cronus\n";
    else if (info.dllType == ECMD_DLL_IPSERIES)
      printed += "IP-Series\n";
    else if (info.dllType == ECMD_DLL_ZSERIES)
      printed += "Z-Series\n";
    else
      printed = "Unknown\n";
    ecmdOutput(printed.c_str());

    printed = "Dll Product      : ";
    if (info.dllProduct == ECMD_DLL_PRODUCT_ECLIPZ)
      printed += "Eclipz\n";
    else
      printed += "Unknown\n";
    ecmdOutput(printed.c_str());

    printed = "Dll Environment  : ";
    if (info.dllEnv == ECMD_DLL_ENV_HW)
      printed += "Hardware\n";
    else
      printed += "Simulation\n";
    ecmdOutput(printed.c_str());

    printed = "Dll Build Date   : "; printed += info.dllBuildDate; printed += "\n"; ecmdOutput(printed.c_str());
    printed = "Dll Capi Version : "; printed += info.dllCapiVersion; printed += "\n"; ecmdOutput(printed.c_str());
    ecmdOutput("================================================\n");

  } else {
    /* Invalid Query Mode */
    ecmdOutputError("ecmdquery - Invalid Query Mode.\n");
    ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n");
    return ECMD_INVALID_ARGS;

  }

  return rc;
}

// Change Log *********************************************************
//
//  Flag Reason   Vers Date     Coder    Description
//  ---- -------- ---- -------- -------- ------------------------------
//                              CENGEL   Initial Creation
//
// End Change Log *****************************************************
<commit_msg>Added ecmdquery configd - doesn't work right though<commit_after>// Copyright ***********************************************************
//
// File ecmdQueryUser.C
//
// IBM Confidential
// OCO Source Materials
// 9400 Licensed Internal Code
// (C) COPYRIGHT IBM CORP. 1996
//
// The source code for this program is not published or otherwise
// divested of its trade secrets, irrespective of what has been
// deposited with the U.S. Copyright Office.
//
// End Copyright *******************************************************
/* $Header$ */

// Module Description **************************************************
//
// Description:
//
// End Module Description **********************************************

//----------------------------------------------------------------------
//  Includes
//----------------------------------------------------------------------
#define ecmdQueryUser_C
#include <stdio.h>

#include <ecmdCommandUtils.H>
#include <ecmdReturnCodes.H>
#include <ecmdClientCapi.H>
#include <ecmdUtils.H>
#include <ecmdDataBuffer.H>

#undef ecmdQueryUser_C
//----------------------------------------------------------------------
//  User Types
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Constants
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Macros
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Internal Function Prototypes
//----------------------------------------------------------------------

//----------------------------------------------------------------------
//  Global Variables
//----------------------------------------------------------------------

//---------------------------------------------------------------------
// Member Function Specifications
//---------------------------------------------------------------------

int ecmdQueryUser(int argc, char* argv[]) {
  int rc = ECMD_SUCCESS;
  std::string printed;
  ecmdLooperData looperdata;            ///< Store internal Looper data

  /************************************************************************/
  /* Parse Common Cmdline Args                                            */
  /************************************************************************/

  rc = ecmdCommandArgs(&argc, &argv);
  if (rc) return rc;

  if (argc == 0) {
    ecmdOutputError("ecmdquery - Too few arguments specified; you need at least a query mode.\n");
    ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n");
    return ECMD_INVALID_ARGS;
  }

  if (!strcmp(argv[0], "rings")) {

    char invmask = 'N';
    char chkable  = 'N';
    char broadmode = 'N';
    std::list<ecmdRingData> ringdata;
    std::list<ecmdRingData>::iterator ringit;
    std::list<std::string>::iterator strit;

    if (argc < 2) {
      ecmdOutputError("ecmdquery - Too few arguments specified for rings; you need at least a query rings <chipname>.\n");
      ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n");
      return ECMD_INVALID_ARGS;
    }

    ecmdChipData chipdata;

    //Setup the target that will be used to query the system config
    ecmdChipTarget target;
    target.chipType = argv[1];
    target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
    target.cageState = target.nodeState = target.slotState = target.posState = ECMD_TARGET_QUERY_WILDCARD;
    target.threadState = target.coreState = ECMD_TARGET_FIELD_UNUSED;

    /************************************************************************/
    /* Kickoff Looping Stuff                                                */
    /************************************************************************/

    bool validPosFound = false;
    rc = ecmdConfigLooperInit(target, ECMD_SELECTED_TARGETS_LOOP, looperdata);
    if (rc) return rc;

    char buf[200];

    while ( ecmdConfigLooperNext(target, looperdata) ) {

      rc = ecmdQueryRing(target, ringdata,argv[2]);
      if (rc == ECMD_TARGET_NOT_CONFIGURED) {
        continue;
      } else if (rc) {
        printed = "ecmdquery - Error occured performing ring query on ";
        printed += ecmdWriteTarget(target);
        printed += "\n";
        ecmdOutputError( printed.c_str() );
        return rc;
      }
      else {
        validPosFound = true;
      }

      /* Let's look up other info about the chip, namely the ec level */
      rc = ecmdGetChipData (target, chipdata);
      if (rc) {
        printed = "ecmdquery - Unable to lookup ec information for chip ";
        printed += ecmdWriteTarget(target);
        printed += "\n";
        ecmdOutputError( printed.c_str() );
        return rc;
      }

      sprintf(buf,"\nAvailable rings for %s ec %d:\n", ecmdWriteTarget(target).c_str(), chipdata.chipEc); ecmdOutput(buf);
      printed = "Ring Names                           Address    Length   Mask Chkable BroadSide ClockState\n"; ecmdOutput(printed.c_str());
      printed = "-----------------------------------  --------   ------   ---- ------- --------- ----------\n"; ecmdOutput(printed.c_str());

      for (ringit = ringdata.begin(); ringit != ringdata.end(); ringit ++) {

        printed = "";
        /* The Ring Names */
        for (strit = ringit->ringNames.begin(); strit != ringit->ringNames.end(); strit ++) {
          if (strit != ringit->ringNames.begin()) printed += ", ";
          printed += (*strit);
        }
        for (int i = printed.length(); i <= 36; i++) {
          printed += " ";
        }

        if(ringit->hasInversionMask) {
          invmask = 'Y';
        } else {
          invmask = 'N';
        }

        if (ringit->isCheckable) {
          chkable = 'Y';
        } else chkable = 'N';

        if (ringit->supportsBroadsideLoad) {
          broadmode = 'Y';
        } else broadmode = 'N';

        sprintf(buf,"0x%.6X\t%d\t  %c     %c         %c     ", ringit->address, ringit->bitLength, invmask, chkable, broadmode);
        printed += buf;

        if (ringit->clockState == ECMD_CLOCKSTATE_UNKNOWN)
          printed += "UNKNOWN\n";
        else if (ringit->clockState == ECMD_CLOCKSTATE_ON)
          printed += "ON\n";
        else if (ringit->clockState == ECMD_CLOCKSTATE_OFF)
          printed += "OFF\n";
        else if (ringit->clockState == ECMD_CLOCKSTATE_NA)
          printed += "NA\n";

        ecmdOutput(printed.c_str());
      }
    }

    if (!validPosFound) {
      ecmdOutputError("ecmdquery - Unable to find a valid chip to execute command on\n");
      return ECMD_TARGET_NOT_CONFIGURED;
    }

  } else if (!strcmp(argv[0],"version")) {

    /* Let's display the dllInfo to the user */
    ecmdDllInfo info;
    rc = ecmdQueryDllInfo(info);
    if (rc) {
      ecmdOutputError("ecmdquery - Problems occurred trying to get Dll Info\n");
      return rc;
    }
    ecmdOutput("================================================\n");
    printed = "Dll Type         : ";
    if (info.dllType == ECMD_DLL_STUB)
      printed += "Stub\n";
    else if (info.dllType == ECMD_DLL_STUB)
      printed += "Stub\n";
    else if (info.dllType == ECMD_DLL_CRONUS)
      printed += "Cronus\n";
    else if (info.dllType == ECMD_DLL_IPSERIES)
      printed += "IP-Series\n";
    else if (info.dllType == ECMD_DLL_ZSERIES)
      printed += "Z-Series\n";
    else
      printed = "Unknown\n";
    ecmdOutput(printed.c_str());

    printed = "Dll Product      : ";
    if (info.dllProduct == ECMD_DLL_PRODUCT_ECLIPZ)
      printed += "Eclipz\n";
    else
      printed += "Unknown\n";
    ecmdOutput(printed.c_str());

    printed = "Dll Environment  : ";
    if (info.dllEnv == ECMD_DLL_ENV_HW)
      printed += "Hardware\n";
    else
      printed += "Simulation\n";
    ecmdOutput(printed.c_str());

    printed = "Dll Build Date   : "; printed += info.dllBuildDate; printed += "\n"; ecmdOutput(printed.c_str());
    printed = "Dll Capi Version : "; printed += info.dllCapiVersion; printed += "\n"; ecmdOutput(printed.c_str());
    ecmdOutput("================================================\n");

  } else if (!strcmp(argv[0],"configd")) {

    if (argc < 2) {
      ecmdOutputError("ecmdquery - Too few arguments specified for configd; you need at least a query configd <chipname>.\n");
      ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n");
      return ECMD_INVALID_ARGS;
    }

    //Setup the target that will be used to query the system config
    ecmdChipTarget target;
    target.chipType = argv[1];
    target.chipTypeState = ECMD_TARGET_QUERY_FIELD_VALID;
    target.cageState = target.nodeState = target.slotState = target.posState = target.threadState = target.coreState = ECMD_TARGET_QUERY_WILDCARD;
    if (ecmdQueryTargetConfigured(target)) {
      printed = "ecmdquery - Target ";
      printed += ecmdWriteTarget(target);
      printed += " is configured!\n";
      ecmdOutput(printed.c_str());
    } else {
      printed = "ecmdquery - Target ";
      printed += ecmdWriteTarget(target);
      printed += " is not configured!\n";
      ecmdOutputError(printed.c_str());
      return ECMD_TARGET_NOT_CONFIGURED;
    }

  } else {
    /* Invalid Query Mode */
    ecmdOutputError("ecmdquery - Invalid Query Mode.\n");
    ecmdOutputError("ecmdquery - Type 'ecmdquery -h' for usage.\n");
    return ECMD_INVALID_ARGS;

  }

  return rc;
}

// Change Log *********************************************************
//
//  Flag Reason   Vers Date     Coder    Description
//  ---- -------- ---- -------- -------- ------------------------------
//                              CENGEL   Initial Creation
//
// End Change Log *****************************************************
<|endoftext|>


<commit_before>// Example implementation of a quicksort that uses a number
// of C++-11 constructs.
#include <algorithm>
#include <chrono>
#include <utility>
#include <vector>
#include <iostream>
#include <random>
using namespace std;

template <typename T>
auto insertionSort(vector<T>& a, size_t beg, size_t end) -> void
{
  for(auto i=beg+1; i<=end; ++i) {
    // all items from beg to i-1 are sorted
    // insert the new one in the appropriate slot
    auto j = i;
    while (j>0 && a[j-1] > a[j]) {
      swap(a[j], a[j-1]);
      --j;
    }
  }
}

template<typename T>
auto partition(vector<T>& a, size_t beg, size_t end) -> size_t
{
  random_device rd;
  mt19937 mt(rd());
  uniform_int_distribution<size_t> dis(beg, end);
  auto idx = dis(mt);
  while (idx != end) {
    idx = dis(mt);
  }
  swap(a[idx], a[end]);

  T pivot = a[end];
  size_t j = beg;
  for(size_t i=beg; i<=end-1; ++i) {
    if (a[i] < pivot) {
      swap(a[i], a[j]);
      ++j;
    }
  }
  swap(a[end], a[j]);
  return j;
}

template <typename T, size_t M=32>
auto quickSort(vector<T>& a, size_t beg, size_t end) -> void
{
  if ((end - beg) < M) {
    insertionSort(a, beg, end);
  }
  else {
    auto pivot = partition(a, beg, end);
    if (pivot > 0) {
      quickSort(a, 0, pivot-1);   // left
    }
    if (pivot < end) {
      quickSort(a, pivot+1, end); // right
    }
  }
}

auto test() -> bool
{
  int M = 100000; // range of numbers in the array
  int N = 1000;   // array size

  cout << "test" << endl;
  random_device rd;
  mt19937 mt(rd());
  uniform_int_distribution<size_t> dis(1, M);

  vector<int> a;
  cout << "populating array with N=" << N << " where 1 <= a[i] <= " << M << endl;
  auto now = chrono::system_clock::now();
  do {
    if (a.size()) {
      cout << "trying again - previous attempt was already sorted" << endl;
    }
    a.clear();
    for(auto i=1; i<N; ++i) {
      int ran = dis(mt);
      a.push_back(ran);
    }
  } while (is_sorted(a.begin(), a.end()));
  auto end = chrono::system_clock::now();
  auto ms = chrono::duration_cast<chrono::milliseconds>(end-now).count();
  cout << "elapsed time: " << ms << "ms" << endl;

  cout << "sorting..." << endl;
  now = chrono::system_clock::now();
  quickSort(a, 0, a.size()-1);
  end = chrono::system_clock::now();
  ms = chrono::duration_cast<chrono::milliseconds>(end-now).count();
  cout << "elapsed time: " << ms << "ms" << endl;

  cout << "testing..." << endl;
  if (is_sorted(a.begin(), a.end())) {
    cout << "PASSED" << endl;
    return true;
  }
  cout << "FAILED" << endl;
  return false;
}

int main()
{
  return test() ? 0 : 1;
}
<commit_msg>Update example.cc<commit_after>// Example implementation of a quicksort that uses a number
// of C++-11 constructs.
#include <algorithm>
#include <chrono>
#include <utility>
#include <vector>
#include <iostream>
#include <random>
using namespace std;

template <typename T>
auto insertionSort(vector<T>& a, size_t beg, size_t end) -> void
{
  for(auto i=beg+1; i<=end; ++i) {
    // all items from beg to i-1 are sorted
    // insert the new one in the appropriate slot
    auto j = i;
    while (j>0 && a[j-1] > a[j]) {
      swap(a[j], a[j-1]);
      --j;
    }
  }
}

template<typename T>
auto partition(vector<T>& a, size_t beg, size_t end) -> size_t
{
  // Randomly select the pivot using a uniform distribution.
  random_device rd;
  mt19937 mt(rd());
  uniform_int_distribution<size_t> dis(beg, end);
  auto idx = dis(mt);
  T pivot = a[idx];
  swap(a[end], a[idx]); // reserve the end slot

  auto i = beg;
  if (end > 0) {
    for(auto j=beg; j<end; ++j) {  // up to end - 1
      if (a[j] <= pivot) {
        swap(a[i], a[j]);
        ++i;
      }
    }
  }
  swap(a[i], a[end]);
  return i;
}

template <typename T, size_t M=32>
auto quickSort(vector<T>& a, size_t beg, size_t end) -> void
{
  if ((end - beg) < M) {
    insertionSort(a, beg, end);
  }
  else {
    auto pivot = partition(a, beg, end);
    if (pivot > 0) {
      quickSort(a, 0, pivot-1);   // left
    }
    if (pivot < end) {
      quickSort(a, pivot+1, end); // right
    }
  }
}

auto test() -> bool
{
  int M = 100000; // range of numbers in the array
  int N = 1000;   // array size

  cout << "test" << endl;
  random_device rd;
  mt19937 mt(rd());
  uniform_int_distribution<size_t> dis(1, M);

  vector<int> a;
  cout << "populating array with N=" << N << " where 1 <= a[i] <= " << M << endl;
  auto now = chrono::system_clock::now();
  do {
    if (a.size()) {
      cout << "trying again - previous attempt was already sorted" << endl;
    }
    a.clear();
    for(auto i=1; i<N; ++i) {
      int ran = dis(mt);
      a.push_back(ran);
    }
  } while (is_sorted(a.begin(), a.end()));
  auto end = chrono::system_clock::now();
  auto ms = chrono::duration_cast<chrono::milliseconds>(end-now).count();
  cout << "elapsed time: " << ms << "ms" << endl;

  cout << "sorting..." << endl;
  now = chrono::system_clock::now();
  quickSort(a, 0, a.size()-1);
  end = chrono::system_clock::now();
  ms = chrono::duration_cast<chrono::milliseconds>(end-now).count();
  cout << "elapsed time: " << ms << "ms" << endl;

  cout << "testing..." << endl;
  if (is_sorted(a.begin(), a.end())) {
    cout << "PASSED" << endl;
    return true;
  }
  cout << "FAILED" << endl;
  return false;
}

int main()
{
  return test() ? 0 : 1;
}
<|endoftext|>