<commit_before>/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond angles, and dihedral
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the molecule.
 */

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cmath>

#include "main.h"
#include "extraction.h"
#include "center_of_mass.h"
#include "bond_angle.h"
#include "dihedral_angle.h"
#include "elements.h"
#include "bond_length.h"
#include "bond_number.h"

using namespace std;

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

    ofstream logfile;
    fstream bond_angle;
    fstream dihedral_angle;
    fstream bond_length;

    //Check that inputfile was directed into the command line
    if (argc < 2) {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Generate a logfile
    logfile.open("log.txt");
    if (!logfile.is_open()) {
        cout << "Error: Unable to open the logfile.";
        return 2;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool" << endl;
    }

    //Extract the raw coordinates from the inputfile in the commandline
    if (extract_input(argv[1]) != 0) {
        cout << "Error occured in extracting the coordinates.\n";
    }

    //Print the vector size and vector contents
    if (print_vector_coords() != 0) {
        cout << "Error occured in printing the coordinates.\n";
    }

    //Calculate the model's total mass
    double model_mass = calculate_total_mass();

    //Calculate the model's center of mass coordinates
    double xcoord = calc_prod_coords_mass(2) / model_mass;
    double ycoord = calc_prod_coords_mass(3) / model_mass;
    double zcoord = calc_prod_coords_mass(4) / model_mass;

    cout << "Model's Center of Mass coordinates: " << endl
         << xcoord << "     " << ycoord << "     " << zcoord << endl;

    //Output the calculated interatomic distances
    Bond_Length model;
    model.atom_dist();

    //Output Bond numbers of atoms
    extern vector< vector<string> > vector_coords;

    int number_atoms = vector_coords.size();

    atom_distance(number_atoms);

    extern vector< vector<double> > R;
    extern vector< vector<int> > bond_exist;

    for(int i = 0; i < number_atoms; i++) {  //for loop for debugging purposes (not permanent)
        for(int j = i + 1; j < number_atoms; j++) {
            cout << bond_exist[i][j] << "    ";
        }

	    cout << endl;

    }

    //Output the number of bonds between atoms
    int number_bonds();

    //Calculate the molecule's bond angles
    extern vector< vector<double> > bond_angle_v;

    bond_angle_f(number_atoms);

    //Calculate the molecule's dihedral angles

}
<commit_msg>updated and got bond_number to print to screen<commit_after>/**
 * @mainpage The Gaussian Optimization Analytical Tool (GOAT)
 *
 * Welcome to the Gaussian Optimization Analytical Tool (GOAT) documentation site!
 * Users may find relevant info related to this program, a program designed to provide
 * structural analyses of biomolecules successfully optimized using Gaussian software.
 *
 * @short   Main program
 * @file    main.cpp
 * @author  Kate Charbonnet, Hannah Lozano, and Thomas Summers
 * @param   none
 * @return  0 on success
 *
 * The purpose of this program is to provide preliminary structural information on biomolecules
 * optimized using Gaussian computational chemistry software.  Structural and chemical properties
 * identified include: element identification, bond length, bond angles, and dihedral
 * angles.  Input of the file to be analyzed will result in an output file listing all the structural
 * information of the molecule.
 */

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cmath>

#include "main.h"
#include "extraction.h"
#include "center_of_mass.h"
#include "bond_angle.h"
#include "dihedral_angle.h"
#include "elements.h"
#include "bond_length.h"
#include "bond_number.h"

using namespace std;

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

    ofstream logfile;
    fstream bond_angle;
    fstream dihedral_angle;
    fstream bond_length;

    //Check that inputfile was directed into the command line
    if (argc < 2) {
        cout << "Error: Inputfile not specified in command line\n";
        return 1;
    }

    //Generate a logfile
    logfile.open("log.txt");
    if (!logfile.is_open()) {
        cout << "Error: Unable to open the logfile.";
        return 2;
    } else {
        logfile << "Logfile for Gaussian Optimization Analytical Tool" << endl;
    }

    //Extract the raw coordinates from the inputfile in the commandline
    if (extract_input(argv[1]) != 0) {
        cout << "Error occured in extracting the coordinates.\n";
    }

    //Print the vector size and vector contents
    if (print_vector_coords() != 0) {
        cout << "Error occured in printing the coordinates.\n";
    }

    //Calculate the model's total mass
    double model_mass = calculate_total_mass();

    //Calculate the model's center of mass coordinates
    double xcoord = calc_prod_coords_mass(2) / model_mass;
    double ycoord = calc_prod_coords_mass(3) / model_mass;
    double zcoord = calc_prod_coords_mass(4) / model_mass;

    cout << "Model's Center of Mass coordinates: " << endl
         << xcoord << "     " << ycoord << "     " << zcoord << endl;

    //Output the calculated interatomic distances
    //Bond_Length model;
    //model.atom_distance();

    //Output Bond numbers of atoms
    extern vector< vector<string> > vector_coords;

    int number_atoms = vector_coords.size();

    atom_distance(number_atoms);

    extern vector< vector<double> > R;
    extern vector< vector<int> > bond_exist;

    for(int i = 0; i < number_atoms; i++) {  //for loop for debugging purposes (not permanent)
        for(int j = i + 1; j < number_atoms; j++) {
            cout << bond_exist[i][j] << "    ";
        }

	    cout << endl;

    }

    //Output the number of bonds between atoms
    number_bonds();

    //Calculate the molecule's bond angles
    extern vector< vector<double> > bond_angle_v;

    bond_angle_f(number_atoms);

    //Calculate the molecule's dihedral angles

}
<|endoftext|>


<commit_before>//  2006-2008 (c) Viva64.com Team
//  2008-2016 (c) OOO "Program Verification Systems"

#include "comments.h"
#include "encoding.h"

#include <cstdio>
#include <cstring>
#include <string>
#include <functional>
#include <algorithm>
#include <vector>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <experimental/filesystem>

using namespace std;
using namespace std::experimental;

static bool IsSourceFile(const filesystem::path &path)
{
  static const vector<string> sourceExtensions = {
      ".c"
    , ".cc"
    , ".cpp"
    , ".cp"
    , ".cxx"
    , ".c++"
    , ".cs"
  };
  string ext = path.extension().string();
  transform(ext.begin(), ext.end(), ext.begin(), [](char ch){return tolower(ch);});
  return find(sourceExtensions.begin(), sourceExtensions.end(), ext) != sourceExtensions.end();
}

class ProgramOptions
{
  ProgramOptions() = default;
  ProgramOptions(const ProgramOptions& root) = delete;
  ProgramOptions& operator=(const ProgramOptions&) = delete;
public:
  size_t m_commentType     = -1;
  vector<string> m_files;
  bool m_multiline         = false;
  bool m_readSymlinks      = false;

  static ProgramOptions& Instance()
  {
    static ProgramOptions programOptions;
    return programOptions;
  }
};

void WriteComment(const filesystem::path &path,
                  const string &comment,
                  const string &source,
                  bool isUnixLineEnding,
                  Encoding enc,
                  size_t bomLen)
{
  ofstream osrc(path, ios::binary);
  if (!osrc.is_open())
  {
    cerr << "Error: Couldn't open " << path << endl;
    return;
  }

  if (bomLen != 0)
  {
    osrc.write(source.c_str(), bomLen);
  }

  ConvertEncoding(osrc, comment, enc, !isUnixLineEnding);
  osrc.write(source.c_str() + bomLen, source.length() - bomLen);
}

static void AddCommentsToFile(const filesystem::path &path, const string &comment, const ProgramOptions &options)
{
  if (!IsSourceFile(path))
    return;

  cout << "+ " << path << endl;

  ifstream isrc(path, ios::binary);
  if (!isrc.is_open())
  {
    cerr << "Error: Couldn't open " << path << endl;
    return;
  }

  string str;
  isrc.seekg(0, ios::end);
  str.reserve(isrc.tellg());
  isrc.seekg(0, ios::beg);

  str.assign((istreambuf_iterator<char>(isrc)), istreambuf_iterator<char>());
  isrc.close();
  string source = str;

  Encoding enc;
  size_t bomLen;
  ConvertEncoding(str, enc, bomLen);

  bool isUnixLineEnding = true;
  size_t idx = str.find('\n');
  if (idx != string::npos && idx != 0 && str[idx - 1] == '\r')
    isUnixLineEnding = false;

  PvsStudioFreeComments::CommentsParser parser;
  auto itFreeComment = parser.readFreeComment(source.c_str());
  const char *beg = parser.freeCommentBegin();
  const char *end = parser.freeCommentEnd();

  if (itFreeComment != PvsStudioFreeComments::Comments.end())
  {
    bool needToChangeComment =    (!options.m_multiline && beg[0] == '/' && beg[1] == '*')
                               || (options.m_multiline  && beg[0] == '/' && beg[1] == '/')
                               || itFreeComment != PvsStudioFreeComments::Comments.begin() + (ProgramOptions::Instance().m_commentType - 1);
    if (needToChangeComment)
    {
      source.erase(source.begin() + distance(source.c_str(), beg), source.begin() + distance(source.c_str(), end));
      WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
    }
  }
  else
  {
    WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
  }
}

static void ProcessFile(filesystem::path path, const string &comment, const ProgramOptions &options)
{
  if (options.m_readSymlinks && filesystem::is_symlink(path))
  {
    std::error_code error;
    path = filesystem::canonical(filesystem::read_symlink(path), path.parent_path(), error);
    if (error != std::error_code())
    {
      return;
    }
  }

  if (filesystem::is_regular_file(path))
  {
    AddCommentsToFile(path, comment, options);
  }
}

static void AddComments(const string &path, const string &comment, const ProgramOptions &options)
{
  auto fsPath = filesystem::canonical(path);
  if (!filesystem::exists(fsPath))
  {
    cerr << "File not exists: " << path << endl;
    return;
  }
  if (filesystem::is_directory(fsPath))
  {
    filesystem::directory_options symlink_flag = options.m_readSymlinks
                                                 ? filesystem::directory_options::follow_directory_symlink
                                                 : filesystem::directory_options::none;
    for (auto &&p : filesystem::recursive_directory_iterator(fsPath, symlink_flag))
    {
      ProcessFile(p.path(), comment, options);
    }
  }
  else
  {
    ProcessFile(fsPath, comment, options);
  }
}

static string Format(const string &comment, bool multiline)
{
  ostringstream ostream;
  istringstream stream(comment);
  string line;

  if (multiline)
  {
    ostream << "/*" << endl;

    while (getline(stream, line))
    {
      ostream << "* " << line << endl;
    }

    ostream << "*/" << endl;
  }
  else
  {
    while (getline(stream, line))
    {
      ostream << "// " << line << endl;
    }
  }

  return ostream.str();
}

static const char Help[] = R"HELP(How to use PVS-Studio for FREE?

  You can use PVS-Studio code analyzer for free, if you add special comments
  to your source code. Available options are provided below.

Usage:

  how-to-use-pvs-studio-free -c <1|2|3> [-m] [-h] <strings> ...

Options:

  -c <1|2|3>,  --comment <1|2|3>
    (required)  Type of comment prepended to the source file.

  -m, --multiline
    Use multi-line comments instead of single-line.

  -h,  --help
    Display usage information and exits.

  <string>  (accepted multiple times)
    (required)  Files or directories.

Description:

  The utility will add comments to the files located in the specified folders
  and subfolders. The comments are added to the beginning of the files with the
  extensions .c, .cc, .cpp, .cp, .cxx, .c++, .cs. You don't have to change
  header files. If you use files with other extensions, you can customize this
  utility for your needs.

  Options of comments that will be added to the code (-c NUMBER):

    1. Personal academic project;
    2. Open source non-commercial project;
    3. Independent project of an individual developer.

  If you are using PVS-Studio as a Visual Studio plugin, then enter the
  following license key:

    Name: PVS-Studio Free
    Key:  FREE-FREE-FREE-FREE

  If you are using PVS-Studio for Linux, you do not need to do anything else
  besides adding comments to the source code. Just check your code.

  In case none of the options suits you, we suggest considering a purchase of a
  commercial license for PVS-Studio. We are ready to discuss this and other
  questions via e-mail: support@viva64.com.

  You can find more details about the free version of PVS-Studio
  here: https://www.viva64.com/en/b/0457/
)HELP";

void help()
{
  cout << Help;
}

struct Option
{
  vector<string> names;
  bool hasArg;
  function<void(string&&)> found;
};

struct ProgramOptionsError {};

typedef vector<Option> ParsedOptions;

static void ParseProgramOptions(int argc, const char *argv[], const ParsedOptions &options, function<void(string&&)> found)
{
  auto findOpt = [&options](const string& arg) {
    return find_if(begin(options), end(options), [arg](const Option &o) {
      return find(o.names.begin(), o.names.end(), arg) != o.names.end();
    });
  };

  for (int i = 1; i < argc; ++i)
  {
    string arg = argv[i];
    auto it = findOpt(arg);
    if (it == end(options))
    {
      found(move(arg));
    }
    else if (it->hasArg)
    {
      ++i;
      if (i == argc)
      {
        cout << "No argument specified for " << arg << endl;
        throw ProgramOptionsError();
      }

      string val = argv[i];
      auto itNext = findOpt(val);
      if (itNext != end(options))
      {
        cout << "No argument specified for " << arg << endl;
        throw ProgramOptionsError();
      }
      it->found(move(val));
    }
    else
    {
      it->found(string());
    }
  }
}

int main(int argc, const char *argv[])
{
  auto &progOptions = ProgramOptions::Instance();
  ParsedOptions options = {
    { {"-c", "/c", "--comment"}, true,   [&](string &&arg) { progOptions.m_commentType  = stoull(arg); } },
    { { "-m", "--multiline" },   false,  [&](string &&)    { progOptions.m_multiline    = true; } },
    { { "-s", "--symlinks" },    false,  [&](string &&)    { progOptions.m_readSymlinks = true; } },
    { {"-h", "--help", "/?"},    false,  [&](string &&)    { throw ProgramOptionsError(); } },
  };

  try
  {
    ParseProgramOptions(argc, argv, options, [&files = progOptions.m_files](string &&arg){files.emplace_back(move(arg));});

    unsigned long long n = progOptions.m_commentType;
    if (n == 0 || n > PvsStudioFreeComments::Comments.size())
    {
      throw invalid_argument("");
    }

    string comment = Format(PvsStudioFreeComments::Comments[n - 1].m_text, progOptions.m_multiline);
    for (const string &file : progOptions.m_files)
    {
      AddComments(file, comment, progOptions);
    }
  }
  catch (ProgramOptionsError &)
  {
    help();
    return 1;
  }
  catch (invalid_argument &)
  {
    cout << "Invalid comment type specified" << endl;
    help();
    return 1;
  }

  return 0;
}
<commit_msg>The flags "/s" and "/m" are added for parsing in command line.<commit_after>//  2006-2008 (c) Viva64.com Team
//  2008-2016 (c) OOO "Program Verification Systems"

#include "comments.h"
#include "encoding.h"

#include <cstdio>
#include <cstring>
#include <string>
#include <functional>
#include <algorithm>
#include <vector>
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <experimental/filesystem>

using namespace std;
using namespace std::experimental;

static bool IsSourceFile(const filesystem::path &path)
{
  static const vector<string> sourceExtensions = {
      ".c"
    , ".cc"
    , ".cpp"
    , ".cp"
    , ".cxx"
    , ".c++"
    , ".cs"
  };
  string ext = path.extension().string();
  transform(ext.begin(), ext.end(), ext.begin(), [](char ch){return tolower(ch);});
  return find(sourceExtensions.begin(), sourceExtensions.end(), ext) != sourceExtensions.end();
}

class ProgramOptions
{
  ProgramOptions() = default;
  ProgramOptions(const ProgramOptions& root) = delete;
  ProgramOptions& operator=(const ProgramOptions&) = delete;
public:
  size_t m_commentType     = -1;
  vector<string> m_files;
  bool m_multiline         = false;
  bool m_readSymlinks      = false;

  static ProgramOptions& Instance()
  {
    static ProgramOptions programOptions;
    return programOptions;
  }
};

void WriteComment(const filesystem::path &path,
                  const string &comment,
                  const string &source,
                  bool isUnixLineEnding,
                  Encoding enc,
                  size_t bomLen)
{
  ofstream osrc(path, ios::binary);
  if (!osrc.is_open())
  {
    cerr << "Error: Couldn't open " << path << endl;
    return;
  }

  if (bomLen != 0)
  {
    osrc.write(source.c_str(), bomLen);
  }

  ConvertEncoding(osrc, comment, enc, !isUnixLineEnding);
  osrc.write(source.c_str() + bomLen, source.length() - bomLen);
}

static void AddCommentsToFile(const filesystem::path &path, const string &comment, const ProgramOptions &options)
{
  if (!IsSourceFile(path))
    return;

  cout << "+ " << path << endl;

  ifstream isrc(path, ios::binary);
  if (!isrc.is_open())
  {
    cerr << "Error: Couldn't open " << path << endl;
    return;
  }

  string str;
  isrc.seekg(0, ios::end);
  str.reserve(isrc.tellg());
  isrc.seekg(0, ios::beg);

  str.assign((istreambuf_iterator<char>(isrc)), istreambuf_iterator<char>());
  isrc.close();
  string source = str;

  Encoding enc;
  size_t bomLen;
  ConvertEncoding(str, enc, bomLen);

  bool isUnixLineEnding = true;
  size_t idx = str.find('\n');
  if (idx != string::npos && idx != 0 && str[idx - 1] == '\r')
    isUnixLineEnding = false;

  PvsStudioFreeComments::CommentsParser parser;
  auto itFreeComment = parser.readFreeComment(source.c_str());
  const char *beg = parser.freeCommentBegin();
  const char *end = parser.freeCommentEnd();

  if (itFreeComment != PvsStudioFreeComments::Comments.end())
  {
    bool needToChangeComment =    (!options.m_multiline && beg[0] == '/' && beg[1] == '*')
                               || (options.m_multiline  && beg[0] == '/' && beg[1] == '/')
                               || itFreeComment != PvsStudioFreeComments::Comments.begin() + (ProgramOptions::Instance().m_commentType - 1);
    if (needToChangeComment)
    {
      source.erase(source.begin() + distance(source.c_str(), beg), source.begin() + distance(source.c_str(), end));
      WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
    }
  }
  else
  {
    WriteComment(path, comment, source, isUnixLineEnding, enc, bomLen);
  }
}

static void ProcessFile(filesystem::path path, const string &comment, const ProgramOptions &options)
{
  if (options.m_readSymlinks && filesystem::is_symlink(path))
  {
    std::error_code error;
    path = filesystem::canonical(filesystem::read_symlink(path), path.parent_path(), error);
    if (error != std::error_code())
    {
      return;
    }
  }

  if (filesystem::is_regular_file(path))
  {
    AddCommentsToFile(path, comment, options);
  }
}

static void AddComments(const string &path, const string &comment, const ProgramOptions &options)
{
  auto fsPath = filesystem::canonical(path);
  if (!filesystem::exists(fsPath))
  {
    cerr << "File not exists: " << path << endl;
    return;
  }
  if (filesystem::is_directory(fsPath))
  {
    filesystem::directory_options symlink_flag = options.m_readSymlinks
                                                 ? filesystem::directory_options::follow_directory_symlink
                                                 : filesystem::directory_options::none;
    for (auto &&p : filesystem::recursive_directory_iterator(fsPath, symlink_flag))
    {
      ProcessFile(p.path(), comment, options);
    }
  }
  else
  {
    ProcessFile(fsPath, comment, options);
  }
}

static string Format(const string &comment, bool multiline)
{
  ostringstream ostream;
  istringstream stream(comment);
  string line;

  if (multiline)
  {
    ostream << "/*" << endl;

    while (getline(stream, line))
    {
      ostream << "* " << line << endl;
    }

    ostream << "*/" << endl;
  }
  else
  {
    while (getline(stream, line))
    {
      ostream << "// " << line << endl;
    }
  }

  return ostream.str();
}

static const char Help[] = R"HELP(How to use PVS-Studio for FREE?

  You can use PVS-Studio code analyzer for free, if you add special comments
  to your source code. Available options are provided below.

Usage:

  how-to-use-pvs-studio-free -c <1|2|3> [-m] [-h] <strings> ...

Options:

  -c <1|2|3>,  --comment <1|2|3>
    (required)  Type of comment prepended to the source file.

  -m, --multiline
    Use multi-line comments instead of single-line.

  -h,  --help
    Display usage information and exits.

  <string>  (accepted multiple times)
    (required)  Files or directories.

Description:

  The utility will add comments to the files located in the specified folders
  and subfolders. The comments are added to the beginning of the files with the
  extensions .c, .cc, .cpp, .cp, .cxx, .c++, .cs. You don't have to change
  header files. If you use files with other extensions, you can customize this
  utility for your needs.

  Options of comments that will be added to the code (-c NUMBER):

    1. Personal academic project;
    2. Open source non-commercial project;
    3. Independent project of an individual developer.

  If you are using PVS-Studio as a Visual Studio plugin, then enter the
  following license key:

    Name: PVS-Studio Free
    Key:  FREE-FREE-FREE-FREE

  If you are using PVS-Studio for Linux, you do not need to do anything else
  besides adding comments to the source code. Just check your code.

  In case none of the options suits you, we suggest considering a purchase of a
  commercial license for PVS-Studio. We are ready to discuss this and other
  questions via e-mail: support@viva64.com.

  You can find more details about the free version of PVS-Studio
  here: https://www.viva64.com/en/b/0457/
)HELP";

void help()
{
  cout << Help;
}

struct Option
{
  vector<string> names;
  bool hasArg;
  function<void(string&&)> found;
};

struct ProgramOptionsError {};

typedef vector<Option> ParsedOptions;

static void ParseProgramOptions(int argc, const char *argv[], const ParsedOptions &options, function<void(string&&)> found)
{
  auto findOpt = [&options](const string& arg) {
    return find_if(begin(options), end(options), [arg](const Option &o) {
      return find(o.names.begin(), o.names.end(), arg) != o.names.end();
    });
  };

  for (int i = 1; i < argc; ++i)
  {
    string arg = argv[i];
    auto it = findOpt(arg);
    if (it == end(options))
    {
      found(move(arg));
    }
    else if (it->hasArg)
    {
      ++i;
      if (i == argc)
      {
        cout << "No argument specified for " << arg << endl;
        throw ProgramOptionsError();
      }

      string val = argv[i];
      auto itNext = findOpt(val);
      if (itNext != end(options))
      {
        cout << "No argument specified for " << arg << endl;
        throw ProgramOptionsError();
      }
      it->found(move(val));
    }
    else
    {
      it->found(string());
    }
  }
}

int main(int argc, const char *argv[])
{
  auto &progOptions = ProgramOptions::Instance();
  ParsedOptions options = {
    { { "-c", "/c", "--comment" },   true,   [&](string &&arg) { progOptions.m_commentType  = stoull(arg); } },
    { { "-m", "/m", "--multiline" }, false,  [&](string &&)    { progOptions.m_multiline    = true; } },
    { { "-s", "/s", "--symlinks" },  false,  [&](string &&)    { progOptions.m_readSymlinks = true; } },
    { { "-h", "/?", "--help" },      false,  [&](string &&)    { throw ProgramOptionsError(); } },
  };

  try
  {
    ParseProgramOptions(argc, argv, options, [&files = progOptions.m_files](string &&arg){files.emplace_back(move(arg));});

    unsigned long long n = progOptions.m_commentType;
    if (n == 0 || n > PvsStudioFreeComments::Comments.size())
    {
      throw invalid_argument("");
    }

    string comment = Format(PvsStudioFreeComments::Comments[n - 1].m_text, progOptions.m_multiline);
    for (const string &file : progOptions.m_files)
    {
      AddComments(file, comment, progOptions);
    }
  }
  catch (ProgramOptionsError &)
  {
    help();
    return 1;
  }
  catch (invalid_argument &)
  {
    cout << "Invalid comment type specified" << endl;
    help();
    return 1;
  }

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Joseph D Poirier
// Distributable under the terms of The Simplified BSD License
// that can be found in the LICENSE file.

#ifdef _WIN32 /* this is set for 64 bit as well */
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif

#ifdef _APPLE_
 #pragma clang diagnostic ignored "-Wall"
 #include <gl.h>
#else
 //#include <GL/gl.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string>
#include <time.h>
#include <iostream>
#include <fstream>
#include <atomic>

#include "./SDK/CHeaders/XPLM/XPLMPlugin.h"
#include "./SDK/CHeaders/XPLM/XPLMProcessing.h"
#include "./SDK/CHeaders/XPLM/XPLMDataAccess.h"
#include "./SDK/CHeaders/XPLM/XPLMUtilities.h"
#include "./SDK/CHeaders/XPLM/XPLMDisplay.h"
#include "./SDK/CHeaders/XPLM/XPLMGraphics.h"

// #include "readerwriterqueue.h"
#include "./include/defs.h"
#include "./include/main.h"

using namespace std;
// using namespace moodycamel;

static void enableLogging(void)
static void disableLogging(void);
static bool openLogFile(void);
static void closeLogFile(void);
static string const currentDateTime(bool useDash);
static void writeFileProlog(string t);
static void writeFileEpilog(void);
static void writeData(double lat, double lon, double alt, const string t);
static void DrawWindowCallback(XPLMWindowID inWindowID, void* inRefcon);
static void HandleKeyCallback(XPLMWindowID inWindowID, char inKey, XPLMKeyFlags inFlags,
                              char inVirtualKey, void* inRefcon, int losingFocus);
static int HandleMouseCallback(XPLMWindowID inWindowID, int x, int y,
                               XPLMMouseStatus inMouse, void* inRefcon);
static float FlightLoopCallback(float inElapsedSinceLastCall, float inElapsedTimeSinceLastFlightLoop,
                         int inCounter, void* inRefcon);

// To define, pass -DVERSION=vX.Y.X when building,
// e.g. in a make file
#ifndef VERSION
#define VERSION "vUNKNOWN"
#endif

// sigh. two levels of macros needed to stringify
// the result of expansion of a macro argument
#define STR(v) "DataRecorder " #v  " " __DATE__ " (jdpoirier@gmail.com)\0"
#define DESC(v) STR(v)

#define STRING2(x) #x
#define STRING(x) STRING2(x)

#pragma message (DESC(VERSION))

static XPLMWindowID gDataRecWindow = NULL;
static atomic<bool> gPluginEnabled(false);
// static atomic<int> gPlaneLoaded(0);

// time interval > 0 (no callback) > flight loop frame rate
static float gFlCbInterval = (float)0.100;

#define WINDOW_WIDTH (150)
#define WINDOW_HEIGHT (30)
static int gRecWinPosX;
static int gRecWinPosY;
static int gLastMouseX;
static int gLastMouseY;

// general & misc
enum {
    PLUGIN_PLANE_ID = 0
    ,DATARECORDER_WINDOW
};

XPLMDataRef lat_dref = NULL;
XPLMDataRef lon_dref = NULL;
XPLMDataRef alt_dref = NULL;

static atomic<bool> gLogging(false);
static atomic<bool> gFileOpenErr(false);
static ofstream gFd;

XPLMDataRef panel_visible_win_t_dataref;

/**
 *
 */
PLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc)
{
    LPRINTF("DataRecorder Plugin: XPluginStart\n");
    strcpy(outName, "DataRecorder");
    strcpy(outSig , "jdp.data.recorder");
    strcpy(outDesc, DESC(VERSION));

    lat_dref = XPLMFindDataRef("sim/flightmodel/position/latitude");
    lon_dref = XPLMFindDataRef("sim/flightmodel/position/longitude");
    alt_dref = XPLMFindDataRef("sim/flightmodel/position/elevation");

    panel_visible_win_t_dataref = XPLMFindDataRef("sim/graphics/view/panel_visible_win_t");
    int top = (int)XPLMGetDataf(panel_visible_win_t_dataref);
    gRecWinPosX = 0;
    gRecWinPosY = top - 150;
    gDataRecWindow = XPLMCreateWindow(gRecWinPosX,                  // left
                                      gRecWinPosY,                  // top
                                      gRecWinPosX+WINDOW_WIDTH,     // right
                                      gRecWinPosY-WINDOW_HEIGHT,    // bottom
                                      true,                         // is visible
                                      DrawWindowCallback,
                                      HandleKeyCallback,
                                      HandleMouseCallback,
                                      (void*)DATARECORDER_WINDOW);  // Refcon
    LPRINTF("DataRecorder Plugin: startup completed\n");
    return PROCESSED_EVENT;
}

/**
 *
 */
bool openLogFile(void)
{
    if (gFd.is_open())
        closeLogFile()

    string t = currentDateTime(true);
    string file = string("DataRecord-") + t + string(".gpx");
    // const char *ptr = file.c_str(); LPRINTF(ptr);

    gFd.open(file, ofstream::app); // creates the file if it doesn't exist
    if (!gFd.is_open()) {
        LPRINTF("DataRecorder Plugin: startup error, unable to open the output file...\n");
        return false;
    }
    writeFileProlog(t);
    return true;
}

/**
 *
 */
void closeLogFile(void)
{
    if (gFd.is_open()) {
        writeFileEpilog();
        gFd.close();
    }
}

/**
 *
 */
void writeFileProlog(string t)
{
    gFd << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    gFd << "<gpx version=\"1.0\">\n";
    gFd << "<metadata>\n";
    gFd << "<time>" << t << "</time>\n";
    gFd << "</metadata>\n";
    gFd << "<trk><name>DataRecorder plugin</name><trkseg>\n";
}

/**
 *
 */
void writeFileEpilog(void)
{
    gFd << "</trkseg></trk>\n";
    gFd << "</gpx>\n";
}

/**
 *
 */
void writeData(double lat, double lon, double alt, const string t)
{
    // <trkpt lat="46.57608333" lon="8.89241667"><ele>2376.640205</ele></trkpt>
    gFd << "<trkpt lat=\""
        << to_string(lat)
        << "\" lon=\""
        << to_string(lon)
        << "\"><ele>"
        << to_string(alt)
        // << to_string(static_cast<int>(alt))
        // << to_string(static_cast<int>(alt/METERS_PER_FOOT))
        << "</ele><time>"
        << t
        << "</time></trkpt>\n";
}

/**
 * Returns the current date and Zulu time.
 *
 * @return
 *      if useDash: YYYY-MM-DDTHH-MM-SSZ
 *      else:       YYYY-MM-DDTHH:MM:SSZ
 */
string const currentDateTime(bool useDash)
{
    time_t now = time(0);
    string buf(22,  '\0');
    // strftime(buf, sizeof(buf), "%FT%XZ", gmtime(&now));
    // strftime(buf, sizeof(buf), "%FT%XZ", localtime(&now));
    if (useDash)
        strftime((char*)buf.c_str(), buf.length(), "%Y-%m-%dT%H-%M-%SZ", gmtime(&now));
    else
        strftime((char*)buf.c_str(),  buf.length(), "%Y-%m-%dT%H:%M:%SZ", gmtime(&now));
    return buf.substr(0, 20);
}

/**
 *
 */
float FlightLoopCallback(float inElapsedSinceLastCall,
                         float inElapsedTimeSinceLastFlightLoop,
                         int inCounter, void* inRefcon)
{
    if (!gPluginEnabled.load() || !gLogging.load()) {
        // LPRINTF("DataRecorder Plugin: recording disabled...\n");
        return 0.0;  // disable the callback
    }
    // LPRINTF("DataRecorder Plugin: FlightLoopCallback writing data...\n");
    writeData(XPLMGetDataf(lat_dref),
                XPLMGetDataf(lon_dref),
                XPLMGetDataf(alt_dref),
                currentDateTime(false));
    return gFlCbInterval; // 10Hz update rate?
}

/**
 *
 */
void enableLogging(void){
    if (openLogFile()) {
        gLogging.store(true)
        XPLMRegisterFlightLoopCallback(FlightLoopCallback, -1.0, NULL);
    } else {
        gFileOpenErr.store(true)
    }
}

/**
 *
 */
void disableLogging(void)
{
    gLogging.store(false);
    XPLMUnregisterFlightLoopCallback(FlightLoopCallback, NULL);
    closeLogFile();
}

/**
 *
 */
PLUGIN_API void XPluginStop(void)
{
    gPluginEnabled.store(false);
    gLogging.store(false);
    XPLMUnregisterFlightLoopCallback(FlightLoopCallback, NULL);
    closeLogFile();
    LPRINTF("DataRecorder Plugin: XPluginStop\n");
}

/**
 *
 */
PLUGIN_API void XPluginDisable(void)
{
    gPluginEnabled.store(false);
    disableLogging();
    LPRINTF("DataRecorder Plugin: XPluginDisable\n");
}

/**
 *
 */
PLUGIN_API int XPluginEnable(void)
{
    gPluginEnabled.store(true);
     LPRINTF("DataRecorder Plugin: XPluginEnable\n");
    return PROCESSED_EVENT;
}

/**
 *
 */
PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom, long inMsg, void* inParam)
{
    if (inFrom == XPLM_PLUGIN_XPLANE) {
        // size_t inparam = reinterpret_cast<size_t>(inParam);
        switch (inMsg) {
        case XPLM_MSG_PLANE_LOADED:
            // gPlaneLoaded.store();
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_LOADED\n");
            break;
        case XPLM_MSG_AIRPORT_LOADED:
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_AIRPORT_LOADED\n");
            break;
        case XPLM_MSG_SCENERY_LOADED:
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_SCENERY_LOADED\n");
            break;
        case XPLM_MSG_AIRPLANE_COUNT_CHANGED:
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_AIRPLANE_COUNT_CHANGED\n");
            break;
        case XPLM_MSG_PLANE_CRASHED:
            // XXX: system state and procedure, what's difference between
            // an unloaded and crashed plane?
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_CRASHED\n");
            break;
        case XPLM_MSG_PLANE_UNLOADED:
            // gPlaneLoaded.store();
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_UNLOADED\n");
            break;
        default:
            // unknown, anything to do?
            break;
        } // switch (inMsg)
    } // if (inFrom == XPLM_PLUGIN_XPLANE)
}

/**
 *
 */
void DrawWindowCallback(XPLMWindowID inWindowID, void* inRefcon)
{
    static char str1[100];
    // RGB: White [1.0, 1.0, 1.0], Lime Green [0.0, 1.0, 0.0]
    static float datarecorder_color[] = {0.0, 1.0, 0.0};
    static int errCnt = 0;

    if (inWindowID != gDataRecWindow)
        return;

    int left;
    int top;
    int right;
    int bottom;

    // XXX: are inWindowIDs our XPLMCreateWindow return pointers
    XPLMGetWindowGeometry(inWindowID, &left, &top, &right, &bottom);
    XPLMDrawTranslucentDarkBox(left, top, right, bottom);

    switch (reinterpret_cast<size_t>(inRefcon)) {
    case DATARECORDER_WINDOW:
        switch (gLogging.load()) {
        case true:
            sprintf(str1, "Logging - %s", (char*)"Enabled...");
            break;
        case false:
            if (gFileOpenErr.load()) {
                errCnt += 1;
                sprintf(str1, "Logging - %s", (char*)"Error opening file");
                if (errCnt == 120) {
                    errCnt = 0;
                    gFileOpenErr.store(false);
                }
            } else {
                sprintf(str1, "Logging - %s", (char*)"Click to enable");
            }
            break
        }
        XPLMDrawString(datarecorder_color,
                       left+4,
                       top-20,
                       str1,
                       NULL,
                       xplmFont_Basic);
        break;
    default:
        break;
    }
}

/**
 *
 */
void HandleKeyCallback(XPLMWindowID inWindowID, char inKey, XPLMKeyFlags inFlags,
                       char inVirtualKey, void* inRefcon, int losingFocus)
{
    if (inWindowID != gDataRecWindow)
        return;
}

/*
 *
 *
 */
int HandleMouseCallback(XPLMWindowID inWindowID, int x, int y,
                        XPLMMouseStatus inMouse, void* inRefcon)
{
    // static int com_changed = COMMS_UNCHANGED;
    static int MouseDownX;
    static int MouseDownY;

    if (inWindowID != gDataRecWindow)
        return IGNORED_EVENT;

    switch (inMouse) {
    case xplm_MouseDown:
        // if ((x >= gRecWinPosX+WINDOW_WIDTH-8) &&
        //     (x <= gRecWinPosX+WINDOW_WIDTH) &&
        //     (y <= gRecWinPosY) && (y >= gRecWinPosY-8)) {
        //         windowCloseRequest = 1;
        //     } else {
                MouseDownX = gLastMouseX = x;
                MouseDownY = gLastMouseY = y;
        // }
        break;
    case xplm_MouseDrag:
        // this event fires while xplm_MouseDown is active
        // and whether or not the window is being dragged
        gRecWinPosX += (x - gLastMouseX);
        gRecWinPosY += (y - gLastMouseY);
        XPLMSetWindowGeometry(gDataRecWindow,
                              gRecWinPosX,
                              gRecWinPosY,
                              gRecWinPosX+WINDOW_WIDTH,
                              gRecWinPosY-WINDOW_HEIGHT);
        gLastMouseX = x;
        gLastMouseY = y;
        break;
    case xplm_MouseUp:
        // Ignore mouse-clicks for a short time
        // for a open file error.
        if (gFileOpenErr.load())
            break;
        if (MouseDownX == x || MouseDownY == y) {
            switch (gLogging.load()) {
            case true:
                disableLogging();
                break;
            case false:
                enableLogging();
                break
            }
        }
        break;
    } // switch (inMouse)
    return PROCESSED_EVENT;
}
<commit_msg>compilation error fixes<commit_after>// Copyright (c) 2015 Joseph D Poirier
// Distributable under the terms of The Simplified BSD License
// that can be found in the LICENSE file.

#ifdef _WIN32 /* this is set for 64 bit as well */
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#endif

#ifdef _APPLE_
 #pragma clang diagnostic ignored "-Wall"
 #include <gl.h>
#else
 //#include <GL/gl.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string>
#include <time.h>
#include <iostream>
#include <fstream>
#include <atomic>

#include "./SDK/CHeaders/XPLM/XPLMPlugin.h"
#include "./SDK/CHeaders/XPLM/XPLMProcessing.h"
#include "./SDK/CHeaders/XPLM/XPLMDataAccess.h"
#include "./SDK/CHeaders/XPLM/XPLMUtilities.h"
#include "./SDK/CHeaders/XPLM/XPLMDisplay.h"
#include "./SDK/CHeaders/XPLM/XPLMGraphics.h"

// #include "readerwriterqueue.h"
#include "./include/defs.h"
#include "./include/main.h"

using namespace std;
// using namespace moodycamel;

static void enableLogging(void);
static void disableLogging(void);
static bool openLogFile(void);
static void closeLogFile(void);
static string const currentDateTime(bool useDash);
static void writeFileProlog(string t);
static void writeFileEpilog(void);
static void writeData(double lat, double lon, double alt, const string t);
static void DrawWindowCallback(XPLMWindowID inWindowID, void* inRefcon);
static void HandleKeyCallback(XPLMWindowID inWindowID, char inKey, XPLMKeyFlags inFlags,
                              char inVirtualKey, void* inRefcon, int losingFocus);
static int HandleMouseCallback(XPLMWindowID inWindowID, int x, int y,
                               XPLMMouseStatus inMouse, void* inRefcon);
static float FlightLoopCallback(float inElapsedSinceLastCall, float inElapsedTimeSinceLastFlightLoop,
                         int inCounter, void* inRefcon);

// To define, pass -DVERSION=vX.Y.X when building,
// e.g. in a make file
#ifndef VERSION
#define VERSION "vUNKNOWN"
#endif

// sigh. two levels of macros needed to stringify
// the result of expansion of a macro argument
#define STR(v) "DataRecorder " #v  " " __DATE__ " (jdpoirier@gmail.com)\0"
#define DESC(v) STR(v)

#define STRING2(x) #x
#define STRING(x) STRING2(x)

#pragma message (DESC(VERSION))

static XPLMWindowID gDataRecWindow = NULL;
static atomic<bool> gPluginEnabled(false);
// static atomic<int> gPlaneLoaded(0);

// time interval > 0 (no callback) > flight loop frame rate
static float gFlCbInterval = (float)0.100;

#define WINDOW_WIDTH (150)
#define WINDOW_HEIGHT (30)
static int gRecWinPosX;
static int gRecWinPosY;
static int gLastMouseX;
static int gLastMouseY;

// general & misc
enum {
    PLUGIN_PLANE_ID = 0
    ,DATARECORDER_WINDOW
};

XPLMDataRef lat_dref = NULL;
XPLMDataRef lon_dref = NULL;
XPLMDataRef alt_dref = NULL;

static atomic<bool> gLogging(false);
static atomic<bool> gFileOpenErr(false);
static ofstream gFd;

XPLMDataRef panel_visible_win_t_dataref;

/**
 *
 */
PLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc)
{
    LPRINTF("DataRecorder Plugin: XPluginStart\n");
    strcpy(outName, "DataRecorder");
    strcpy(outSig , "jdp.data.recorder");
    strcpy(outDesc, DESC(VERSION));

    lat_dref = XPLMFindDataRef("sim/flightmodel/position/latitude");
    lon_dref = XPLMFindDataRef("sim/flightmodel/position/longitude");
    alt_dref = XPLMFindDataRef("sim/flightmodel/position/elevation");
    panel_visible_win_t_dataref = XPLMFindDataRef("sim/graphics/view/panel_visible_win_t");
    int top = (int)XPLMGetDataf(panel_visible_win_t_dataref);
    gRecWinPosX = 0;
    gRecWinPosY = top - 150;
    gDataRecWindow = XPLMCreateWindow(gRecWinPosX,                  // left
                                      gRecWinPosY,                  // top
                                      gRecWinPosX+WINDOW_WIDTH,     // right
                                      gRecWinPosY-WINDOW_HEIGHT,    // bottom
                                      true,                         // is visible
                                      DrawWindowCallback,
                                      HandleKeyCallback,
                                      HandleMouseCallback,
                                      (void*)DATARECORDER_WINDOW);  // Refcon
    LPRINTF("DataRecorder Plugin: startup completed\n");
    return PROCESSED_EVENT;
}

/**
 *
 */
bool openLogFile(void)
{
    if (gFd.is_open())
        closeLogFile();

    string t = currentDateTime(true);
    string file = string("DataRecord-") + t + string(".gpx");
    // const char *ptr = file.c_str(); LPRINTF(ptr);

    gFd.open(file, ofstream::app); // creates the file if it doesn't exist
    if (!gFd.is_open()) {
        LPRINTF("DataRecorder Plugin: startup error, unable to open the output file...\n");
        return false;
    }
    writeFileProlog(t);
    return true;
}

/**
 *
 */
void closeLogFile(void)
{
    if (gFd.is_open()) {
        writeFileEpilog();
        gFd.close();
    }
}

/**
 *
 */
void writeFileProlog(string t)
{
    gFd << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    gFd << "<gpx version=\"1.0\">\n";
    gFd << "<metadata>\n";
    gFd << "<time>" << t << "</time>\n";
    gFd << "</metadata>\n";
    gFd << "<trk><name>DataRecorder plugin</name><trkseg>\n";
}

/**
 *
 */
void writeFileEpilog(void)
{
    gFd << "</trkseg></trk>\n";
    gFd << "</gpx>\n";
}

/**
 *
 */
void writeData(double lat, double lon, double alt, const string t)
{
    // <trkpt lat="46.57608333" lon="8.89241667"><ele>2376.640205</ele></trkpt>
    gFd << "<trkpt lat=\""
        << to_string(lat)
        << "\" lon=\""
        << to_string(lon)
        << "\"><ele>"
        << to_string(alt)
        // << to_string(static_cast<int>(alt))
        // << to_string(static_cast<int>(alt/METERS_PER_FOOT))
        << "</ele><time>"
        << t
        << "</time></trkpt>\n";
}

/**
 * Returns the current date and Zulu time.
 *
 * @return
 *      if useDash: YYYY-MM-DDTHH-MM-SSZ
 *      else:       YYYY-MM-DDTHH:MM:SSZ
 */
string const currentDateTime(bool useDash)
{
    time_t now = time(0);
    string buf(22,  '\0');
    // strftime(buf, sizeof(buf), "%FT%XZ", gmtime(&now));
    // strftime(buf, sizeof(buf), "%FT%XZ", localtime(&now));
    if (useDash)
        strftime((char*)buf.c_str(), buf.length(), "%Y-%m-%dT%H-%M-%SZ", gmtime(&now));
    else
        strftime((char*)buf.c_str(),  buf.length(), "%Y-%m-%dT%H:%M:%SZ", gmtime(&now));
    return buf.substr(0, 20);
}

/**
 *
 */
float FlightLoopCallback(float inElapsedSinceLastCall,
                         float inElapsedTimeSinceLastFlightLoop,
                         int inCounter, void* inRefcon)
{
    if (!gPluginEnabled.load() || !gLogging.load()) {
        // LPRINTF("DataRecorder Plugin: recording disabled...\n");
        return 0.0;  // disable the callback
    }
    // LPRINTF("DataRecorder Plugin: FlightLoopCallback writing data...\n");
    writeData(XPLMGetDataf(lat_dref),
                XPLMGetDataf(lon_dref),
                XPLMGetDataf(alt_dref),
                currentDateTime(false));
    return gFlCbInterval; // 10Hz update rate?
}

/**
 *
 */
void enableLogging(void){
    if (openLogFile()) {
        gLogging.store(true);
        XPLMRegisterFlightLoopCallback(FlightLoopCallback, -1.0, NULL);
    } else {
        gFileOpenErr.store(true);
    }
}

/**
 *
 */
void disableLogging(void)
{
    gLogging.store(false);
    XPLMUnregisterFlightLoopCallback(FlightLoopCallback, NULL);
    closeLogFile();
}

/**
 *
 */
PLUGIN_API void XPluginStop(void)
{
    gPluginEnabled.store(false);
    gLogging.store(false);
    XPLMUnregisterFlightLoopCallback(FlightLoopCallback, NULL);
    closeLogFile();
    LPRINTF("DataRecorder Plugin: XPluginStop\n");
}

/**
 *
 */
PLUGIN_API void XPluginDisable(void)
{
    gPluginEnabled.store(false);
    disableLogging();
    LPRINTF("DataRecorder Plugin: XPluginDisable\n");
}

/**
 *
 */
PLUGIN_API int XPluginEnable(void)
{
    gPluginEnabled.store(true);
     LPRINTF("DataRecorder Plugin: XPluginEnable\n");
    return PROCESSED_EVENT;
}

/**
 *
 */
PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom, long inMsg, void* inParam)
{
    if (inFrom == XPLM_PLUGIN_XPLANE) {
        // size_t inparam = reinterpret_cast<size_t>(inParam);
        switch (inMsg) {
        case XPLM_MSG_PLANE_LOADED:
            // gPlaneLoaded.store();
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_LOADED\n");
            break;
        case XPLM_MSG_AIRPORT_LOADED:
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_AIRPORT_LOADED\n");
            break;
        case XPLM_MSG_SCENERY_LOADED:
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_SCENERY_LOADED\n");
            break;
        case XPLM_MSG_AIRPLANE_COUNT_CHANGED:
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_AIRPLANE_COUNT_CHANGED\n");
            break;
        case XPLM_MSG_PLANE_CRASHED:
            // XXX: system state and procedure, what's difference between
            // an unloaded and crashed plane?
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_CRASHED\n");
            break;
        case XPLM_MSG_PLANE_UNLOADED:
            // gPlaneLoaded.store();
            // LPRINTF("DataRecorder Plugin: XPluginReceiveMessage XPLM_MSG_PLANE_UNLOADED\n");
            break;
        default:
            // unknown, anything to do?
            break;
        } // switch (inMsg)
    } // if (inFrom == XPLM_PLUGIN_XPLANE)
}

/**
 *
 */
void DrawWindowCallback(XPLMWindowID inWindowID, void* inRefcon)
{
    static char str1[100];
    // RGB: White [1.0, 1.0, 1.0], Lime Green [0.0, 1.0, 0.0]
    static float datarecorder_color[] = {0.0, 1.0, 0.0};
    static int errCnt = 0;

    if (inWindowID != gDataRecWindow)
        return;

    int left;
    int top;
    int right;
    int bottom;

    // XXX: are inWindowIDs our XPLMCreateWindow return pointers
    XPLMGetWindowGeometry(inWindowID, &left, &top, &right, &bottom);
    XPLMDrawTranslucentDarkBox(left, top, right, bottom);

    switch (reinterpret_cast<size_t>(inRefcon)) {
    case DATARECORDER_WINDOW:
        switch (gLogging.load()) {
        case true:
            sprintf(str1, "Logging - %s", (char*)"Enabled...");
            break;
        case false:
            if (gFileOpenErr.load()) {
                errCnt += 1;
                sprintf(str1, "Logging - %s", (char*)"Error opening file");
                if (errCnt == 120) {
                    errCnt = 0;
                    gFileOpenErr.store(false);
                }
            } else {
                sprintf(str1, "Logging - %s", (char*)"Click to enable");
            }
            break;
        }
        XPLMDrawString(datarecorder_color,
                       left+4,
                       top-20,
                       str1,
                       NULL,
                       xplmFont_Basic);
        break;
    default:
        break;
    }
}

/**
 *
 */
void HandleKeyCallback(XPLMWindowID inWindowID, char inKey, XPLMKeyFlags inFlags,
                       char inVirtualKey, void* inRefcon, int losingFocus)
{
    if (inWindowID != gDataRecWindow)
        return;
}

/*
 *
 *
 */
int HandleMouseCallback(XPLMWindowID inWindowID, int x, int y,
                        XPLMMouseStatus inMouse, void* inRefcon)
{
    // static int com_changed = COMMS_UNCHANGED;
    static int MouseDownX;
    static int MouseDownY;

    if (inWindowID != gDataRecWindow)
        return IGNORED_EVENT;

    switch (inMouse) {
    case xplm_MouseDown:
        // if ((x >= gRecWinPosX+WINDOW_WIDTH-8) &&
        //     (x <= gRecWinPosX+WINDOW_WIDTH) &&
        //     (y <= gRecWinPosY) && (y >= gRecWinPosY-8)) {
        //         windowCloseRequest = 1;
        //     } else {
                MouseDownX = gLastMouseX = x;
                MouseDownY = gLastMouseY = y;
        // }
        break;
    case xplm_MouseDrag:
        // this event fires while xplm_MouseDown is active
        // and whether or not the window is being dragged
        gRecWinPosX += (x - gLastMouseX);
        gRecWinPosY += (y - gLastMouseY);
        XPLMSetWindowGeometry(gDataRecWindow,
                              gRecWinPosX,
                              gRecWinPosY,
                              gRecWinPosX+WINDOW_WIDTH,
                              gRecWinPosY-WINDOW_HEIGHT);
        gLastMouseX = x;
        gLastMouseY = y;
        break;
    case xplm_MouseUp:
        // Ignore mouse-clicks for a short time
        // for a open file error.
        if (gFileOpenErr.load())
            break;
        if (MouseDownX == x || MouseDownY == y) {
            switch (gLogging.load()) {
            case true:
                disableLogging();
                break;
            case false:
                enableLogging();
                break;
            }
        }
        break;
    } // switch (inMouse)
    return PROCESSED_EVENT;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdint.h>
#include "message.hpp"
#include "message_handler.hpp"

void handler(void* args)
{
	printf("Handler Called\n");
}

/*
uint8_t process_messages(uint8_t* buffer, const uint8_t size)
{
	if(size < sizeof(PayloadHeader)) { return size; }
	PayloadHeader* payload = static_cast<PayloadHeader*>(buffer);

}*/

int main()
{

	PeripheralMessages::VersionQueryMsg::set_callback(&handler,NULL);
	printf("Messaging test\n");

	/*processMessages(PeripheralMessages::MessageId::VersionQuery);
	processMessages(PeripheralMessages::MessageId::TemperatureQuery);
	processMessages(PeripheralMessages::MessageId::VersionData);*/
	PeripheralMessages::VersionQueryMsg msg;
	//processMessages(msg.get_message_buffer(),msg.get_message_buffer_size());

	PeripheralMessages::MessageHandlerInterface msg_handler;
	msg_handler.process_messages(msg.get_message_buffer(),msg.get_message_buffer_size());
	//msg.trigger_callback();

}

<commit_msg>RPI updates to main<commit_after>#include <stdio.h>
#include <stdint.h>
#include "rf24_message_handler_rpi.hpp"

PeripheralMessages::RF24MessageHandlerRpi rpihandler;

void handle_ping(void* args, void*  msg, uint16_t calling_id)
{
	PeripheralMessages::PingPongQueryMsg* ping_ptr =
			static_cast<PeripheralMessages::PingPongQueryMsg*>(msg);
	printf("Ping received: %u\n", ping_ptr->get_message_payload()->count);

	PeripheralMessages::PingPongDataMsg pong;
	pong.get_message_payload()->count = ping_ptr->get_message_payload()->count;

	rpihandler.publish_message(pong.get_message_buffer(),pong.get_message_buffer_size(),calling_id);
}

int main()
{

	PeripheralMessages::PingPongQueryMsg::set_callback(&handle_ping);

	while(1)
	{
		rpihandler.service_once();
	}

}

<|endoftext|>


<commit_before>/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 1.0c
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date		Revision	Changed By		Changes
------  	---------   ------------	---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM BETA TO GAMMA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/03/13	1.0c		Patrick Rye		-Move from beta revisions to gamma revisions.
										-Changed some int to smaller variables because they don't need to be that big.
										-Fixed bug where new dungeon wasn't generating properly. (This is what happens when you don't play test changes for a while).
										-Made it so you have to be in debug mode to force a monster (Don't know why you would want this otherwise)
										-General code improvement.
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple and won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon.
#include "spells.h" //Functions that deal with spells and magic
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
unsigned char intMainLevel = 1; //The level of the dungeon.
unsigned char intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "1.0c"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(unsigned char intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}
void setmainvalue(unsigned char intlocation, unsigned int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{
	PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
	cout << string(48, '\n');
	char charPlayerDirection;
	bool blBattleEnding = false;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';

	char chrSaveSuccess = 'N'; //N means that save has not been run.

	//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
	if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }

	if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true); SetSpellDebugMode(true);} //Sets debug mode for both rooms.h, battle.h, & spells.h

	ShowOpeningMessage();
	getchar();
	cout<<string(50,'\n');

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave();
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by @ ."<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {d.cmain();/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<(int)intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go: "<<endl;
			cout<<"[N]orth,  [E]ast,  [S]outh,  [W]est  "<<endl;
			cout<<"E[X]it,   [C]heck your health, [H]eal,   Sa[V]e  "<<endl;
			if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);

			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10 || (charExitFind == 'M' && blDebugMode)) //Random chance to encounter monster, or debug code to force monster encounter.
				{
					cout << string(50, '\n');
					blBattleEnding = startbattle(intMainLevel); //Starts battle.
					if(!blBattleEnding) {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	//End of FOR levels.
	}
	cout << string(50, '\n');
	ShowWinningMessage();
	getchar();
	return 0;
//End of main
}
<commit_msg>Update main to V1.1c<commit_after>/*
Made By: Patrick J. Rye
Purpose: A game I made as an attempt to teach myself c++, just super basic, but going to try to keep improving it as my knowledge increases.
Current Revision: 1.1c
Change Log---------------------------------------------------------------------------------------------------------------------------------------------------
Date		Revision	Changed By		Changes
------  	---------   ------------	---------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
-------------------------------------------------------------------------------------------------------------------------------------------------------------
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MOVED FROM BETA TO GAMMA~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-------------------------------------------------------------------------------------------------------------------------------------------------------------
=============================================================================================================================================================
2015/03/13	1.0c		Patrick Rye		-Move from beta revisions to gamma revisions.
										-Changed some int to smaller variables because they don't need to be that big.
										-Fixed bug where new dungeon wasn't generating properly. (This is what happens when you don't play test changes for a while).
										-Made it so you have to be in debug mode to force a monster (Don't know why you would want this otherwise)
										-General code improvement.
=============================================================================================================================================================
2015/03/17	1.1c		Patrick Rye		-Grammar & spelling fixes.
										-Updated save.h with more values.
										-Implemented mana system.
=============================================================================================================================================================
*/

/*********************************************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
#include <cstdlib>
#include <cmath>
#include <locale>
#include <cstdio>
#include <ctime>
/*********************************************************************************************************/
#include "basic.h" //Functions that are simple, referenced many places and/or won't need to be changed very often.
#include "battle.h" //Functions that deal with battling, levelling up and making a player.
#include "rooms.h" //Functions that deal with generating a dungeon, and moving through it.
#include "spells.h" //Functions that deal with spells and magic.
/*********************************************************************************************************/
using namespace std;
Dungeon d; //Define the dungeon class as 'd' so I can use functions in there anywhere later in the code.
/*********************************************************************************************************/
//Make all the global variables that I need.
unsigned char intMainLevel = 1; //The level of the dungeon.
unsigned char intLevelStart = 1; //The level that the game starts at. Will be 1 unless loading from a save.
bool blDebugMode = false; //If game is in debug mode or not, effects if player has access to debug commands.
const string CurrentVerison = "1.1c"; //The current version of this program, stored in a save file later on.
/*********************************************************************************************************/
//These functions have to be up here as functions in save.h use them.
//These values are used to pass values to the save header so that they may be saved.
//Or to set values from a load.
int getmainvalue(unsigned char intvalue)
{
	if(intvalue == 0 ) {return intMainLevel;}
	else if (intvalue == 1) {return intLevelStart;}
	else {return 1;}
}
void setmainvalue(unsigned char intlocation, unsigned int intvalue) {if (intlocation == 0) {intLevelStart = intvalue;}}
void setdebugmode(bool blsetdebugmode) {blDebugMode = blsetdebugmode;}
#include "save.h" //A header to hold functions related to saving and loading.
/*********************************************************************************************************/

int main()
{
	PassProgramVerison(CurrentVerison); //Pass current program version into the save header.
	cout << string(48, '\n');
	char charPlayerDirection;
	bool blBattleEnding = false;
	char charExitFind;
	bool blOldSave = false;
	char chrPlayerMade = 'F';
	char chrSaveSuccess = 'N'; //N means that save has not been run.
	//If game is not already in debug mode, checks if source code exists then put it in debug mode if it does.
	if (!(blDebugMode)) {blDebugMode = fileexists("main.cpp"); }
	//Sets debug mode for rooms.h, battle.h, & spells.h
	if (blDebugMode) {SetBattleDebugMode(true); SetRoomDebugMode(true); SetSpellDebugMode(true);}
	ShowOpeningMessage();
	getchar();
	cout<<string(50,'\n');

	if (fileexists("save.bif")) //Check if there is a save present.
	{
		blOldSave = LoadOldSave();
		if (blOldSave) {chrPlayerMade = 'T';}
	//End of if save exists.
	}
	else {cout<<string(50, '\n');}

	if(!blOldSave) //If it is not an old save show welcome message.
	{
		cout<<endl<<"Your objective is to go through 10 randomly generated dungeons."<<endl;
		cout<<"You are looking for the stairs down ( > ). While you are represented by @ ."<<endl;
		cout<<"Every step brings you closer to your goal, but there might be a monster there as well."<<endl;
		cout<<"Each level is harder than the last, do you have what it takes to win?"<<endl;
		cout<<"Good luck!"<<endl<<endl<<endl<<endl;
		while (chrPlayerMade != 'T') {chrPlayerMade = PlayerInitialize();}; //Repeat initialization until player is made.
	}

	for(intMainLevel = intLevelStart; intMainLevel <= 10; intMainLevel++)
	{
		//Do level up if new level.
		if (intMainLevel > intLevelStart) {LevelUpFunction();}
		charExitFind = 'F';
		cout<<endl;
		if (blOldSave && intMainLevel == intLevelStart) {/*d.playerfind();*/ d.showDungeon();} //If old save and the level of that save, just load old dungeon.
		else {d.cmain();/*Generates dungeon.*/} //If it is not old game OR a different level of old game, make new dungeon.

		do
		{
			cout << string(50, '\n');
			d.showDungeon();
			cout<<"Level "<<(int)intMainLevel<<" of 10."<<endl;
			cout<<"Please enter a direction you would like to go: "<<endl;
			cout<<"[N]orth,  [E]ast,  [S]outh,  [W]est  "<<endl;
			cout<<"E[X]it,   [C]heck your health, [H]eal,   Sa[V]e  "<<endl;
			if (blDebugMode) {cout<<"[L]evel up, or [M]onster."<<endl;}
			cout<<"> ";
			cin>>charPlayerDirection;
			charPlayerDirection = CharConvertToUpper(charPlayerDirection);
			charExitFind = d.PlayerMovement(charPlayerDirection);
			if (charExitFind == 'E') {return 0;} //If we get an error exit program.
			if (charExitFind == 'S') {chrSaveSuccess = savefunction();} //Save the game.
			switch (chrSaveSuccess)
			{
				case 'T' :
					cout<<endl<<"Save succeeded."<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
				case 'F' :
					cout<<endl<<"Save failed!"<<endl;
					getchar();
					chrSaveSuccess = 'N'; //Set this back to N, so that player is not spammed with this message.
					break;
			}
			if (!(charExitFind=='S') && !(charPlayerDirection == 'C')) //If player did not save or did not check himself, see if player runs into monster.
			{
				if(rand() % 101 <= 10 || (charExitFind == 'M' && blDebugMode)) //Random chance to encounter monster, or debug code to force monster encounter.
				{
					cout << string(50, '\n');
					blBattleEnding = startbattle(intMainLevel); //Starts battle.
					setbattlevalue(statKeys,getbattlevalue(statKeys) + getmonstervalue(statKeys)); //Give player a key if monster had one.
					if(!blBattleEnding) {return 0;} //Player lost battle.
				}
			}
		}while (charExitFind != 'T'); //Repeat until player finds exit.
	//End of FOR levels.
	}
	cout << string(50, '\n');
	ShowWinningMessage();
	getchar();
	return 0;
//End of main
}
<|endoftext|>


<commit_before>#include "html5viewer/html5viewer.h"
#include "ClientWrapper.hpp"
#include "Utilities.hpp"
#include "MainWindow.hpp"

#include <boost/thread.hpp>
#include <bts/blockchain/config.hpp>
#include <bts/wallet/url.hpp>
#include <signal.h>

#include <QApplication>
#include <QSettings>
#include <QPixmap>
#include <QErrorMessage>
#include <QSplashScreen>
#include <QDir>
#include <QWebSettings>
#include <QWebPage>
#include <QWebFrame>
#include <QJsonDocument>
#include <QGraphicsWebView>
#include <QTimer>
#include <QAuthenticator>
#include <QNetworkReply>
#include <QResource>
#include <QGraphicsWidget>
#include <QMainWindow>
#include <QMenuBar>
#include <QLayout>
#include <QLocalSocket>
#include <QLocalServer>
#include <QMessageBox>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <boost/program_options.hpp>

#include <bts/client/client.hpp>
#include <bts/net/upnp.hpp>
#include <bts/blockchain/chain_database.hpp>
#include <bts/rpc/rpc_server.hpp>
#include <bts/cli/cli.hpp>
#include <bts/utilities/git_revision.hpp>
#include <fc/filesystem.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/git_revision.hpp>
#include <fc/io/json.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/signals.hpp>

#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>

#include <fstream>
#include <iostream>
#include <iomanip>

void setupMenus(ClientWrapper* client, MainWindow* mainWindow)
{
  auto accountMenu = mainWindow->accountMenu();

  accountMenu->addAction("&Go to My Accounts", mainWindow, SLOT(goToMyAccounts()));
  accountMenu->addAction("&Create Account", mainWindow, SLOT(goToCreateAccount()));
  accountMenu->addAction("&Import Account")->setEnabled(false);
}

void prepareStartupSequence(ClientWrapper* client, Html5Viewer* viewer, MainWindow* mainWindow, QSplashScreen* splash)
{
  viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("bitshares", client);
  viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("magic_unicorn", new Utilities, QWebFrame::ScriptOwnership);

  QObject::connect(viewer->webView()->page()->networkAccessManager(), &QNetworkAccessManager::authenticationRequired,
                   [client](QNetworkReply*, QAuthenticator *auth) {
    auth->setUser(client->http_url().userName());
    auth->setPassword(client->http_url().password());
  });
  client->connect(client, &ClientWrapper::initialized, [viewer,client,mainWindow]() {
    ilog( "Client initialized; loading web interface from ${url}", ("url", client->http_url().toString().toStdString()) );
    client->status_update("Calculating last 3 digits of pi");
    viewer->webView()->load(client->http_url());
    //Now we know the URL of the app, so we can create the items in the Accounts menu
    setupMenus(client, mainWindow);
  });
  auto loadFinishedConnection = std::make_shared<QMetaObject::Connection>();
  *loadFinishedConnection = viewer->connect(viewer->webView(), &QGraphicsWebView::loadFinished, [mainWindow,splash,viewer,loadFinishedConnection](bool ok) {
    ilog( "Webview loaded: ${status}", ("status", ok) );
    viewer->disconnect(*loadFinishedConnection);
    mainWindow->show();
    splash->finish(mainWindow);
    mainWindow->processDeferredUrl();
  });
  client->connect(client, &ClientWrapper::error, [=](QString errorString) {
    splash->hide();
    QMessageBox::critical(nullptr, QObject::tr("Error"), errorString);
    exit(1);
  });
  client->connect(client, &ClientWrapper::status_update, [=](QString messageString) {
    splash->showMessage(messageString, Qt::AlignCenter | Qt::AlignBottom, Qt::white);
  });
}

QLocalServer* startSingleInstanceServer(MainWindow* mainWindow)
{
  QLocalServer* singleInstanceServer = new QLocalServer();
  if( !singleInstanceServer->listen(BTS_BLOCKCHAIN_NAME) )
  {
    std::cerr << "Could not start new instance listener. Attempting to remove defunct listener... ";
    QLocalServer::removeServer(BTS_BLOCKCHAIN_NAME);
    if( !singleInstanceServer->listen(BTS_BLOCKCHAIN_NAME) )
    {
      std::cerr << "Failed to start new instance listener: " << singleInstanceServer->errorString().toStdString() << std::endl;
      exit(1);
    }
    std::cerr << "Success.\n";
  }

  std::cout << "Listening for new instances on " << singleInstanceServer->fullServerName().toStdString() << std::endl;
  singleInstanceServer->connect(singleInstanceServer, &QLocalServer::newConnection, [singleInstanceServer,mainWindow](){
    QLocalSocket* zygote = singleInstanceServer->nextPendingConnection();
    QEventLoop waitLoop;

    zygote->connect(zygote, &QLocalSocket::readyRead, &waitLoop, &QEventLoop::quit);
    QTimer::singleShot(1000, &waitLoop, SLOT(quit()));
    waitLoop.exec();

    mainWindow->raise();
    mainWindow->activateWindow();

    if( zygote->bytesAvailable() )
    {
      QByteArray message = zygote->readLine();
      ilog("Got message from new instance: ${msg}", ("msg",message.data()));
      mainWindow->processCustomUrl(message);
    }
    zygote->close();

    delete zygote;
  });

  return singleInstanceServer;
}

int main( int argc, char** argv )
{
  QCoreApplication::setOrganizationName( "BitShares" );
  QCoreApplication::setOrganizationDomain( "bitshares.org" );
  QCoreApplication::setApplicationName( BTS_BLOCKCHAIN_NAME );
  QApplication app(argc, argv);
  app.setWindowIcon(QIcon(":/images/qtapp.ico"));

  MainWindow mainWindow;

  //Custom URL handling. OSX handles this differently from Windows and Linux
  //On OSX, the OS will always pass the URL as an event to QApplication.
  //Windows and Linux will just run our program with the URL as an argument.
#ifdef __APPLE__
  //Install OSX event handler
  app.installEventFilter(&mainWindow);
#endif

  //We'll go ahead and leave Win/Lin URL handling available in OSX too
  QLocalSocket* sock = new QLocalSocket();
  sock->connectToServer(BTS_BLOCKCHAIN_NAME);
  if( sock->waitForConnected(100) )
  {
    if( argc > 1 && app.arguments()[1].startsWith(QString(CUSTOM_URL_SCHEME) + ":") )
    {
      //Need to open a custom URL. Pass it to pre-existing instance.
      std::cout << "Found instance already running. Sending message and exiting." << std::endl;
      sock->write(argv[1]);
      sock->waitForBytesWritten();
      sock->close();
    }
    //Note that we connected, but may not have sent anything. This means that another instance is already
    //running. The fact that we connected prompted it to request focus; we will just exit now.
    delete sock;
    return 0;
  }
  else
  {
    if( argc > 1 && app.arguments()[1].startsWith(QString(CUSTOM_URL_SCHEME) + ":") )
    {
      //No other instance running. Handle URL when we get started up.
      mainWindow.deferCustomUrl(app.arguments()[1]);
    }

    //Could not connect to already-running instance. Start a server so future instances connect to us
    QLocalServer* singleInstanceServer = startSingleInstanceServer(&mainWindow);
    app.connect(&app, &QApplication::aboutToQuit, singleInstanceServer, &QLocalServer::deleteLater);
  }
  delete sock;

  //License agreement
  if( !mainWindow.settings()->value("license_accepted", false).toBool() )
  {
    QQmlApplicationEngine engine(QUrl("qrc:/qml/LicenseAgreement.qml"));
    QFile license(":/license.txt");
    license.open(QIODevice::ReadOnly);
    engine.rootObjects()[0]->setProperty("licenseText", license.readAll());
    app.exec();
    mainWindow.settings()->setValue("license_accepted", engine.rootObjects()[0]->property("accepted"));
  }
  if( !mainWindow.settings()->value("license_accepted", false).toBool() )
    return 0;

  auto viewer = new Html5Viewer;
  ClientWrapper* client = new ClientWrapper;
  app.connect(&app, &QApplication::aboutToQuit, client, &ClientWrapper::close);

  mainWindow.setCentralWidget(viewer);
  mainWindow.setClientWrapper(client);

  QTimer fc_tasks;
  fc_tasks.connect( &fc_tasks, &QTimer::timeout, [](){ fc::usleep( fc::microseconds( 1000 ) ); } );
  fc_tasks.start(33);

  QPixmap pixmap(":/images/splash_screen.jpg");
  QSplashScreen splash(pixmap);
  splash.showMessage(QObject::tr("Loading configuration..."),
                     Qt::AlignCenter | Qt::AlignBottom, Qt::white);
  splash.show();

  prepareStartupSequence(client, viewer, &mainWindow, &splash);

  QWebSettings::globalSettings()->setAttribute( QWebSettings::PluginsEnabled, false );

  try {
    client->initialize();
    return app.exec();
  }
  catch ( const fc::exception& e)
  {
    elog( "${e}", ("e",e.to_detail_string() ) );
    QErrorMessage::qtHandler()->showMessage( e.to_string().c_str() );
  }
}
<commit_msg>disable license for now<commit_after>#include "html5viewer/html5viewer.h"
#include "ClientWrapper.hpp"
#include "Utilities.hpp"
#include "MainWindow.hpp"

#include <boost/thread.hpp>
#include <bts/blockchain/config.hpp>
#include <bts/wallet/url.hpp>
#include <signal.h>

#include <QApplication>
#include <QSettings>
#include <QPixmap>
#include <QErrorMessage>
#include <QSplashScreen>
#include <QDir>
#include <QWebSettings>
#include <QWebPage>
#include <QWebFrame>
#include <QJsonDocument>
#include <QGraphicsWebView>
#include <QTimer>
#include <QAuthenticator>
#include <QNetworkReply>
#include <QResource>
#include <QGraphicsWidget>
#include <QMainWindow>
#include <QMenuBar>
#include <QLayout>
#include <QLocalSocket>
#include <QLocalServer>
#include <QMessageBox>
#include <QQmlApplicationEngine>
#include <QQmlContext>

#include <boost/program_options.hpp>

#include <bts/client/client.hpp>
#include <bts/net/upnp.hpp>
#include <bts/blockchain/chain_database.hpp>
#include <bts/rpc/rpc_server.hpp>
#include <bts/cli/cli.hpp>
#include <bts/utilities/git_revision.hpp>
#include <fc/filesystem.hpp>
#include <fc/thread/thread.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/io/json.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/git_revision.hpp>
#include <fc/io/json.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/signals.hpp>

#include <boost/iostreams/tee.hpp>
#include <boost/iostreams/stream.hpp>

#include <fstream>
#include <iostream>
#include <iomanip>

void setupMenus(ClientWrapper* client, MainWindow* mainWindow)
{
  auto accountMenu = mainWindow->accountMenu();

  accountMenu->addAction("&Go to My Accounts", mainWindow, SLOT(goToMyAccounts()));
  accountMenu->addAction("&Create Account", mainWindow, SLOT(goToCreateAccount()));
  accountMenu->addAction("&Import Account")->setEnabled(false);
}

void prepareStartupSequence(ClientWrapper* client, Html5Viewer* viewer, MainWindow* mainWindow, QSplashScreen* splash)
{
  viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("bitshares", client);
  viewer->webView()->page()->mainFrame()->addToJavaScriptWindowObject("magic_unicorn", new Utilities, QWebFrame::ScriptOwnership);

  QObject::connect(viewer->webView()->page()->networkAccessManager(), &QNetworkAccessManager::authenticationRequired,
                   [client](QNetworkReply*, QAuthenticator *auth) {
    auth->setUser(client->http_url().userName());
    auth->setPassword(client->http_url().password());
  });
  client->connect(client, &ClientWrapper::initialized, [viewer,client,mainWindow]() {
    ilog( "Client initialized; loading web interface from ${url}", ("url", client->http_url().toString().toStdString()) );
    client->status_update("Calculating last 3 digits of pi");
    viewer->webView()->load(client->http_url());
    //Now we know the URL of the app, so we can create the items in the Accounts menu
    setupMenus(client, mainWindow);
  });
  auto loadFinishedConnection = std::make_shared<QMetaObject::Connection>();
  *loadFinishedConnection = viewer->connect(viewer->webView(), &QGraphicsWebView::loadFinished, [mainWindow,splash,viewer,loadFinishedConnection](bool ok) {
    ilog( "Webview loaded: ${status}", ("status", ok) );
    viewer->disconnect(*loadFinishedConnection);
    mainWindow->show();
    splash->finish(mainWindow);
    mainWindow->processDeferredUrl();
  });
  client->connect(client, &ClientWrapper::error, [=](QString errorString) {
    splash->hide();
    QMessageBox::critical(nullptr, QObject::tr("Error"), errorString);
    exit(1);
  });
  client->connect(client, &ClientWrapper::status_update, [=](QString messageString) {
    splash->showMessage(messageString, Qt::AlignCenter | Qt::AlignBottom, Qt::white);
  });
}

QLocalServer* startSingleInstanceServer(MainWindow* mainWindow)
{
  QLocalServer* singleInstanceServer = new QLocalServer();
  if( !singleInstanceServer->listen(BTS_BLOCKCHAIN_NAME) )
  {
    std::cerr << "Could not start new instance listener. Attempting to remove defunct listener... ";
    QLocalServer::removeServer(BTS_BLOCKCHAIN_NAME);
    if( !singleInstanceServer->listen(BTS_BLOCKCHAIN_NAME) )
    {
      std::cerr << "Failed to start new instance listener: " << singleInstanceServer->errorString().toStdString() << std::endl;
      exit(1);
    }
    std::cerr << "Success.\n";
  }

  std::cout << "Listening for new instances on " << singleInstanceServer->fullServerName().toStdString() << std::endl;
  singleInstanceServer->connect(singleInstanceServer, &QLocalServer::newConnection, [singleInstanceServer,mainWindow](){
    QLocalSocket* zygote = singleInstanceServer->nextPendingConnection();
    QEventLoop waitLoop;

    zygote->connect(zygote, &QLocalSocket::readyRead, &waitLoop, &QEventLoop::quit);
    QTimer::singleShot(1000, &waitLoop, SLOT(quit()));
    waitLoop.exec();

    mainWindow->raise();
    mainWindow->activateWindow();

    if( zygote->bytesAvailable() )
    {
      QByteArray message = zygote->readLine();
      ilog("Got message from new instance: ${msg}", ("msg",message.data()));
      mainWindow->processCustomUrl(message);
    }
    zygote->close();

    delete zygote;
  });

  return singleInstanceServer;
}

int main( int argc, char** argv )
{
  QCoreApplication::setOrganizationName( "BitShares" );
  QCoreApplication::setOrganizationDomain( "bitshares.org" );
  QCoreApplication::setApplicationName( BTS_BLOCKCHAIN_NAME );
  QApplication app(argc, argv);
  app.setWindowIcon(QIcon(":/images/qtapp.ico"));

  MainWindow mainWindow;

  //Custom URL handling. OSX handles this differently from Windows and Linux
  //On OSX, the OS will always pass the URL as an event to QApplication.
  //Windows and Linux will just run our program with the URL as an argument.
#ifdef __APPLE__
  //Install OSX event handler
  app.installEventFilter(&mainWindow);
#endif

  //We'll go ahead and leave Win/Lin URL handling available in OSX too
  QLocalSocket* sock = new QLocalSocket();
  sock->connectToServer(BTS_BLOCKCHAIN_NAME);
  if( sock->waitForConnected(100) )
  {
    if( argc > 1 && app.arguments()[1].startsWith(QString(CUSTOM_URL_SCHEME) + ":") )
    {
      //Need to open a custom URL. Pass it to pre-existing instance.
      std::cout << "Found instance already running. Sending message and exiting." << std::endl;
      sock->write(argv[1]);
      sock->waitForBytesWritten();
      sock->close();
    }
    //Note that we connected, but may not have sent anything. This means that another instance is already
    //running. The fact that we connected prompted it to request focus; we will just exit now.
    delete sock;
    return 0;
  }
  else
  {
    if( argc > 1 && app.arguments()[1].startsWith(QString(CUSTOM_URL_SCHEME) + ":") )
    {
      //No other instance running. Handle URL when we get started up.
      mainWindow.deferCustomUrl(app.arguments()[1]);
    }

    //Could not connect to already-running instance. Start a server so future instances connect to us
    QLocalServer* singleInstanceServer = startSingleInstanceServer(&mainWindow);
    app.connect(&app, &QApplication::aboutToQuit, singleInstanceServer, &QLocalServer::deleteLater);
  }
  delete sock;

  //License agreement
#ifdef REQUIRE_LICENSE_AGREEMENT
  if( !mainWindow.settings()->value("license_accepted", false).toBool() )
  {
    QQmlApplicationEngine engine(QUrl("qrc:/qml/LicenseAgreement.qml"));
    QFile license(":/license.txt");
    license.open(QIODevice::ReadOnly);
    engine.rootObjects()[0]->setProperty("licenseText", license.readAll());
    app.exec();
    mainWindow.settings()->setValue("license_accepted", engine.rootObjects()[0]->property("accepted"));
  }
  if( !mainWindow.settings()->value("license_accepted", false).toBool() )
    return 0;
#endif

  auto viewer = new Html5Viewer;
  ClientWrapper* client = new ClientWrapper;
  app.connect(&app, &QApplication::aboutToQuit, client, &ClientWrapper::close);

  mainWindow.setCentralWidget(viewer);
  mainWindow.setClientWrapper(client);

  QTimer fc_tasks;
  fc_tasks.connect( &fc_tasks, &QTimer::timeout, [](){ fc::usleep( fc::microseconds( 1000 ) ); } );
  fc_tasks.start(33);

  QPixmap pixmap(":/images/splash_screen.jpg");
  QSplashScreen splash(pixmap);
  splash.showMessage(QObject::tr("Loading configuration..."),
                     Qt::AlignCenter | Qt::AlignBottom, Qt::white);
  splash.show();

  prepareStartupSequence(client, viewer, &mainWindow, &splash);

  QWebSettings::globalSettings()->setAttribute( QWebSettings::PluginsEnabled, false );

  try {
    client->initialize();
    return app.exec();
  }
  catch ( const fc::exception& e)
  {
    elog( "${e}", ("e",e.to_detail_string() ) );
    QErrorMessage::qtHandler()->showMessage( e.to_string().c_str() );
  }
}
<|endoftext|>


<commit_before>0ac4c173-2748-11e6-9584-e0f84713e7b8<commit_msg>compiles now<commit_after>0acf1b05-2748-11e6-8f73-e0f84713e7b8<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Solidity commandline compiler.
 */

#include <string>
#include <iostream>

#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>

using namespace std;
using namespace dev;
using namespace solidity;

void help()
{
	cout << "Usage solc [OPTIONS] <file>" << endl
		 << "Options:" << endl
		 << "    -o,--optimize Optimize the bytecode for size." << endl
		 << "    -h,--help     Show this help message and exit." << endl
		 << "    -V,--version  Show the version and exit." << endl;
	exit(0);
}

void version()
{
	cout << "solc, the solidity complier commandline interface " << dev::Version << endl
		 << "  by Christian <c@ethdev.com>, (c) 2014." << endl
		 << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

int main(int argc, char** argv)
{
	string infile;
	bool optimize = false;
	for (int i = 1; i < argc; ++i)
	{
		string arg = argv[i];
		if (arg == "-o" || arg == "--optimize")
			optimize = true;
		else if (arg == "-h" || arg == "--help")
			help();
		else if (arg == "-V" || arg == "--version")
			version();
		else
			infile = argv[i];
	}
	string sourceCode;
	if (infile.empty())
	{
		string s;
		while (!cin.eof())
		{
			getline(cin, s);
			sourceCode.append(s);
		}
	}
	else
		sourceCode = asString(dev::contents(infile));

	CompilerStack compiler;
	try
	{
		compiler.compile(sourceCode, optimize);
	}
	catch (ParserError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", compiler.getScanner());
		return -1;
	}
	catch (DeclarationError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", compiler.getScanner());
		return -1;
	}
	catch (TypeError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", compiler.getScanner());
		return -1;
	}
	catch (CompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", compiler.getScanner());
		return -1;
	}
	catch (InternalCompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", compiler.getScanner());
		return -1;
	}
	catch (Exception const& exception)
	{
		cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
		return -1;
	}
	catch (...)
	{
		cerr << "Unknown exception during compilation." << endl;
		return -1;
	}

	cout << "Syntax tree for the contract:" << endl;
	ASTPrinter printer(compiler.getAST(), sourceCode);
	printer.print(cout);
	cout << "EVM assembly:" << endl;
	compiler.streamAssembly(cout);
	cout << "Opcodes:" << endl;
	cout << eth::disassemble(compiler.getBytecode()) << endl;
	cout << "Binary: " << toHex(compiler.getBytecode()) << endl;
	cout << "Interface specification: " << compiler.getJsonDocumentation(ABI_INTERFACE) << endl;
	cout << "Natspec user documentation: " << compiler.getJsonDocumentation(NATSPEC_USER) << endl;
	cout << "Natspec developer documentation: " << compiler.getJsonDocumentation(NATSPEC_DEV) << endl;

	return 0;
}
<commit_msg>Replacing old cstyle enums with c++11 enums in natspec<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2014
 * Solidity commandline compiler.
 */

#include <string>
#include <iostream>

#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>

using namespace std;
using namespace dev;
using namespace solidity;

void help()
{
	cout << "Usage solc [OPTIONS] <file>" << endl
		 << "Options:" << endl
		 << "    -o,--optimize Optimize the bytecode for size." << endl
		 << "    -h,--help     Show this help message and exit." << endl
		 << "    -V,--version  Show the version and exit." << endl;
	exit(0);
}

void version()
{
	cout << "solc, the solidity complier commandline interface " << dev::Version << endl
		 << "  by Christian <c@ethdev.com>, (c) 2014." << endl
		 << "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
	exit(0);
}

int main(int argc, char** argv)
{
	string infile;
	bool optimize = false;
	for (int i = 1; i < argc; ++i)
	{
		string arg = argv[i];
		if (arg == "-o" || arg == "--optimize")
			optimize = true;
		else if (arg == "-h" || arg == "--help")
			help();
		else if (arg == "-V" || arg == "--version")
			version();
		else
			infile = argv[i];
	}
	string sourceCode;
	if (infile.empty())
	{
		string s;
		while (!cin.eof())
		{
			getline(cin, s);
			sourceCode.append(s);
		}
	}
	else
		sourceCode = asString(dev::contents(infile));

	CompilerStack compiler;
	try
	{
		compiler.compile(sourceCode, optimize);
	}
	catch (ParserError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", compiler.getScanner());
		return -1;
	}
	catch (DeclarationError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", compiler.getScanner());
		return -1;
	}
	catch (TypeError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", compiler.getScanner());
		return -1;
	}
	catch (CompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", compiler.getScanner());
		return -1;
	}
	catch (InternalCompilerError const& exception)
	{
		SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", compiler.getScanner());
		return -1;
	}
	catch (Exception const& exception)
	{
		cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
		return -1;
	}
	catch (...)
	{
		cerr << "Unknown exception during compilation." << endl;
		return -1;
	}

	cout << "Syntax tree for the contract:" << endl;
	ASTPrinter printer(compiler.getAST(), sourceCode);
	printer.print(cout);
	cout << "EVM assembly:" << endl;
	compiler.streamAssembly(cout);
	cout << "Opcodes:" << endl;
	cout << eth::disassemble(compiler.getBytecode()) << endl;
	cout << "Binary: " << toHex(compiler.getBytecode()) << endl;
	cout << "Interface specification: " << compiler.getJsonDocumentation(DocumentationType::ABI_INTERFACE) << endl;
	cout << "Natspec user documentation: " << compiler.getJsonDocumentation(DocumentationType::NATSPEC_USER) << endl;
	cout << "Natspec developer documentation: " << compiler.getJsonDocumentation(DocumentationType::NATSPEC_DEV) << endl;

	return 0;
}
<|endoftext|>


<commit_before>15afbd73-ad59-11e7-b5b6-ac87a332f658<commit_msg>fixed bug<commit_after>16230c99-ad59-11e7-8832-ac87a332f658<|endoftext|>


<commit_before>f5fc6bf0-2747-11e6-a772-e0f84713e7b8<commit_msg>almost working<commit_after>f616abb3-2747-11e6-a94d-e0f84713e7b8<|endoftext|>